Is every member of A216594 the order of a capable group?

Question: A capable group is a group that is isomorphic to $G/Z(G)$ for some group $G$.
So, is every member of the OEIS sequence A216594 (consisting of those $n$ for which there is a non-nilpotent group, but no centerless group, of order $n$) the order of a capable group?
Every even number $2n$ (for $n>1$) is the order of a capable group. Indeed, the dihedral group of order $2n$ is isomorphic to the central quotient of the dihedral group of order $4n$ as pointed out at Non-cyclic numbers that are not the order of any capable group.
So, only odd numbers need to be considered. The first odd member of A216594 is $63$. Since $63$ is not a powerful number (it is divisible by the prime $7$ but not by $7^2=49$), there is no capable abelian group of order $63$ by the known characterization of finite capable abelian groups (isomorphic to a direct sum of cyclic groups, with the order of each one dividing the order of the next one and the last two being isomorphic, or equivalently, having the same order).
So, to try to find a capable group of order $63$, one must consider nonabelian groups. If $G$ is the nonabelian group of order $21$ (given as the semidirect product $\mathbb{Z}_7 \rtimes \mathbb{Z}_3$ with $(a, b)(c, d)=(a+2^bc, b+d)$), then one could consider the direct product $G \times \mathbb{Z}_3$. The other nonabelian group of order $63$ is given by the semidirect product $\mathbb{Z}_7 \rtimes \mathbb{Z}_9$ (again with $(a, b)(c, d)=(a+2^bc, b+d)$). If neither of those two nonabelian groups of order $63$ turns out to be capable, then the answer to the question must be "no".
Otherwise, one could consider the next odd member of A216594, namely $105$, which is also the first squarefree member. The only nonabelian group of order $105$ is given by the direct product of the nonabelian group of order $21$ with the cyclic group of order $5$. If that group of order $105$ turns out to not be capable, then the answer to the question must again be "no".
If neither $63$ nor $105$ succeeds in finding a member of A216594 that is not the order of any capable group, then one could consider $117$ (the next odd member) or $165$ (the next odd squarefree member). But $117$ and $165$ have the same "nilpotent number relationships" (of the form $p^k \equiv 1 \pmod q$) among their prime factors and the same prime signature as $63$ and $105$ respectively, so I do not think that $117$ or $165$ would succeed if $63$ and $105$ did not succeed. So, the next order to consider would be $189$.
Comment: Any nilpotent group (not just abelian groups) of order a non-powerful number cannot by capable, as a finite nilpotent group is capable if and only if its $p$-parts are.
Answer: The group of order $63$ with elementary abelian Sylow $3$-subgroup is capable - it is isomorphic to $G/Z(G)$ with $|Z(G)|=3$.
However the nonabelian group of of order $105$ is not capable, because it has the form $H \times C_p$ where $|H|$ is coprime to the prime $p$.
Suppose such a group was isomorphic to $G/Z(G)$.  Then the inverse image of the $C_p$ factor of $G/Z(G)$ would be abelian and normal in $G$, and $G$ would have a normal Sylow $p$-subgroup $P$. A complement of $P$ is $G$ would centralize both $P \cap Z(G)$ and $P/P \cap Z(G)$ and hence centralize $P$, so $P$ would be a direct factor of $G$ and hence in $Z(G)$, contradicting  the structure of $G/Z(G)$.
Answer: To generalize Derek Holt's observation, I claim that any group of the form $G=H\times C_q$ with $q\gt 1$ and $\gcd(|H|,q)=1$ cannot be capable. I believe this follows from a theorem of Beyl, Felgner and Schmidt ("On groups occurring as center factor groups", J. Algebra, 61 (1979)) which gives sufficient conditions under which the capability of a direct product of finitely many groups would imply the capability of the direct factors, but below I give a direct argument. Note that $q$ need not be squarefree, so this is a more general result.
Indeed, let $K$ be a group and $N\leq Z(K)$ be a central subgroup such that $K/N\cong G= H\times C_q$. It is known that if a finite group is capable then it is the central quotient of a finite group, so we may take $K$ to be finite. We will show that $N\neq Z(K)$.
Let $M$ be the preimage of $C_q$ in $K$; then $M/N$ is cyclic, with $N$ central, so $M$ is abelian. Since the image is normal in $G$, then $M$ is normal in $K$. Moreover, if $y\in K$ has order prime to $|H|$ (in particular, if it has order that divides a power of $q$), then its image lies in the $C_q$ factor, so $y\in M$.
Let $x$ be an element that maps to a generator of the $C_q$ factor of $G$. We may assume the order of $x$ divides a power of $q$: if the order is $rs$ with $\gcd(r,s)=\gcd(r,q)=1$, then $x^r$ has order $s$ (which divides a power of $q$); it maps to the $r$th power of the original generator, and since $\gcd(r,q)=1$, this element also generates.
I claim that $x$ commutes with every element whose order is relatively prime to $q$. Indeed, if $h$ has order $r$, $\gcd(r,p)=1$, then $1=[hN,xN]=[h,x]N$, so $[h,x]\in N\leq Z(K)$. In particular, $[h,x]\in Z(\langle h,x\rangle)$, so $\langle h,x\rangle$ is nilpotent of class at most $2$. Since $h$ and $x$ have relatively prime order, they commute.
We also know that $x$ commutes with every element of order dividing a power of $q$, since they all lie in $M$ and $M$ is abelian.
Now let $k\in K$ be arbitrary, and let its order be $r$. Write $r=st$ with $\gcd(s,t)=\gcd(s,q)=1$. Let $u,v\in\mathbb{Z}$ be such that $1=us+vt$. Then
$$ k=k^{us+vt} = (k^s)^{u}(k^{t})^v.$$
Note that $k^s$ has order $t$, so $k^{su}$ has order that divides a power of $q$. And $k^{t}$ has order $s$, so $k^{vt}$ has order prime to $q$. Thus $k$ is a product of elements that centralize $x$, and hence $k$ itself centralizes $x$.
Thus, $x\in Z(K)$. However, $xN$ is nontrivial, so $N\neq Z(K)$, which is what we needed to prove.
Note that if $n$ is not a nilpotent number, then neither is any positive multiple of $n$. This gives a way of constructing non-nilpotent numbers that are not the order of any capable group: take any non-nilpotent number $m$, and find a prime $p$ such that:

$\gcd(m,p)=1$.
If $d$ is a positive integer such that $d\mid m$ and $d\equiv 1\pmod{p}$, then $d=1$.
$\gcd(m,p-1)=1$.

Let $n=mp$. If $G$ is a group of order $n$, then it has the form $H\times C_p$. Indeed, conditions 1 and 2 ensure the Sylow $p$-subgroup of $G$ is normal of order $p$, and condition 3 ensures the action of any element of $G$ on this subgroup by conjugation is trivial. Since the Sylow $p$-subgroup of $G$ is central, then by Burnside's Normal $p$-complement Theorem, the subgroup has a normal $p$-complement $H$ in $G$. And since the Sylow $p$-subgroup is normal, we conclude that $G=H\times C_p$ (Burnside's theorem says that if a Sylow $p$-subgroup of $G$ lies in the center of its normalizer, then it has a $p$-complement).
We can find non nilpotent numbers of this type by taking any odd non-nilpotent number $m$, and picking a prime of the form $p=km+2$. If $p\gt m$ we get properties 1 and 2. To see $3$, let $q$ be a prime dividing $m$. Then $p-1=km+1\equiv 1\pmod q$, so $q\nmid p-1$. So $\gcd(m,q-1) =1$. Then $n=mp$ is not a nilpotent number.
And of course there are other orders in which we are guaranteed that a Sylow subgroup is of prime order and central in any group of that order, even if it is not always for the same prime, and even if it is not an odd nilpotent number. For $n=105$, if there is a normal Sylow $5$-subgroup then it is central; if it is not normal, then there are $21$ of them, then that accounts for $80$ nontrivial elements, which means the Sylow $7$-subgroup is normal and central (as if there is more than one, there are $15$ of them...)
Comment: I don't understand the first sentence - doesn't Derek Holt's answer prove that $H \times  C_p$ for $\gcd(|H|,p) = 1$ is not capable?
Comment: @testaccount I meant to change that to any cyclic factor of order prime to $|H|$,not just prime order.
Comment: @testaccount fixed.
Comment: I see, thanks. (With the same notation, and especially $p$ suggests a prime..)
Comment: @testaccount I originally thought, "any cyclic factor prime to $|H|$"; then I chickened out but didn't correct it properly, then I realized, yes any cyclic factor and didn't correct it properly and used bad notation. I think it's fixed now.


Passing object with prepareForSegue Swift

Question: I am trying to pass an object to another scene with prepareForSegue()
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        var nextScene =  segue.destinationViewController as! VehicleDetailsTableViewController

        // Pass the selected object to the new view controller.
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            let selectedVehicle = vehicles[indexPath.row]
            nextScene.currentVehicle = selectedVehicle
        }
    }

And I have currentVehicle object to catch these object. But, when I try to run, it brokes and get error about downcasting.
Error EDIT

Could not cast value of type 'XXX.DisplayViewController'
  (0x1082dcd80) to 'XXX.VehicleDetailsTableViewController'
  (0x1082dc9a0). (lldb)
Comment: You really should be checking that segue identifier to make sure you are correctly casting the destinationViewController. What exactly is the error message you are getting?
Comment: check my question, updated.
Comment: It looks like `segue.destinationViewController` is giving you a `DisplayViewController`  Check connections in storyboard.
Answer: You have to give the segue an identifier in the storyboard.(say mySegue)
Using Xcode 10 swift 4.x(Also works with Xcode 9 & 8 , swift 3.x)
override func prepare(for segue: UIStoryboardSegue, sender: Any?){}

Is called for all segues being called from your current UIViewController. So the identifier is to differentiate the different segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "mySegue" ,
       let nextScene = segue.destination as? VehicleDetailsTableViewController ,
       let indexPath = self.tableView.indexPathForSelectedRow {
        let selectedVehicle = vehicles[indexPath.row]
        nextScene.currentVehicle = selectedVehicle
    }
}

If you are using Using Xcode 7, swift 2.x
Then use this code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "mySegue" {
    var nextScene =  segue.destinationViewController as! VehicleDetailsTableViewController

    // Pass the selected object to the new view controller.
    if let indexPath = self.tableView.indexPathForSelectedRow {
        let selectedVehicle = vehicles[indexPath.row]
        nextScene.currentVehicle = selectedVehicle
    }
  }
}

Place a breakpoint after nextScene and see if it is being triggered by clicking any cell in the TableView. If it isn't then the identifier name u provided in the storyboard must be different then the one given here.
Comment: Almost worked. **println(currentVehicle?.location** returns nil on secondScene. I don't understand why, normally it has a value I can't pass
Comment: Place a break point after `var nextScene` and see if it is being triggered on clicking any cell in the `TableView`. If it isn't then the identifier name u provided in the storyboard must be different then the one given here.
Answer: In swift 3.0 Xcode 8 beta 6
AnyObject has been renamed to Any?
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
    let nextScene =  segue.destinationViewController as! VehicleDetailsTableViewController

    // Pass the selected object to the new view controller.
    if let indexPath = self.tableView.indexPathForSelectedRow {
        let selectedVehicle = vehicles[indexPath.row]
        nextScene.currentVehicle = selectedVehicle
    }
  }
}

Comment: It should be noted that segue.destinationViewController has been renamed to segue.destination
Comment: this is not a valid answer ... You are not checking for the segue.identifier....This will lead to crash if there are multiple segues
Answer: In Swift 3, Xcode 8
Just don't use "identifier". I don't know why but "segue.identifier" is always nil. I just used prepare method like this and works!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let secondController = segue.destination as? SecondController {
        secondController.anyItemInSecondController = self.anyItemInFirstController
    }

Answer: What that error is telling you is that segue.destinationViewController isn't a VehicleDetailsTableViewController. We don't have enough details to tell you why.
Check your segues and make sure they're all pointing to the correct place, and always check the identifier of your segue before you perform a cast.
if segue.identifier == "theNameOfYourSegue" // then do your cast

Comment: I'd use a switch statement instead of in if, but yeah.
Comment: @Abizern I know this is really old, however, Do you have any good reason for doing so?
Comment: @iShaalan Where there are multiple choices, in this case multiple possible values of the identifier, I find `switch` statement clearer to read.


How to accomplish IDA GenFuncGdl?

Question: How to accomplish GenFuncGdl? I mean, what idc functions are used to accomplish GenFuncGdl? I look up idc.py, about this function:
def GenFuncGdl(outfile, title, ea1, ea2, flags):
"""
Generate a flow chart GDL file

@param outfile: output file name. GDL extension will be used
@param title: graph title
@param ea1: beginning of the area to flow chart
@param ea2: end of the area to flow chart.
@param flags: combination of CHART_... constants

@note: If ea2 == BADADDR then ea1 is treated as an address within a function.
       That function will be flow charted.
"""
return idaapi.gen_flow_graph(outfile, title, None, ea1, ea2, flags)

from there, we just know that simply call idaapi.gen_flow_graph.
In fact, I need to reverse a function flow, because there are many branches in this function, I do not know how to recognize branch chunks. only check jump instruction, Maybe?
Answer: As you saw, idaapi.gen_flow_graph will just call a native c++ IDA function.
Your question isn't clear about what you are trying to achieve exactly (finding chunks in the GDL file?)
If you just want to find a function chunks then you can use idautils.Chunks() function which returns a python generator with the start and end addresses of all chunks in a function.
Comment: I want to achieve a flow graph for each function, just like the results of  idaapi.gen_flow_graph, but i do not want call that. I know there will be a GDL format file if calling gen_flow_graph, a clumsy way to achieve my goal is to parse that GDL file.

How to accomplish IDA GenFuncGdl?


Feature automatically reverts on cache clear

Question: I have an issue with Features which contains a view.  If I update the feature and then clear the Drupal cache, the view will revert to the configuration in the updated feature.
My understanding was that a feature would not be reverted unless it is specifically made to (e.g. manually revert the feature).  Is this a wrong assumption?
Here is more information of what I have tried.  On server A, I modify a view which is contained in a feature.  I then update the feature so that it contains the modification to the view.  I then commit the updated feature to git.
Now, I log into the other server, and pull in the changes from git (e.g. bring in the updated feature).  If I go to the feature's admin page I can now see that it is overridden (so far so good).
I then clear the drupal cache (e.g. via performance page or drush cc all).  If I now check the feature status, it is set to default and the view has also been modified.
Why would the feature and the view change on cache clear if I haven't specifically reverted the feature?
UPDATE:
It seems the issue only occurs if the status of the feature on Server B was 'default' prior to deploying the updated feature. See following scenarios:
SCENARIO 1:
Feature on Server B is in 'default' state.  Updated feature from Server A is deployed to Server B.  The features admin page shows on Server B now shows the feature to be "Overridden" (expected given we have deployed updated feature).
If I now clear cache, the feature's status has now changed to 'default' and examination of the relevant view shows that the changes in the updated feature have been applied.
SCENARIO 2:
Feature on Server B is already in 'Overridden' state, due to a local change I made to the view.  The updated feature from Server A is deployed to Server B.  The features admin page shows feature on Server B to be "Overridden" (expected given we made local changes to relevant view).
If I now clear cache, the feature is still shown as "Overridden" and the relevant view has not been altered.
As you can see in SCENARIO 1 the updated feature is automatically reverted on cache clear, but in SCENARIO 2 it is not.
Answer: This is not supposed to happen, a cache clear should not have any effect on overridden features.
I'm just guessing here, but have you tried to uncheck the option 'Rebuild features on cache clear' on the features settings page (admin/structure/features/settings)?
Rebuild and revert are two different things where rebuild should leave the overridden features as they are, but who knows? It's worth the try.
Comment: Thanks for reply.  I am not able to find the features' settings page you refer to.
Comment: On the features overview page, there is a tab in the top right corner. You can also go to http://www.yoursite.com/admin/structure/features/settings
Comment: What version of features are you using. The path you mentioned does not seen to exist. I checked the features source code and could not find any reference to it either
Comment: That's strange. I used version 2.5 but updated to 2.7 after reading your comment and the settings page is still there. I also checked the code and as you can see [here](http://www.drupalcontrib.org/api/drupal/contributions%21features%21features.module/function/features_menu/7) admin/structure/features/settings is defined in hook_menu. Just to make sure we're on the same level: you're using Drupal 7 with Features 2.7, right?


How to config server to send out email

Question: I register my domain at 1and1.com, let's say it is abc.com. Then, I start an aws ec2 instance, with ip address 188.8.131.52.
At 1and1 dns control panel, I created a A record to point abc.com to aws server ip address 18.104.22.168.
So far so good, I open abc.com will display the right content which I setup at 188.8.131.52 web server.
In the meanwhile, I use the free 1and1.com webmail service(so someone send to me firstname.lastname@example.com, I will receive the email via 1and1 free mail server). Also, I need 18.104.22.168 web server to send notification emails to user represent my abc.com site. Thus, I install postfix in 22.214.171.124 for send out email only.
The trouble is some public email providers will reject emails from 18.104.22.168.
I checked the log

(host mx01.mail.com[188.8.131.52] refused to talk to me: 554-mail.com
  (mxgmxus006) Nemesis ESMTP Service not available 554-No SMTP service
  554-Bad DNS PTR resource record. 554 For explanation visit
  http://postmaster.gmx.com/en/error-messages?ip=184.108.40.206&c=rdns)

For example, the below is the typical answer I asked them why rejecting my email sent from 188.8.131.52 since it is not a spam.
They said

Your mailserver ip has still the generic default rDNS / PTR-RR from
  the beginning:
$ host 188.8.131.52
  188.8.131.52.in-addr.arpa domain name pointer ec2-1-2-4-7.ap-southeast-2.compute.amazonaws.com.
Please setup an valid und speaking mailservername in the rDNS /
  PTR-RR.
Why not mail.domain.tld?

To be frank, I've no idea what they are talking about and I have no clue what shall I do either. Could anyone enlighten me? Thank you.
Answer: Many MXs check a connecting host for proper setup. Make sure you've set up

meaningful PTR for reverse DNS
A record for that PTR (FCrDNS)
meaningful HELO FQDN host name (must resolve to IP)
reasonable security that your host isn't an open relay
and don't send spam so you get listed on a DNSBL

How to config server to send out email


Python Multiple Inheritance super().__init__()

Question: I have two classes, with the same parameter initialized by their __init__ method.
I would like to inherit both classes in class "X". But I will get: TypeError: B.__init__() missing 1 required positional argument: 'my_param'
Reproducible Example:
class A:
    def __init__(self, my_param):
        super().__init__()
        self.my_param = my_param

class B:
    def __init__(self, my_param):
        super().__init__()
        self.my_param = my_param * 2

class X(A, B):
    def __init__(self, my_param):
        super().__init__(my_param=my_param)

a = X(my_param=1)
print(a.my_param)

A and B are Mixins, they provide additional functionality for Child Classes. They can be used separetly or together. Lets's say class A provides searhc functionality for search by ID, where class B provides search by value.
Is there a way to set my_param for each of A and B or to set it without getting the error?
Comment: I would comment out `super().__init__()` call in `A` constructor method
Comment: X calls A with the parameter, but then A calls B without it. Your parent classes need to be written to collaborate in the inheritance.
Comment: so A and B are not related to each other? i.e. I assume it wouldn't make sense to inherit one from the other?
Comment: also, note that class `Abstract` is not used anywhere.
Answer: This can't be done just using super() calls, because the superclass of the last class in the chain will be object, which doesn't take a my_param parameter.
See python multiple inheritance passing arguments to constructors using super for more discussion of parameter passing to __init__() methods with multiple inheritance.
So you need to change X to call the superclass init methods explicitly, rather than using super(). And A and B shouldn't call super().__init__() because they're subclasses of object, which doesn't do anything in its __init__().
class A:
    def __init__(self, my_param):
        self.my_param = my_param

class B:
    def __init__(self, my_param):
        self.my_param = my_param * 2

class X(A, B):
    def __init__(self, my_param):
        A.__init__(self, my_param=my_param)
        B.__init__(self, my_param=my_param)

Comment: Thank you for your answer!, Unfortunately when I try this, I get the error: ´TypeError: object.__init__() takes exactly one argument (the instance to initialize)` I
Comment: ahhh, thank you so much for the explanation! I tried to solve it in the meantime by creating an abstract class shared by A and B but it feels not really clean, I definetly can use your solution and learned something new on the way, thank you again.
Answer: Since A and B share the same fields, I think it makes sense to make one inherit from the other - in this case, B inherit from A. That way, you'll only need to subclass from B in class X.
For example:
class A:
    def __init__(self, my_param):
        self.my_param = my_param

class B(A):
    def __init__(self, my_param):
        super().__init__(my_param * 2)
        # or:
        #   A.__init__(self, my_param * 2)

class X(B):
    def __init__(self, my_param):
        super().__init__(my_param=my_param)

a = X(my_param=1)
print(a.my_param)  # 2

Comment: This class hierarchy may not make sense for the rest of the behavior of B.
Comment: @rv.kvetch thank you for your answer, class A and B are Mixins, they provided different functunalities e.g. search by value (A) and search by id (B). Some childs of A and B only need A as parent, some only B and some both. But both classes share some attributes.
Comment: Totally right, I did make an assumption that since B and A share the same field, it might make sense to introduce some sort of inheritance. But I agree that this might not be the best idea, depending on the use case or scenario.


Subscript out of range when copying range to another workbook

Question: I am writing a reporting system where the user fills out a form and a form button runs a macro to save the file with a name based on several fields including a timestamp.
All the data is is also on a second sheet but in one row for ease of copying to a master sheet.
I am trying to to extend the save macro to copy this row to the last line of a second workbook.
This was successful when the macro was run from a separate workbook but I can't for the life of me work out how to do it from within the file itself.
I've triple checked the paths themselves, I know they're right as the new files are being created, I've run msgbox in the code to check the filename and the variable are the same too.
timestampedfile = Worksheets("single_line").Range("b3")
totalpath = Path & timestampedfile & ".xlsm"

ActiveWorkbook.SaveCopyAs filename:=totalpath
master_wb = "s:\blah\blah\blah.xlsx"
master_sht = "Master_Database"
contact_wb = totalpath
contact_sht = "single_line"

Workbooks.Open (master_wb)
Workbooks.Open (contact_wb)

MsgBox (totalpath)

Workbooks(contact_wb).Worksheets(contact_sht).Range("A3:AQ3").Copy Worksheets(master_wb).Sheets(master_sht).Range("A" & Rows.Count).End(xlUp)(2)

'
Both the Workbooks open so I know the paths are right, can anyone help?
Comment: With that error it means the spelling of the sheet or workbook is wrong
Comment: It's good that you edited your post and gave credit to @BigBen. However, the proper way to give credit to someone is to mark their comment/answer using the checkbox/up-arrow next to it. That way they get recognized and have more points/privileges on the forum.
Comment: Use workbook variables, instead of referencing the workbook by name: `Dim masterWb as Workbook`, then `Set masterWb = Workbooks.Open("s:\blah\blah\blah.xlsx" )`. Similarly for the contact workbook. You might consider using worksheet variables too, instead of using sheet names.
Comment: To test things like this add lines like, "s = masterWb.name", where s is defined earlier using "Dim s as string". Then you can hover over the variable after that line is executed to see if it's what you expect. Simple debugging, but it solves a lot of problems.
Comment: It wasn't appearing, I think I have to have 15 trip to do that. I'll look again.
Answer: Solution by OP
Solved thanks to comment about workbook variables by BigBen:

Use workbook variables, instead of referencing the workbook by name: Dim masterWb as Workbook, then Set masterWb = Workbooks.Open("s:\blah\blah\blah.xlsx" ). Similarly for the contact workbook. You might consider using worksheet variables too, instead of using sheet names.

Code changed to:
Dim master_wb As Workbook
Dim contact_wb As Workbook
Dim master_sht As Worksheet
Dim contact_sht As Worksheet

Path = "S:\blah\" & Worksheets("report").Range("c8") & "\"
filename = Worksheets("back_end_formulas").Range("e10")
timestampedfile = Worksheets("single_line").Range("b3")
totalpath = Path & timestampedfile & ".xlsm"

ActiveWorkbook.SaveCopyAs filename:=totalpath
SetAttr totalpath, vbReadOnly

Set master_wb = Workbooks.Open("S:\blah\Master_Database2.xlsx")
Set master_sht = master_wb.Sheets("Master_Database")
Set contact_wb = Workbooks.Open(totalpath)
Set contact_sht = contact_wb.Sheets("single_line")

ThisWorkbook.Activate

contact_sht.Range("A3:AQ3").Copy master_sht.Range("A" & Rows.Count).End(xlUp)(2)

master_wb.Close SaveChanges:=True
contact_wb.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False


Transformar Number em texto binário

Question: Como conseguir a representação de um Number (inteiro) em binário com JavaScript?
Ex:
47 = 00101111

Answer: Se quiser que funcione de forma genérica, incluindo negativos:

function dec2bin(dec) {
    return dec >= 0 ? dec.toString(2) : (~dec).toString(2);
}
console.log(dec2bin(47));
console.log(dec2bin(-47));

Se quiser fazer um padding:

function dec2bin(dec) {
    var binario = dec >= 0 ? dec.toString(2) : (~dec).toString(2);
    var tamanho = binario.length > 32 ? 64 : binario.length > 16 ? 32 : binario.length > 8 ? 16 : 8;
    return ("0".repeat(tamanho) + binario).substr(-tamanho);
}
console.log(dec2bin(47));
console.log(dec2bin(-47));
console.log(dec2bin(12347));
console.log(dec2bin(5612347));

Coloquei no GitHub para referência futura.
Comment: Se encaixou perfeito na minha função. Test.assertEquals rodou de boa =)
Answer: Como já foi referido podes usar o .toString() e passando como argumento o 2, que quer dizer base 2, radix 2 ou binário.
Para completar os zeros à esquerda basta mais uma linha de código, algo assim:
function binarificar(nr){
    var str = nr.toString(2);
    return '00000000'.slice(str.length) + str;
}

console.log(binarificar(1));  // 00000001
console.log(binarificar(47)); // 00101111

Answer: Uma opção é essa:
(47).toString(2)

O método toString, em Javascript, aceita em qual base você deseja obter a representação do número inteiro. No caso acima foi na base 2.

Transformar Number em texto binário


Place text box in appbar in Flutter

Question: I want to implement an Appbar like below where there are a textbox and multiple icons:

The icons can be added in action easily, but how to add the text box and add search action to it. There are many search bar plugins available, but all of them occupy the whole app bar and no way to mention the hints. Can anyone give some idea, it will be a great help for me.
Comment: add what you done till now
Answer: In the title propiery, inside the AppBar, you can pass a widget, which means you can add any component you want, like a TextField. see the example below:
appBar: AppBar(
        title: TextField(
          decoration: InputDecoration(
            hintText: 'Search',
            prefixIcon: Icon(Icons.search)
          ),
        ),
      ),

I suggest to you, to wrap this TextField in a GestureDetector, disable the TextField with the proprierty called enable (set to false), and in the onTap method inside the GestureDetector, you can call a showSearch() method.
To call this showSearch(), you'll need to pass a context and a searchDelegate which is a component that extends a class, check this example:
class CustomSearchDelegate extends SearchDelegate {
  @override
  List<Widget> buildActions(BuildContext context) {
    // TODO: implement buildActions
    return null;
  }

  @override
  Widget buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    return null;
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return null;
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    return null;
  }
}

Source: Implementing search in Flutter
Now, you can do this:
GestureDetector:
  onTap: () => showSearch(context: context, delegate: CustomSearchScreen()),
  child: ....

Comment: Thank you. It is a great help.
Comment: The Idea of converting text field into the Search bar wtih Search delegate fun. is a great idea. Thanks

Place text box in appbar in Flutter


Unexpected Python Arithmetic Behavior

Question: I'm working on a huffman encoder/decoder in Python, and am experiencing some unexpected (at least for me) behavior in my code. Encoding the file is fine, the problem occurs when decoding the file. Below is the associated code:
def decode(cfile):
    with open(cfile,"rb") as f:
        enc = f.read()
        len_dkey = int(bin(ord(enc[0]))[2:].zfill(8) + bin(ord(enc[1]))[2:].zfill(8),2) # length of dictionary
        pad = ord(enc[2]) # number of padding zeros at end of message
        dkey = { int(k): v for k,v in json.loads(enc[3:len_dkey+3]).items() } # dictionary
        enc = enc[len_dkey+3:] # actual message in bytes
        com = []
        for b in enc:
            com.extend([ bit=="1" for bit in bin(ord(b))[2:].zfill(8)]) # actual encoded message in bits (True/False)
    cnode = 0 # current node for tree traversal
    dec = "" # decoded message
    for b in com:
        cnode = 2 * cnode + b + 1 # array implementation of tree
        if cnode in dkey:
            dec += dkey[cnode]
            cnode = 0

    with codecs.open("uncompressed_"+cfile,"w","ISO-8859-1") as f:
        f.write(dec)

The first with open(cfile,"rb") as f call runs very quickly for all file sizes (tested sizes are 1.2MB, 679KB, and 87KB), but the part that slows down the code significantly is the for b in com loop. I've done some timing and I honestly don't know what's going on.
I've timed the whole decode function on each file, as shown below:
87KB      1.5 sec
679KB     6.0 sec
1.2MB   384.7 sec

first of all, I don't even know how to assign this complexity. Next, I've timed a single run through of the problematic loop, and got that the line cnode = 2*cnode + b + 1 takes 2e-6 seconds while the if cnode in dkey line takes 0.0 seconds (according to time.clock() on OSX). So it seems as if the arithmetic is slowing down my program significantly...? Which I feel like doesn't make sense.
I actually have no idea what is going on, and any help at all would be super welcome
Comment: Quite hard to tell, it looks more like a memory allocation problem then a arithmetic one. Things to check are:  1) print the length of com before entering the loop - does it go exponentially big with the 1.2MB file? 2) Check the contents of dkey - does this dictionary contain a large amount of data for a given key? perhaps print the size of the item on each iteration and see if there is a difference for the 1.2MB file. 3) take a look at task manager / top to see if the process is using a large amount of memory
Comment: Does your decoder actually work? Does the output look like you think it should? Particularly, is the decoded output as long as it should be?
Comment: to answer @user2357112, yes, the decoder works as expected, the output file is the same as the input file (before encoding). to answer @matt-young, the length of com scales linearly with file size, each value in `dkey` is one byte, and i've double checked, and Python goes from running 40MB of memory to 100MB of memory (I'm running it in terminal), which admittedly is strange
Answer: I found a solution to my problem, but I am still left with confusion afterwards. I solved the problem by changing the dec from "" to [], and then changing the dec += dkey[cnode] line to dec.append(dkey[cnode]). This resulted in the following times:
87KB    0.11 sec
679KB   0.21 sec
1.2MB   1.01 sec

As you can see, this has immensely cut down the time, so in that aspect, this was a success. However, I am still confused as to why python's string concatenation seems to be the problem here.

Unexpected Python Arithmetic Behavior


Executar um som em outra tela quando é inserido um registro novo

Question: Bom dia a todos!
Bom! gostaria de uma grande ajuda de vocês. Estou tentando fazer um Painel de chamada de pacientes bem simples para quando o médico esteja no consultório veja uma tabela de pacientes e clique o nome desejado e na sala de recepção apareça o nome dele e toque um som.
No momento só consigo fazer que toque um som no PC que é chamado que seria o do médico, pois não seria o ideal já que teria que colocar caixas de sons do lado externo para cada consultório.
Esse é meu código:

**db.php**

<?php

  $servidor = "localhost";
  $usuario= "root";
  $password = "";
  $db = "painel";

  $conexao = new mysqli($servidor, $usuario, $password, $db);

?>

**chamar.php**

<?php
  include "db.php";
?>
<!DOCTYPE html>

 <title>CHAMAR CLIENTE</title>
 <link rel="stylesheet" type="text/css" href="estilos.css">

  <form method="POST" action="chamar.php">
   <input type="text" name="nome">
   <input id="id2" type="submit" name="enviar" value="Chamar Paciente"
            onclick="ajax();">

  </form>

  <?php
   if (isset($_POST['enviar'])) {

    $nome = $_POST['nome'];

    $consulta = "INSERT INTO chamar (nome) VALUES ('$nome')";

    $executar = $conexao->query($consulta);

    if ($executar) {
     //EXECUTA O SOM QUANDO É INSERIDO UM REGISTRO
     echo "<embed loop='false' src='beep.mp3' hidden='true'
                    autoplay='true'>";
    }

   }
  ?>

**index.php**

<?php
include "db.php";
?>
<!DOCTYPE html>

 <title>PAINEL DE CHAMADA</title>
 <link rel="stylesheet" type="text/css" href="estilos.css">

  <?php

   $consulta = "SELECT * FROM chamar";

     $executar = $conexao->query($consulta);

     if ($executar) {
      //SÓ EXECUTA O SOM QUANDO É ATUALIZA A PÁGINA
      echo "<embed loop='false' src='beep.mp3' hidden='true'
                        autoplay='true'>";
     }

  ?>

**painel.php**

<?php
 include "db.php";

 $consulta = "SELECT * FROM chamar ORDER BY id DESC";
 $executar = $conexao->query($consulta);
 $chamar = $executar->fetch_array();

?>

<?php echo $chamar['nome']; ?>

Agradeço desde já!!!
Comment: pode enviar a estrutura do banco pra eu pode replicar aqui e fazer um teste?
Answer: Basicamente você precisará de uma página que fica consultando a tabela chamar
modifiquei então a painel.php para capturar os dados necessários e devolve-los em JSON:
<?php
    include "db.php";

    //ARMAZENA O TOTAL
    $consulta = "SELECT * FROM chamar ";
    $executar = $conexao->query($consulta);
    $total = mysqli_num_rows($executar);

    //SELECIONA APENAS OS 6 ULTIMOS
    $sql = "SELECT * FROM chamar ORDER BY id DESC LIMIT 6";
    $exec = $conexao->query($sql);
    $ultimos = array();
    $i = 0;

    while($chamar = $exec->fetch_array()){
        //eis o proximo
        if($i==0){
            $proximo = $chamar['nome'];
        }else{

            // forma os 5 ultimos
            array_push($ultimos,
                array('nome' => $chamar['nome'])
            );
            //para pegar mais que 5, aumente o limit no $sql;
        }
        $i++;
    }

    echo json_encode(
        [
            'total' => $total, //quantos nomes foram chamados
            'proximo' => $proximo, // nome do proximo
            'ultimos' => $ultimos // array contendo o nome dos 5 ultimos
        ]
    );

?>

criei daí uma pagina chamada painel_exibe.php que irá usar a painel.php para exibir os dados:

<input type="hidden" id="total" value="0">

Próximo:

Carregando...

Ultimos chamados:

Carregando...

Explicando esse código passo a passo:
1 - Este campo serve para armazenar o ultimo n° de registros de nomes que chegaram a partir do banco de dados. Não é interessante ler o nome e comparar com o ultimo pois é comum que pessoas possuam exatamente o mesmo nome (Por exemplo João Silva).

<input type="hidden" id="total" value="0">

2 - Lugar onde vamos colocar o nome do ultimo cliente chamado:

Próximo:

Carregando...

3 - Exibe o nome dos 5 ultimos chamados (Para as pessoas saberem se perderam ou não a vez)

Ultimos chamados:

Carregando...

4 - div que vamos usar só pra recolocar o código que toca o som:

5 - JQUERY para usarmos o ajax:

6 - Requisição AJAX para painel.php - Nessa página iremos :
a) contar quantos pacientes temos, para adicionar no campo "total"
b) guardar o nome do proximo paciente
c) guardar um array com o nome dos ultimos pacientes chamados
(veja o codigo da painel.php dela no inicio da resposta)
Explicações nos comentários do código:

Comment: na tela que vai ficar visivel pro pessoal da recepção, você carrega a pagina painel_exibe.php e deixa aberta...
Comment: Will Knippelberg! Era tudo que eu precisava. Codificação perfeito... Valeu mestre!!!
Comment: Vota como resposta útil então pra dar aquela moral :D


How to run 'lm' function in R, but with a formula with only an intercept?

Question: I've tried running a formula similar to y ~ 1. This gives me just an intercept, but is the value that's shown equal to intercept estimate(without covariates) + 1, or just intercept estimate(without covariates)?
Any help would be appreciated.
Comment: Won't the intercept just be mean(y)
Comment: Since the formula references only `y` and the constant `1`, *how could it possibly even know about any covariates?*
Comment: Option or not, if you don't supply any covariates to a procedure, there isn't any way for it to use them, is there?
Comment: @whuber you're probably right, even though I could say that lm(formula, data), and in data the lm function could find the covariates...
Comment: @whuber I do not know. In R if you put -1, then lm does a regression without a constant. By putting just a 1, we could activate another option, unknown to me... That's why I'm asking.
Answer: When you do linear regression on only a constant, you will only get the intercept value, which is really just the mean of the outcome.
In R we have:
y <- rnorm(1000)
lm(y ~ 1)
# intercept = 0.00965
mean(y)
# Equal to 0.00965

The reason for doing it the regression way, rather than just computing the mean, is to get an easy standard error.
If have no idea what you mean with "intercept +1", but what you do get is the mean of the outcome, i.e. the expected value of y when you do not control for anything.
Comment: Thanks Repmat.

Also, another reason for doing this, is that some packages require the user to define a base model, e.g. 'BayesVarSel'.


Analysis Question? Fixed Point?

Question: How would you go about proving this assertion?

$f:A \to A$ has a fixed point iff the graph of f intersects the diagonal

Also, in class we've proven that given $a,b \in \mathbb{R}$ with $a < b$ and letting $f:[a,b] \to [a,b]$ be continuous, $f$ has a fixed point, that is, there is an $x \in [a,b]$ with $f(x)=x$.
But does this hold for $f:(a,b) \to (a,b)$ and discontinuous functions?
Comment: It is practically the definition of fixed point!
Answer: The fact that was proven in class is different from what you are trying to prove.  By the diagonal, I assume you mean the line $y=x$.  Remember, that when you are graphing a function, you are graphing the equation $y=f(x)$.  So, if $f(x)=x$, then $y=x$.  In other words the point $(x,x)$ is on the graph of $f(x)$ and on the line $y=x$.
Comment: Thanks Tim! I think I have a better understanding now.
Comment: And yes, I knew those two points were not necessarily related... they were just separate uncertainties I had about the material :)
Comment: Glad I could help.

Analysis Question? Fixed Point?


How to Convert Data in Json File to Values (double,int...)

Question: I am new to JSON files, so this might be a very silly error:
I have converted a Shape File into a GeoJson file Using GDAL in C++. The code I used is the one showed in the GDAL API for c++ (Link). I correctly read the shape file, and then I convert it to a JSON file with the following code
    char * json_poly = Polygon->exportToJson();
    Json::Value GeoJson;
    Json::Reader reader;
    reader.parse(json_poly,GeoJson);

Where Polygon is a GDAL object. Now GeoJson is a JSON:: VALUE which looks like this
   "coordinates" :
    [
            [
                    [
                            586417.77972987387,
                            6884063.8642021669
                    ],
                    [
                            586655.1163914972,
                            6884198.7810712075
                    ],
                    [
                            586707.31919375062,
                            6884238.8010942638
                    ],
                    [
                            586703.2053746446,
                            6884258.7722300319
                    ],
                    [
                            586754.77872091066,
                            6884309.6043649064
                    ],
                    [
                            586832.7780266488,
                            6884413.5168099366
                    ]

But when I try to calculate the centroid with a simple for cycle, like in the following snippet
double x = 0 ;
double y = 0 ;
for( int i = 0 ; i < GeoJson["coordinates"][0].size() ; i++ )
{
    x +=  GeoJson["coordinates"][0][i][0];
    y +=  GeoJson["coordinates"][0][i][1];
}
x /=  GeoJson["coordinates"][0].size() ;
y /=  GeoJson["coordinates"][0].size() ;

cout << "The centroid is in " << x<< " , " << y << endl;

I get the following error
 no match for 'operator+=' (operand types are 'double' and 'Json::Value')

and if I try to cast the values to double  double(GeoJson["coordinates"][0][i][0]) I get the following error
error: invalid cast from type 'Json::Value' to type 'double'

How do I cast the values in order to operate an arithmetical operation with them ?
Comment: *How do I cast the values* -- I would be surprised if the library you're using relies on you casting things -- needing casts goes against the type-safety that C++ touts.  There are probably member functions that do the job.
Comment: Thank you for your comment. I am using the following libraries #include
#include
#include
#include
Comment: OK I found the answer to this here https://stackoverflow.com/questions/19707898/convert-json-value-to-int-in-c. Thank you for pointing in the right direction @PaulMcKenzie.
Answer: Link explains under the topic "Getting Dataset Information"
double        adfGeoTransform[6];
printf("Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(),
       poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );
printf("Size is %dx%dx%d\n",
       poDataset->GetRasterXSize(), poDataset->GetRasterYSize(),
       poDataset->GetRasterCount() );
if( poDataset->GetProjectionRef()  != NULL )
    printf( "Projection is `%s'\n", poDataset->GetProjectionRef() );
if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None )
{
    printf( "Origin = (%.6f,%.6f)\n",
            adfGeoTransform[0], adfGeoTransform[3] );
    printf( "Pixel Size = (%.6f,%.6f)\n",
            adfGeoTransform[1], adfGeoTransform[5] );
}

virtual CPLErr GetGeoTransform (double *padfTransform) is documented here: Link


Raid0 IOPS poor performance

Question: I've set up 8x500gb disks in raid0 on an EBS optimized EC2 instance and I ran iops.py to check the speed, but it seems really slow.
Does anyone know if this is normal speeds for raid0? I'd think I'd be getting IO/s over 1000 more or less constantly?
Here are the stats:
python python/iops.py --num_threads 16 --time 2 /dev/md0
/dev/md0,   4.29 TB, 32 threads:
 512   B blocks:  831.6 IO/s, 415.8 KiB/s (  3.4 Mbit/s)
   1 KiB blocks:  290.8 IO/s, 290.8 KiB/s (  2.4 Mbit/s)
   2 KiB blocks:  543.7 IO/s,   1.1 MiB/s (  8.9 Mbit/s)
   4 KiB blocks:  581.5 IO/s,   2.3 MiB/s ( 19.1 Mbit/s)
   8 KiB blocks:  275.5 IO/s,   2.2 MiB/s ( 18.1 Mbit/s)
  16 KiB blocks:  486.8 IO/s,   7.6 MiB/s ( 63.8 Mbit/s)
  32 KiB blocks:  415.3 IO/s,  13.0 MiB/s (108.9 Mbit/s)
  64 KiB blocks:  277.8 IO/s,  17.4 MiB/s (145.6 Mbit/s)
 128 KiB blocks:  205.3 IO/s,  25.7 MiB/s (215.3 Mbit/s)
 256 KiB blocks:  116.4 IO/s,  29.1 MiB/s (244.2 Mbit/s)
 512 KiB blocks:  114.1 IO/s,  57.0 MiB/s (478.5 Mbit/s)
   1 MiB blocks:   60.4 IO/s,  60.4 MiB/s (506.8 Mbit/s)
   2 MiB blocks:   28.5 IO/s,  57.1 MiB/s (478.9 Mbit/s)

cat /proc/mdstat
Personalities : [raid0]
md0 : active raid0 xvde[0] xvdf[7] xvdg[6] xvdh[5] xvdi[4] xvdb[3] xvdc[2] xvdd[1]
      4194295808 blocks super 1.2 512k chunks

unused devices: <none>

mdadm --detail /dev/md0
/dev/md0:
        Version : 1.2
  Creation Time : Mon Jul 29 08:23:38 2013
     Raid Level : raid0
     Array Size : 4194295808 (3999.99 GiB 4294.96 GB)
   Raid Devices : 8
  Total Devices : 8
    Persistence : Superblock is persistent

    Update Time : Mon Jul 29 08:23:38 2013
          State : clean
 Active Devices : 8
Working Devices : 8
 Failed Devices : 0
  Spare Devices : 0

     Chunk Size : 512K

           Name : hostname
           UUID : 7df463c3:5de17a1b:cfe3345c:8e8c22ac
         Events : 0

    Number   Major   Minor   RaidDevice State
       0     202       64        0      active sync   /dev/xvde
       1     202       48        1      active sync   /dev/xvdd
       2     202       32        2      active sync   /dev/xvdc
       3     202       16        3      active sync   /dev/xvdb
       4     202      128        4      active sync   /dev/xvdi
       5     202      112        5      active sync   /dev/xvdh
       6     202       96        6      active sync   /dev/xvdg
       7     202       80        7      active sync   /dev/xvdf

Comment: Amazon is a cloud service provider, who lives on sharing hardware resources across different customers. It's impossible for us to say if this is enough IOPS or not, you'll have to direct this question to Amazon. Alternatively, look at your contract and see if there is any SLA on performance.
Answer: Are you paying for provisioned IOPS? If not, you'll be getting around 100 IOPS per EBS on average, which ties in with what you're seeing with 8 EBS volumes tied together.
From here:

Standard volumes offer storage for applications with moderate or bursty I/O requirements. Standard volumes deliver approximately 100 IOPS on average with a best effort ability to burst to hundreds of IOPS. Standard volumes are also well suited for use as boot volumes, where the burst capability provides fast instance start-up times.
Comment: I have tried with a 2*500gb raid0 as well getting ~80 iops from iops.py which I do not understand
Comment: I'm not familiar with iops.py I'm afraid. Is is doing random or sequential access?
Answer: You're not really giving us enough information to go off of.  Taking any kind of write penalty out of the equation if we assume your using standard 7200rpm Sata drives then your IOPS would be as follows:
1/(12ms seek time (.012)+ 5.5ms latency (.0055))= 57.14 IOPS

So we would use the following to determine the IOPS of the array:
8 (numdisks)* 57.14 (MaxIOofSingleDisk)=457 max read IO for the array.

So it comes down to, what speed/type of disks are you using? Then find out the avg. seek time and latency from the manufacturer and use the above values to see if the IOPS is what is expected (again write penalty and overhead should be factored in for write IO).
This might be harder since your not in a physical environment but I'm sure someone can give you a clue about the disks used in EC2 pools.

Raid0 IOPS poor performance


Cannot get boostraps jQuery tooltips to appear

Question: Starting to get frustrated which is making it harder to see where I might be going wrong, but essentially I'm trying to get Bootstrap's jQuery tooltips to work upon hovering over an image in the content of my page.
HTML in body:

Header:

I've shortened the paths to make it easier to browse, but feel free to check out the problem live on:
http://okamistudio.com/ssawp/pennants/

I'm trying to achieve the tooltip on the small boat icon underneath the 'Yellow Pennant' block of text.
Any help or guidance would be much appreciated.
Answer: Firstly you need to include bootstrap.js before you write your own code. Secondly you need to wrap your code in a document ready handler.
Also, you haven't included it in your example, so for the sake of completeness I've included the required jquery.js too. Try this:

Comment: I had the bootstrap.js included (see in the bottom of the second source snippet), was missing the document ready handler (if that's the $function() { bit) and it seems I've been using an outdate version of jQuery (1.2.3) which wasn't helping either.

Thank you for that, I don't have much working knowledge of JS at all which is why I missed that opening bit. Would you mind just briefly explaining what it does - creates it into a function as opposed to plain script?

I have to wait 8mins to answer but you solved it. Much appreciated.
Comment: Glad to help. The document ready handler (you're corerct, it's the `$(function() { ... });` wrapper) means that the code within that block is not executed until the DOM is ready. Previously your code was looking for the `.tooltip-demo.well` element in the DOM before it existed, which is why it did not work.
Comment: Aha, fantastic. Thank you for taking the time to explain that! Have a great day.


Getting GPS Coordinates Windows Phone 7

Question: I've been looking quite some time today to gather GPS coordinates from a Windows Phone 7 device - however since I do not have an actual test device here I tried to set some dummy data which I want to have returned instead of real GPS Data ... that, however ist not working out too well:
This code ist partially an example from so which I found here. However I tried to put it into a class which I can access later.
public class GetGPS : GeoCoordinateWatcher
{
    GeoCoordinateWatcher watcher;

    public GetGPS()
    {
        watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
        watcher.MovementThreshold = 20;

        watcher.PositionChanged += this.watcher_PositionChanged;
        watcher.StatusChanged += this.watcher_StatusChanged;
        watcher.Start();
    }

    private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
    {
        switch (e.Status)
        {
            case GeoPositionStatus.Ready:
                //plingpling
                break;
            case GeoPositionStatus.Disabled:
                // location is unsupported on this device
                break;
            case GeoPositionStatus.NoData:
                watcher.Position.Location.Latitude = 54.086369f;
                watcher.Position.Location.Longitude = 12.124754f;
                break;
        }
    }

    private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
    {
        var epl = e.Position.Location;

        // Access the position information thusly:
        epl.Latitude.ToString("0.000");
        epl.Longitude.ToString("0.000");
        epl.Altitude.ToString();
        epl.HorizontalAccuracy.ToString();
        epl.VerticalAccuracy.ToString();
        epl.Course.ToString();
        epl.Speed.ToString();
        e.Position.Timestamp.LocalDateTime.ToString();
    }
}

This is my other class in which I try to access the data - however I always get NaN as lat1Rad and long1Rad ... can you please help me?
I want that example to be functional on the emulator ( with a fixed GPS Coordinate ) and on a phone 7 device - where it actually grabs the value.
GetGPS location1= new GetGPS();

//GeoCoordinate myPosition = location1.getPosition();

//Radianten berechnen
double lat1Rad = GradZuRad(location1.Position.Location.Latitude);
double long1Rad = GradZuRad(location1.Position.Location.Longitude);

I basically just want to program a class which returns me the CURRENT GPS Position.
Answer: Why are you deriving frmo GeoCoordinateWatcher? That's a mistake, IMO. It makes it unclear when you're using the members of your own class and when you're using the delegated instance. At the moment you're setting the coordinates on the delegated watcher, but then asking for the coordinates from the GetGPS instance directly.
I suggest you implement IGeoPositionWatcher<GeoCoordinate> with your own "fixed" position watcher - and then decide at execution time whether to use that or the real GeoCoordinateWatcher. Obviously this means your client code should only depend on IGeoPositionWatcher<GeoCoordinate> instead of GeoCoordinateWatcher directly. This should also help for unit testing purposes.
Answer: Where is your example code from?
Have you tried using the sample on MSDN?
Alternatively, there's a greate simulator available from http://phone7.wordpress.com/2010/08/02/no-device-no-gps-no-matter-with-code/
Comment: I have looked at the MSDN Example - but I could not comprehend it. I've tried the simulator and got it to work, but I would like to have either a static GeoPosition - or the acutal GPS GeoPosition.
Answer: Of course Jon's answer is very apropos - I think you've not done reasonable interface abstraction, but even when you get that, for simulated data have you taken a look at Kevin Wolf's GPS Simulator for Windpws Phone?
Comment: I've found an example from some MvP it's the following:

            GeoCoordinateWatcher location1 = new GeoCoordinateWatcher();
            var myPosition = location1.Position;

            double latitude = 54.086369f;
            double longitude = 12.124754f;

            if (!myPosition.Location.IsUnknown)
            {
                latitude = myPosition.Location.Latitude;
                longitude = myPosition.Location.Longitude;
            }

that might work, or?

Getting GPS Coordinates Windows Phone 7


How to get the name of a file as a "string" without the path (to compare with other strings)

Question: I'm trying to get the name of a file in php, but I'm iterating through an array of files so I don't have the exact path... unless there is a method inside the file that returns the name of the file (or the path, in which I can use basename()), which I haven't been able to find. My code looks like this:
foreach ($myfiles as $myfile) {
  // Get name of $myfile here. (Technically as a string)
  if ($myfilename == "Something) {
    // Do something
  }
}

I am trying to find the name of the file ($myfile) so I can manipulate it as if it were a string.
Getting the name of file in PHP is not what I'm looking for, as all the answers imply you have a path, which I do not.
Basically the php equivalent of Java's: File.getName()
Thank you.
Comment: Is [`basename()`](https://www.php.net/manual/en/function.basename.php) what you're looking for?
Comment: What's inside `$myfiles`. An 'array of files' doesn't really make sense.
Comment: @Barmar `basename()` takes a path parameter. I don't have the path, just the file as a file. @Evert `$myfiles` is a list of files in a directory. It iterates through the list of files `as files`, not as their names. I'm trying to get the name of `$myfile`.
Comment: What do you mean by "an array of files"? Are they file handles returned by `open()`? The Java function you mention works on open files. If that's what you have, I don't think PHP has an equivalent function.
Comment: When I say an array of files, I mean all of the files in a given directory put into an array. I just am trying to get the name of `$myfile`.
Comment: You have not shown us what is in `$myfiles` (or even how it is declared).
Comment: _"I mean all of the files in a given directory put into an array. "_ - put into an array _as what_? A "file" is an abstract entity, you need to explain what exactly your array contains. List of file _names_, so just strings? Some sort of file _entity_, some class instance that has been created based on the directory entry, to encapsulate some properties of the file, and maybe provide additional methods?
Answer: Do you need like this?
$file = fopen("File.txt", "r");
// $filename = $file->name; // no way

There is no method for PHP.
Try this way:
<?php

$myfiles = [];
$files = ['fileA.txt', 'fileB.txt'];

foreach($files as $filename) {
    $myfiles[] = ['file' => fopen($filename, "r"), 'filename' => $filename];
}

foreach ($myfiles as $myfile) {
  if ($myfile['filename'] == "Something") {
    // Do something
  }
}

?>

Answer: The method that you are looking for is pathinfo.
It returns an array with information about the file, the filename index has the name of the file.
Comment: Read the question, I don't have the path.
Comment: It's not required to have the path, just the filename is enough. See the examples returned by the function in the docs linked, if it helps.


How to add text inside <> tags using builder?

Question: So I am trying to build an XML document for export. But I need to add extra text inside the headers and can't figure out how.
def as_xml
  require 'rubygems'
  require 'builder'

  builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2)

  xml = builder.propertyList { |b|
    b.description(self.description);
    self.highlights.each do |h|
      b.highlight(h);
    end
  }
end

returns:
<propertyList>
  <description>"Description goes here"
  </description>
  <highlight>Highlight 1</highlight>
  <highlight>Highlight 2</highlight>
</propertyList>

Is there a way to make it so that I can add an ID attribute to the highlight tags?
Such as <highlight id=1>, etc.
Also wondering if there a way to define whether or not a tag should be self-closing using builder?
e.g.:
<auction date=self.auctionDate />

Answer: You can pass in attributes as a hash for the secondary argument:
self.highlights.each_with_index do |h, i|
  b.highlight(h, id: i+1);
end

=> <highlight id='1'>Highlight 1</highlight>
=> <highlight id='2'>Highlight 2</highlight>

And if you pass only a hash, you can get a self-closing node:
b.auction(date: 'someDate')

=> <auction date='someDate' />


In blues, country blues, why don't songwriters get sued for aping the same progressions/tempos/scales as other established blues songs?

Question: Thought: As a guitar player, you can play the blues in pretty much any scale, A for instance with stock rhythms and endings.
Example: You write a song in that scale you may even use the same solo runs as other more famous blues artists. You release your song on the radio list it with a Performing Rights Organization and no one cries a foul of your blatant usage of chords/performance or solo runs that lift directly off of other more famous artists. But yet if someone in another genre does this, say for example, the ColdPlay vs Joe Satriani/Cat Stevens or even Led Zeppelin in their lifting of riffs and lyrics from old blues folk rile up the copyright demons and cries of plagiarism. Why didn't Cat Stevens sue Joe as well?
Question: Where does the line between what is acceptable to call plagiarism and musical "style" come in to play? I would rather like this to be discussed from a non-financial place and a more creative artist stance without regard to lawyers. Maybe it is just a legal matter I don't understand?
Comment: Don't go giving the "MAFIAA" any ideas.  It's bad enough as it is.
Comment: Oh noes. How will Tom Petty eat?
Comment: In regards to the creative/artistic stance I believe that you're observing a feature that comes from the original, word-of-mouth, tradition for these styles.  A tradition where imitation was more often considered flattery rather than theft, and where the idea of connecting with established traditional material and then (slightly) modifying it to make it your were integral to the style/genre;  however I'm not enough of a musicologist to back this up.
Comment: good artists copy; great artists steal.
Comment: *Who exactly* would have legal standing to sue someone over such an infringement? If you bring a lawsuit, the judge asks you to prove that you have standing to sue, meaning that you own something that somebody else is stealing. Nowhere does "the law" *prosecute* someone for plagiarism or copyright infringement. The party who owns something has to bring a lawsuit against someone that they allege is stealing something from them. Nobody would have legal standing for the kind of lawsuit you are envisioning.
Comment: @CarlWitthoft LOL!
Comment: seriously I heard a country "HIT" song plagiarize Tom Petty's free falling melody and chords, yet the guy is getting $200k checks for it...ugh
Answer: I think there's an element of pragmatism to this. Some people are out for what they can get, but they also have an eye on what they could lose.
Let's say you wrote Stack Exchange Blues, you're collecting royalties from it, and you hear my song Downvotes Got Me Cryin', which you believe steals enough to perhaps warrant a law suit.
Well, you're going to have to consider: do you think Stack Exchange Blues stands up to close examination. Might my lawyer argue that your song is actually a rip-off of something else -- leaving you exposed to the risk of being sued by the owner of that song?
Or might he say "Sure, my client's song has the same chords as Stack Exchange Blues, but that chord sequence is shared by these 100 songs, some dating to Victorian times"?
So, if your song sounds like something else that's unique, you could be accused of plagiarism. If your song sounds like a thousand other songs, you're clear.
Comment: Those are some funny song titles, Slim. Good response.
Answer: To answer the question: "Where does the line between what is acceptable to call plagiarism and musical "style" come in to play?" I have to say that unfortunately, pragmatically, it comes down to what you as a plaintiff can prove in court. It really does come down to the law.
Disclaimer: I am not a lawyer, and I am not giving any legal advice, which in any case would meet different requirements under the laws of different nations.
The over-simplified answer is that a melody is copyrightable, and a lyric is copyrightable, whereas a chord progression is not copyrightable and the finer points of an arrangement are not copyrightable either.
Anyone can register a copyright on a song or piece of music. If that person believes that someone else has infringed on their copyright, it is up to that copyright holder to sue the other party and to try to prove in court that copyright infringement has occurred. To do so successfully, the copyright holder would have to prove several things, among them that the plaintiff's piece holds a valid copyright that has not expired, that the piece copyrighted was unique, that the defendant had copied the characteristics of the plaintiff's copyrighted piece to a degree that constitutes infringement in the opinion of the judge or jury, and also to prove that the defendent must have heard the plaintiff's copyrighted song before the defendant wrote the song that it is alleged had infringed on the plaintiff's copyright.
If there are indeed hundreds of different copyrighted blues or country songs in the world with the same chord progression and song structure, then a plaintiff cannot successfully prove in court that someone else has infringed on his one copyrighted song with regard to the chord progression and song structure alone. The defendant would successfully argue that they were copying the characteristics of many songs, but not the specific song they were being sued for that day.
In other words, if you assert that you have a copyright, you have to defend it yourself in court with your own lawyers and your own money. The burden is on you to prove that what you have is entirely unique and a specific person has infringed upon the entirely unique characteristics of your property in a distinct way, and that neither you nor the other person got your ideas from anywhere else.
The outcome of this, over many years of court trials all over the world, and reflected in the writing of laws all over the world, including international copyright treaties, is that it is easy to prove that a melody or lyrics are distinct and defendable in court. However, generally, things like a chord progression, a song structure, and a rhythm, all by themselves and not in conjunction with a certain melody or lyrics, are not things that can be asserted in court to be copyrightable. Nobody could win a case with that.
Comment: Nice answer. BTW, in the jazz world it's very common for musicians to take the chords of a pop song, get rid of the words and melody, and create a new jazz song out of it. Also, when a song is originally created as a jazz composition, it's common for other jazz musicians to use the chords, eliminate any words or melody, and record it under a new title without credit to or royalties paid to the original author of the chord progression. A classic example of this is Coltrane's "Giant Steps." This is not considered plagiarism. It's a normal practice in jazz.
Comment: I like this answer, but it oversimplifies with the suggestion that the chords of a song are not subject to copyright. That's often true, but not true in general. International copyright law does not simply put lyrics and melodies in one column, chords and rhythms in the other.
Comment: Yes, @MarcksThomas, you are correct. But when a composer registers a copyright, it does not mean that a court has judged that the piece is unique. It just means that there has been a record that a piece has been registered for a copyright. It still all comes down to the plaintiff's ability to convince a judge and a courtroom that he holds a copyright that has been infringed upon by a defendant. And generally, at least in the United States of America, where I live, a chord progression in the absence of a melody does not hold up in court as grounds for infringement.
Answer: This is an interesting summary of the whole George Harrison My Sweet Lord/He's So Fine plagiarism case, with some discussion of the legal issues involved: http://abbeyrd.best.vwh.net/mysweet.htm
Of course, there are many examples of legal plagiarism of classical tunes.  To name three: "I'm Always Chasing Rainbows" was taken from the middle of Chopin's "Fantasie Impromptu", the piano lick in Barry Manilow's "Could it Be Magic" is part of Chopin's C Minor prelude, and "Groovy Kind of Love" is nearly identical to the Rondo in Clementi's G Major Sonatina.
Comment: Well, plagiarism is different from copyright.  The old melodies are out of copyright, so you can use them any way you want.  All the same, IMHO Emerson,Lake,&Palmer are guilty of gross plagiarism because they fail to give authorial credit to Janacek  and others for nearly every tune on their first album. In fact, they list themselves as the composers, which they certainly aren't.  Meanwhile, the Anacreontic Society is planning a lawsuit against the USofA over a certain National Anthem :-)
Comment: So there is a concept of "legal" plagiarism? I guess this might point out that people have always repeated popular melodies through the ages but in modern times there is this "commodification" of melodies that was not present in earlier societies?
Comment: But I should point out that we don't use your term of "legal plagiarism". We call it "adapting something that is in the public domain". It is not considered plagiarism if everyone knows what the source is, and no copyright is being violated. This is a legitimate technique in songwriting and music composition.
Comment: Yes, certainly. "Legal" plagiarism involves copying something from a song that is **in the public domain**, meaning that it is so old that it cannot be copyrighted, or if it once had a copyright, said copyright has expired. Songwriters and composers do this all the time, and it is legitimate.
Comment: Basically anything written before about 1920, anywhere in the world, is **in the public domain** and can be freely adapted into new compositions. This is an important concept.
Comment: I'm also a little puzzled by your comment about "commodification that was not present in earlier societies". The reality is the opposite. For centuries, composers have *always* "borrowed" material from other composers. However, it is only in the *most recent* 100 years or so that there has been a legal framework for copyrighting of music that enabled people to sue for damages for infringement, and only in the last 100 years or so that there has been a concept called "in the public domain" for songs.
Answer: Folk, country and blues draw on what is called "the oral tradition". Song "families" have always been part of the oral tradition, and building on -- even re-using -- pre-existing harmonic/melodic structures was/is common practice in those genres. Artists in those genres just kind of "get" that's the case. In the oral tradition, there was no concept of ownership. The idea of ownership is a relatively recent one.
Comment: There is the possibility that a traditional song may be copyrighted later. A famous example is "Happy Birthday to You" that was copyrighted in 1935 despite it being based on earlier works.
Comment: Any time you make a substantially new arrangement or version of a traditional song in the public domain, you can copyright your new version. That is permissable under international copyright law.
Answer: This is a complicated topic, but I think it all boils down to conditioning and what listeners like to hear. There are many ways to harmonize a melody, yet most people use predictable chord progressions because they're easy to follow, work with, and understand.
Jazz is a form of music that is very alienating to non-musicians. I'm certain there are countless people that are not musicians that claim to like jazz, but nonetheless jazz is harder for non musicians to appreciate. Even in the complexities of jazz there are still patterns and a sense of predictability, but their harmonies are more complex and thus may be harder for people to enjoy.
Chord progressions such as the I IV V and ii V I are commonly used because people like to hear them. We could harmonize the tunes that use these progressions in countless ways, but then we have to worry about how much dissonance we introduce. I think that the use of chord progressions are pretty much out of the realm of being considered plagiarism.
I think it is plagiarism when a melody is almost a complete copy of another melody. I have heard countless songs that are rip off's yet they are not considered plagiarism. Take Sublime's "What I got"  vs. The Beatles "Lady Madonna". Obviously The Beatles are better and Sublime's song is not good, but nonetheless there are glaring similarities in the melody.
Inevitably two composers will arrive at similar or perhaps even the same melodies. Plagiarism fights usually go on when a composer feels that the other person listened to their song before composing the accused work. There are standards and even generic riffs that seem like they're free for the public to use. Such as blues progressions, bass riffs, etc. Again, main melodies are usually the tipping point for plagiarism.
Comment: I read that Joe Satriani stresses that his motives are ruled by artistic purity and an overriding sense of right and wrong. But if that were the case he would have to concede to ripping of Cat Stephen's "Foreigner Suite" from 1973 in melody as well.
Comment: I like your answer minus the opinion based "Obviously The Beatles are better and Sublime's song is not good, but nonetheless there are glaring similarities in the melody."  Doesn't add anything to your answer's validity and in some cases (like anyone who likes Sublime) it would detract from it.
Answer: There are law-based answers to this question, but the laws about music had to be constructed around the preexisting musical culture. Ultimately the reason you don't get sued for copying a chord progression probably has to be explained in terms of the reasons why chord progressions are not considered as unique and individualistic as melodies. Here are three such reasons:
(1) A chord progression is more arguably a form, while a melody is more arguably a composition. If someone asks you to explain the sonata form or the 12-bar blues form, you're not going to be able to explain it without explaining how the chords create the foundation of the form.
(2) There are theoretically infinitely many possible chord progressions, just as there are infinitely many melodies. But in reality chord progressions aren't really as varied. For example, some huge number of musical compositions consist of I-V-I-V-I-V-I... In a harmony course, they teach you certain rules about harmonic progression, and those rules aren't really prescriptions but descriptions of things that composers in the past seem to have done, because they worked well. There are infinitely many other things you can do with chords, but they generally don't work as well.
(3) Chord progressions can be blurred by various chord substitutions, added tones, suspensions, etc. A jazz musician might recognize a certain piano accompaniment as being based on the chords of "I Got Rhythm" or "Giant Steps," but to the average person, or even to a professional musician who's not a jazz musician, there might be no resemblance at all. (I had a harmony teacher once who ridiculed a jazz musician's claim that the notes D, G, and B could be a voicing of a C chord...with the root and third omitted and an added M7 and 9.)
Answer: For blues specifically :
A good percentage of blues follows the same chord progression (good ol' 12-bar) and a LOT follow very similar paths with melody, riffs, bridges, and lyrics.
Why don't they all sue each other ?
The problem would be identifying who did it first. The 12-bar progression is thought to have eminated from African slave/chain gangs, meaning there's no single "owner" and the blues style of singing gives rise to a lot of similar melodies meaning it's hard to identify who 'invented' it - if any one person ever did.
As for lyrics .. Who woke up earliest this morning ...
This doens't apply to other genres so much (eg Coldplay vs Satriani) because they're not so much following a traditional way of making a tune (blues); they're coming up with their own traits and so I guess it's easier to identify one tune from another, and easier to stake a claim on a particular sequence of melody etc.
This makes it sound like I'm saying "all blues sounds the same" - I'm not because a lot goes into the feel of the song of course, but essentially 12 bar blues is one chord sequence served up in a zillion songs, and no-one knows who did it first.
Answer: To answer the OP question of 'In blues, country blues, why don't songwriters get sued for aping the same progressions/tempos/scales as other established blues songs?'
Progressions, tempos and scales are tools to use to express a musical thought that we all use. The melody and combination of chords with rhythmic patterns are the work of these tools and therefore a creation of the author.
Answer: I think DougusMaximus came the closest to the real answer. Being a rock musician (and especially for guitar players), just about the first "whole song" chord progression one learns is the "12 bar blues". Written by... well, no one.  There is no copyright or ownership on it, because it has been around for so long, no one knows who to give first credit to it for, and basically anyone/everyone is able to use it whenever they feel like it. Now if you start deviating from the "standard" 12 bar blues chord progression, and you deviate enough, and your deviation is exactly like someone else's deviation, then there MIGHT be a problem.  But generally, in blues/rock/country or any genre of music really, if it sounds exactly like or close to the standard 12 bar blues progression (look that up to see what the actual chords are), then there will not be a problem. From a music composition standpoint - obviously lyrics become a whole other matter.
Answer: I'm a blues guitarist/singer and I think that suing someone for plagiarism on a melody I might have come up with in a song is somewhat pointless. First of all when I play the 12 bar chord progression say in the key of A, then I can use most notes in the pentatonic scale in that same key to solo over it or construct a melody line for the lyrics.
My point is : who am I to deny another artist the use of the same notes that I do over a similar 12 bar blues in the same key? There is no way I could claim any of those notes as uniquely mine since they simply belong to that specific scale and anyone is free to use them in any order they see fit.
To me the music is a vehicle to get the story of the song across, to support and underline the emotion of it and the only thing I feel could be subject to copyrights would be the actual lyrics that tell that story.
I feel that almost anything you can come up with ( in blues as well as any other style of music) has been pretty much done before many times over in one form or another. This whole copyright madness is all about 1 thing only: money..  nothing else.
If I were to sue someone for publishing a song that very closely resembles one of mine and demanded part of the money he/she earned with it, well that would as stupid as suing my neighbour for doing the same daytime job as I do, using the same tools, driving more or less the same pickup and wearing the same work clothes and demand they pay me part of their earnings for copying my way of generating income.
Someone like SRV played a lot of other peoples songs, played 'em in his own unique way but always acknowledged the original artists and never claimed their songs to be his own. And by doing so gained a lot of respect and still made some decent cash. Put the love of music before the money, after all that's what it should really be about.
Comment: walloftextishardtoread… not does this answer the question, it's more of a rant or a blog post.


Maximum of sum of fractions with tans

Question: Let $ABC$ be an acute triangle. What is the maximum value of
$$\frac{\tan^2A+\tan^2B}{\tan^4A+\tan^4B}+\frac{\tan^2B+\tan^2C}{\tan^4B+\tan^4C}+\frac{\tan^2C+\tan^2A}{\tan^4C+\tan^4A}?$$
For the equilateral triangle, $\tan A=\tan B=\tan C=\sqrt{3}$, and the sum is $1$. For the isosceles triangle with $\angle A=\angle B\rightarrow\pi/2$ and $\angle C\rightarrow 0$, the sum approaches zero.
Comment: The sum also approaches 1 when
$\angle A=\angle B\rightarrow \tfrac\pi4$ and $\angle C \rightarrow \tfrac\pi2$.
Answer: Say $x= \tan A$, $y= \tan B$ and $z = \tan C$. It is
well-known that $x+y+z=xyz$. Then we have $$E = {x^2+y^2\over
x^4+y^4} +{y^2+z^2\over y^4+z^4} + {z^2+x^2\over
z^4+x^4}$$
By Cauchy inequality and then by $AM-GM$ we have
$${x^2+y^2\over x^4+y^4} \leq {2\over x^2+y^2}\leq {1\over xy}$$
So $$ E \leq {1\over xy} +{1\over yz}+{1\over zx} = 1$$
We get equality exactly when $x=y=z$, thus $3x=x^3 \Longrightarrow  x=\sqrt{3}$.

Maximum of sum of fractions with tans


What are the Steps to Translate the Current Search Block and Facet Search block(s)

Question: I have been unable to configure things such that the Current Search Block or Search Facet block(s) have their strings show up in the Translation tool at :

admin/config/regional/translate/translate

They are however available in options in the translation tools filter

I do have Facet API Translation installed
I have tried refreshing String translations at:

admin/config/regional/translate/i18n_string

And I have tried specifying the blocks as translatable on their respective blocks configuration forms (the form states that because the module is responsible for the content of the block that only Title translations are possible ... this is obviously not what I need to do to translate the blocks contents)
What are the Steps required to Translate Facet Search Block(s) and Current Search Block ?
Answer: I was able to solve this issue; however not in an ideal way:
see: https://drupal.org/node/1478908
see: https://drupal.org/node/1387504
see: https://drupal.org/node/1376786
see: https://drupal.org/project/facetapi_i18n
By implementing hook_block_view_alter and passing pieces of the markup to the translation function.
function MY_MODULE_block_view_alter(&$data, $block) {
    if($block->module == 'current_search'){
            $original_markup = $data['content']['results']['#markup'];
            $original_filtered = strip_tags($original_markup);
            $results_count_int = filter_var($original_filtered, FILTER_SANITIZE_NUMBER_INT);
            if($results_count_int){
                    $new_text = t('Search found @count item(s)', array('@count' => $results_count_int));
                    $new_markup = "
$new_text
";
                    $data['content']['results']['#markup'] = $new_markup;
            }
    }

}
Comment: hi @SMTF, can i see where did you implement this. thanks.


How do i get a transparent background after rotaing a png image with php?

Question: So I have png image and I rotate it but i get a black background..  or if i do the color code ofr white i get white..  I tried doing this..
$trans = imagecolorallocatealpha(image, 0, 0, 0, 127);
imagerotate($image, $degree, $trans)

i have also tried..
$trans = imagecolorallocatealpha($image, 255, 255, 255, 127);

Can someone help me out?
here is my code..  if i change allocatealpha to 0, 0, 255, 0 then it goes blue.  but with 0, 0, 0, 127 its still black.
function rotate($degrees) {
    $image = $this->image;
    imagealphablending($image, false);
    $color = imagecolorallocatealpha($image, 0, 0, 0, 127);
    imagefill($this->image, 0, 0, $color);
    $rotate = imagerotate($image, $degrees, $color);
    imagesavealpha($image, TRUE);
    $this->image = $rotate;
}

Comment: Does the original code use `image` instead of `$image` like here?
Comment: yea they original code uses $image
Answer: $destimg = imagecreatefromjpeg("image.png");
$transColor = imagecolorallocatealpha($destimg, 255, 255, 255, 127);
$rotatedImage = imagerotate($destimg, 200, $transColor);
imagesavealpha($rotatedImage, true);
imagepng($rotatedImage,"rotated.png");

As per the correct comment below, this should be:
$destimg = imagecreatefrompng("image.png");
$transColor = imagecolorallocatealpha($destimg, 255, 255, 255, 127);
$rotatedImage = imagerotate($destimg, 200, $transColor);
imagesavealpha($rotatedImage, true);
imagepng($rotatedImage,"rotated.png");

Comment: "imagecreatefromjpeg("image.png")" should be "imagecreatefrompng("image.png")"
Answer: Make sure you set imagesavealpha to TRUE in order to preserve transparency. http://www.php.net/manual/en/function.imagesavealpha.php
imagesavealpha($image, TRUE);
Answer: Have you tried this?
imagecolortransparent
Hope i understood your question!
Comment: @Great to hear!! Remember to check on one answer as the correct on! (Doest have to be mine but the one that most helped you out)
Comment: Yea I found it didnt actually work.  It was just a white background so it appeared that way so i still looking for an answer.  Thanks for showing me that function though!
Answer:         // Turn off transparency blending (temporarily)
        imagealphablending($image, false);

        // Create a new transparent color for image
        $color = imagecolorallocatealpha($image, 0, 0, 0, 127);

        // Completely fill the background of the new image with allocated color.
        imagefill($image, 0, 0, $color);

        // Restore transparency blending
        imagesavealpha($image, true);

Comment: Ok so I lied that imagecolortransparent isnt working it just looked like that because of a white background..  I tried this way again and I know it works because i can change the background to blue and red etc etc but when I mess with the alpha channel all it does make it transparent to black.. for example if i have the allocate like this.. 0, 0, 255, 75 it just makes a darker shade of blue as if it makes the blue transparent but there is a black color behind it
Answer: You can try this: http://www.exorithm.com/algorithm/view/rotate_image_alpha
Answer:     $info = pathinfo($pathToImage);
    $name = str_replace("." . $info['extension'], "", $info['basename']);

    $size = getimagesize($pathToImage);

    $type = isset($size['type']) ? $size['type'] : $size[2];

    // Check support of file type
    if (!(imagetypes() & $type)) {
        // Server does not support file type
        return false;
    }

    $source = self::imageCreateFrom($pathToImage, trim($info['extension'])) or notfound();
    $transColor = imagecolorallocatealpha($source, 255, 255, 255, 127);

    // $transparency = imagecolorallocatealpha($source, 0, 0, 0, 127);
    $rotate = imagerotate($source, 360 - $rotate_angle, $transColor);
    //imagealphablending($rotate, false);

    imagesavealpha($rotate, TRUE);
    //imagejpeg($rotate,$pathToThumbs.DIRECTORY_SEPARATOR.$info['basename']);
    self::createImage($rotate, $pathToThumbs, $info['basename'], trim($info['extension']));

    // imagejpeg($rotate);
    imagedestroy($source);
    imagedestroy($rotate);

Answer: This is what I am using, this work great for .png files with transparent backgrounds. High fives!
function rotate($degrees) {

    // Switch from default counter-clockwise to clockwise
    $degrees = 360 - $degrees;

    // Get the image
    $source =  imagecreatefrompng("images/image.png");

    // Rotate the image
    $rotated_image = imagerotate($source, $degrees, imageColorAllocateAlpha($source, 0, 0, 0, 127));

    // Save the rotated image
    imagepng($rotated_image, 'images/rotated_image.png');

}


Azure Universal Package Versioning

Question: We're building out binaries and publishing them over in an Artifact feed in Azure Devops. Our current versioning scheme is using SemVer2.0 with the three part version (x.x.x), we wanted to place some tag on versions (e.g. 1.0.0-beta) but when downloading the universal packages using a wildcard version ( * ) we get an error saying the version doesn't exist.
Is placing version suffixes supported in Azure DevOps universal package? Or is there a way to tag a certain version as a beta release or alpha release.
Answer: You can use views for exactly this purpose, if my understanding is correct.
By default, your feed will have 3 views: @local, @prerelease and @release. You can rename the views, change the default view and add additional views in feed settings (the cog icon on the right) - Views

You can then promote your packages to the appropriate view and use that information to trigger a release or to download the specific version that was promoted (at least in a pipeline you can use this as a 'filter' in the Download package task). The below example is of a UP as a release pipeline trigger:

In this example I'm actually trying to trigger the same pipeline in 2 different cases (promotion of the package to either @prerelease or to @release should both trigger the pipeline, but the subsequent logic in the pipeline should be different). I'm still not sure this is actually possible, which was the initial reason why I was reading your question. I'll probably create a separate question for that specific topic.

Azure Universal Package Versioning


Xcode, can't remove "Launch image" from project

Question: I am playing with my Xcode, following tutorial, learning this stuff. I added an image to "Launch Images", rebuilt my project, it showed up.

I removed the image, rebuilt my project .... image still flashed before app started
I deleted my project, redid my project, this time with no image, launched the app and voila ... image is still there?
I reset simulator counters and settings ... same issue

Is there a permanent location where this file can be removed from? Is there a cache that needs to be reset etc?
Please let me know.
Answer: iPhone Simulator caches stuff. Try a clean build, or actually deleting the app from the simulator (by holding down on a home screen icon until it wiggles, then X-ing it).
Comment: The same goes for the device - if you don't delete the app from the device before deploying a developer build onto it, the old files remain in place.
Comment: Indeed this was the issue. Thank you
Comment: Was beating the wall with my head on this one.  Delete the app from the device, Product > Clean got it for me.  Thanks Inspire48 & Jim!
Comment: in xcode 7.3 i also had to reboot my device. any uiimage i change in the launch screen storyboard wouldn't update from the old one to the new one.
Answer: With the project open Goto xcode > Product > Clean
Answer: Navigate to the project folder, go to Resources folder and delete the folders called splash and icon (do this from both from Xcode and Finder). Also delete the app from either the device or the simulator by pressing on it and x-ing it out then go to Product->Clean.
I know this was very painful, but now you can set the new icons and launch images from Xcode.
Good luck.
Answer: Check that the image is not in the project folder anywhere, also ensure that in the info.plist there is no value relating to launch image.
Comment: The only image in place is the icon image and it's different one from the one flashing. Checked directory structure as well - no image in question
Answer: Are you looking for an image named "Default.png" (or whatever suffix)?  When assigning an image to the default launch, Xcode makes a copy and renames it "Default".


Meta-analysis with zero values for mean difference and s.d

Question: For a meta-analysis, means and s.d. for the experimental and control groups were required to calculate the mean difference (MD or yi) and variance (vi) of each study with the escalc function of metafor.
In some studies, s.d. needed to be back-calculated from reported p-value and n in experimental (ne) and control (nc) groups (no dispersion measures available).
A problem arise when MD tends toward zero or is null (p-value is always not significant). In such cases, back-calculated s.d. also tends toward zero because MD is the numerator in the formula (see http://handbook.cochrane.org/chapter_7/7_7_3_3_obtaining_standard_deviations_from_standard_errors.htm)
Indeed, very small or null s.d. are not valid when p-value is not significant. Moreover, inclusion of a study with null s.d. in a dataset leads to a warning message in rma.mv: there are outcomes with non-positive sampling variances; and the model doesn't solve.
My question: one approach would be to exclude all studies where back-calculated s.d. is very small or null due to small or null MD. However, these not significant studies contribute to the overall knowledge and should be included somehow in the meta-analysis.
Or should a s.d. be imputed to these studies; e.g., the mean s.d. of the other not significant studies where s.d. could be computed from a dispersion measure (e.g., sem or sed).
Or something else?
Comment: If the difference is not significant I would expect the standard error (and hence standard deviation) to be large, not small. Can you show us a concrete example of what is going on?
Answer: Without an example of how you are doing it, it's hard to say. I coded up a toy example for myself in R to see what was happening. I could find no values of the mean difference or sample size that would reproduce your problem. Here is some code that you can play around with to confirm that you are doing your calculations correctly.
<code>#back calculating a standard deviation
set.seed(1423)
#data
N = 20 # sample size of each group
truemeandiff = 0.01
# two samples
x1 = rnorm(N, .01, 1)
x2 = rnorm(N, .01-truemeandiff, 1)
meandiff = mean(x1-x2)
(se <- sqrt(var(x1)/N + var(x2)/N))
</code>

> 0.3222331

<code>#getting two tailed p-value
z = meandiff/se
(pval.z <- 2*(min(1-pnorm(z), pnorm(z)))) # z-test p-value
</code>

> 0.8910154

<code>(pval.t <- t.test(x1, x2, var.equal=TRUE)$p.value) # t-test p-value
</code>

> 0.8917388

<code>#back calculating standard deviation from z-test(two-tailed p-value)
abs(meandiff/qnorm(pval.z/2))/(sqrt(1/N + 1/N))
</code>

> 1.01899

<code>#back calculating standard deviation from t-test (two-tailed p-value)
abs(meandiff/qt(pval.t/2, N+N-2))/(sqrt(1/N + 1/N))
</code>

> 1.01899

<code># actual standard deviation
se/(sqrt(1/N + 1/N))
</code>

> 1.01899

Edit: based on the discussion to this answer, you are putting in 0 values for SD, which is not a valid approach to this. A better approach is to back calculate with a substitution of a small non-zero value for the mean difference, as here:
<code>#true mean difference is zero
x1 = rnorm(N, .01, 1)
x2 = x1
(meandiff <- mean(x1-x2))
#meandiff=0.0001
(se <- sqrt(var(x1)/N + var(x2)/N))

#getting two tailed p-value (works as long as the p-value is not rounded to 1)
fudge = 0.0000001 # making the mean difference small
meandiff = meandiff + fudge
z = meandiff/se
(pval.z <- 2*(min(1-pnorm(z), pnorm(z)))) # z-test p-value
(pval.t <- t.test(x1, x2-fudge, var.equal=TRUE)$p.value) # t-test  p-value

#back calculating standard deviation from t-test (two-tailed p-value)
abs(meandiff/qt(pval.t/2, N+N-2))/(sqrt(1/N + 1/N))
</code>
1.19729
<code># the true sd
se/(sqrt(1/N + 1/N))
</code>
1.19729
Comment: Calculations were correct. However, I am doing a meta-analysis on a dataset of 81 studies. In 12 studies, SD was back-calculated from p-value. Mean difference = 0 and sd = 0 if means of experimental and control groups are the same because meandiff is the numerator in abs(meandiff/qt(pval.t/2, N+N-2))/(sqrt(1/N + 1/N)). Indeed, sd should be large for not significant MD (or MD=0). Inclusion of a single study with sd=0 doesn't solve with rma.mv of library(metafor).
Comment: Here is an example:
Comment: Example1:
study m1 n1 sd1 m2 n2 sd2
1 10 5 2.5 15 5 2.5
2 11 10 3 16 10 3
3 12 8 2.2 13 8 2.2
4 13 7 4 15 7 4
5 14 6 3 14 6 3

example1.md <- escalc(m1i=m1, sd1i=sd1, n1i=n1, m2i=m2, sd2i=sd2,n2i=n2, measure="MD", data=example1, append=TRUE, digits=4)
m1 <- rma(yi, vi, method="ML", data=example1.md)
summary(m1, digits=3) # results are okay
m2 <- rma.mv(yi, vi, method="ML", random = ~ 1|study, data=example1.md)
summary(m2, digits=3) # results are okay
Comment: Sorry, I tried to include a table of studies but it did not work. There was 5 studies and id of study (1 to 5), means, sd, and n for group 1 and 2 were given in sequence. In any study, if you replace the reported sd1 and sd2 by 0, rma function will not produce I^2 and H^2; and rma.mv will not solve.
Comment: Look up dump files for how to give data for working examples with R data.
Comment: It looks to me like you are giving values of SD=0 to the function that calculates effect measures. I don't see anything in the documentation for  that says anything about filling in correct values of the SD. You can use my code to calculate that from the p-values and then put those in your data instead of '0.' This is more of a coding than stats question, since it looks like you just need to understand more about what R is doing under the hood.
Comment: You say you have the sd and then you say you have overwritten them with zeroes. Why did you do that?
Comment: This was just an example with 5 studies for illustration purposes. When sd in studies is different from zero, rma.mv works fine. If one study has sd=0 for both groups, then rma.mv doesn't solve. In the fifth study, means were equal at 14, so MD=0. If sem is reported for this study, I can back-calculate a sd different from zero. If only p-value is reported and it sure will be not significant as MD=0, then sd are also 0 according to back-calculation formulae (because MD is the numerator). Thanks for your help. I hope it helps.
Comment: I see. See updated answer.