Solving an equation with Lambert's W function? Or by any other means?

Question: I am trying to solve the following equation for x in terms of $y$ and $c$ (with $x,y \in [0,1]$)
\begin{equation}
  \log\left(\frac{x}{1-x-y}\right) + \frac{x}{1-x-y} + \frac{y}{1-x-y} = c
\end{equation}
I can solve this easier equation
\begin{equation}
  \log\left(\frac{x}{1-x-y}\right) + \frac{x}{1-x-y} = c
\end{equation}
Let
\begin{equation}
  z = \frac{x}{1-x-y}
\end{equation}
Then I can solve for $x$ using Lambert's W function
\begin{align}
  \log(z) + z &= c \notag \\
  z &= \exp(c)\exp(-z) \notag \\
  z \exp(z) &= \exp(c) \notag \\
  z &= W(\exp(c)) \notag \\
  x &= \frac{(1-y)W(\exp(c))}{1+W(\exp(c))} \notag
\end{align}
Can anyone help me solve the harder equation? Is Lambert's W function helpful here?
Thanks!
Answer: \begin{align}
\ln\left(\frac{x}{1-x-y}\right)
+\frac{x}{1-x-y} + \frac{y}{1-x-y}
&= c
\tag{1}\label{1}
\end{align}
\begin{align}
\ln\left(\frac{x}{1-x-y}\right)
&= c+\frac{1-x-y-1}{1-x-y}
,\\
\ln\left(\frac{1-y}{1-x-y}-1\right)
&= c+1-\frac{1}{1-x-y}
,\\
\ln\left(\frac{1-y}{1-x-y}-1\right)
&= c-\left(\frac{1}{1-x-y}-1\right)
,\\
\ln\left(\frac{1-y}{1-x-y}-1\right)
&= c-\frac{1}{1-y}\left(\frac{1-y}{1-x-y}-(1-y)\right)
,\\
\ln\left(\frac{1-y}{1-x-y}-1\right)
&= c-\frac{1}{1-y}\left(\frac{1-y}{1-x-y}-(1-y)\right)
,\\
\ln\left(\frac{1-y}{1-x-y}-1\right)
&= c-\frac{y}{1-y}-\frac{1}{1-y}\left(\frac{1-y}{1-x-y}-1\right)
.
\end{align}
Let
\begin{align}
\frac{1-y}{1-x-y}-1&=z
,\\
c-\frac{y}{1-y}&=u
,\\
-\frac{1}{1-y}&=v
\end{align}
and we have an equation
\begin{align}
\ln z&=u+vz
,
\end{align}
which has a standard solution for $z$ in terms Lambert W function
\begin{align}
z&=-\frac{\operatorname{W}(-v\exp(u))}{v}
,\\
x&=(1-y)\left(1-\frac1{1+z}\right)
.
\end{align}
Answer: You can use the Lambert $W$ to solve
$$ \log(s) + s + t = c $$
and get a curve parameterized by $t$.
For each value of $(s,t)$, then,
$$ \frac{x}{1-x-y} = s \qquad\qquad \frac{y}{1-x-y} = t $$
now reduces to a system of linear equations in $x$ and $y$, which is easy to solve.
All in all, you get $(x,y)$ as afunction of $t$.
Comment: Hi Henning, thanks for your answer! This makes sense to me. Do you agree that it gives an implicit solution in the sense that $t = y / (1 - x - y)$? Is an implicit solution the best we can hope for here? Thanks!
Comment: @alex: I can't rule out that there is _something_ smarter that could be done with this result, but I don't immediately see what it would be.
Answer: I fill in the details of Henning Makholm's answer here
First, the parametrized curve
\begin{align}
  \log(s) + s + t &= c \notag \\
  s \exp(s) &= \exp(c - t) \notag \\
  s &= W(\exp(c-t)) \notag
\end{align}
Second, the linear system gives
\begin{equation}
  x = \frac{s}{1+s+t}, \quad \quad  y = \frac{t}{1+s+t}
\end{equation}
Substituting $s$ gives
\begin{equation}
  x = \frac{W(\exp(c-t))}{1+W(\exp(c-t))+t}, \quad \quad  y = \frac{t}{1+W(\exp(c-t))+t}
\end{equation}
This solves for $x$ and $y$ in terms of $c$ and $t$. The solution is implicit in the sense that $t = \frac{y}{1-x-y}$.


Great Chaos Fireball from Chancellor Wellager

Question: I'm going for the platinum trohpy hopefully prior to DS3 hitting the US next week and I think I'm down to just a handful of spells/hexes/miracles.
One of the NPCs sells a spell or two that you would otherwise get from covenant ranking.  Info on Chancellor Wellager.  According to this, bonfire ascetics do not change his inventory, but does anyone know if joining the covenant of champions would in effect make your game a ng++ (if you're currently in ng+ that is)
Comment: I've never tried this, but I think it's unlikely. That article seems to say that the covenant of champions makes the game *as hard as* NG+, but not that it actually *counts as* NG+.
Answer: No, joining the CoC does not increase the playthrough, it only simulates the difficulty. Wellager will still only sell his extra wares once you have defeated the game at least twice, regardless of Bonfire Ascetics, or Covenants.
To be specific - joining the Company of Champions will only change the game by:

Reducing damage dealt by 50%
Increasing damage taken by 50%
Cut off summoning (including NPC summons)


WCAG guidelines (CSS+HTML+Javascript)

Question: How can I make sure my web site follows the WCAG guidelines and works reasonably for users with low-bandwidth connections?
Answer: Here is a primer on WCAG from the W3C.
Your best bet is to run your site through these validators:

W3C Markup Validator
Wave Accessibility Evaluation Tool
W3C CSS Validator

It's a good practice to follow the guidelines of the W3C when coding a website. If you follow their suggestions, you're usually set in terms of accessibility.
Look through this list of web accessibility evaluation tools.
As an extra resource, follow some of these guidelines for low bandwidth sites:

Web Design Guidelines for Low Bandwidth
Answer: WCAG is a series of web accessibility guidelines published  by W3C.
There are 3 levels of WCAG 2.0 specifications.
1. WCAG Single Level A,
2. WCAG Double Level A.
3. WCAG Triple Level A

These are some of the tips for making sure that our site is WCAG compliant

Label  all form elements
Provide alternate text for non-text content. This would help people who are blind with assistance technology which can announce to them.People who are blind can use screen readers like
VoiceOver is inbuilt in mac,
NVDA and JAWS has to be downloaded for windows
,Chrome browser has chromevox

for more information you can look at this article enter link description here
Answer: I agree with running the tools suggested. However, these tools will not get you to an fully compliant site, usually far from it. You need to make sure that the site is completely operable by the keyboard.  You need to make sure that the alternative text you provide is meaningful and that links are labeled in a way the provide context and purpose. You should read up on WAI-ARIA.  The subject is more complex than people realize. WCAG is a usability standard and if your site has any complexity at all the automated tools will let you down.

WCAG guidelines (CSS+HTML+Javascript)


Should I install the exhaust hood outlet through the chimney or house wall?

Question: What are the advantages and disadvantages of implementing an outlet of a kitchen exhaust hood through a chimney or directly through the outer wall of the house? There are unused chimneys in the house but there is not a hole to one of them at the right place in the kitchen.
I think there could be differences in these parameters:

heat leakage (the house is insulated by polystyrene foam boards from the outside)
staining of the house wall
complexity and price of the maintenance
difficulty and price of the construction

If the chimney will be unused is it worth to enclose the open top end because of lower heat leakage and easier maintenance?
Answer: A hole in a wall is less likely to leak than a hole in the roof. Furthermore, when a hole in the wall leaks, it is likely to produce fewer problems than a leaky hole in the roof.
In the future, during reroofing, unused chimneys might be removed, and the associated hole in the roof along with them.
Answer: If the chimney is really unused, that would work... but you'd be setting yourself up for a safety hazard if the chimney is ever used again, since combustion gasses could back-draft through the vent. Bad Practice, I think.
Comment: Maybe chimney is not the right word. In Czech Republic where I live chimneys are used both for combustion gases exhaustion and ventilation (but not the same chimney for both). I think that there are pretty strict regulations for chimneys being used for combustion gases exhaustion. ------ In the past chimneys were certainly being used for kitchen exhaust hoods but I have heard that nowadays it is preferred to make a hole to a side wall of the house instead. I am wondering if there are reasons to make a new hole to the house.
Comment: Chimneys are not just for fireplaces. Any upward vent through the roof for removing the products of combustion serving a fuel burning appliance is a chimney.
Comment: Here in the US, "chimney" in the context of housing almost always means combustion exhaust -- fireplace, heating system, water heater, or other. You certainly wouldn't want that connected with ventilation. Even a ventilation chimney might not want to be connected to a kitchen exhaust, since that could result in sending the fumes you want to exhaust into other parts of the house. Sending the exhaust directly outside is probably a better solution.


dimmable led bulbs won't work in dimmable fixture

Question: Our living room has 4 dimmable lights controlled by 1 switch and slider. Many years ago, we replaced the incandescent lights with fluorescent bulbs (we didn't know that fluorescent bulbs don't dim out of the box). A couple weeks ago, some of the fluorescent bulbs randomly stopped working. Some days they'd turn on, other days they wouldn't,so we decided to replace them all with LED bulbs.
However, only one of the LED bulbs will turn on and dim while none of the others will turn on--let alone dim. When I reverted back to fluorescent bulbs, all but one work normally (at least in the 5 hours since reversion to fluorescent).
Do y'all have any tips for troubleshooting? I'd like to use the LEDs from now on.

UPDATE, 2018-01-26: My dad replaced the light fixtures, and now all of the LED bulbs dim properly. Unfortunately, I didn't get a chance to see what spec/model the old fixtures were before he threw them out.
Comment: What is the make and model of LED bulb?  It matters.  Also, what's the general style and era of the dimmer, i.e. is it an 80s classic or a fairly new model intended for LED dimming?
Comment: Dimmers don't always play well with LED or CFL bulbs. They make dimmers now that are better compatible with dimmable LED and CFL bulbs you may want to try replacing your dimmer with one of those. Even then they're not always compatible but the dimmer specs usually list bulbs they've been tested with.
Answer: I found that when I replaced the four incandescent 40 watt lamps in my ceiling fan light fixture with LED 60 watt rated (about 6 watts) they wouldn't work unless I reinstall one incandescent. I think it's because the dimmer needs at least 40 watts to work. I guess I'd better replace the dimmer with one rated for LED, but so far they will dim or work bright. I think I'll just run on bright until I replace the dimmer switch.
Answer: There are different types of dimmers and different types of bulbs ( aside from incandescent ) ; some work together and some don't. As a home owner I just try them to see which ones work together.


Running a command for each line of a text file (Bash)

Question: I am working on a program that does the following:
Reads 270 file in the folder X and calls another program to run a command with the contents of the file. For example:
$ cat X/1.txt
AAAA
BBBB
CCCC

The program is supposed to read that text (there are 270 of them) and in the loop it's supposed to do:
$python file.py AAAA;

then
python file.py BBBB;

then
python file.py CCCC.

and the move on the next file like 22.txt (the files aren't numeric so a counter wouldn't be much help).
I tried the following:
function text(){
for i in $(ls Domains/);
while read line;
do
        $line
        f= done < Domains/$i.txt
        python file.py $f
}

text;

Thanks, guys!
Comment: Not like that (ignore this comment)
Comment: It seems like every second bash-tagged question I see here needs someone to point out the dangers of [parsing LS](http://mywiki.wooledge.org/ParsingLs).  Please read the link, and don't do what you're doing.  And read about `find` and its `-exec` option, that's in the direction of what you want to use.
Answer: This is where xargs comes in handy: Concatenate all the files and pipe that into xargs which feeds each line to the python program one by one.
cat * | xargs -L1 python file.py

Comment: From what I have read online, it is advised not to ever use cat for things like that.. makes things messy.. but +1 for xargs!
Comment: @user3610137: On the contrary, that's an excellent use of `cat`. In contrast, you should not do this: `for i in $(ls Domains/);` which will fail when files have whitespace or glob characters in their names. `for i in *;` is preferred. If you don't care which file a line comes from, though, `cat * |` is simple and reliable, unless your directories have tens of thousands of files in them.
Answer: This should work:
function text(){
for i in $(ls Domains/)
do
while read line;
do
python file.py $line
done < Domains/$i.txt
done
}

Comment: is it possible to dump the output for each file in it's own text file?
Comment: Yes, first collect all the outputs in a variable or in a separate file, then dump it in the text file after the text file is finished being used (after the while loop).
Comment: How? I tried adding

 done < Domains/$i.txt > $i-DONE.txt but that doesn't work.
Comment: That's not how you get output.. Your output will be produced by python file.py $line, redirect them to another file.
Comment: I'm trying to run python file and put the ouput of that in it's own file.. so run python file.py $line of each .txt file and dump the output into $i-OUTPUT.txt
Comment: change the python... line to: `output+=$(python file.py $line)`
then after `done < Domains/$i.txt ` add this:
`echo "$output" >> "$i.txt"`
and also flush output variable adding `output=""` after this line


Open Source library / tool for converting PDF to HTML?

Question: My needs are quite simple, I need a tool or library (library would be perfect), to convert a PDF file to an HTML file keeping as many of the information as possible, except any images or styles, just semantic information.
I've checked out iTextPdf, but I haven't found anything like it. Any help would be nice.
Thanks in advance
Comment: C'mon people. Please stop recommending HTML to PDF when asked about PDF to HTML.
Comment: This question has only been asked a couple dozen times already.  C'mon people.
Comment: possible duplicate of [Convert HTML to PDF in .NET](http://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net)
Answer: Use iTextSharp. It's free and you only need the "itextsharp.dll".
http://sourceforge.net/projects/itextsharp/
Here is a simple function for reading the text out of a PDF.
<code>Public Shared Function GetTextFromPDF(PdfFileName As String) As String
    Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)

    Dim sOut = ""

    For i = 1 To oReader.NumberOfPages
        Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy

        sOut &= iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)
    Next

    Return sOut
End Function
</code>


Pulseaudio stops youtube playback when bluetooth A2DP headset connected

Question: I'm using Ubuntu 14.04 and pulseaudio is installed.
When I connect to bluetooth A2DP headset, the video playback on YouTube (google-chrome) stops with message:

if playback doesn't begin shortly try restarting your device.

If I remove or disconnect from the bluetooth headset, the video will start playing again immediately.
I added Disable=socket in /etc/bluetooth/audio.conf and that solved the problem. I also found some different bluetooth A2DP issues have the same solution, but there is no explanation.
Why does disabling the socket fix this?
Answer: Here is an article about bluez I found.
It said that the option Enable=Socket in /etc/bluetooth/audio.conf enables the audio socket API of bluez. The ALSA PCM plugin talks to bluez using this socket interface and it is already deprecated for sometime.
Also it mentioned that bluez cannot handle the d-bus API correctly when the socket interface is enabled.
So this might explain why pulseaudio would not work properly with bluetooth when Disable=socket is removed from /etc/bluetooth/audio.conf.


My game progress is lost!

Question: I've been playing the game for quite a while now and I decided to call it a day yesterday and when I returned today my saved game was wiped.
Any ideas?
Answer: Konami has revealed a bug which kills your saved game.
This bug triggers when you bring Quiet with you on "Mission 29" or "Mission 42".
If you want to be 100% sure this does not happen to you, then you don't bring her as a buddy on the missions mentioned above.
UPDATE: Konami has revealed a work-around.

As previously communicated, a critical bug has been identified that may halt progress and corrupt game save data under certain circumstances. Further investigation has revealed the exact trigger of the bug, so we would like to share these details to enable players to effectively avoid the issue.
The bug is triggered only under certain circumstances in Episode 29 or Episode 42 when Quiet is used as your buddy. However, you may still safely use Quiet in these missions if you use the Butterfly Emblem throughout the mission or avoid raising your Bond Level with Quiet to MAX during the course of the mission.
Comment: Worth noting that Konami has indicated that the next patch will fix your save game and allow you to continue with your game even if the bug has already happened.
Comment: http://www.konami.jp/mgs_portal/jp/info/?id=677
Comment: Source? All I've heard is "we'll fix it in a future patch". Which can mean anytime from now till when they send out the last patch for the game.

My game progress is lost!


Get name of abstract type

Question: I'm trying to create a trait that would provide the name of the abstract type that is added in the sub-class:
trait T {
  type T
  def myClassOf[T:ClassTag] = implicitly[ClassTag[T]].runtimeClass
  def getType = {
    myClassOf[T].getSimpleName
  }
}

class TT extends T {
  type T = String
}

However, this fails to compile:
Error:(7, 15) not enough arguments for method myClassOf: (implicit evidence$1: scala.reflect.ClassTag[T.this.T])Class[_].
Unspecified value parameter evidence$1.
    myClassOf[T].getSimpleName
             ^

But it works fine if I move the getType method to the sub-class. Can someone explain why and whether there is a way to do this call from the sub-class?
Answer: At the point where you call myClassOf[T] T is still abstract, so the compiler can not generate a ClassTag for it. You can fix it by delaying the generation of the ClassTag[T] until T is known.
trait Trait {
  type T
  def myClassOf[A:ClassTag] = implicitly[ClassTag[A]].runtimeClass
  def getType(implicit tag: ClassTag[T]) = {
    myClassOf[T].getSimpleName
  }
}

class Sub extends Trait {
  type T = String
}

If adding an implicit parameter is impossible for some reason I think the best way is probably requiring some method getClassT to be implemented in subclasses. Since its return type is Class[T] it's difficult to provide a wrong implementation in a subclass.
trait Trait {
  type T
  def getType = {
    getClassT.getSimpleName
  }
  def getClassT: Class[T]
}

class Sub extends Trait {
  type T = String
  def getClassT = classOf[T]
}

Comment: Thanks. That makes sense.
Comment: Is there any way that I can call the method `getType` from within the same trait? I'd like to use it in a method where the signature is fixed, so that it'd need to pass the implicit parameters
Comment: I don't immediately see a way.
Answer: Note that the above answers, while good are now obsolete as of scala 2.10.
the preferred method now is to use TypeTag or ClassTag.
As described in the docs (see below) you can now use them in implicit param lists or context bounds to do this kind of thing:-
import scala.reflect.runtime.universe._

def paramInfo[T: TypeTag](x: T): Unit = {
  val targs = typeOf[T] match { case TypeRef(_, _, args) => args }
  println(s"type of $x has type arguments $targs")
}

scala> paramInfo(42)
type of 42 has type arguments List()

scala> paramInfo(List(1, 2))
type of List(1, 2) has type arguments List(Int)

see scala docs on Typetags
see api docs

Get name of abstract type


How can I lock the FPS of CSGO to lower than 60?

Question: In Counter-Strike: Global Offensive fps_max can limit your FPS, but will only go down to 59. I know this is weird but I can't play on anything more than ~35 fps without getting sick. A lot of friends want me to play with them, but I can't at that high of an FPS
Does anyone have any ideas for how to lock the framerate under 60 FPS?
Comment: You might want to look into changing FoV instead, as **higher** framerate shouldn't make you feel sick, but the wrong FoV can.
Comment: I really agree with Chippies here; and actually, I would think a lower framerate wouldn't really help the problem; I know with VR, low FPS makes a lot of people sick.
Comment: Try creating an artificial bottleneck in your system. This might be crude, but a simple way would be to limit the power usage of your CPU to something like 70% (similar to using power saving mode). Although this may cause stuttering and and the system can overcome it's bottleneck, allowing it to surpass the frame rate you are looking for.
Answer: There are a couple of ways to do that but not from the game:

Use MSI Afterburner
Lower monitor to 30hz and force VSync
nVidia Inspector - It has an option Force Refresh Rate
Use Fraps and lock framerate (it has this option and it should be the simplest)


Should I repair the kraft paper vapor barrier after remodeling work?

Question: R-60 kraft-faced fiberglass batts were installed in our modular home when it was built in 1994.  We recently remodeled two rooms and the contractor made a real mess of the insulation when installing new ceiling lights and a new bathroom exhaust fan.  Batts appear to have been simply ripped up without concern for protecting them for re-use.
Some effort was made to replace batts but large gaps were left between them.  Many of the batts probably can be relaid between the trusses with some care; others may have to be replaced because the facing is torn.
My questions are these.

Is it important to maintain the (admittedly minimal) vapor barrier afforded by the kraft facing or is it OK to relay batts that have torn facing?
If batts have to be replaced, do I need to get ones that are faced?
Might it be more cost-effective to pull all the batts in the messed up areas and have them replaced by blown fiberglass insulation?  (Blown insulation at least has the advantage of making it easier to insulate around IC-rated light fixtures.)
Finally, how important is it to remove construction debris, such as sawdust, scraps of paper, cable jacketing, etc. on top of the batts in areas where they are still intact but hard to access?
Answer:
Yes, you should repair or replace the vapor barrier, depending on your climate. In most areas it's important to prevent moisture due to human activity from reaching the frost front inside the insulation, where it will condense and cause mold or damage.
Yes, you should use faced batts as replacements, unless you intend to install poly sheeting over those cavities instead.
Yes, it may make sense to simply blow in cellulose or fiberglass over a new vapor barrier, but we can't say with the limited information provided. (Cost questions are also generally off-topic.)
Minor debris is inconsequential, except where it's large or heavy enough to cause compression of the insulation medium.
Comment: Well, if your home was built 20 years ago and it hasn't been a problem as-is, it's unlikely to be a problem going forward. The fact is that homes don't have moisture *barriers*, but vapor *retarders*--mechanisms that slow the movement of moisture to the point where it doesn't accumulate. No home has a complete seal.
Comment: Isherwood, thanks for the advice, especially about the light weight debris.  I should have noted that our house is in northern Virginia: hot and humid in the summer and cold in the winter.  So vapor barrier certainly is called for.  The kraft faced insulation in the walls was installed using the nailing flanges, but the batts in the attic were simply laid in place after the drywall was up and so provide only a partial vapor barrier at best.  That's why I was wondering about how important it is to establish a good vapor barrier where the batts have been disturbed.
Answer: We decided to simply put the original insulation batts back as carefully as possible with only minimal additions.  Two contractors who were here on other matters said that the few areas that aren't covered as well as they "should" be wouldn't make much difference and that the cost of fixing them would greatly exceed the cost due to heating or cooling losses.  Thanks for the advice.


Why does the "Thank you for contacting us" page still include the contact form?

Question: After submitting a subscription or contact page, the user is typically presented with the same form with one change: an often small statement saying "Thank you for your response." Why would the "Thank you for subscribing" page still include the subscription form? It makes me think I'm supposed to fill it out again. Wouldn't it be better to replace the form with the confirmation message? But this anti-pattern is so common, it makes me assume it has supporters in the UX community.
Related:
"Contact us" form submission best practice
Answer: My answer is going to be a mix of Business Understanding and UX, feel free to query / comment accordingly.
Answer -
A subscription or contact us page is the first line of contact with the customer online for many businesses. Mostly the submitted form includes information like phone number / email id etc. which helps the organisation to reach out back to the customer. Hence it is a good practice to show back the data entered by the user, just in case if the user has mis-entered some information he should be allowed to correct it again.
Specifically to your doubt -

It might be better to show all fields non-editable with the user's data.
Add a message - "The following data was submitted by you, we will reach out to you on your provided contact details"
Give a "Edit" button which allows to resubmit the info with minor edits.

An Example -
Your designed contact page is being used by ABC.corp.
User X is requesting for quotations from ABC and its competitors and has queried for an order of 1000 units of whatever ABC produces, but since he is doing this on 5 different sites in a hurry he swaps 2 digits of his phone number.
Loss of business and negative reviews to a business matter a lot and also its a good practice in UX terms.


typescript JSON.stringify loose type and function

Question: I know JSON.stringify doesn't stringify function, but what's the good practice because hydration is really exhausting. I don't want to create a new object. Any idea ?
class pers {
    name = "";
    last = "";

    constructor(name: string, last: string) {
        this.name = name;
        this.last = last;
    }

    alo() {
        alert(this.name);
    }
}

let pa = new pers("ben", "troq");
let s = JSON.stringify(pa);
let o = <pers>JSON.parse(s);
let pb = new pers("", "");

pb = o;
pb.alo();

Comment: Unrelated, but do yourself a favour and make the code consistent (put spaces around `=` everywhere, or do it nowhere if that makes you happier) and write out names (class `person`, with attributes `firstname` and `lastname` for example, instead of pers, name, last). What would `pa`, `s`, `o` and `pb` even stand for?
Comment: http://stackoverflow.com/questions/8111446/turning-json-strings-into-objects-with-methods
Answer: The problem is this line:
let o = <pers>JSON.parse(s);

I belive you think this is a type-cast, but it is not. This is a type-assertion, which does not imply runtime support. Basically, you are only telling the compiler to believe o is of type pers, but that is not true at runtime:
o instanceof pers; // false

You will either need to manually create the object instance using your JSON as Nitzan suggests, or create a routine that reads some metadata information to automatically create the correct instances with the corresponding properties.

For the latter approach, I would recommend trying out TypedJSON, which I created to provide an elegant and widely adaptable solution to this exact problem:
@JsonObject
class pers {
    @JsonMember name = "";
    @JsonMember last = "";

    constructor(name?: string, last?: string) {
        this.name = name;
        this.last = last;
    }

    alo() {
        alert(this.name);
    }
}

let o = TypedJSON.parse(s, pers);
o instanceof pers; // true
o.alo(); // "ben"

Note the parameterless constructor, that is required (in most similar systems, as well).
This solution builds on ReflectDecorators, but it's not required (however, without it you will need to manually specify the constructor function of properties: @JsonMember({ type: String }) ... for example).
Answer: How about separating the data from the functionality?
interface PersData {
    name: string;
    last: string;
}

class pers {
    private data: PersData;

    constructor(data: PersData | string) {
        this.data = typeof data === "string" ? JSON.parse(data) : data;
    }

    alo() {
        alert(this.data.name);
    }
}

Answer: replace:
let o  = <pers>JSON.parse(s);
let pb = new pers("", "");

pb = o;
pb.alo();

with:
let o  = JSON.parse(s);
let pb = Object.create(pers.prototype);
Object.assign(pb, o);

pb.alo();

It should work. Object.create (ES5.1) creates an object whose linked prototype is the one from the pers class but without running the pers constructor. Then Object.assign (ES6) copies the properties from the object unserialized from JSON to the object referenced by pb. Because the prototype was correctly set by Object.create calling the methods will work.
Comment: Can you explain your answer instead of just putting code in here? What is the key thing that makes your answer work? I ask because with an explanation others can learn from your answer and apply that to other questions. That is what stackoverflow is about --- not blindly copying & pasting some code.
Comment: Sorry, I thought the snippet was self-evident. Edited and added an explanation.


MySQL database restore code using java is not working and makes application not responding

Question: Here is my code for mysql database restore code .when i tried this code app works without exception but application get hangs and database is not restored ..please help me
String databaseName = "sample"; //database name
String userName = "root"; // MySQL username
String password = ""; // MySQL password
int processComplete; // this variable for verify the process

String[] executeCmd = new String[]{"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
        databaseName, "-u" + userName, "-p" + password, "-e", " source D:/data.sql"};

System.out.println(executeCmd);
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);// execute the command
processComplete = runtimeProcess.waitFor();
System.out.println(processComplete);

if (processComplete == 1) { // if return value equal to 1 then failed the process
    JOptionPane.showMessageDialog(null, "Restore Failed");
} else if (processComplete == 0) {{// if return value equal to 0 then failed the process
    JOptionPane.showMessageDialog(null, "Restore Completed");
}

Answer: I suspect that the last parameter is been mishandled
String[] executeCmd = new String[]{
    "C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
    databaseName,
    "-u" + userName,
    "-p" + password,
    "-e",
    " source D:/data.sql" }

It should probably look more like...
String[] executeCmd = new String[]{
    "C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",
    databaseName,
    "-u" + userName,
    "-p" + password,
    "-e",
    "source",
    "D:/data.sql" }

Each element in the array will be a separate argument passed to the command, this allows you the flexibility of passing arguments that have spaces in them without need to first escape them using quotes
You should consider using ProcessBuilder instead of trying to build the Process yourself, apart from allowing you to re-direct the error stream to the input stream, it also allows you to specify the starting context for the process.
You should also be reading the output of the process (via it's InputStream) which would possibly highlight issues and may also allow the process to exit (as some process won't exit until there stdout is read completely)
For example: How do I execute Windows commands in Java?
Comment: Thank you for response but still database is not restoring
here is my code
Comment: Thank you for response but still database is not restoring and process value is 1
here is my code
<<--->>
 String[] executeCmd = new String[]{"C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysql",databaseName,"-u" + userName,"-p" + password,"-e","source","D:/data.sql" };
ProcessBuilder pb = new ProcessBuilder(executeCmd);
pb.redirectError();
Process p = pb.start();
InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream());
isc.start();
int exitCode = p.waitFor();
isc.join();
System.out.println("Process terminated with " + exitCode);
<<-------------->>
any solution i am using win7 ??
Comment: Does the `InputStreamConsumer` display any error messages?  Does the command work from the command line?
Comment: no error and no change in database.
process status is 1
Comment: Where is the database located?
Comment: Is the program running from the correct directory context (`startIn`)
Comment: " C:\wamp\bin\mysql\mysql5.5.24\bin>mysql -u root -p    sample < D:/data.sql " this code works from command line
Comment: There's in input redirection (`<`) in your example, and I' not sure if that would work any way...


Brakepoints in xcode subproject don't work

Question: We have static lib project, and other "sample" project.
I added static lib project as a subproject to "sample" project and also to target dependancy.
When I run "sample" brakepoints work properly, but not in subproject (static lib).
Is it possible somehow to debug my subproject, or it's impossible if it's static lib?
UPDATED
Fixed:

For some reasons "Generate Debugging symbols" flag was set to NO
Answer: Create one workspace and put it as separate projects. Now You need to add static lib in sample project. So add library from sub project product folder (where your lib get created) as reference. It will work also for debugging and whenever you will build for static lib that changes will reflect in sample project also.


How to convince users to allow their browser notification in my website?

Question: Currently we have a notification features like SMS/Email to inform the user about their latest status, but sometimes users don't get noticed by them, thus i need them to allow their browser notification which will prevent any new missed in the future.
My question is how to convince them to click "allow" button rather than "block"?
Update:
This is what i mean, because every people i've met for testing always block it or accidentally block it.
Comment: Is there a benefit to them as well as to you?  Do *they* see it as a benefit? If they don't, that's your problem.
Comment: No, Rob, all you *really* know for sure is that they said "yes" when you first asked.  If they said "yes" then, but are blocking you now, that means they changed their mind.  Why did they change their mind?  Do you send them notices too often?  Did your notices interfere with their ability to concentrate on something else?  Was blocking you the only way to get your messages to stop because you didn't provide a way to temporarily *suspend* them?  All these questions are important.
Comment: @MMacD I'm sure, the user want to know about their latest financial stuff status because they applied it.
Comment: I see, well good advices @MMacD i will think about it, FYI we will send them notification just everytime their status get updated (Processing, Rejected/Accepted).
Answer: Notifications take up my time and intrude into my life and I already get dozens of them every day. My personal instinct is to automatically block all notifications until I understand them and see a benefit in allowing them.
Tell the user why the notifications are worthwhile in clear terms. What will they be sent notifications about and how often. Clearly explain how to turn notifications off if they allow them and don't want them anymore. Ideally this would be explained before the choice to allow notifications is presented.
Answer: Tragedy of the Commons is the problem
I spend some of my online experience in FOMO.  Checking email anytime see a red circle with a 1 in it.  Digging through Facebook and twitter. Text messages. Phone. Those are the platforms where I put my antenna up and react to input directed at me by others: I am pushed and interrupted.  Ding! Facebook notification must click etc.  Call it reaction mode.
One place I don't have that is the browser.  I open a browser, I choose my sites, choose my activities. (ironically, many are to log onto reaction-mode sites). But when I leave those sites, reaction mode is over.
Haven't you ever realized the time was midnight, your desktop is covered in tabs, and you spent the last 2 hours recursing into the TVTropes site, Worth1000 or Wikipedia?  Isn't that wonderful?   That's explore mode, the opposite of reaction-mode.  Some people hate it but others thrive there.
Another explore-mode is binge-watching Netflix til 1am.  Obviously, these are things people love to do.
If I say yes to your notifications, it'll only be part of a greater habit to say "yes" to many other sites.  So the issue becomes the aggregate effect of dozens of sites like yours on my browsing experience.  This will become a "tragedy of the commons" that will be the permanent end of explore-mode.
And I really like explore-mode.
They're not snubbing you.  They're snubbing everyone.
Answer: Notifications are generally considered bad because they distract the user from whatever he is doing. Even for things such as emails, new messages from chat etc. people get annoyed pretty fast especially if 1)these come in bulk and 2)have some sound or flashy visual feedback attached to them. Combine these two and you get a very, very pissed off user who will leave your site and never return no matter how valuable information you offer. Do take a note also that your site might not be the only one that uses notifications in the current session which would make the chance of 1) and/or 2) happening skyrocket.
That said notifications are necessary depending on the use case. However notifications don't need be intrusive. If you have a sidebar or similar component in your website you can place your notification there. Example: SMS messages or emails on a smartphone. Of course there is the poorly done notification and the good one. The good one appears in a place which 1)is always there such as the bar where signal strength, time etc. are shown and 2)takes a very small part of the screen. Notifications that cover whatever the user is doing are annoying...very, very annoying. If you place your notification at such a location which is visible to the user all the time and he looks at it (even with just part of his vision but enough to notice a change) you will make sure that the user will see it and at the same time the notification will not be viewed as something intrusive.

UPDATE: The notification type you have posted (should have done it at the very beginning omho to clarify things) has two flaws even though it's a very widely used one - it covers contents of the page and in addition doesn't give any information about the nature of what the user is supposed to allow or block.

Due to it's size the first one might not be such a big issue (although it really annoys me where such a notification covers something that I'm currently reading LOL).
The second issue namely missing explanation is something that I view as a more serious one. If a person is asked a question that he doesn't have enough information about you might think that there is a 50/50 chance of him pressing the "Allow" button. Well, no. At least in my experience you have a much higher chance of him pressing the "Block". This is due to the nature of most users being suspicious (human nature actually). If they don't understand something they often try to avoid it or reject it...or ignore it if no alarm is triggered.

I will talk about the second problem since I view it as the core problem here. If the screenshot you've provided is indeed what you give the user and ask the question "Allow/block notifications" here is a counter example for a better notification (though not perfect) of a very similar nature which we can dissect in order to see what you can improve in your own:

There are two important things here:

the notification explains what has happened and why it has appeared namely an outdated Flash plugin is obviously an issue for the browser (it even offers a perk - you can go and download a newer version by clicking on a provided link which give the user a fast way to fix the issue). It gives the user important information followed by an informed (due to the provided info) decision that he has to make
the notification offers multiple choices to the user how to handle this information it has provided namely:

Close (the X sign in the top right corner) - the user is allowed to continue blocking the plugin
Allow Now - the user can unblock the plugin just for this session so he is offered the ability to reverse the decision by just starting a new session (more on that later)
Allow and remember - the user can unblock the plugin permanently thus avoiding some tedious decision making if he is sure that he is okay with an outdated plugin

I've mentioned that even though better this notification still has a flaw (at least from my point of view) namely the fact that it assumes that the user knows that he can reverse the decision (unblocking for the current session or "till death do us part"). In order to reverse the decision the user has to again click in that tiny area right in front of the address bar:

It doesn't give this information during the initial decision making (namely the allow or block xyz question) and as a new user if I get annoyed by the notifications I will have too google how to reverse my decision. For a user that is already annoyed (but lacks the knowledge how to reverse the setting) having to look on the Internet how to block the notifications is way too much work. Sure, the tiny arrow at the top left corner indicates that something is going on in that area but is this really enough?
In your case you offer a similar choice to the user. In your case your notification lacks any information that might help the user make up his mind. No matter what the notification does it has to inform the user what he is about to do and why the notification has appeared in the first place. The decision making is optional but in your case present too just like the one for blocking the Flash plugin. If you just use the default

https://... would like to use your:

Notifications

you are not giving your user any information about what kind of notifications he will get. Some web sites for example use a very intrusive way of advertisement through notifications. The missing explanation, the fact that this feature gets abused out there and the missing information how to adjust the settings once a decision has been made lead to mistrust in your user hence the tendency of choosing "Block" instead of "Allow".

A rule of thumb:
Always inform your user whenever you require him to make a decision about something especially if it's about a feature which (according to you) will improve his user experience.

Along with the information what the notification is all about never assume that you know perfectly what the user needs or will use from your feature set. Statements such as I'm sure, the user wants to know about ... because they applied it. will shoot you in the foot one day. Always allow things to be turned on and off upon user's request. Restricting the freedom of a user even for something seemingly small as turning notifications on and off is a sure path to failure. Make this clear in the information in that Allow/Block notification (again - something missing from the example I've posted above about the Flash plugin!) otherwise your general user will see a one time deal and this is a pretty tough decision to make for anything. A power user will just delete the cookie(s) that you app provides or just know how to open the notification for Block/Allow again and reverse the decision he made and that's that but this isn't exactly a normal way to change a setting, right? :D
PS: My initial post still stands due to the fact that email/SMS notification can easily come in bulk and create a mess. Personally I would try to do some sort of stacking (not familiar with the implementation side of these sort of notifications to be honest). For example: show parts of the message which has arrived first and then add some sort of a counter to indicated that there are more messages after it that require attention.


Would a concrete ramp added to an existing slab be less durable?

Question: To remediate a situation my concrete company caused by changing the layout without consulting me, they propose to add a ramp partially on an existing (though new ~10 days) slab.  I'm worried that it won't be durable, and I am having trouble trusting them for obvious reasons.
Here is a (bad) drawing of the proposed ramp: It would be straight on the left matching the lower pad, I'm just bad at Photoshop.  The ramp will be 2 feet by 8-10, and will rise to 6 inches high to meet the higher level.
They say "We will cut and remove the lower portion out of the trash can pad so we can pour solid 4" down so we are not going to zero on top of the existing. The area on the sides will have rebar to tie the two together. This is standard practice."
Is that OK, or should I insist on tearing out the lower slab and redoing it with the ramp as part of the same pour?
Background:
I had a company build a concrete pad in my back yard.  Without consulting me, they changed the layout to have two levels: a lower level for a small extension for my trash bins to sit on, and the main part 6 inches higher.
I wanted the whole thing to be the same level as the lower pad.  They obviously don't want to tear it all out and redo.  I'm mostly OK with the higher level, except the trip hazard, since my young kids will be playing back there.
Comment: I have edited your question to include the picture directly.  It should be approved eventually, but if you approve it, it will appear immediately.
Answer: They are taking out the lower area to have a full 4" pour, they are tying them together with rebar so I don't see any issues, for foot traffic in a small area 2" even works. I see driveways poured at 4" all the time so I think they are planning a proper fix as long as you are happy with there design.
Comment: thanks.  I have given the company the go-ahead.  I believe SE etiquette is to wait 24 hours before accepting, but will do so later tonight.


Replacing html from javascript

Question: I've such peace of html:
teeeeeeest >>

Using Mozilla Firefox and Greasemonkey-addon I need to replace

request_url="/int_studies/json/callback_display_test_task_list"

to

request_url="#"

Greasemonkey executes your javascript-code on linked pages, so how should I access request_url parameter value from js? Please, help.
Comment: have you tried something ?
Comment: Have a look at jquery's attr method: http://api.jquery.com/attr/
Comment: now i'm playng with tries inside function $('a').each(function() { }, but I don't know if it's a right way
Answer: You can bind an event when your dom is ready. You should write your snippet in document.ready function. Your snippet would be
$(function () {
  $("a[control_type=dialog]").prop("request_url", "#");
})

Comment: Why `prop` over `attr` ?
Comment: thanks, also .attr() I found as working. Apperciate!
Comment: @RayonDabre Nice question By the way. This link will explain you better http://stackoverflow.com/questions/16051491/difference-between-prop-and-attr-in-jquery-and-when-to-use-attr-and-prop
Comment: @RayonDabre You can user `attr` as well
Comment: @Vineet, Yes but the point is about **readability** and I dont find `href` as **property**, it is an **attribute**

Replacing html from javascript


How to find $\int_{0}^{\pi} \ln (b \cos x+c)$ without using Feynman's integration technique?

Question: I shall find the integral by Feynman's Technique Integration on a particular integral
$\displaystyle I(a)=\int_{0}^{\pi} \ln (a \cos x+1) d x,\tag*{} $
where $-1\leq a \leq 1.$
$\displaystyle \begin{aligned}I^{\prime}(a) &=\int_{0}^{\pi} \frac{\cos x}{a \cos x+1} d x, \\&=\frac{1}{a} \int_{0}^{\pi} \frac{(a \cos x+1)-1}{a \cos x+1} d x \\&=\frac{\pi}{a}-\frac{1}{a} \int_{0}^{\pi} \frac{d x}{a \cos x+1} \\&\stackrel{t=\tan \frac{x}{2}}{=} \frac{\pi}{a}-\frac{1}{a} \int_{0}^{\infty} \frac{1}{1+\frac{a\left(1-t^{2}\right)}{1+t^{2}}} \cdot \frac{2 d t}{1+t^{2}} \\&=\frac{\pi}{a}-\frac{2}{a} \int_{0}^{\infty} \frac{d t}{(1-a) t^{2}+(1+a)} \\&=\frac{\pi}{a}-\frac{2}{a \sqrt{1-a^{2}}} \tan^{-1}\left[\frac{\sqrt{1-a} t}{\sqrt{1+a}}\right]_{0}^{\infty} \\&=\frac{\pi}{a}-\frac{\pi}{a \sqrt{1-a^{2}}}\end{aligned}\tag*{} $
Integrating both sides w.r.t. $a$ yields
\begin{aligned}\int I^{\prime}(a) d a &=\pi\int\left(\frac{1}{a}-\frac{1}{a \sqrt{1-a^{2}}}\right) da \\& \stackrel{a=\sin \theta}{=} \pi\int\left(\frac{1}{\sin \theta}-\frac{1}{\sin \theta \cos \theta}\right) \cos \theta d \theta \\&=\pi\int \frac{\cos \theta-1}{\sin \theta} d \theta\\&I(a) =\pi \int \frac{-\sin ^{2} \theta}{\sin \theta(\cos \theta+1)} d \theta\\&=\pi \ln (1+\cos \theta) +C\end{aligned}
Putting $a=0$ gives $C=-\pi\ln 2$ and hence
$$
\boxed{\int_{0}^{\pi} \ln (a \cos x+1) d x =\pi \ln \left[1+\cos \left(\sin ^{-1} a\right)\right]= \pi \ln \left(\frac{1+\sqrt{1-a^{2}}}{2}  \right)}
$$
I now want to generalize it to
$$I(b,c)=\displaystyle \int_{0}^{\pi} \ln (b \cos x+c),\tag*{} $$
where $c\neq 0$ and $-1\leq \frac{b}{c} \leq 1.$
$$
\begin{aligned}
I(b,c)&=\int_{0}^{\pi} \ln (b \cos x+c) \\
&=\int_{0}^{\pi} \ln \left[c\left(\frac{b \cos x}{c}+1\right)\right] \\
&=\pi \ln c+\int_{0}^{\pi} \ln \left(\frac{b}{c} \cos x+1\right) d x \\
&=\pi \ln c+I\left(\frac{b}{c}\right)
\end{aligned}
$$
Putting $a=\frac{b}{c}$ yields
$$\boxed{\int_{0}^{\pi} \ln (b \cos x+c) = \pi\left[\ln c+\ln \left(1+\sqrt{1-\frac{b^{2}}{c^{2}}}\right)\right] = \pi \ln \left(\frac{c+\sqrt{c^{2}-b^{2}}}{2}\right)}
$$
For example,
$$
\int_{0}^{\pi} \ln (\cos x+1)=\pi \ln \left(\frac{1}{2}\right)=-\pi \ln 2;
$$
$$
\int_{0}^{\pi} \ln (\sqrt{3} \cos x+2) d x=\pi\ln \frac{3}{2}
$$
Is there any  method other than Feynman's integration technique?
Answer: Concerning the antiderivative
$$I=\int \log (b \cos (x)+c)\,dx=2\int \frac 1{t^2+1}\Big[\log[ (c-b)t^2+(b+c)]-\log(t^2+1)\Big]\,dt$$ But
$$\log[ (c-b)t^2+(b+c)]=\log(c-b)+\log \left(t-\sqrt{\frac{b+c}{b-c}}\right)+\log \left(t+\sqrt{\frac{b+c}{b-c}}\right)$$
Now, using
$$\frac 1{t^2+1}=\frac 1{(t+i)(t-i)}=\frac i2  \left(\frac{1}{t+i}-\frac{1}{t-i}\right)$$ we face four integrals
$$J(\alpha,\beta)=\int \frac {\log(t+\alpha)}{t+\beta}\,dt=\text{Li}_2\left(\frac{t+\alpha }{\alpha -\beta }\right)+\log (t+\alpha ) \log
   \left(\frac{\beta +t}{\beta -\alpha }\right)$$
Answer: Note that, with $r= \frac cb -\sqrt{\frac{c^2}{b^2}-1}$
$$\ln (b \cos x+c)=\ln\frac{c+\sqrt{c^2-b^2}}2+\ln\left(1+2r\cos x+r^2\right)
$$
Thus, per $\int_0^\pi \ln\left(1+2r\cos x+r^2\right)dx=0$
$$\int_{0}^{\pi} \ln (b \cos x+c)dx
=\pi \ln\frac{c+\sqrt{c^2-b^2}}2
$$
Comment: A nice approach. For $c>b\,$ I used
$$\frac{b}{2}(e^{ix}+e^{-ix})+c=\frac{c+\sqrt{c^2-b^2}}{2}\Big(1+\frac{b}{c+\sqrt{c^2-b^2}}e^{ix}\Big)\Big(1+\frac{b}{c+\sqrt{c^2-b^2}}e^{-ix}\Big)$$
and, decomposing logarithms, $\int_0^{2\pi}e^{inx}dx=0;\,\, n=1,2,...$
Answer: Another option as opposed to using an infinite sequence and piecewise integration is to use a Weierstrass substitution and then a double integral.
Take $x\mapsto\tan\left(\tfrac x2\right)$ such that $\cos x\mapsto(1-x^2)/(1+x^2)$. The integral then becomes
$$\begin{align*}I & \equiv\int\limits_0^\pi\mathrm dx\,\log(1+a\cos x)\\ & =2\int\limits_0^{+\infty}\frac {\mathrm dx}{1+x^2}\log\left(1+a\frac {1-x^2}{1+x^2}\right)\\ & =2\int\limits_0^{+\infty}\frac {\mathrm dx}{1+x^2}\left[\log(1+a)+\log\left(1+\frac {1-a}{1+a}x^2\right)-\log(1+x^2)\right]\end{align*}$$
The first integral is trivial
$$\log(1+a)\int\limits_0^{+\infty}\frac {\mathrm dx}{1+x^2}=\frac \pi2\log(1+a)$$
The last two integrals can be evaluated using the general case
$$J\equiv\int\limits_0^{+\infty}\mathrm dx\,\frac {\log(1+z^2 x^2)}{1+x^2}$$
With the middle integral being the special case $z^2=(1-a)/(1+a)$ and the last integral being the case $z=1$. To evaluate $J$, we make use of a double integral, namely
$$\log(1+z^2)=\int\limits_0^1\mathrm dy\,\frac {2yz^2}{1+y^2z^2}$$
Substituting the identity above into $J$ and switching the order of integration gives
$$\begin{align*}J & =\int\limits_0^1\mathrm dy\,\int\limits_0^{+\infty}\mathrm dx\,\frac {2x^2yz^2}{(1+x^2)(1+x^2y^2z^2)}\\ & =\int\limits_0^1\mathrm dy\,\frac {2yz^2}{y^2z^2-1}\int\limits_0^{+\infty}\mathrm dx\,\left(\frac 1{1+x^2}-\frac 1{1+x^2y^2z^2}\right)\\ & =\pi z^2\int\limits_0^1\mathrm dy\,\frac y{y^2z^2-1}\left(1-\frac 1{yz}\right)\\ & =\pi z\int\limits_0^1\frac {\mathrm dy}{1+yz}\\ & =\pi\log(1+z)\end{align*}$$
Hence
$$\int\limits_0^{+\infty}\frac {\mathrm dx}{1+x^2}\log\left(1+\frac {1-a}{1+a}x^2\right)=\pi\log\left(1+\sqrt{\frac {1-a}{1+a}}\right)$$
And
$$\int\limits_0^{+\infty}\frac {\mathrm dx}{1+x^2}\log(1+x^2)=\pi\log 2$$
Putting everything together, then
$$\int\limits_0^\pi\mathrm dx\,\log(1+a\cos x)\color{blue}{=\pi\log\left(\frac {1+a}4\right)+2\pi\log\left(1+\sqrt{\frac {1-a}{1+a}}\right)}$$
Let $a=1$ and we get the integral stated in the question
$$\int\limits_0^\pi\mathrm dx\,\log(1+\cos x)=\pi\log\left(\frac 12\right)=-\pi\log 2$$

The more general case considering $\log(a+b\cos x)$ can be evaluated by transforming the integrand such that the constant term becomes one. Factoring out an $a$ gives
$$K\equiv\int\limits_0^\pi\mathrm dx\,\log(a+b\cos x)=\pi\log a+\int\limits_0^\pi\mathrm dx\,\log\left(1+\frac ba\cos x\right)$$
Using the formula we derived above and after some simplification, then
$$\int\limits_0^\pi\mathrm dx\,\log(a+b\cos x)\color{blue}{=\pi\log\left(\frac {a+b}4\right)+2\pi\log\left(1+\sqrt{\frac {a-b}{a+b}}\right)}$$
Substituting $a=2$ and $b=\sqrt3$ gives
$$\int\limits_0^\pi\mathrm dx\,\log(2+\sqrt3\cos x)=\pi\log\left(\frac {2+\sqrt3}4\right)+2\pi\log\left(1+\sqrt{\frac {2-\sqrt3}{2+\sqrt3}}\right)=\pi\log\left(\frac 32\right)$$
Answer: You can use Chebyshev polynomials of the second kind. The identity
$$ U_n(x) = 2^n \prod_{k=1}^{n}\left(x-\cos\frac{\pi k}{n+1}\right) $$
leads to
$$\log U_n(A) = n\log 2+\sum_{k=1}^{n}\log\left(A-\cos\frac{\pi k}{n+1}\right) $$
then to
$$ \int_{0}^{\pi}\log(A-\cos\theta)\,d\theta = -\pi\log 2+\lim_{n\to +\infty}\frac{\pi \log U_n(A)}{n+1} $$
for any $A>1$.

How to find $\int_{0}^{\pi} \ln (b \cos x+c)$ without using Feynman’s integration technique?


Javascript - Print on thermal printer on client (No applet)

Question: First I want to know if is possible to such thing.
I'm developing a web application where the user has to print receipts on their own thermal printer.
I don't want to use Java applet or Flash on client as with the entry of html5 these technology are going to be not supported by browsers. So I want to do this using PHP on server side, JavaScript on client browser if is possible.
If only JavaScript isn't enough what kind of application should I develop to install on client so it will help the JavaScript to accomplish is duty. I need some information and references how I can reach this objective. (Please No Microsoft technologies for the client app... Java, Python, NodeJs are welcome)
Thanks in advance
Comment: Never worked with a thermal (receipt) printer, so... Is there a difference in data that needs to be sent to a thermal printer compared to a regular inkjet? Wouldn't just constructing the required output and calling `print()` in JavaScript be enough? *(Letting the client - browser, driver - handle the actual printing.)*
Comment: Browser insert headers and footer of the printed page, and to remove these should be done in the browser configuration. This is not the perfect way to this as PC clients are to many and of course if they change their browser they should re-configure browser.
Answer: I have found the way to do a printing with a JAVA client application. Each Client PC that want to do the printing process should install a JAVA application. This JAVA application should be a HttpServer that listen to a specified port and of course should allow CORS. So the flow is this:

The JavaScript in the browser do a HTTP request in http://127.0.0.1:[port_nr]/[context]
The Java application will receive the request with the data to print and then should do the printing process

The JAVA app of course should be executed on startup so it always will be listening to the request on that port.


Can I use regular expression for job name dependency in IBM LSF?

Question: I have a job which is supposed to be dependent on DONE state of multiple LSF Jobs having name prefix similar, let's say,
job 'A' depends on jobs with names 'Job-1', 'Job-2', 'Job-3',....,'Job-100'
Can I use following regex in defining job dependency for Job 'A'?
Job-*

Something like,
bsub -J 'A' -w "done(Job-*)"

Answer: I have found the answer in the documentation

Use double quotes (") around job names that begin with a number. In
  the job name, specify the wildcard character asterisk (*) at the end
  of a string, to indicate all jobs whose name begins with the string.
  For example, if you use jobA* as the job name, it specifies jobs named
  jobA, jobA1, jobA_test, jobA.log, etc.


How can I break up a controller in ASP.NET MVC while preserving the controller name?

Question: I'm working on a controller that is a part of a very flat hierarchy of pages, and it looks like one section of the site could have over a dozen action methods, not including their corresponding post actions.  Is there a good way to break this controller up while still preserving the section name?  I don't want that controller class getting out of control.
Answer: If your controller class is getting out of control on a dozen actions, you might want to rethink how much logic should be in there and how much can be refactored out into services.
Also, if your controller is getting up to much more than a dozen actions, you might want to consider whether it can be broken down into separate controllers.  Remember, you can change the routing rules and controller factory such that the URL remains the same but the controller is broken up.
If you're comfortable that you've done what you can and still want to break it into separate files - use a partial class.
Answer: If I understand correctly, you just want to split a class across multiple files so each file is easier to understand.
That would mean you want to use Partial Classes. They allow you to split the definition of a single class across multiple files.
Answer: Take a look at this. Worked for me just fine.


Zf2, Ussing expression in identifier in Where\In

Question: I try use expression in identifier in where->in.
For example SQL:
SELECT * FROM table WHERE DATE(created) IN ('2014-03-05','2013-06-07')

I tried use it:
$days = ['2014-03-05','2013-06-07'];
$where = new Where();
$where->addPredicate(new Predicate\In(new Expression('DATE(created)'), $days));
$select->where($where);

It's not work
Answer: Still couldn't find the solution via the Predicate\In but found something that could be used to make it run -
$days = array('2014-08-07', '2014-08-08');

$platform = $this->tableGateway->adapter->getPlatform();
$predicateIn = 'DATE('.$platform->quoteIdentifierChain(array('created')).')';
$predicateIn .= " in (";
$predicateIn .= $platform->quoteValueList($days);
$predicateIn .= ")";
$select->where(array($predicateIn));

Sql query formed is -
SELECT * FROM tablename WHERE DATE(created) in ('2014-08-07', '2014-08-08')
Will definitely let you know if I could find the required solution.


How would I go about solving for $x$ in $\frac{(x-a)\sqrt{x-a}+(x-b)\sqrt{x-b}}{\sqrt{x-a}+\sqrt{x-b}}=a-b$?

Question: The question
This is a homework question. Given the following, I am to solve for $x$ in terms of $a$ and $b$:
$$\frac{(x-a)\sqrt{x-a}+(x-b)\sqrt{x-b}}{\sqrt{x-a}+\sqrt{x-b}}=a-b;a>b.$$
My attempt
Although I see the pattern of multiple occurrences of $(x-a)$, $(x-b)$ I can't see any way to simplify the fraction further, so I go on to simplify the expression by multiplying by $\sqrt{x-a}+\sqrt{x-b}$:
$$\begin{align*}
(x-a)\sqrt{x-a}+(x-b)\sqrt{x-b}&=(a-b)(\sqrt{x-a}+\sqrt{x-b})\\
&=a\sqrt{x-a}+a\sqrt{x-b}-b\sqrt{x-a}-b\sqrt{x-b}
\end{align*}$$
Now I have the following:
$$(x-a)\sqrt{x-a}+(x-b)\sqrt{x-b}=a\sqrt{x-a}+a\sqrt{x-b}-b\sqrt{x-a}-b\sqrt{x-b}$$
Simplifying the RHS as I was out of ideas at that point:
$$x\sqrt{x-a}-a\sqrt{x-a}+x\sqrt{x-b}-b\sqrt{x-b}=a\sqrt{x-a}+a\sqrt{x-b}-b\sqrt{x-a}-b\sqrt{x-b}$$
I noticed that all one of the common factors $\sqrt{x-a},\sqrt{x-b}$ so I tried to isolate them and factor them out -- that is, all $\sqrt{x-b}$ terms on one side and $\sqrt{x-a}$ terms on the other.
$$\sqrt{x-b}(x-a)=\sqrt{x-a}(2a-b-x)$$
I tried to then square both sides, but that led to quite a mess.
$$(x-b)(x^2-2ax+a^2)=(x-a)(4a^2-4ab+2bx-4ax+b^2+x^2)$$
I'm afraid to even begin trying to simplifying this. I'm convinced I'm going about it in the wrong way.
The $a>b$ hint is interesting, but I have no clue what implication it may have here.
I think the $(x-a)\sqrt {x-a}$ patterns may mean something, perhaps I could do something with $a\sqrt a=\sqrt{a^3}$, but at this point it is probably a dead end.
I appreciate any help.
Comment: $(x-a)\sqrt{x-a}=(\sqrt{x-a})^3$ and $(x-b)\sqrt{x-b}=(\sqrt{x-})^3$.
Comment: Split the numerator, then rationalize and see that you get $((x-a)-(x-b))^2$ in the numerator
Answer: Use the formula: $a^3+b^3=(a+b)(a^2-ab+b^2)$.
We get:
$$\frac{(x-a)\sqrt{x-a}+(x-b)\sqrt{x-b}}{\sqrt{x-a}+\sqrt{x-b}}=\\
\frac{(\sqrt{x-a}+\sqrt{x-b})((x-a)-\sqrt{(x-a)(x-b)}+(x-b))}{\sqrt{x-a}+\sqrt{x-b}}=\\
2x-a-b-\sqrt{(x-a)(x-b)}=a-b \Rightarrow \\
(x-a)(x-b)=(2x-2a)^2 \Rightarrow \\
3x^2+(b-7a)x+4a^2-ab=0 \Rightarrow \\
x=\frac{(7a-b)\pm \sqrt{(b-7a)^2-12(4a^2-ab)}}{6}=\\
\frac{7a-b\pm (a-b)}{6}=\\
\frac{4a-b}{3}; a.$$
Answer: Hint: Define $$u=\sqrt{x-a}\\w=\sqrt{x-b}$$therefore $${w^3+u^3\over u+w}=w^2-u^2$$which yields to $$2u^3=uw^2-u^2w$$one answer is $u=0$ or $x=a$ which is valid. The others can be found by solving $$2u^2=w^2-uw$$or $$u^2+uw=a-b$$by substituting we obtain $$x-a+\sqrt{(x-a)(x-b)}=a-b$$
Answer: Hint: Write your equation in the form
$$\sqrt{x-a}(x+b-2a)=\sqrt{x-b}(a-x)$$ and square it. We get in the case of $$a>b$$ $$x=a$$ or $$x=\frac{1}{3}(4a-b)$$
Answer: Another way is as follows:

Set $\boxed{x = a + t(a-b)}$ for $t \geq 0$
$$\begin{eqnarray*}
\frac{(x-a)\sqrt{x-a}+(x-b)\sqrt{x-b}}{\sqrt{x-a}+\sqrt{x-b}} & = & a-b \\
& \Leftrightarrow & \\
\frac{t(a-b)\sqrt{t(a-b)}+(t+1)(a-b)\sqrt{(t+1)(a-b)}}{\sqrt{t(a-b)}+\sqrt{(t+1)(a-b)}} & = & a-b \\
& \Leftrightarrow & \\
\frac{t\sqrt{t}+(t+1)\sqrt{t+1}}{\sqrt{t}+\sqrt{t+1}} & = & 1 \\
& \Leftrightarrow & \\
(t(\sqrt{t+1} + \sqrt{t})+\sqrt{t+1})(\sqrt{t+1}-\sqrt{t}) & = & 1 \\
& \Leftrightarrow & \\
t+ t+1 - \sqrt{t(t+1)} & = & 1 \\
& \Leftrightarrow & \\
2t & = & \sqrt{t(t+1)} \\
& \Leftrightarrow & \\
t =\frac{1}{3} & \mbox{ or } & t= 0   \\
& \stackrel{x = a + t(a-b)}{\Leftrightarrow} & \\
\boxed{x = a + \frac{1}{3}(a-b)} &\mbox{ or } & \boxed{x= a}
 \end{eqnarray*}$$


How do you summon Fishron?

Question: How do you summon Fishron in Terraria Mobile?
I tried to find a Truffle Worm but I couldn't find one.
Comment: Then shouldn't your question be 'How do I find a truffle worm in terraria mobile?'
Answer: You do not. Duke Fishron is only available in the PC version of Terraria: http://terraria.gamepedia.com/Duke_Fishron as is the Truffle Worm used to summon him
Comment: This awnser is, WORNG. Duke Fishron can be summoned with a Truffle Worm on any platform.
Answer: Actually you're wrong. A truffle worm can be found in the glowing mushroom biome on Hardmode for mobile but you need a bug net to catch it. However it is very hard to catch.

How do you summon Fishron?


rollup-plugin-dynamic-import-variables Identifier 'React' has already been declared Vite + Storybook + React

Question: I'm experimenting with POC component library built with Vite + Storybook + React (JS, not TS).  The dev environment works great, but I want to be able to build to a dist folder.  That is when I encounter this error...
[rollup-plugin-dynamic-import-variables] Identifier 'React' has already been declared
...attributed to the one component in my POC, Button.jsx.  Which only imports React the one time here:
import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
...

If I delete import React from "react"; from the above file the application builds.  But that just seems wrong to me. I shouldn't have to remove a valid import, right?
There must be something I'm doing wrong on config side which I Frankensteined from various tutorials on the topic... so likely.
vite.config.js:
import path from "path";
import react from '@vitejs/plugin-react'
import { defineConfig } from "vite";

const isExternal = (id) => !id.startsWith(".") && !path.isAbsolute(id);

export default defineConfig(() => ({
    esbuild: {
        jsxInject: "import React from 'react'",
    },
    build: {
        lib: {
            entry: path.resolve(__dirname, "src/index.js"),
            name: "Bae Jay UI",
            fileName: (format) => `bae-jay-ui.${format}.js`,
            formats: ["es", "cjs"],
        },
        rollupOptions: {
            external: isExternal,
        },
        plugins: [
            react(),
        ],
    },
}));

package.json:
...
"scripts": {
    ...
    "build": "vite build",
    ...
  },
...

...
"devDependencies": {
    "@babel/core": "^7.16.12",
    "@storybook/addon-actions": "^6.5.0-alpha.23",
    "@storybook/addon-essentials": "^6.5.0-alpha.23",
    "@storybook/addon-links": "^6.5.0-alpha.23",
    "@storybook/react": "^6.5.0-alpha.23",
    "babel-loader": "^8.2.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "storybook-builder-vite": "^0.1.13",
    "vite": "^2.7.13"
  }

Answer: So... in the process of reviewing this post I noticed the vite.config.js was importing react:
    esbuild: {
        jsxInject: "import React from 'react'",
    },

likely making my component level import duplicative. It's defiantly code I poached from a tutorial without giving it much thought. Once these lines were removed my issue was resolved.
Maybe this will help someone else.
Cheers


C# Visual Studio Local Database

Question: I have a C# application that is using a local SQLite3 database.  I need to package the database with the application.  I am currently just interacting with the database from my desktop.  I am just connecting to the database from the desktop using the database path.
Where should I store this database, so the application can access this when I package, and distribute it?
Answer: You should put your database file in a read/write folder.
The exact position depends on the usage of your database.
If every user of the computer should be able to use the database then choose
C:\programdata\yourfolder

if every user of your program has its own database then a folder inside the user profile will be good
C:\users\username\documents\yourfolder

or
c:\user\username\appdata\local\yourfolder

where yourfolder will be a folder name of your choice referring to your application name
and username is the name of the current installing user of your application
These paths vary with the operating system where you deploy your application, so to be free from the operating system differences remember to use the Environment.GetFolderPath method and Environment.SpecialFolder enum
Of course you can always choose to install your database in a particular folder you create during setup like C:\database or, if you plan to share your database in a network location, choose an existing sharename or create a new one.
At the end of the setup work you need to update the connectionstring stored in your config file with the value where you have stored the database file.
Comment: Is this the method I should use if I am not creating the database tables with code?  I have an already semi-populated database
Comment: Yes, prepare your database file for distribution and use a setup tool to choose the location where to place the file. The same setup tool should allow you to update the config file of your application
Comment: Just for clarification, what do you mean by prepare the database file, and use a setup tool?
Comment: A setup tool (InstallShield, the same setup project of Visual Studio or many others free/paid tools) allows you to prepare a single executable (or MSI) that contains your app, its data files (database, graphics or what else) and the actions to be executed on the customer machine to 'setup' your application for first use (copy files, update configuration files, create folders, set permissions etc...)
Comment: I stored the database in Program Files (x86)\Common Files but I do not have write access apparently, where do I have write/read access to for a database?
Comment: That's one of the locations to avoid in a Window7 or Vista computer. You should choose one of the examples shown above.
Comment: programdata is a read only as well, and the last two you mention, how do you access them to save in the installer, I only see special folders?  Also, using the Enviroment. how to get the path?
Comment: It depends from the tool you use to install your application. It should have these predefined folders to choose from. What kind of installation tool are you using?
Comment: Visual Studio .NET installer, if you recommend another, let me know and i'll give it a shot
Comment: thanks a lot I used the AppData folder, the installer was just a pain!

C# Visual Studio Local Database


iOS 7 Locked Bug via Ubuntu 13.10

Question: I wanted to bring up an issue with the latest Ubuntu release that I hope can be solved. Although I will agree with the community that iOS 7 is not the most open platform release, it still is my desire to be able to grab Photos, Music, and Files off my Phone similar to what I would do to any other device.
Every time I connect my device to Ubuntu, I receive the following notification:
The device "Justin's iPhone" is locked. Enter the passcode on the device and click "Try again".

On my iPhone, I select the following
permissions.
Unfortunately, this is where problems start to arise. It appears that Ubuntu either does not recognize the permissions from my iPhone or the iPhone is not allowing itself to truly be unlocked. As we can see the permissions are denied.
Browsing askubuntu, I encountered the following suggestion.
After running the code, I receive the following error:
justin@justin-CT15:~$ idevicepair unpair && idevicepair pairERROR: Device d1fea2c56e51199f901eb34020a1581ea31a2a50 is not paired with this host

If I call the command again, i receive another error:
justin@justin-CT15:~$ idevicepair pair
ERROR: Could not pair with the device because a passcode is set. Please enter the passcode on the device and retry.

Ultimately, I am stuck to experiment with solutions that end up not working. I am troubled by the lack of information and support for the iOS 7 platform on Ubuntu's latest release. If anyone has a workable solution or experiment for a workaround, I am happy to try
Thanks for reading and have a wonderful day!
Comment: Just wanted to mention that the bug pointed out by Dong Hao is a duplicate of https://bugs.launchpad.net/ubuntu/+source/libimobiledevice/+bug/1207812 , which is now fixed.
A clean install or update to Ubuntu 14.04 should let you use your phone flawlessly.
Comment: Just had the same issue with you. There is a bug report [here](https://bugs.launchpad.net/ubuntu/+source/libimobiledevice/+bug/1215098), but it seems no one actually fixed it. Anyway I think the bug is about ios7, rather than ubuntu.
Comment: It appears that we need to wait for Development/Unstable Release: 1.1.6 in order to receive a proper update for iOS7 devices. Until then, the best option is to wait -unless of course anyone wants to take a stab at their repository.
Comment: There is a workaround, but you have to jailbreak your device. http://ubuntuforums.org/showthread.php?t=2199251
Comment: I would note that the solution must not include jail breaking. This goes against my original question of connecting iOS7 with ubuntu --within a pure state.
Answer: This issue is an attempt by Apple to stop the use of fake charging cables. You can solve the trust-loop error with IOS7 mobile devices by installing the latest release of libimobiledevice.
For 12.04:
sudo apt-add-repository ppa:ingo/ios7support
sudo apt-get update
sudo apt-get upgrade

If you get "lock down error", try using the following commands:
sudo mkdir /var/lib/lockdown
sudo chmod 777 /var/lib/lockdown

For 13.10 you can download the .deb package from the launchpad site here.
For Ipad users that are seeing the 'Not Charging' message on their device when plugged in via usb:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install ipad-charge

Reboot, and enjoy.
Comment: You sir are a winner. It worked! ;) Congratulations and enjoy the recognition.
Answer: I've gotten it to work by running those commands with sudo at the beginning.  Try plugging your iPhone in first and unlock it. When it asks to trust or not, don't tap anything and type:
sudo idevicepair pair

If that doesn't work at first run:
sudo idevicepair unpair
sudo idevicepair pair

If that fails, tap trust or don't trust (try with both) and try the above again.  If that fails, then you might have to wait for libimobiledevice to fully update its iOS 7 support.
Comment: Unfortunately, this does not work. I've tried all permutations that you have offered, and none work. However, I would like to thank you for the suggestion.
Comment: I'm sorry to hear that.  This is what I did with my iPhone 4 on iOS 7.0.2 and it worked. When my laptop was on Ubuntu 12.04, I sometimes had to reboot my iPhone while it was still plugged in, haven't had to do that though on the Ubuntu 13 series, worth a try though
Answer: As a work-around to this issue, I found that doing the following would allow me to browse the phone freely with nautilus:

Power cycle phone but do not unlock it
Logout of Ubuntu desktop
Connect the phone to the PC
Log back in to Ubuntu desktop

At this point it seems I can freely browse the phone in nautilus.
Answer: Same problem, different solution?
With 12.04 running I plug in the locked iPhone 5s (ios7),
answer "trust" or "don't trust" (choice doesn't seem to matter),
then ignore subsequent trust questions.
It soon stops asking.
The iPhone charges, and I can access/download my photos
from "home folder".
Not sure what other functions can be done from that point.
Not sure this even qualifies as a solution as I don't really do anything technical!
Just seems to work if I let it beep a couple of times.
I came here searching for the answer, before I found this post it quit asking the trust question and all was good. ASKUBUNTU magic in action!
PS: while iPhone is accessible I unlocked it, the trust question came up again, I answered "don't trust", no changes, still have access, still charging.

iOS 7 Locked Bug via Ubuntu 13.10


Integration with Google (OAuth)

Question: I'm planning on building a G suite integration with my existing SaaS site.
I want Gsuite admins to allow access for their organisation.  So I only want "domain install" possible.
After this has been done users can be imported from Google into our application. Users should be able to use SSO to login but I don't want each user having to pass the consent screen.
I also want the app to have readonly access to the calendar of the user.
What is confusing for me: do I need to create a regular web app integration or a Service account integration?  I don't really need offline access but I want to avoid all users having to grant access individually.
Here it says: The user sees the OAuth Consent screen only once; if you're using a service account to allow a domain admin accept terms on behalf of the domain users, then the end users must never see the OAuth consent screen.
So does that mean only service accounts allow this?
Answer: Yes, using a service account you can install and authorize one app for all your domain user impersonating the admin account. In such a way, your users won't have to authorize the app individually.
You will have to enable domain wide delegation in order to impersonate the admin account when using a service account.
Reference
Service Account

Integration with Google (OAuth)


override class variable in python?

Question: Below, base_id and _id is a class variable and shared among all child classes.
Is there a way to separate them into each class?
from itertools import count

class Parent(object):
    base_id = 0
    _id = count(0)

    def __init__(self):
        self.id = self.base_id + self._id.next()

class Child1(Parent):
    base_id = 100
    def __init__(self):
        Parent.__init__(self)
        print 'Child1:', self.id

class Child2(Parent):
    base_id = 200
    def __init__(self):
        Parent.__init__(self)
        print 'Child2:', self.id

c1 = Child1()                   # 100
c2 = Child2()                   # 201 <- want this to be 200
c1 = Child1()                   # 102 <- want this to be 101
c2 = Child2()                   # 203 <- want this to be 201

Comment: That doesn't actually matter here; even if eugene changed IDs to 2-tuples (e.g. (1,0), (1,1), (1,2)... for `Child1`) the problem of creating independent counters remains.
Comment: Is there any particular reason why you want the hundreds digit to represent the class? What about if you get more than 100 instances? Then you'll have overlap. Where will you see the ID, and could there be a better way to distinguish between classes than using the ID? (Perhaps you could display some extra information, for instance.)
Answer: If you really need to use the ID this way, use parameters:
class Parent(object):
    def __init__(self, id):
        self.id = id

class Child1(Parent):
    _id_counter = count(0)
    def __init__(self):
        Parent.__init__(self, 100 + self._id_counter.next())
        print 'Child1:', self.id

etc.
This assumes you won't be constructing instances of Parent directly, but that looks reasonable with your example code.
Answer: As you said in the question, _id is shared by parent and all children classes. Define _id for every children classes.
from itertools import count

class Parent(object):
    base_id = 0
    _id = count(0)

    def __init__(self):
        self.id = self.base_id + self._id.next()

class Child1(Parent):
    base_id = 100
    _id = count(0) # <-------
    def __init__(self):
        Parent.__init__(self)
        print 'Child1:', self.id

class Child2(Parent):
    base_id = 200
    _id = count(0) # <-------
    def __init__(self):
        Parent.__init__(self)
        print 'Child2:', self.id

c1 = Child1()                   # 100
c2 = Child2()                   # 200
c1 = Child1()                   # 101
c2 = Child2()                   # 201

UPDATE
Using metaclass:
class IdGenerator(type):
    def __new__(mcs, name, bases, attrs):
        attrs['_id'] = count(0)
        return type.__new__(mcs, name, bases, attrs)

class Parent(object):
    __metaclass__ = IdGenerator
    base_id = 0
    def __init__(self):
        self.id = self.base_id + next(self._id)

Answer: If you don't want to violate the DRY principle like falsetru suggests, you'll need to use metaclasses. I was thinking of writing something up, but there's already a good long description of metaclasses on SO, so check it out.
Metaclasses, in short, let you control subclass creation.
Basically, what you need to do is, upon the creation of a subclass of Parent, add the _id member to the newly-created subclass.

override class variable in python?


give access with spring security in xml file for one user

Question: I was using waffle and spring security 3.2 to set access to jsf2 pages.
I used this example
Everything works fine, but I am curious, if posible to set access to page via xml file for one user???
Something like that:
 <sec:intercept-url pattern="/**" access="PRINCIPAL='tom'" />

I couldn't find answer in internet
Thanks
Answer: Yes it is possible if you use SpEL expressions:
<sec:http use-expressions="true">
    ....
    <sec:intercept-url pattern="/**" access="principal.name=='tom'" />
    ....
</sec:http>

Comment: You are welcome. @Darka, I've seen your edit for my answer that was rejected. You can post `authentication.name` way as a separate answer and accept it.
Comment: thanks again, but I wlll leave your answer. I think it depends from configuration.
Answer: Using @Maksym answer I found my solution (I think in some cases both can be right) :
<sec:http use-expressions="true">
    ....
    <sec:intercept-url pattern="/**" access="authentication.name=='tom'" />
    ....
</sec:http>


How to install Mendeley on Ubuntu 22.04?

Question: I just installed Ubuntu 22.04 and I have been trying to install Mendeley through its .deb installer and the .tar.bz2, but in both cases it throws me a problem with the dependencies:
/usr/bin/env: "python": No such file or directory

I really liked the experience with the new version of Ubuntu and I would not like to go back, but Mendeley is a program that I use a lot due to my work.
I would appreciate any help!
Comment: @Natan The solutions below work but do not allow referencing in libreoffice. Eventually I moved to zotero. I use mendeley in the browser to capture references and periodically sync it to zotero. I hope this helps.
Comment: Did you resolve this issue?
Comment: Same question as @Just_Alex
Comment: @Natan, I'm not sure I can post it here, but on github you can find a script to do what the answers below suggest (i.e., repackage mendeley) completely effortless :)
Comment: This question is  no longer relevant, since Mendeley Desktop is no longer available for download and installation.
Comment: @climatestudent, I just downloaded and installed Mendeley Desktop v1.19.8 for Linux from https://www.mendeley.com/autoupdates/installers/1.19.8
Comment: @HalHollis, thanks for noting that and providing the link; I should probably change the above then to say that Mendeley Desktop is no longer officially supported or updated by Mendeley.
Answer: When installing Mendeley on Ubuntu 22.04 I was met with the following
error:
dpkg: dependency problems prevent configuration of mendeleydesktop:
 mendeleydesktop depends on python; however:
  Package python is not installed.

The following solution worked for me:

Check that the command python executes Python properly. If you don't have the python command, then please install python-is-python3.

NOTE: If the version of Python is 2.xx then you can skip steps 2 and 4.

Unpack the .deb file, remove "python" from its dependencies, and then repack it. I followed the instructions in @Janus Troelsen's answer in How do I get apt-get to ignore some dependencies?. So modify the third line in the control file from:
Depends: libc6, python, gconf2, desktop-file-utils

to:
Depends: libc6, gconf2, desktop-file-utils

And then make a softlink /usr/bin/python to indicate python2:
cd /usr/bin
sudo mv python python_old
sudo ln -s python2 python

Install Mendeley with the repacked .deb file without errors (I hope).

Restore /usr/bin/python as before:
sudo rm python
sudo mv python_old python

I hope my answer is helpful for others in the same situation.
Comment: This worked perfectly for me. Thanks!
Comment: Can someone make this deb file available?
Comment: It works, but does not close. Prompting `ERROR:service_manager_context.cc(171)`
Comment: The libre-writer citation plugin still causes freezing.
Comment: @Just_Alex I felt the same error too, however, I don't know how to resolve this issue yet. It seems like that the error is related to Qt but no ideas more than this. I'll share information if I find a solution.
Comment: Hi @philip , not sure. Running in terminal suggests some possible culprits.1. `distutils package is deprecated` 2. `ERROR:service_manager_context.cc(171)` and 3 `File "/usr/lib/python3.10/subprocess.py", line 1896`
Comment: Thanks, worked fine for me after removing the broken install with `apt --fix-broken install` , installing Python 2 (`apt install python2`) and symlinking it to `python` (`ln -s /usr/bin/python2.7 /home/$USER/.local/bin/python`)
Comment: can you explain why you needed to backup python?
Comment: Hi, thanks for the solution. I can install the new package without error. But can't open mendeleydesktop. When I click on the icon, nothing happens.
Answer: Maybe this is not such a good idea; I run Mendeley Desktop and it keeps using 12.5% of my CPU power (I have eight processors). I don't know why, maybe it's mining Bitcoin.

An easier solution is to install with the generic Linux installer, see Holger_Gehrke's answer.

Download the generic linux installer and extract in your $HOME folder.
Run python3 mendeleydesktop-1.19.8-linux-x86_64/bin/mendeleydesktop.
You can isnstall with bash mendeleydesktop-1.19.8-linux-x86_64/bin/install-mendeley-link-handler.sh ~/mendeleydesktop-1.19.8-linux-x86_64/
To start Mendeley Desktop I hit win-D and then start typing mendeley.
Comment: thanks it is working
Answer: The command python is not installed by default on Ubuntu 22.04. Install python-is-python3 to have a symlink python that points to python3, and then it is hoped that application works well with the current python version, because Python 2 is not anymore supported on Ubuntu.
Answer: Installing python-is-python3 worked perfectly. But before creating the symlink, you need to uninstall Mendeley. If you keep it installed (even though it is not working), it will mess up the python-is-python3 installation.
Steps:

Uninstall medeleydesktop:
sudo apt-get remove mendeleydesktop

Install python-is-python3:
sudo apt-get install python-is-python3 -y

Then install Mendeley again:
sudo dpkg -i <package_path>

where <package_path> is the path to Mendeley .deb file.
Comment: This does not resolve the issue. Tried both ppa and .deb file.
Comment: Unfortunately, I'm still getting the error.
Answer: What worked for me was installing the desktop version trough a flatpak
flatpak install flathub com.elsevier.MendeleyDesktop

flatpak run com.elsevier.MendeleyDesktop

Downloading and installing it directly from flathub site works fine. I was not able to solve the "python" missing package (and dependences) problem, but this is an acceptable workaround. Since there won´t be a desktop version in the future I dont know if this will be working so far.
Comment: it seems like mendeley has been removed from flatpak
Comment: Unfortunately by running this via flatpak I get a very high CPU usage
Answer: I had this same problem and followed the instructions just to discuss that Mendeley Desktop doesn't link to academic accounts. I tried Mendeley Reference Manager and the installation worked straight away and as I want. I'm guessing the desktop version is old now.
Answer: I came across this question after trying the new web-based Mendeley reference manager and becoming frustrated with its lack of features compared to the older desktop version.
I ended relying on Docker to install Mendeley Desktop 1.19.8 on my machine, using the image from this github repository: Mendeley-Docker.
In a nutshell:
# Make sure docker is installed
docker run hello-world

# Clone repository
git clone https://github.com/javadr/mendeley-docker
cd mendeley-docker

# Build image
./build.sh

# Run image
./run.sh

It worked like a charm for me!
Answer: It seems like Python is only required for the install. And it requires Python 2, because there are some statements like print "bla" in the install code.
So you need to do two simple steps:

make Python 2 your default python, for instance:

sudo apt-get install python2
sudo ln -sf /usr/bin/python2 /usr/bin/python
python --version
> Python 2.7.18

Install mendeley, but without python dependency (I don't know why that is necessary, but it was for me):

sudo dpkg --ignore-depends=python -i Downloads/mendeleydesktop_1.19.8-stable_amd64.deb

That's it. You probably want to remove the symlink to Python2 again.
Answer: @Just_Alex your solution to repackage after removing python dependency worked for me. Thanks! But it did later complain that it could not find gconf2.
I was able to fix that by first running:
 sudo apt --fix-broken install

And then installing the repackaged file.


Why is my SD card not formatting?

Question: I literally tried about a millionth time that to format my card. When I got to Menu > USB Stick Format, it says that the format is confirmed, but when the local file browser is opened all files remain the same. What should I do?
EDIT: Question has been resolved.
Comment: You've provided no OS & release details; but are you sure you're not just viewing cached files in RAM (because you failed to flush/unmount the SD card first)?    The SD card maybe *toast* (no longer writable) and so changes aren't writing to it, or at least the section being written to... they are cheap/consumable media without diagnostics ..
Comment: Are you sure you're formatting the correct USB stick?
Comment: You must `umount` the SD first. Read `man umount`.
Comment: [This link](https://askubuntu.com/questions/144852/cant-format-my-usb-drive-i-have-already-tried-with-mkdosfs-and-gparted/933035#933035) can help you analyze the problem, and if you are lucky, solve it.
Answer: Install gparted (it is in the repository) . Put your card in the machine and start gparted.  It will ask your password. THen you can see, unmount,format etc.
Answer: You can use "Disks" for it , select your sd card and you can find gear icon at top of the window , select format device/card , it takes some time and after that select the sdcard and again select the gear icon and select create partition , here you go...

Why is my SD card not formatting?


.htaccess - url ending char (/)

Question: please help me with modifications .htaccess. How add ending character [/] in url.
Now .htaccess doing
www.mysite.cz/about.php > www.mysite.cz/about
www.mysite.cz/about/ > www.mysite.cz/about
i need this
www.mysite.cz/about.php > www.mysite.cz/about/
www.mysite.cz/about > www.mysite.cz/about/
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mysite\.cz$
RewriteRule (.*) http://www.mysite.cz/$1 [R=301,L]
RewriteRule ^index.php$ http://mysite.cz/$1 [R=301,L]

RewriteCond %{THE_REQUEST} \ /+(.+)(?:/|\.php)(?:\?|\ )
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /%1 [L,R=301]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)$ $1.php    [L]

Answer: Try this :
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mysite\.cz$
RewriteRule (.*) http://www.mysite.cz/$1 [R=301,L]
RewriteRule ^(index.php)$ http://mysite.cz/$1 [NC,R=301,L]

RewriteCond %{THE_REQUEST} \ /+(.+)(?:/|\.php)(?:\?|\ )
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /%1/ [NC,L,R=301]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)/?$ $1.php    [NC,L]

This adds a trailing slash at  the end of the path :
 www.mydomain.cz/about.php

would redirect to
  www.mydomain.cz/about/

Comment: This solution does not work - browser reports an error [ERR_TOO_MANY_REDIRECTS]

.htaccess - url ending char (/)


Describe the graph of $f^{-1}$ when $f$ is decreasing and always negative - dispute with solution from Spivak.

Question: The question comes from Calculus by Spivak - Ch 12 - 2) iv). It asks us to describe the graph of $f^{-1}$ when $f$ is decreasing and always negative. I interpret the inverse function as decreasing and not defining it for $x \geq 0$. But using the tools I have at my disposal, mainly the diagonal line test and drawings, I would get a function  that is increasing but still defined only on for $x < 0$. This is also what the solution manual says: here is a screenshot of its solution.

I really don't agree with the drawing of the inverse function. I agree with how the original function, $f$, is drawn. Based on the tools this is correct, but it feels wrong......What may I be missing to reconcile this somewhat simple issue?
Comment: You are right.  The inverse of a decreasing function is another decreasing function.  In fact, the text says $f^{-1}$ is decreasing.  But the picture shows $f^{-1}$ increasing.
Answer: You are right, the graph of $f^{-1}$ is incorrect: I think that the graph of $f$ was rotated 90 degrees clockwise instead of being flipped with respect to the line $y=x$. It should diverge to $-\infty$ as $x\to \alpha^-=\lim_{x\to-\infty}f(x)$, and diverge to $\infty$ as $x\to\beta=\lim_{x\to\infty}f(x)$. Here, from the graph of $f$, it seems that $\alpha=0$ and $\beta=-\infty$, but this is not part of the hypothesis, strictly speaking.
Comment: just adding to this answer: here's an example of what it [could look like](https://www.desmos.com/calculator/s4wia5ocpe) (I put $f(x)=-e^{x}$, $x\in \Bbb{R}$ and $f^{-1}(y) = \ln(-y)$, $y>0$)
Comment: Good. At least I know I'm not beating myself up for nothing, but that means I applied the diagonal line procedure wrong because I got the incorrect reflection  (i got the one above instead of the correct one).....time to refine my application of the diagonal criterion


Dismissing Alert View of controller or app whose object refference is not available..!

Question: How to dismiss the alert view (and execute its cancellation handler) when my
application moves back to the foreground or my refference object is not
available?
If any one knows please reply.
Thanks in advance..!
Answer: I don't think there is a way. You need to keep a reference and subscribe to the UIApplicationDidEnterBackgroundNotification notifications. When you get that message you can call the dismissWithClickedButtonIndex:animated: which, as the documentation says, "in iPhone OS 4.0, you may want to call this method whenever your application moves to the background."


Downloading Large file to certain directory from within app using DownloadManager

Question: I have an application that needs to be able to download a ~3GB file to a user specified location, I currently have the below code, which seems to work.
i.e the download takes place with it showing up in the download manager etc.
However once the download is complete it fails to appear in the correct location, and the space has not been taken up at all.
This is my current code:
 public void file_download(String uRl) {
install_txt = AppPreferences.getPrefs().getString(
                "path",
                Environment.getExternalStorageDirectory().getPath()
                + "/test.img");

            DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);

            Uri downloadUri = Uri.parse(uRl);
            DownloadManager.Request request = new DownloadManager.Request(
                    downloadUri);

            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
                    .setAllowedOverRoaming(false).setTitle("test")
                    .setDescription("Downloading test")
                    .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS , install_txt);

            mgr.enqueue(request);
        }

So my question really is why does the above not work well? or is it just that the download manager struggles to download such large files?
If that is the case is there a better method I could use to download reliably such a large file
After the download finishes the below is shown in the logcat
07-19 13:19:28.112: W/DownloadManager(19199): Exception for id 8952: Invalid int: "3891000000"
07-19 13:19:28.112: W/DownloadManager(19199): java.lang.NumberFormatException: Invalid int: "3891000000"
07-19 13:19:28.112: W/DownloadManager(19199):   at java.lang.Integer.invalidInt(Integer.java:138)
07-19 13:19:28.112: W/DownloadManager(19199):   at java.lang.Integer.parse(Integer.java:378)
07-19 13:19:28.112: W/DownloadManager(19199):   at java.lang.Integer.parseInt(Integer.java:366)
07-19 13:19:28.112: W/DownloadManager(19199):   at java.lang.Integer.parseInt(Integer.java:332)
07-19 13:19:28.112: W/DownloadManager(19199):   at com.android.providers.downloads.DownloadThread.handleEndOfStream(DownloadThread.java:516)
07-19 13:19:28.112: W/DownloadManager(19199):   at com.android.providers.downloads.DownloadThread.transferData(DownloadThread.java:314)
07-19 13:19:28.112: W/DownloadManager(19199):   at com.android.providers.downloads.DownloadThread.executeDownload(DownloadThread.java:278)
07-19 13:19:28.112: W/DownloadManager(19199):   at com.android.providers.downloads.DownloadThread.runInternal(DownloadThread.java:193)
07-19 13:19:28.112: W/DownloadManager(19199):   at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:142)

Comment: Do smaller files work OK? Are you reasonably sure it's just a problem with large files?
Comment: @KenWolf yes smaller files seem to work ok
Comment: Thanks - Are you sure there's enough space on the device?
Comment: @KenWolf yes I check for free space before running the above function, and on my test device I have 10GB free to be sure
Comment: Your `setDestinationInExternalPublicDir()` call is odd. Your code implies that the default value of `install_txt` will be something like `/mnt/sdcard/test.img`, which is a rather strange set of subdirectories to put in the user's `Downloads` directory. Beyond that, have you tried putting a 3GB file in your desired location by any other means, such as DDMS or **`adb push`**?
Comment: @CommonsWare yes the above code was copied wrong, I was trying to get it to download to /mnt/sdcard/test.img but couldn't get this work either so was downloading it to the environments Download folder to test. yes I can move the file on to the device via other means
Comment: Any interesting messages in LogCat around the time the download is flagged as complete?
Comment: @CommonsWare shall have to try the download again, but I did not see anything last time
Comment: @CommonsWare seems there was some issue with it see changes to question
Comment: you can always use a library like this one here: https://blog.mindorks.com/how-to-download-a-file-in-android-and-show-the-progress-very-easily
Answer: That error message would suggest that DownloadManager, at present, is limited to files that are 2147483647 (Integer.MAX_VALUE) bytes or smaller.
There has been a bug report filed for this already, with no response from Google at present.
In the meantime, I'd see if you could arrange to split that ~3GB file into two smaller files. If not, you may need to do the downloading yourself.
Comment: Thank you, shall have to look at splitting the files