text:
Q: How to disable first option in an Ember.js select menu I'm pretty new to Ember, and I'm loving it so far! However, I feel like I've lost a little bit control over some of my HTML elements, in particular the <select> menu and it's <option>s.
I'd like for the default (selected) <option> to be disabled as well, i.e. have the attribute disabled. I'm used to this approach for setting a "placeholder" on select menus, but I'm up for other suggestions as well.
For example, if I had a select menu for gender, I'd want to end up with this piece of code:
<select>
  <option selected disabled>Please select gender</select>
  <option value="m">Male</select>
  <option value="f">Female</select>
</select>

I have the following JavaScript and Handlebars code:
JavaScript
genders = [
  Ember.Object.create({value: 'm', label: 'Male'}),
  Ember.Object.create({value: 'f', label: 'Female'}),
];

App.GenderSelect = Ember.Select.extend({
  contentBinding: "genders",
  optionValuePath: "content.value",
  optionLabelPath: "content.label"
});

Handlebars
{{view App.GenderSelect prompt="Please select gender"}}

Generated HTML
This gives me almost the code that I want. However, the first <option> is missing the disabled attribute, hence this question.
<select>
  <option value>Please select gender</select>
  <option value="m">Male</select>
  <option value="f">Female</select>
</select>

Also, it doesn't set the selected attribute, but that's not strictly necessary, because it is the first option in the menu.
I appreciate any answers, both direct answers to this question and valid suggestions for using some other approach than disabled.
Thanks in advance!

A: That HTML is hard-coded into the template and there's no brain-dead simple way to do it.
That said, you can subclass Ember.Select with the following
didInsertElement: function () {
    this.$('option:first').attr('disabled', true);
}

You could also use the layout property to insert the placeholder manually above the auto-rendered options:
layout: precompileTemplate("<option selected disabled>Please select gender</option>{{yield}}")

Seeing as that would also require a subclass, I think it wiser to use didInsertElement.

A: This answer shamelessly leverages @ChristopherSwasey's answer, but will affect all Ember.Selects globally that use the prompt attribute.
Ember.Application.initializer({
    name: 'ember-select-with-nullprompt',

    initialize: function(container, application) {
        Ember.Select.reopen({
            didInsertElement: function () {
                if (this.prompt)
                    this.$('option:first').attr('disabled', true);
            }
        });
    }
});


text:
Q: Group by a var and filter by an other var on condition, in r I have the following df:
data <- data.frame(group = c("A", "A", "A",  "B", "C", "C", "C", "C"),
                   x = c("A1", "A12", "A123", "BA", "C12", "CA", "C123", "C132"),
                   y = c("ir1", "ir2", "ir3",  "ir4", "ir5", "ir6", "ir7", "ir8"))
data

> data
  group    x   y
1     A   A1 ir1
2     A  A12 ir2
3     A A123 ir3
4     B   BA ir4
5     C  C12 ir5
6     C   CA ir6
7     C C123 ir7
8     C C132 ir8

and I would like to group by the group variable and select the x values that have the minimum characters. The required output is
  group  x   y
1     A A1 ir1
2     B BA ir4
3     C CA ir6

Thank you

A: A nice succinct option is using dplyr::slice_min(nchar(...)):
library(dplyr)

data <- data.frame(group = c("A", "A", "A",  "B", "C", "C", "C", "C"),
                   x = c("A1", "A12", "A123", "BA", "C12", "CA", "C123", "C132"),
                   y = c("ir1", "ir2", "ir3",  "ir4", "ir5", "ir6", "ir7", "ir8"))

data %>%
  group_by(group) %>%
  slice_min(nchar(x)) %>%
  ungroup()
#> # A tibble: 3 × 3
#>   group x     y
#>   <chr> <chr> <chr>
#> 1 A     A1    ir1
#> 2 B     BA    ir4
#> 3 C     CA    ir6

Created on 2022-07-27 by the reprex package (v2.0.1)

A: Try this
library(dplyr)

data |> group_by(group) |>
summarise(x = x[which.min(nchar(x))] ,
y = y[which.min(nchar(x))]) |> ungroup()

*

*output

# A tibble: 3 × 3
  group x     y
  <chr> <chr> <chr>
1 A     A1    ir1
2 B     BA    ir4
3 C     CA    ir5

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenLDAP as Proxy First, please note that I have experience with Linux, but for some reason, the OpenLDAP proxy authentication has me very confused and so I'm hoping someone can simply answer my questions to help me better understand it.  I was following this tutorial to set up a proxy to a Active Directory authentication (https://wiki.samba.org/index.php/OpenLDAP_as_proxy_to_AD).
Some notes:

*

*The OpenLDAP server's IP is 10.41.22.103

*The Windows AD server IP is 10.41.22.100

*OpenLDAP admin account is cn=admin,dc=example,dc=com
Following the tutorial, here are the files I modified.
My slapd.conf file (/etc/ldap/slapd.conf):
### Schema includes ####

include                 /etc/ldap/schema/core.schema
include                 /etc/ldap/schema/cosine.schema
include                 /etc/ldap/schema/inetorgperson.schema
include                 /etc/ldap/schema/misc.schema
include                 /etc/ldap/schema/nis.schema

## Module paths ##############################################################

modulepath              /usr/lib/ldap
moduleload              back_ldap
moduleload              rwm

# Main settings ###############################################################

pidfile                 /var/run/slapd/slapd.pid
argsfile                /var/run/slapd/slapd.args

### Database definition (Proxy to AD) #########################################

database                ldap
readonly                yes
protocol-version        3
rebind-as-user          yes
uri                     "ldap://10.41.22.100:389"
suffix                  "dc=OneGeo,dc=local"
overlay                 rwm
rwm-map                 attribute       uid     sAMAccountName
#rwm-map                 attribute       mail    proxyAddresses

### Logging ###################################################################

logfile                 /var/log/slapd/slapd.log
loglevel   0

In my Server 2012 AD, I created a user as requested and this is its DN:
CN=nslcd connect,CN=Users,DC=OneGeo,DC=local

Here is what I put into the core.schema (/etc/ldap/schema/core.schema):
####sAMAccountName AttributeType####

attributetype ( 1.2.840.113556.1.4.221
NAME 'sAMAccountName'
SYNTAX '1.3.6.1.4.1.1466.115.121.1.15'
SINGLE-VALUE )

Here is what I put into the nslcd.conf file (/etc/nslcd.conf):
# Mappings for Active Directory

pagesize 1000
referrals off

# Passwd

filter passwd (&(objectClass=posixAccount)(!(objectClass=computer))(uidNumber=*))

map    passwd homeDirectory     UnixHomeDirectory
map    passwd gecos             displayName
map    passwd gidNumber         primaryGroupID

# Shadow

filter shadow (&(objectClass=posixAccount)(!(objectClass=computer))(uidNumber=*))
map    shadow shadowLastChange  pwdLastSet

##new
filter passwd (uid=*)

# Groups

#filter group (&(objectClass=posixGroup)(gidNumber=*))
filter group  (&(objectClass=group)(gidNumber=*))
#map    group gid       member

# Local account for nsclcd

uid nslcd
##gid ldap
gid nslcd

# Where is the LDAP

uri ldap://10.41.22.100:389
base dc=OneGeo,dc=local

# Connect-Account

binddn  CN=nslcd\connect,CN=Users,DC=OneGeo,DC=local
bindpw n3m3s1s
ssl no

The last step in that tutorial mentions the pam_ldap.conf file, but I can't seem to find it on the OpenLDAP server.  Here are some questions I have (more will probably come):

*

*Where is the pam_ldap.conf file and should it be on the OpenLDAP server or on a client?

*Once all of this is set up properly, how do I fully test it to ensure authentication is happening at the AD level?  I'm really confused about this part!

Thank you!

*

*Christian


text:
Q: Block with NSSet can anyone tell me please why returnSet is returning as nil when there are lowercase characters in 'program'
I have stepped through and the NSLog is definitely picking the variables out but when it addObject: it just doesn't?
+ (NSSet *)variablesUsedInProgram:(id)program
{
    NSMutableSet *returnSet = [[NSMutableSet alloc]init];

    if ([program isKindOfClass:[NSArray class]]) {
        [program enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop)
        {
            if ([obj isKindOfClass:[NSString class]]) {
                if ([obj rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]].location != NSNotFound) {
                    NSLog(@"Variable: %@", obj);
                    [returnSet addObject:obj];
                }
            }
        }];
    }

    return returnSet;
}

A: The posted code has no bug. It cannot return a value of nil.
Your error is elsewhere.

A: I'm guessing that your problem is an ARC memory management problem. The code you posted returns a non-owning reference to the set it creates. Unless you save it to a strong instance variable, it will be deallocated.


text:
Q: Finding Power Using Recursion In Python 3
def power(base,exponent):
    if exponent == 1:
        return base
    return base * power(base, exponent - 1)

I haven't considered corner cases ( exponent <= 0)
Why don't we use the above-written code in-place of code computed using Divide and Conquer Technique, this code looks more simple and easy to understand? Is this code less efficient by any means?

A: These are the steps taken for calculating 2^8 with your code:
power(2,8)=
2*power(2,7)=
2*2*power(2,6)=
2*2*2*power(2,5)=
2*2*2*2*power(2,4)=
2*2*2*2*2*power(2,3)=
2*2*2*2*2*2*power(2,2)=
2*2*2*2*2*2*2*power(2,1)=

These are the steps taken for calculating 2^8 with divide and conquer:
power(2,8)=
power(2,4)**2=
power(2,2)**2**2=
power(2,1)**2**2**2=

As you can see your method takes O(n) steps while divide and conquer takes O(lg(n)) steps which is significantly faster.
Using recursion for such problems is never a good idea if you are concerned with speed since as you can see iterative approach(tail recursion in functional languages) is usually much faster, in this example it's twice as fast as you can see in the benchmarks, as for the divide and conquer approach, you should always use that unless you are working with powers of less than ~22.
Here are some benchmarks:
The codes:
def r_power(base, exponent):  # recursive credits to OP
    if exponent == 1:
        return base
    return base * r_power(base, exponent - 1)

def lindc_power(x, y):  # linear divide and conquer, credits to Smitha Dinesh Semwal
    if y == 0:
        return 1
    elif int(y % 2) == 0:
        return lindc_power(x, int(y / 2)) * lindc_power(x, int(y / 2))
    else:
        return x * lindc_power(x, int(y / 2)) * lindc_power(x, int(y / 2))

def lgdc_power(x, y):  # logarithmic divide and conquer
    if y == 0:
        return 1
    elif int(y % 2) == 0:
        return lgdc_power(x, int(y / 2)) ** 2
    else:
        return x * lgdc_power(x, int(y / 2)) ** 2

def i_power(base, exponent):  # iterative, credits to Yugandhar Chaudhari
    acc = 1
    while True:
        if exponent == 0:
            return acc
        base, exponent, acc = base, exponent - 1, acc * base

The results:
|---------------------------------------------------------------------|
| base | power   | recursive | iterative | linear dc | logarithmic dc |
|---------------------------------------------------------------------|
| 2    | 10      | 1.27 µs   | 746 ns    | 8.99 µs   | 2.33 µs        |
| 2    | 22      | 2.96 µs   | 1.58 µs   | 18.6 µs   | 2.95 µs        |
| 2    | 100     | 15.1 µs   | 8.31 µs   | 75.3 µs   | 4.14 µs        |
| 2    | 500     | 96.7 µs   | 48.9 µs   | 312 µs    | 5.69 µs        |
| 2    | 1000    | 424 µs    | 178 µs    | 1.3 ms    | 6.58 µs        |
| 2    | 1500    | 201 µs    | 108 µs    | 620 µs    | 7.89 µs        |
| 2    | 2000    | 435 µs    | 242 µs    | 1.23 ms   | 8.15 µs        |
| 2    | 3000    | error     | 409 µs    | 2.49 ms   | 10.3 µs        |
| 2    | 6000    | error     | 1.13 ms   | 5.01 ms   | 17.6 µs        |
| 2    | 10000   | error     | 2.64 ms   | 9.84 ms   | 25.2 µs        |
| 2    | 20000   | error     | 8.74 ms   | 19.9 ms   | 45.7 µs        |
| 2    | 100000  | error     | 161 ms    | 82.4 ms   | 249 µs         |
| 2    | 200000  | error     | 626 ms    | 159 ms    | 532 µs         |
| 2    | 1000000 | error     | 15 s      | 651 ms    | 3.23 ms        |
|---------------------------------------------------------------------|

My maximum recursion depth is 3000.

A: Yes this could be less efficient if it is not tail recursive. Recursion creates stack frames for a too large number you can go out of memory. Right way would be expressing it using tail recursion. You just need to use a variable to store the result acc here it will evaluate the result in a variable instead of making recursive function calls
def power2(base,exponent,acc):
    if exponent == 0:
        return acc
    return power2(base,exponent-1,acc*base)

print(power2(10,2,1)) #start acc from 1 initially

But python is not tail optimized so this is the way to use tail optimization here
def power2(base,exponent,acc):
    while True:
        if exponent == 0:
            return acc
        base,exponent,acc = base,exponent-1,acc*base

print(power2(10,100,1))


text:
Q: Implementing an interface without implementing it Can implement an interface without implementing it-- as in:
interface A { void m2(); }

class B { public void m2() { ... } }

class C extends B implements A { ... /* no implementation of m2() here */ }

What i'm wondering is, is there a way to force the descendant class, class C here, to implement the method m2()?
This looks a bit sideways-- breaking the expected chain in inheritance.
There can be cases i can't think of now where it would be necessary to force the subclass in this fashion.
TIA.
//==========================
EDIT: one scenario:
There is a class B and an interface A developed in two different places in the application with a method m2() having the same signature in both.
B is implementing m2() in its own way-- without even knowing what A is all about.
when C above gets quickly in, it has an m2() that has nothing to do with the contract in A.
This takes poor management of development. but, still.
//=================================
EDIT-2:
Restricting m2()-of-B's access to package level or protected works.
This way, m2() of B that C is inheriting won't do for that of A since it isn't public.
This is a bit of tempering with what a class should do in itself-- but then it isn't.
A super-class should be able to direct a sub this much. loosely similar to the use of final on methods or on the class itself. Note AndyThomas's useful ans. though.

A: As written, class C must satisfy both the contracts for B.m2() and A.m2().
Those contracts are either compatible or not.
If those contracts are compatible, then B.m2() is either a sufficient implementation for C or not.

*

*If it is sufficient, an override is not required.

*If it is not sufficient, then it is the responsibility of class C to override it.

*

*Inside class C, you can force an override by ... simply overriding the method.

*Outside class C, you cannot force C to override an existing, non-abstract superclass method.

If those contracts are not compatible, then C cannot both extend B and implement A. In this case, you could use composition instead of inheritance -- have C implement A, and include a B in its representation.
There is no mechanism in Java to force all instantiable classes implementing an interface to override superclass implementations of methods in the interface.  You can, however, force all instantiable classes to implement an abstract method somewhere in their inheritance hierarchy.

A: If you declare class B to be abstract it wouldn't be required to implement m2 and therefore C (by inheriting B) would be required to:
abstract class B implements A {}


text:
Q: Is there a simple proof that if $(b-a)(b+a) = ab - 1$, then $a, b$ must be Fibonacci numbers? Consider the identity $(b-a)(b+a) = ab - 1$, where $a, b$ are nonnegative integers.
We can also express this identity as $a^2 + ab - b^2 = 1$.
This identity is clearly true when $a = F_{2i-1}$ and $b = F_{2i}$, where $F_i$ is the $i^{th}$ term of the Fibonacci sequence. This is equivalent to one case of Cassini's identity, $(F_{2i-1})(F_{2i+1}) = F_{2i}^2 + 1$, and is easily proven by induction or several other simple elementary means.
My question is this: Is there a simple elementary proof that these Fibonacci numbers are the only solutions of this identity?
By simple elementary proof, ideally I mean a proof using methods and steps that a mathematically gifted high school student could follow and understand. Alternatively, I could define it as a proof using methods that would have been known to mathematicians in Cassini's time, in the late 17th century. In other words, I am looking for a proof that does not rely on more advanced methods such as quadratic number fields or generalized solutions of Pell equations.

A: Here's one approach:
Step 1a: Show that if $a$ and $b$ satisfy this, and $0 < a < b$, then $a' = (b-a)$ and $b' = a$ also satisfy it and have $a' \le b' < b$, so that the max absolute value of the two items in the pair decreases
What the heck...let's check that: we want to show that $(b' - a') (b' + a') - (a'b' -1)
$ is zero. So compute
\begin{align}
(b' - a') (b' + a') - (a'b' -1)
&=(a - (b-a)) (a + (b-a)) - (a(b-a) -1)\\
&=(2a - b)) (b)) - (a(b-a) -1)\\
&=2ab - b^2 - ab + a^2  +1 \\
&=ab - b^2  + a^2  +1
\end{align}
which is $0$ because $a$ and $b$ satisfy the relation, which expanded out says that $b^2 - a^2  - ab + 1 = 0$.
Case 1b: if $b < a < 0$, then $b' = b-a$ and $a' = b$ do as well, and $b' < a' < 0$, and $|b'| = |a| < |b|$. Proof: exactly the same as before. Once again, the max absolute value of the two items in the pair decreases.
Case 1c: $b$ and $a$ have opposite signs. If $b$ is positive, then $a$ is negative, and $|a| > |b|$. If $b$ is negative, then $a$ is positive, so $b-a$ is negative, so $b+a$ is positive, and once again $|a| > |b|$. Again, by an argument like the one above, the pair $(a, b)$ can be adjusted to a pair $(b, a-b)$ where the larger number (in absolute value) is smaller in the new pair than in the old one, i.e., the max absolute value of the two items in the pair decreases.
Other cases: you still have to deal with other similar cases in ways rather like this, and I don't have the stomach to go through it all.
Step 2: Conclude that for any such pair, we can reduce the pair to a smaller (in the sense of max-absolute-value) pair of numbers, until until $a = b$ (which fails unless $a = b = \pm 1$).
Step 3: Conclude that our pair is part of the sequence that arises from
$(1, 1) \to (1, 2) \to (2, 3) \to  (3, 5) \to  ...$, i.e., the F-sequence.
[This does only handle the case where $0 < a < b$; the $a=b$ case is trivial (indeed, Step 2 addresses it); the $a > b$ case can almost certainly be handled by essentially the same method. The case where $a$ or $b$ is zero should not be difficult for a bright high-school student.]

A: Open this up to solving $a^2+ab-b^2=\pm1$ in positive integers.
Unless $a$ and $b$ are very small, then $a<b$. Let $c=b-a$.
Then
$$c^2+ca-a^2=(b-a)^2+(b-a)a-a^2=-a^2-ab+b^2=\mp1.$$
So if $c$ and $a$ are consecutive Fibonacci's then so are $a$ and $b$.
To complete this, one needs to analyse the solutions for small $a$ and $b$
in order to start off the induction.

A: It turns out I have a diagram of Conway's topograph  pdf for this.
The very simple statement is that "the river is periodic." This means that, if we can find all solutions within one period, we have them all.
Recent book by Allen Hatcher pdf
ALSO: Recent book at a fairly elementary level: Weissman
Broken down further, it means that any solution to $a^2 + ab - b^2 = 1$ leads to another,
$$ (a,b) \mapsto (a+b, a + 2b)  $$
As you can see from the (vertical) vectors when the form value is $1,$ this makes $a,b$ consecutive Fibonacci, by induction.
As you can see, I draw in little $(x,y)$ "coordinate" pairs as column vectors. This is crucial for my approach; the other two books do not really push this aspect, but it is done well in Stillwell, Elements of Number Theory.

I have drawn a portion of the river, with colors as in the tree diagrams, and showing the relative positions of the values $11.$ I have worked out how to force the given mapping $ (a,b) \mapsto (a+b, a + 2b)  $ as we move to the right, or $ (a,b) \mapsto (2a-b, -a + b)  $ as we move to the left.

There was a question in comment about $a^2 + ab - b^2 = 11.$ It is enough to draw a single "tree" of positive values climbing away from the river. We see $11$ as $(a,b)$ pairs $(3,1)$ and $(3,2).$ All other solutions with positive $(a,b)$ occur in other trees along the river. They can be found with $ (a,b) \mapsto (a+b, a + 2b)  .$ In the next tree to the right, we get $(4,5)$ and $(5,7).$ A second tree to the right, we get $(9,14)$ and $(12,19).$ Also, Cayley-Hamilton says that we get two orbits under a pair of linear degree two recurrences,
$$ a_{n+2} = 3 a_{n+1} - a_n, $$
$$ b_{n+2} = 3 b_{n+1} - b_n. $$
I wrote out a simple proof without using Cayley-Hamilton at How does one solve this recurrence relation?

Alright, I did one tree over, I mostly left off the blue edge labels, which match the previous tree.

Other answers/questions I did with the topograph:
http://math.stackexchange.com/questions/342284/generate-solutions-of-quadratic-diophantine-equation/346821#346821
http://math.stackexchange.com/questions/81917/another-quadratic-diophantine-equation-how-do-i-proceed/144794#144794
http://math.stackexchange.com/questions/228356/how-to-find-solutions-of-x2-3y2-2/228405#228405
http://math.stackexchange.com/questions/342284/generate-solutions-of-quadratic-diophantine-equation/345128#345128
http://math.stackexchange.com/questions/487051/why-cant-the-alpertron-solve-this-pell-like-equation/487063#487063
http://math.stackexchange.com/questions/512621/finding-all-solutions-of-the-pell-type-equation-x2-5y2-4/512649#512649
http://math.stackexchange.com/questions/680972/if-m-n-in-mathbb-z-2-satisfies-3m2m-4n2n-then-m-n-is-a-perfect-square/686351#686351
http://math.stackexchange.com/questions/739752/how-to-solve-binary-form-ax2bxycy2-m-for-integer-and-rational-x-y/739765#739765
http://math.stackexchange.com/questions/742181/find-all-integer-solutions-for-the-equation-5x2-y2-4/756972#756972
http://math.stackexchange.com/questions/822503/positive-integer-n-such-that-2n1-3n1-are-both-perfect-squares/822517#822517
http://math.stackexchange.com/questions/1078450/maps-of-primitive-vectors-and-conways-river-has-anyone-built-this-in-sage/1078979#1078979
http://math.stackexchange.com/questions/1091310/infinitely-many-systems-of-23-consecutive-integers/1093382#1093382
http://math.stackexchange.com/questions/1132187/solve-the-following-equation-for-x-and-y/1132347#1132347  <1,-1,-1>
http://math.stackexchange.com/questions/1132799/finding-integers-of-the-form-3x2-xy-5y2-where-x-and-y-are-integers
http://math.stackexchange.com/questions/1221178/small-integral-representation-as-x2-2y2-in-pells-equation/1221280#1221280
http://math.stackexchange.com/questions/1404023/solving-the-equation-x2-7y2-3-over-integers/1404126#1404126
http://math.stackexchange.com/questions/1599211/solutions-to-diophantine-equations/1600010#1600010
http://math.stackexchange.com/questions/1667323/how-to-prove-that-the-roots-of-this-equation-are-integers/1667380#1667380
http://math.stackexchange.com/questions/1719280/does-the-pell-like-equation-x2-dy2-k-have-a-simple-recursion-like-x2-dy2
http://math.stackexchange.com/questions/1737385/if-d1-is-a-squarefree-integer-show-that-x2-dy2-c-gives-some-bounds-i/1737824#1737824
http://math.stackexchange.com/questions/1772594/find-all-natural-numbers-n-such-that-21n2-20-is-a-perfect-square/1773319#1773319


text:
Q: Having issues with UPI deep-link from a web application for non-merchant initiated transaction I am working on a web application where I would like to enable UPI transactions between two UPI Ids (non-merchant UPIs) for non-business purposes. Example, transactions between friends to settle the balances for domestic spends.
I am able to generate the UPI intent uri as per the spec and able to open the UPI app, and able to initiate transaction with out any merchant id. However most of hte times transaction fails with below message and observed occasional successful transfers using same flow on retrying.
Here is the Codesandbox link for a sample app which I tried.

*

*How can I get more details about the failed transactions, and how are some transactions successful?

*Is it possible to allow p2p transactions between consumers without registering any business account (merchant id with NPCI)?

A: Pay using Intent is not allowed in P2P UPI App.
You can download the UPI Merchant App (P2M App), I tried in phonepe merchant App it working ok, but if Intent is not working on merchant Account, call customer care they will active it.


text:
Q: Trivialising cover for étale morphisms Let $f:Y \to X$ be a finite étale morphism of smooth and proper schemes over a field $k$ (not necessarily separable closed).

Is there a geometrically connected étale cover $\{U_i\}$ of $X$ which trivializes $Y$, i.e. $Y \times_k U_i$ is the disjoint union of copies of $U_i$?

EDIT: it seems that, for general $k$, the above is not necessarily true. I have a couple of follow-up questions:

*

*If $k = k^{sep}$, is there a positive answer to my original question?

*Is there a connected étale cover $\{U_i\}$ of $X$ which  trivializes $Y$, for a general $k$?


text:
Q: Lambda errors not being caught by try/catch blocks or error handler I'm trying to log errors in an alexa skill that runs in a Lambda function, but no matter what I try, errors somehow get through my try/catch blocks without being logged.
This is my index.js:
const Alexa = require('ask-sdk-core');

try {
  const handlers = require('./handlers');

  const wrappedHandlers = handlers.map(handler => ({
    ...handler,
    async handle(handlerInput) {
      try {
        console.log(`Running handler ${handler.name}`, JSON.stringify(handlerInput, null, 2));
        const response = await handler.handle(handlerInput);
        console.log(`Successfully ran handler ${handler.name}`, JSON.stringify(response, null, 2));
        return response;
      } catch(error) {
        console.log(`Failed to run handler ${handler.name}`, error.stack);
        throw error;
      }
    },
  }));

  exports.handler = Alexa.SkillBuilders
    .custom()
    .addRequestHandlers(...wrappedHandlers)
    .addErrorHandlers(require('./handlers/error'))
    .lambda();
} catch(error) {
  console.log('Fatal initialization error', error);
  exports.handler = Alexa.SkillBuilders
    .custom()
    .addRequestHandlers({
      canHandle() { return true; },
      handle(handlerInput) {
        return handlerInput.responseBuilder
          .speak(`Initialization error`, error.stack);
      },
    })
    .lambda();
}

The top-level try/catch should catch any errors thrown during require('./handlers'). I've observed this working in the past catching syntax errors in my handlers.
I'm also wrapping every handler's handle function in a try/catch (see wrappedHandlers). My error handler also logs any errors it sees:
// handlers/error.js
module.exports = {
  canHandle() { return true; },

  handle(handlerInput, error) {
    console.log(`Error handled: ${error.stack}`);

    // During tests, include the error in the response
    if(process.env['NODE_ENV'] === 'test') {
      const { attributesManager } = handlerInput;
      const sessionAttributes = attributesManager.getSessionAttributes();
      sessionAttributes.error = error;
      attributesManager.setSessionAttributes(sessionAttributes);
    }

    const message = error && error.speachMessage || `Sorry, I can't understand the command. Please say again. ${error.stack}`;
    return handlerInput.responseBuilder
      .speak(message)
      .reprompt(message)
      .getResponse();
  },
};

Despite all of this, the Alexa simulator is spitting out [Error]: An unexpected error occurred., but the cloudwatch logs don't contain any errors or failed requests. How is this possible?

A: I'm also experiencing this problem and I've got a function which is throwing with a lambda 502 bad gateway, the cloudwatch log entry contains
Invoke Error {"errorType":"UnauthorizedError","errorMessage":"Forbidden","name":"UnauthorizedError","stack":["UnauthorizedError: Forbidden"," at /var/task/ApiServerClass.js:57:27"," at processTicksAndRejections (internal/process/task_queues.js:97:5)"," at async module.exports.me (/var/task/ApiServerClass.js:68:43)"," at async module.exports.run (/var/task/ApplicationClass.js:42:22)"]}

But wrapped around that entire function is a try/catch
It's as if throwing an exception immediately causes lambda to quit and all your exception handling is ignored. But when running local tests through mocha. The exceptions are respected


text:
Q: Como adicionar ao 'data' do Ajax um valor enviado de um onclick? Tenho uma table em HTML e em uma table column existe um link que abre um Modal. Nessa modal eu faço cadastro de aprovações e mostro quem aprovou e a data da aprovação (Mais de uma pessoa pode aprovar, logo tem uma lista de aprovações). Para fazer o cadastro eu preciso de IdSolicitação e IdEmpresa e para listar só preciso de IdSolicitação. E estou nessa situação:
Table Column:
    `Histórico	`

Modal:

      @using (Html.BeginForm("CreateSolicitacao", "Solicitacoes", FormMethod.Post))
      {
      <input hidden="hidden" id="IdSolicitacao" name="IdSolicitacao"/>
      <input hidden="hidden" id="IdEmpresa" name="IdEmpresa" />

APROVAÇÕES

HISTÓRICO

                  @Html.RadioButton("Situacao", true, true)
                  @Html.Label("Aprovar")
                  @Html.RadioButton("Situacao", false)
                  @Html.Label("Reprovar")

                  @Html.SolyosTextArea("Observacao", "col-md-12 controls", "Digite o motivo, ou alguma observação")

                      <input type="submit" value="SALVAR" onclick=""/>
                      <input type="button" data-dismiss="modal" value="Cancelar" onclick="Solyos_Modal_Form_Close();" />

      }

No onclick da td eu consigo setar o IdSolicitacao e o IdEmpresa nos inputs hidden para fazer o cadastro, mas não consigo acessar o IdSolicitacao para jogar no data do Ajax.
Como eu consigo fazer isso?
EDIT
Resolvi o problema da seguinte maneira:
Adicionei ao onclick uma função chamando meu Ajax
Histórico
E no script:

A: No ajax do javascript, faça assim
$.ajax({
    type: 'POST',
    url: "@Url.Action("_ListaHistorico", "Solicitacoes")",
    data: { IdSolicitacao: $("#IdSolicitacao").val(), IdEmpresa: $("#IdEmpresa").val() },
    dataType: 'JSON',
//.....


text:
Q: Finding the frequency of each word in a file I'm trying to find the frequency of each word in a file.
Not just searching for how many instances of a certain word there are, but the frequency of each word.
For example, if the file contained this sentence:

"Super awesome super cool people are awesome!"

It would output this:
Super - 2
Awesome - 2
Cool - 1
People - 1
Are - 1

Showing the frequency of each word.
How can I do this in Java, but counting the entire file, and not knowing what words that I might be testing?

A: Try the following:
// This will match all non-word characters, i.e. characters that are
// not in [a-zA-Z_0-9]. This should match whitespaces and interpunction.
String nonWordDelimiter="[\W]+";

String[] words = text.split(nonWordDelimiter);

Map<String, Integer> frequencies = new LinkedHashMap<String, Integer>();
for (String word : words) {
    if (!word.isEmpty()) {
        Integer frequency = frequencies.get(word);

        if (frequency == null) {
            frequency = 0;
        }

        ++frequency;
        frequencies.put(word, frequency);
    }
}

Finally, the map frequencies will contain the frequency of each word.


text:
Q: Reading/Writing self heap Could the own heap space be readed? could the software be self modified in memory?
I write some code to show the subject,
am I reading own code at memory?
how (if possible) to write it and change instruction on runtime?
#include<stdio.h>
#include<stdint.h>

volatile int addressBase;
uint8_t read(int address);

int main(void) {

    printf("Helium word");

    addressBase=(int)&main;
    printf("[%X]", read( 0 ));
    getchar();

    return 0;
}

uint8_t read(int address)
{

       const uint8_t *addr;
       addr=(const unsigned char *)(addressBase+(int)address);
       return (*addr);
}

A: Memory is normally divided into read-only instruction memory and writable data memory which may or may not be executable. If you application wants to write and then run its own code (like a JIT compiler), you will probably need to use some operating specific method of obtaining the necessary memory block. So yes you can read your own instructions but I highly doubt you will be able to modify them.

A: You can read and write heap space at your own risk.
Self-modifiying code might be a useful trick in restricted, small environments like small embedded systems. Modern desktop or server CPUs however do not like self-modifying code at all because it breaks instruction caching, prefetching and pipelining. One anecdote: TI-Scheme ran blazingly fast on 386 CPUs. It used self-modifying code. 486 CPUs introduced instruction caching and TI-Scheme crashed.


text:
Q: Does Google Chrome v77 have a HTML5-Canvas bug? We run the graphical part of our software in Canvas. With the latest version of Google Chrome (v77) being released, our product doesn't display anything on load. Canvas simply doesn't draw anything.
When you resize the windows or scroll, Canvas draws the elements correctly, but not initially. For every refresh, we are back to a blank page.
If we disable Accelerated 2D canvas, it works. We have tried the upcoming versions of Google Chrome (v78 and v79), and here canvas renders and draws correctly.
Does anybody experience anything similar, i.e. is it a Chrome bug?

A: Dropzonejs doesn't work with Chrome 77 on Android. It is probably same isue with canvas.
more on this isue here


text:
Q: How do I hide/show tabBar when tapped using Swift in iOS8 I am trying to mimic the UINavigationController's new hidesBarsOnTap with a tab bar. I have seen many answers to this that either point to setting the hidesBottomBarWhenPushed on a viewController which only hides it entirely and not when tapped.
 @IBAction func tapped(sender: AnyObject) {

    // what goes here to show/hide the tabBar ???

}

thanks in advance
EDIT: as per the suggestion below I tried
self.tabBarController?.tabBar.hidden = true

which does indeed hide the tabBar (toggles true/false on tap), but without animation. I will ask that as a separate question though.

A: You can just add this line to ViewDidLoad() in swift :
self.tabBarController?.tabBar.hidden = true

A: After much hunting and trying out various methods to gracefully hide/show the UITabBar using Swift I was able to take this great solution by danh and convert it to Swift:
func setTabBarVisible(visible: Bool, animated: Bool) {

    //* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time

    // bail if the current state matches the desired state
    if (tabBarIsVisible() == visible) { return }

    // get a frame calculation ready
    let frame = self.tabBarController?.tabBar.frame
    let height = frame?.size.height
    let offsetY = (visible ? -height! : height)

    // zero duration means no animation
    let duration: TimeInterval = (animated ? 0.3 : 0.0)

    //  animate the tabBar
    if frame != nil {
        UIView.animate(withDuration: duration) {
            self.tabBarController?.tabBar.frame = frame!.offsetBy(dx: 0, dy: offsetY!)
            return
        }
    }
}

func tabBarIsVisible() -> Bool {
    return (self.tabBarController?.tabBar.frame.origin.y)! < self.view.frame.maxY
}

// Call the function from tap gesture recognizer added to your view (or button)

@IBAction func tapped(_ sender: Any?) {
    setTabBarVisible(visible: !tabBarIsVisible(), animated: true)
}

A: Loved Michael Campsall's answer. Here's the same code as extension, if somebody is interested:
Swift 2.3
extension UITabBarController {

    func setTabBarVisible(visible:Bool, animated:Bool) {

        // bail if the current state matches the desired state
        if (tabBarIsVisible() == visible) { return }

        // get a frame calculation ready
        let frame = self.tabBar.frame
        let height = frame.size.height
        let offsetY = (visible ? -height : height)

        // animate the tabBar
        UIView.animateWithDuration(animated ? 0.3 : 0.0) {
            self.tabBar.frame = CGRectOffset(frame, 0, offsetY)
            self.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height + offsetY)
            self.view.setNeedsDisplay()
            self.view.layoutIfNeeded()
        }
    }

    func tabBarIsVisible() ->Bool {
        return self.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
    }
}

Swift 3
extension UIViewController {

    func setTabBarVisible(visible: Bool, animated: Bool) {
        //* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time

        // bail if the current state matches the desired state
        if (isTabBarVisible == visible) { return }

        // get a frame calculation ready
        let frame = self.tabBarController?.tabBar.frame
        let height = frame?.size.height
        let offsetY = (visible ? -height! : height)

        // zero duration means no animation
        let duration: TimeInterval = (animated ? 0.3 : 0.0)

        //  animate the tabBar
        if frame != nil {
            UIView.animate(withDuration: duration) {
                self.tabBarController?.tabBar.frame = frame!.offsetBy(dx: 0, dy: offsetY!)
                return
            }
        }
    }

    var isTabBarVisible: Bool {
        return (self.tabBarController?.tabBar.frame.origin.y ?? 0) < self.view.frame.maxY
    }
}

A: I use tabBar.hidden = YES in ObjC to hide the tab bar in certain cases. I have not tried wiring it up to a tap event, though.

A: Code is okay but when you use presentViewController, tabBarIsVisible() is not working. To keep UITabBarController always hidden use just this part:
extension UITabBarController {
    func setTabBarVisible(visible:Bool, animated:Bool) {
        let frame = self.tabBar.frame
        let height = frame.size.height
        let offsetY = (visible ? -height : height)
        UIView.animateWithDuration(animated ? 0.3 : 0.0) {
            self.tabBar.frame = CGRectOffset(frame, 0, offsetY)
            self.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height + offsetY)
            self.view.setNeedsDisplay()
            self.view.layoutIfNeeded()
        }
    }
}

A: I had to adapt the accepted answer to this question a bit. It was hiding the bar but my view wasn't sizing itself appropriately so I was left with a space at the bottom.
The following code successfully animates the hiding of the tab bar while resizing the view to avoid that issue.
Updated for Swift 3 (now with less ugly code)
func setTabBarVisible(visible: Bool, animated: Bool) {
    guard let frame = self.tabBarController?.tabBar.frame else { return }
    let height = frame.size.height
    let offsetY = (visible ? -height : height)
    let duration: TimeInterval = (animated ? 0.3 : 0.0)

    UIView.animate(withDuration: duration,
                   delay: 0.0,
                   options: UIViewAnimationOptions.curveEaseIn,
                   animations: { [weak self] () -> Void in
                    guard let weakSelf = self else { return }
                    weakSelf.tabBarController?.tabBar.frame = frame.offsetBy(dx: 0, dy: offsetY)
                    weakSelf.view.frame = CGRect(x: 0, y: 0, width: weakSelf.view.frame.width, height: weakSelf.view.frame.height + offsetY)
                    weakSelf.view.setNeedsDisplay()
                    weakSelf.view.layoutIfNeeded()
    })
}

func handleTap(recognizer: UITapGestureRecognizer) {
    setTabBarVisible(visible: !tabBarIsVisible(), animated: true)
}

func tabBarIsVisible() -> Bool {
    guard let tabBar = tabBarController?.tabBar else { return false }
    return tabBar.frame.origin.y < UIScreen.main.bounds.height
}

Older Swift 2 Version
func setTabBarVisible(visible: Bool, animated: Bool) {
    // hide tab bar
    let frame = self.tabBarController?.tabBar.frame
    let height = frame?.size.height
    var offsetY = (visible ? -height! : height)
    println ("offsetY = \(offsetY)")

    // zero duration means no animation
    let duration:NSTimeInterval = (animated ? 0.3 : 0.0)

    // animate tabBar
    if frame != nil {
        UIView.animateWithDuration(duration) {
            self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!)
            self.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height + offsetY!)
            self.view.setNeedsDisplay()
            self.view.layoutIfNeeded()
            return
        }
    }
}

@IBAction func handleTap(recognizer: UITapGestureRecognizer) {
    setTabBarVisible(!tabBarIsVisible(), animated: true)
}

func tabBarIsVisible() -> Bool {
    return self.tabBarController?.tabBar.frame.origin.y < UIScreen.mainScreen().bounds.height
}

A: Swift 3 version:
func setTabBarVisible(visible:Bool, animated:Bool) {

    //* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time

    // bail if the current state matches the desired state
    if (tabBarIsVisible() == visible) { return }

    // get a frame calculation ready
    let frame = self.tabBarController?.tabBar.frame
    let height = frame?.size.height
    let offsetY = (visible ? -height! : height)

    // zero duration means no animation
    let duration:TimeInterval = (animated ? 0.3 : 0.0)

    //  animate the tabBar
    if frame != nil {
        UIView.animate(withDuration: duration) {

            self.tabBarController?.tabBar.frame = (self.tabBarController?.tabBar.frame.offsetBy(dx: 0, dy: offsetY!))!
            return
        }
    }
}

func tabBarIsVisible() ->Bool {
    return (self.tabBarController?.tabBar.frame.origin.y)! < self.view.frame.midY
}

A: Swift 5
To hide
  override func viewWillAppear(_ animated: Bool) {
     self.tabBarController?.tabBar.isHidden = true
   }

To show again
   override func viewDidDisappear(_ animated: Bool) {
    self.tabBarController?.tabBar.isHidden = false
  }

A: For Swift 4, and animating + hiding by placing tabBar outside the view:
if let tabBar = tabBarController?.tabBar,
   let y = tabBar.frame.origin.y + tabBar.frame.height {
   UIView.animate(withDuration: 0.2) {
     tabBar.frame = CGRect(origin: CGPoint(x: tabBar.frame.origin.x, y: y), size: tabBar.frame.size)
   }
}

A: To make the animations work with self.tabBarController?.tabBar.hidden = true just do this:
UIView.animateWithDuration(0.2, animations: {
    self.tabBarController?.tabBar.hidden = true
})

Other than the other solution this will also work nicely with autolayout.


text:
Q: SPARQL DBpedia - Retrieve category information in any language by using labels I have a problem, which I explain on following example:
I want to retrieve all information in any language on a category. I must use ?category as a label and the language labels en, as they are inputs in my program.
The query looks like this, but when I change the language I don't receive any information on the category. I know the problem lies in the dcterms:subject, because ?category returns http://dbpedia.org/resource/Category:Countries_in_Europe (see first example below).
For example to search for a category label in german you have to use http://de.dbpedia.org/resource/Kategorie:Staat_in_Europa (see second example below).
prefix dcterms: <http://purl.org/dc/terms/>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?objectLabel WHERE {
       ?subject dcterms:subject ?category ; rdfs:label ?objectLabel
       ?category rdfs:label "Countries in Europe"@en .
FILTER (LANG(?objectLabel)='en')
}

Equivalent query in different language that doesn't work as example:
prefix dcterms: <http://purl.org/dc/terms/>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?objectLabel WHERE {
       ?subject dcterms:subject ?category ; rdfs:label ?objectLabel
       ?category rdfs:label "Staat in Europa"@de .
FILTER (LANG(?objectLabel)='de')
}

Is there a similar or different way / method to solve the problem? Thanks in advance for any help.


text:
Q: Tool to convert t-sql (SQL Server) stored procedure to pgsql (postgre sql) Can anybody suggest a tool or share code which can help me converting large number of t-sql stored procedures in database to postgresql while migrating from SQL Server database to postgresql?
== Edited==
here are some clear goals:

*

*Convert all sps to postgre sql without considering performance / tuning etc, by only focusing that syntax is right and query returns correct data

Language conversion and transformation related guidelines are really useful. I see couple of old vbscript examples (most of them not working for me) and could try to convert them to T4 templates.
I am surprised no one really needed this kind of conversion! I still don't have a right tool to do so.
Thanks in advance.

A: Translating languages is hard.  You need to parse the original (with all the strange syntax and warts it allows above and beyond what the documentation says), determine what names mean, discover the semantics, and translate to the target language without losing the subtle details.
I'd be surprised if you found a solution for this off-the-shelf. Part of the problem is there are a vast number N of source languages (made worse by dialects), and a vast number of targets M, requiring a library of NxM translators to be lying around.   And if you wait a few months, N and M both move.  One hope is to translate N langauges to a common universal core language, and translate that to M targets, now only requiring N+M... but nobody has found a really universal language, and if you wait a few months, N and M move anyway.
One can consider building (or getting someone else to build) a specific translator for the task; this usually is uneconomical, at least if you want it to be reliable, because so much of the translator machinery (parsing, name resolution, pattern matching/translating, ...) tends to get rebuilt from scratch.
One can amortize the cost of the translator infrastructure if you are careful, by building (a lot of) shared machinery.  Once you do that, building a translator is easier (still not easy) and the economics make more sense for individual cases.  You can read more about this approach at: What kinds of patterns could I enforce on the code to make it easier to translate to another programming language?

A: Have you seen this page:
Convert from other databases to PostgreSQL?

A: I'm sure that every SP needs to be converted by developers.
Ira Baxter says (absolutelly correct) about languages, but I want to say about platform differences. for example, how to translate to different platform the usage temporary tables?
What to do with performance-tuned queries? Performance tuning uses the specific features of RDBMS, and this tuning cannot be automatically converted. And so on...


text:
Q: Magento 1.9: How to create order programmatically I found similar topics, but they are not up to date.
I have to generate around 1000 orders with random products. I found good article about creating orders http://inchoo.net/magento/programmatically-create-order-in-magento/ but it's kinda old and it's not working on version 1.9.
I get following errors:
array (size=5)
  0 => string 'Please specify the product's option(s).' (length=39)
  1 => string 'Please specify the product's option(s).' (length=39)
  2 => string 'Please specify the product's option(s).' (length=39)
  3 => string 'Please specify the product's option(s).' (length=39)
  4 => string 'Please specify the product's option(s).' (length=39)

#0 E:\xampp\htdocs\magento\app\code\core\Mage\Adminhtml\Model\Sales\Order\Create.php(1631): Mage::throwException('')
#1 E:\xampp\htdocs\magento\app\code\core\Mage\Adminhtml\Model\Sales\Order\Create.php(1523): Mage_Adminhtml_Model_Sales_Order_Create->_validate()

As you can see in my create method I add options to product, so why do I get this errors?
Here is my class
class MyNamespace_MyModule_Model_Generate_Sample {

    protected $orderData;
    protected $product;

    public function run()
    {
        //$customer is a random customer object

        $product = Mage::getModel('catalog/product')->load(342);

        $this->product = $product;

        $this->orderData = array(
            'session'       => array(
                'customer_id'   => $customer->getId(),
                'store_id'      => Mage::app()->getStore('default')->getId(),
            ),
            'payment'       => array(
                'method'    => 'checkmo',
            ),
            'add_products'  =>array(
                $product->getId() => array('qty' => 1),
            ),
            'order' => array(
                'currency' => 'USD',
                'account' => array(
                    'group_id' => $customer->getGroupId(),
                    'email' => $customer->getEmail()
                ),
                'billing_address' => array(
                    'customer_address_id' => $customer->getCustomerAddressId(),
                    'prefix' => '',
                    'firstname' => $customer->getFirstname(),
                    'middlename' => '',
                    'lastname' => $customer->getLastname(),
                    'suffix' => '',
                    'company' => '',
                    'street' => array($customer->getStreet(),''),
                    'city' => $customer->getCity(),
                    'country_id' => $customer->getCountryId(),
                    'region' => '',
                    'region_id' => $customer->getRegionId(),
                    'postcode' => $customer->getPostcode(),
                    'telephone' => $customer->getTelephone(),
                    'fax' => '',
                ),
                'shipping_address' => array(
                    'customer_address_id' => $customer->getCustomerAddressId(),
                    'prefix' => '',
                    'firstname' => $customer->getFirstname(),
                    'middlename' => '',
                    'lastname' => $customer->getLastname(),
                    'suffix' => '',
                    'company' => '',
                    'street' => array($customer->getStreet(),''),
                    'city' => $customer->getCity(),
                    'country_id' => $customer->getCountryId(),
                    'region' => '',
                    'region_id' => $customer->getRegionId(),
                    'postcode' => $customer->getPostcode(),
                    'telephone' => $customer->getTelephone(),
                    'fax' => '',
                ),
                'shipping_method' => 'flatrate_flatrate',
                'comment' => array(
                    'customer_note' => 'This order has been programmatically created via import script.',
                ),
                'send_confirmation' => 0
            ),
        );

        $this->create();

    }

    /**
     * Creates order
     */
    public function create()
    {
        $orderData = $this->orderData;

        if (!empty($orderData)) {

            $this->_initSession($orderData['session']);

            $this->_processQuote($orderData);
            if (!empty($orderData['payment'])) {
                $this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
                $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
            }

            $item = $this->_getOrderCreateModel()->getQuote()->getItemByProduct($this->product);

            foreach($this->product->getAttributes() as $option)
            {
                if ($option->getIsVisibleOnFront()) {
                    $item->addOption(new Varien_Object(
                        array(
                            'product' => $this->product,
                            'code' => $option->getAttributeCode(),
                            'value' => $option->getFrontend()->getValue($this->product)
                        )
                    ));;
                }
            }

            Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");

            $_order = $this->_getOrderCreateModel()
                ->importPostData($orderData['order'])
                ->createOrder();

            $this->_getSession()->clear();
            Mage::unregister('rule_data');

            return $_order;
        }

        return null;
    }

    protected function _processQuote($data = array())
    {
        /* Saving order data */
        if (!empty($data['order'])) {
            $this->_getOrderCreateModel()->importPostData($data['order']);
        }

        $this->_getOrderCreateModel()->getBillingAddress();
        $this->_getOrderCreateModel()->setShippingAsBilling(true);

        /* Just like adding products from Magento admin grid */
        if (!empty($data['add_products'])) {
            $this->_getOrderCreateModel()->addProducts($data['add_products']);
        }

        /* Collect shipping rates */
        $this->_getOrderCreateModel()->collectShippingRates();

        /* Add payment data */
        if (!empty($data['payment'])) {
            $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
        }

        $this->_getOrderCreateModel()
            ->initRuleData()
            ->saveQuote();

        if (!empty($data['payment'])) {
            $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
        }

        return $this;
    }

    /**
     * Retrieve order create model
     *
     * @return  Mage_Adminhtml_Model_Sales_Order_Create
     */
    protected function _getOrderCreateModel()
    {
        return Mage::getSingleton('adminhtml/sales_order_create');
    }

    /**
     * Retrieve session object
     *
     * @return Mage_Adminhtml_Model_Session_Quote
     */
    protected function _getSession()
    {
        return Mage::getSingleton('adminhtml/session_quote');
    }

    /**
     * Initialize order creation session data
     *
     * @param array $data
     * @return Mage_Adminhtml_Sales_Order_CreateController
     */
    protected function _initSession($data)
    {
        /* Get/identify customer */
        if (!empty($data['customer_id'])) {
            $this->_getSession()->setCustomerId((int) $data['customer_id']);
        }

        /* Get/identify store */
        if (!empty($data['store_id'])) {
            $this->_getSession()->setStoreId((int) $data['store_id']);
        }

        return $this;
    }

}

Thanks for any help


text:
Q: Does Asymptotic notation is a reflection of derivatives? Why does:
O(3n)=O(2n)=O(n)

Whereas their derivatives w.r.t n being 3, 2 and 1 respectively

A: Asymptotic Notation has no relation with derivatives. It is actually a measure of growth of function w.r.t. size of n. So, it tells us how a function will be changed on changing the value of n. If two functions get changed in same manner on changing n in the same way, we would call them the functions of same order. For example,Let f(n)=3n2+n+1 and g(n)=5n2+3n+1
If we double the n, both functions will roughly get 4 times of previous value. Hence they both are of order O(n2). We removed the constant coefficients(5 and 3) in Big-oh notation, because they are not contributing in telling how function is growing w.r.t. n (In every case, function will get 4 times). However we didn't remove the constant 2(power or exponent of n) because it is contributing in telling how function is growing w.r.t. n(Had we removed that constant and our function would get twice instead of 4 times hence we know it is contributing). Formally, we define Big-Oh notation as follows:
See here: Definition of Big O notation

f(n)=O(g(n)),  if and only if f(n)<=c.g(n) for some c>0 and n>=n0

Now let me show you how O(3n)=O(2n)=O(n)

Informal Proof:
f(n)=2n and g(n)=3n both will grow linearly w.r.t. n. By linearly, I mean that if we double/halve n, the function output will also get doubled/halved. It doesn't matter if we change the coefficient to 2,3, or 1000, it will grow linearly w.r.t n. So, that's why O(n)=O(2n)=O(3n)Notice that it is not about removing constants, it's about whether these constants contribute in telling about how our function is growing w.r.t. n.
As a counter-example for this, Let's suppose
f(n)=2n andg(n)=22n
We can't remove the 2 in exponent because that 2 is contributing and saying that g(n) will actually change in terms of square w.r.t. how f(n) would change.So,f(n)=O(2n)while g(n)=O(4n)
Formal Proof:

Suppose n is sufficiently largeif f(n)=O(n), g(n)=O(2n) and h(n)=O(3n) then f(n)<=c1n for some c1>0g(n)<=2c2n for some c2>0, let's have c3=2c2 hence g(n)<=c3n or g(n)=O(n) or O(2n)=O(n)Similarly h(n)<=3c4n or h(n)=O(n) or O(3n)=O(n)Hence, O(3n)=O(2n)=O(n)

Final Words:The key point is just to check how a function is growing. After practicing, you'd have some idea like anp+bnp-1+...+c = O(np)And many more.Read CLRS Book. I don't remember exactly but I think Chapter-3 is dedicated for this concept.


text:
Q: When does Postfix use IPv6 and when IPv4? I've configured my mail server for IPv6 and IPv4 but in the most cases it uses IPv4 while IPv6 is available on the remote host. I use Postfix in version 2.9. So my thought was that postfix uses IPv6 if available and has a fallback to IPv4 or am I wrong?

A: Granted that Postfix is correctly configured with IPv6, it is instructed to use both protocols and the MX host it connects to has both A and AAAA record, Postfix makes a random choice every time, as Wietse Wenema himself explained:

Recent Postfix SMTP clients randomly select between IPv4 and IPv6
  so that mail won't get stuck when one of the two is down.

A: Have you set the smtp_address_preference option to expliclity prefer IPv6?
From postconf(5):
smtp_address_preference (default: any)
       The address type ("ipv6", "ipv4" or "any") that the Postfix SMTP client will try first, when a destination has IPv6 and IPv4 addresses with equal MX preference. This feature has no effect unless  the
       inet_protocols setting enables both IPv4 and IPv6.  With Postfix 2.8 the default is "ipv6".

       Notes for mail delivery between sites that have both IPv4 and IPv6 connectivity:

       ·      The setting "smtp_address_preference = ipv6" is unsafe.  It can fail to deliver mail when there is an outage that affects IPv6, while the destination is still reachable over IPv4.

       ·      The setting "smtp_address_preference = any" is safe. With this, mail will eventually be delivered even if there is an outage that affects IPv6 or IPv4, as long as it does not affect both.

       This feature is available in Postfix 2.8 and later.


text:
Q: segment intersecting a tetrahedron I am trying to write C++ code to find the intersection points of a segment intersecting a tetrahedron. I reduced the problem like this:
For each face of the tetrahedron (a triangle), find the intersection point of the line segment. Then, I have three cases: a) The segment doesn't intersect any face - thus either the segment is entirely in the tetrahedron or completely outside. b) The segment only intersects one face. Then I just need to determine the side of the segment that is in the tetrahedron and I get the two points that are in the tetrahedron. c) The segment intersects two faces.
I am having trouble implementing this algorithm. Here are the issues:
If the segment and triangle are in the same plane, how do I find the intersection points?
How can I determine if the segment lies on one of the edges of the tetrahedron?
Thanks.

A: So your segment has endpoints $\mathbf p_1, \mathbf p_2$ and one of the planes is $\mathbf n \cdot \mathbf r = d$, where $\mathbf n$ points into the tetrahedron, then examine $\mathbf n \cdot \mathbf r - d$ for $\mathbf r = \mathbf p_1$ and $\mathbf r = \mathbf p_2$.

*

*If they are both negative for any of the 4 planes, then your segment does not intersect the tetrahedron.

*If for some plane, one is negative and the other point is $0$, and if the $0$ point is negative for some other plane, then your segment also does not intersect the tetrahedron.

*If all 4 planes have both points giving positive results, your segment lies entirely inside the tetrahedron, but does not intersect the faces.

Otherwise, your segment intersects the tetrahedron in at least one point. Go through your planes and if for any of them you have a negative point:

*

*If the other point is $0$, then the $0$ endpoint is the sole point of intersection with the tetrahedron.

*Otherwise, replace the negative point with $t\mathbf p_1 + (1-t)\mathbf p_2$, where $t = \frac{d - \mathbf n \cdot \mathbf p_2}{\mathbf n \cdot \mathbf p_1 - \mathbf n \cdot \mathbf p_2}$. This is the intersection of the segment with that plane. Check this new point against the all other planes.

When you are done, both points will have positive or 0 values for each plane, and at least one of them will have 0 values for some plane.

*

*If a point gives a $0$ value for some plane, then it lies within the triangular face in that plane.

*If it is $0$ for 2 planes, it lies within their common edge.

*If it is $0$ for 3 planes, it is their common vertex.

*If it is $0$ for all 4 planes, then your "tetrahedron" is degenerate.

*If it is positive for all planes, then it lies within the interior of the tetrahedron, and only the other endpoint is a point of intersection.

The segment is in a plane if both endpoints lie within that plane. The segment is along an edge, if both endpoints lie within the edge.


text:
Q: Proving $\frac{\sqrt{n}(S_n^2-\sigma^2)}{\sqrt{u_2-\sigma^4}}\rightarrow N(0,1)$ in distribution
Let $X_l, X_2,\ldots$ be i.i.d. with $E(X_1 ) = u$, $\operatorname{Var } (X_1) = \sigma^2$ and  $u_2 = E[(X_1 - u)^4]$. Let $S_n^2 = \frac{1}{n} \sum_{i=1}^{n} (X_i - \bar{X}_n)^2$ where $\bar{X}_n = \frac{\sum_{n=1}^{n} X_i}{n}$. Prove that $\frac{\sqrt{n}(S_n^2-\sigma^2)}{\sqrt{u_2-\sigma^4}}\rightarrow N(0,1)$ in distribution sense.

My thought: I tried to prove this using Levy-Cramer theorem with the help of Taylor series expansion, but I could not find the characteristic function of the given messy expression. Could someone please help find $\phi_{\frac{\sqrt{n}(S_n^2-\sigma^2)}{\sqrt{u_2-\sigma^4}}} (t)$ in terms of $\phi_{X} (h(t))$ where $h(t)$ could be any functions as long as the transformation makes sense? Otherwise, any inputs would really be appreciated.

A: We can replace $X_n$ by $X_n-u$, hence we can assume that $u=0$. We haved
\begin{align}
 \sqrt n\left( S_n^2-\sigma^2\right)&=\frac 1{\sqrt n}\sum_{i=1}^n \left(X_i^2 -\sigma^2\right) -2 \sqrt n\overline{X_n}^2 +  \sqrt n\overline{X_n}^2\\
&=\frac 1{\sqrt n}\sum_{i=1}^n \left(X_i^2 -\sigma^2\right) - \sqrt n\overline{X_n}^2.
\end{align}
Now, notice that $$\tag{*}   \sqrt n\overline{X_n}^2 =\frac 1{\sqrt n}\left(\frac 1{\sqrt n}  \sum_{i=1}^nX_i   \right)^2, $$
hence by Slutsky's lemma and the central limit theorem, $\sqrt n\overline{X_n}^2\to 0$ in probability.
In order to reach the wanted conclusion, use the central limit theorem for the i.i.d. centered sequence $\left(\left(X_i^2-\sigma^2\right)/\sqrt{ u_2-\sigma^2} \right)_{i\geqslant 1}$ (because the variance of $X_1^2-\sigma^2$ is $\mathbb E\left[X_1^4\right]-\sigma^4=u_2-\sigma^4$).

A: First assume that $u = 0$ without loss of generality. You can do this because $S_n^2$ doesn't change if you consider $X_i-u$ instead of $X_i$.
We are going to need the multivariate central limit theorem here. It is the same as the ordinary central limit theorem but instead of variance you have the covariance matrix of the random vector. Note that the sequence $\left(\begin{pmatrix}X_i\\ X_i^2\end{pmatrix}\right)_i$ is i.i.d and it does have a covariance matrix since the fourth moment of $X_1$ exists as stated in your question. So let's apply the central limit theorem to this sequence.
$$\sqrt{n}\left(\begin{pmatrix}\frac{1}{n}\sum_{i=1}^nX_i\\ \frac{1}{n}\sum_{i=1}^nX_i^2\end{pmatrix} - \begin{pmatrix}0\\ \sigma^2 \end{pmatrix}\right) \rightsquigarrow N(0,\Sigma)$$
Here $\Sigma$ denotes the covariance matrix of  $\begin{pmatrix}X_1\\ X_1^2\end{pmatrix}$.
Next we are going to use the delta method. Note that $S_n^2 = \frac{1}{n}\sum_{i=1}^nX_i^2 - \bar{X}_n^2$. So then (using the notation on the Wikipedia page) the transformation we have is $g(x,y) = y - x^2$. Make sure you check the conditions needed on $g$ for the delta method to work.
So then,
$$\sqrt{n}\left(S_n^2-\sigma^2\right) \rightsquigarrow N(0,\begin{pmatrix}0 & 1\end{pmatrix}\Sigma\begin{pmatrix}0 \\ 1\end{pmatrix})$$
By construction $\begin{pmatrix}0 & 1\end{pmatrix}\Sigma\begin{pmatrix}0 \\ 1\end{pmatrix} = Var(X_1^2)$. Check that $Var(X_1^2) = u_2 - \sigma^4$.
Hence
$$\frac{1}{\sqrt{u_2 - \sigma^4}}\sqrt{n}\left(S_n^2-\sigma^2\right) \rightsquigarrow N(0,1)$$


text:
Q: Share session variable over different ports in local development I currently have Django on port 8000 and Angular on port 4200.
In production they will be on the same port 80.
Due to the ports being different the session cookies are different so the authentication fails.
How can I have these two app on different ports share one set of cookies / session?

A: In production you will set the SESSION_COOKIE_DOMAIN in your project settings.
If you're using django-cors-headers in development you can just set CORS_ALLOW_CREDENTIALS to True (you'll want to disable this in production) and add your frontend port to the CORS_ORIGIN_WHITELIST to allow requests from that origin.


text:
Q: Sort this list of tuples by the time span content_dict = [(u'Bowe Bergdahl', [u'Sat, 31 May 2014 16:03:32 EDT']), (u"U.S. 'hypocrisy' in cybertheft charge", [u'Fri, 23 May 2014 02:30:44 EDT'])

What is wrong with this lambda function:
content2_dict =  sorted(content_dict, key=lambda x: datetime.strptime(x[0],'%a, %d %b %H:%M:%S %z'))

I get the following error:
Traceback (most recent call last):
  File "/Users/amirnakhostin/Documents/Computer Science /Python/test.py", line 17, in <module>
    content2_dict =  sorted(content_dict, key=lambda x: datetime.strptime(x[1],'%a, %d %b %H:%M:%S'))
  File "/Users/amirnakhostin/Documents/Computer Science /Python/test.py", line 17, in <lambda>
    content2_dict =  sorted(content_dict, key=lambda x: datetime.strptime(x[1],'%a, %d %b %H:%M:%S'))
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'o' does not match format '%a, %d %b %H:%M:%S'

A: I also had a problem with a timezone, had to remove it.

import datetime

content_dict = [(u'Bowe Bergdahl', [u'Sat, 31 May 2014 16:03:32']), (u"U.S. 'hypocrisy' in cybertheft charge", [u'Fri, 23 May 2014 02:30:44'])]

content2_dict =  sorted(content_dict, key=lambda x: datetime.datetime.strptime(x[1][0],'%a, %d %b %Y %H:%M:%S'))
print content2_dict

A: There is a missing %Y between %b and %H:%M:%S.
To access a time string in your content_dict, x[1][0] should be used instead of x[0].
Here lies a workaround solution, since python (or datetime module) has some problem handling time zones (HKT can be parsed while EDT can't which confuses me) and assuming that all the timezones are the same, I just simply stripped all the time zones away.
content2_dict = sorted(content_dict, key=lambda x: datetime.strptime(x[1][0][:-4], '%a, %d %b %Y %H:%M:%S'))

A: There are a couple problems, you are indexing the wrong thing in your lambda, you forgot a year, %H:%M:%S can be written as %X, and EDT, unfortunately, can't be parsed:
from datetime import datetime
content_dict = [(u'Bowe Bergdahl', [u'Sat, 31 May 2014 16:03:32']), (u"U.S. 'hypocrisy' in cybertheft charge", [u'Fri, 23 May 2014 02:30:44'])]
content_dict_ = sorted(content_dict, key=lambda x: datetime.strptime(x[1][0],'%a, %d %B %Y %X'))

A: Several problems with your code.  You improperly formatted strptime by omitting the year %Y.  You also enclosed the date in a list which caused other problems.  You were trying to use x[0] when your date was enclosed in x[1].  Here is a working example of (almost all) of your code (note that the time zone has been removed.  See below for why).
>>> content = [(u'Bowe Bergdahl',u'Sat, 31 May 2014 16:03:32'), (u"U.S. 'hypocrisy' in cybertheft charge", u'Fri, 23 May 2014 02:30:44')]
>>> content2 = sorted(content, key=lambda x:datetime.datetime.strptime(x[1], '%a, %d %B %Y %H:%M:%S'))
>>> content2
[(u"U.S. 'hypocrisy' in cybertheft charge", u'Fri, 23 May 2014 02:30:44'), (u'Bowe Bergdahl', u'Sat, 31 May 2014 16:03:32')]

However we get from this question that strptime has some issues with time zones.  To fix that issue we use the dateutil package
>>> from dateutil import parser
>>> parser.parse(u'Sat, 31 May 2014 16:03:32 -0400')
datetime.datetime(2014, 5, 31, 16, 3, 32, tzinfo=tzoffset(None, -14400))

Note that -0400 is EDT relative to GMT.
To use this to sort your list do something like the following
>>> from dateutil import parser
>>> unformatted_content = [(u'Bowe Bergdahl', u'Sat, 31 May 2014 16:03:32 -0400'), (u"U.S. 'hypocrisy' in cybertheft charge", u'Fri, 23 May 2014 02:30:44 -0400')]
>>> real_content = [(item[0], parser.parse(item[1])) for item in unformatted_content]
>>> real_content
[(u'Bowe Bergdahl', datetime.datetime(2014, 5, 31, 16, 3, 32, tzinfo=tzoffset(None, -14400))), (u"U.S. 'hypocrisy' in cybertheft charge", datetime.datetime(2014, 5, 23, 2, 30, 44, tzinfo=tzoffset(None, -14400)))]
>>> content2 = sorted(real_content, key=lambda x:x[1])
>>> content2
[(u"U.S. 'hypocrisy' in cybertheft charge", datetime.datetime(2014, 5, 23, 2, 30, 44, tzinfo=tzoffset(None, -14400))), (u'Bowe Bergdahl', datetime.datetime(2014, 5, 31, 16, 3, 32, tzinfo=tzoffset(None, -14400)))]


text:
Q: Likert problems with grouping in R I recently asked a question regarding using grouping with the likert package in order to visualise my data. The answer I got worked fine on my example data set.
link: likert grouping question
Here was the solution proposal:
foo <- data.frame(car = rep(c("Toyota", "BMW", "Ford"), times = 10),
                  satisfaction = c(1,3,4,7,7,6,2,3,5,5,5,2,4,1,7),
                  quality = c(1,1,3,5,4,3,6,4,3,6,6,1,7,2,7),
                  loyalty = c(1,1,3,5,4,3,9,4,3,10,6,1,7,2,8) )

foo[2:4] <- lapply(foo[2:4], factor, levels=1:10)
likt <- likert(foo[,c(2:4)], grouping = foo$car)
plot(likt)

However, when I tried this on my dataset I got an error message I was not able to understand:
library(reshape)
library(likert)

setwd("C:/mypath")
df<- fread("myfile.csv", select = 1:9)
df <- as.data.frame(df)

#reduce the colnames length
names(df) <- sub("^(.+[:])([^.]+)$", "\\2", names(df))

col_names <- names(df[1:9])
df[,col_names] <- lapply(df[,col_names] , factor, levels = 1:10)
str(df)

df[2:9] <- lapply(df[2:9], factor, levels=1:10)
lik2 <- likert(df[,c(2:9)], grouping = df$Make)
plot(lik2)

error message:
Error in `$<-.data.frame`(`*tmp*`, "low", value = c(NA_real_, NA_real_,  :
  replacement has 8 rows, data has 0

Any ideas?

A: Found the rookie misstake!!
Should start at the second column sinnce the numerical data starts there.. simple as that..
col_names <- names(df[2:9])


text:
Q: Deadlocks c# Solution Hi guys I'm improving my knowledge of multithreading C# and  was wondering how to solve this classic deadlock issue.
public class SomeClass
{
    private object _lock1 = new object();
    private object _lock2 = new object();

    public void Method1()
    {
        lock (_lock1)
        {
            Thread.Sleep(10000);
            lock (_lock2)
            {
                Thread.Sleep(10000);
            }
        }
    }

    public void Method2()
    {
        lock (_lock2)
        {
            Thread.Sleep(10000);
            lock (_lock1)
            {
                Thread.Sleep(10000);
            }
        }
    }
}

If two threads run simultaneously there is a risk of a deadlock.
Thanks

A: *

*Take your locks in a consistent order

*Keep your locks as granular as possible

*Avoid locks when possible by using immutable data structures

*Use Monitor.TryEnter instead of lock (which doesn't timeout)

A: This is not a C# issue it is more general.
Your example is obviously not correct.
Try to avoid lock imbrication is the common pattern were you end up in a deadlock.
There a good book about synchronization:
 http://greenteapress.com/semaphores/

A: You must always take locks in the same order: first lock one, then lock two and so on.
You don't need to always take all locks: for example, you can have method1() take lock1 and lock2, and method2() take only lock2, it will not cause a deadlock.


text:
Q: CSS Rounded corners for table header with background-color I'm trying to create a table with rounded top corners and a different background color for the header line. I succeeded in making both individually (super beginner in html/css) thanks to online ressources but I fail when it comes to have the two at the same time.
What I mean is (and you can see it in the fiddle below), I can round the corners just fine and have the design I want for my table except that the header background-color is still a perfect rectangle and thus is overflowing outside the rounded corners.
I tried adding the border-radius property in various places but none worked the way I intended. How can I make the corners rounded and having the thead background-color fitting nicely in it ?

table.std {
  margin-top: 0.2cm;
  width: 100%;
  border: 0.03cm solid #8a8a8a;
  border-spacing: 0;
  border-radius: 15px 15px 0px 0px;
  font-size: 10pt;
}

table.std thead {
  text-align: left;
  background-color: lightgray;
  height: 25px;
}

table.std thead tr th:first-child {
  padding-left: 0.25cm;
  /* To align with section title */
  border-bottom: 0.03cm solid #8a8a8a;
}

table.std tbody tr td:first-child {
  padding-left: 0.25cm;
  /* To align with section title */
  width: 30%;
}

table.std tbody tr td {
  border-bottom: 0.01cm dashed lightgray;
  height: 20px;
}

        Test

        ID
        id1

        Date
        2019/12/19

        foo
        bar

        lorem
        ipsum

        john
        doe

https://jsfiddle.net/co7xb42n/
Thanks for the help

A: Add the border-radius to th
table.std thead tr th:first-child {
    padding-left: 0.25cm; /* To align with section title */
    border-bottom: 0.03cm solid #8a8a8a;
    border-radius: 15px 15px 0px 0px;
}

https://jsfiddle.net/53eshg64/

A: add border-radius from th tag.

table.std {
    margin-top: 0.2cm;
    width: 100%;
    border: 0.03cm solid #8a8a8a;
    border-spacing: 0;
    border-radius: 15px 15px 0px 0px;
    font-size: 10pt;
}

table.std thead {
    text-align: left;
    background-color: lightgray;
    height: 25px;
}

table.std thead tr th:first-child {
    padding-left: 0.25cm; /* To align with section title */
    border-bottom: 0.03cm solid #8a8a8a;
    border-radius: 15px 15px 0px 0px;
}

table.std tbody tr td:first-child {
    padding-left: 0.25cm; /* To align with section title */
    width: 30%;
}

table.std tbody tr td {
    border-bottom: 0.01cm dashed lightgray;
    height: 20px;
}

                            Test

                            ID
                            id1

                            Date
                            2019/12/19

                            foo
                            bar

                            lorem
                            ipsum

                            john
                            doe

A: This is cause the th tag is above of the table tag and it doesn't have any border-radius
Add the border-radius to th


text:
Q: Cordova: Share webview cookies with native plugins I have a cordova app, running iOS and Android, which uses cookies for authentication (the user just types in email and password, and the in app browser sets the cookies, backend in Rails with devise). This works so far.
Now I have a native plugin for android and iOS, which uploads some data in background mode (iOS) / as a service (Android). The problem is, that the URL the plugin is trying to access is also protected. So the plugins somehow needs to send the cookies along with the request.
I have found a number of articles, most of them a little bit old (like this one http://blog.winfieldpeterson.com/2013/01/17/cookies-in-hybrid-android-apps), and every solutoin feels like a little bit of overkill.
I'm using Cordova 4.3.0, and maybe there is a standard solution to this, that I haven't found (and got updated since all the other articles were written).
Here is a part of my Android and iOS code, which sends the data to the server:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpClient httpclient = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(httpclient.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, httpclient.getParams());

// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

HttpPost httppost = new HttpPost(locationCache.getUrl());
httppost.setHeader("Content-type", "application/json");

JSONObject body;
body = new JSONObject();
body.put("someKey", "someData");

HttpResponse response = httpclient.execute(httppost);

And the iOS version:
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:geodata options:0 error:&err];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:url]];
postRequest.HTTPMethod = @"POST";
[postRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
postRequest.HTTPBody = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:postRequest queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if(error) {
                             NSLog(@"Httperror: %@, %d", error.localizedDescription, error.code);
                           } else {
                              NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                              NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                              NSLog(@"REQUEST SENT TO SERVER! HTTP response code: %d; response body: %@", responseCode, responseString);
                           }
                       }];

Hope somedbody can help.

A: On iOS you can get the cookies for an url like this:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"__YOUR_URL__"]];

or all the cookies like this:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];

after that, you can set the request header like this:
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[postRequest setAllHTTPHeaderFields:headers];

On android you have the webview CookieManager
CookieManager cookieManager=CookieManager.getInstance();
String cookie=cookieManager.getCookie(url);


text:
Q: Any gotchas with changing IP address of Postgres Master? We have to replace our Master Postgres database and due to restrictions in AWS, we cannot use the same IP address for the new server (not 100% true, but cannot do this until the original is terminated and for the sake of safety I'd rather not terminate it before the new one is bedded in).
Aside from the IP changes required in the pg_hba.conf, are there any other points I need to be mindful of?
I'm currently going through the slave and checking for instances of the primary's IP address and it's showing up in some files in $POSTGRES_DATA/main/base/ which is why I'm asking.
Postgres 9.1 on Ubuntu 12.04
Thanks

A: There are several places you'd want to change the IP address for a PostgreSQL primary server. Most of them are actually outside of PostgreSQL itself or its configuration, though.
You already mentioned the pg_hba.conf so that doesn't need to be mentioned.

*

*Tables that you have inet types for, or other columns you store IP addresses in. If you found IP addresses in $PGDATA/base via a grep, then that probably means that you have IP address entries in your tables, and looking at the information_schema.columns table for those would be most helpful.
Really, needing to touch anything inside of a PostgreSQL data directory outside of .conf files is not recommended at all.

*postgresql.conf listen_addresses entries.

*Any recovery.conf files that have the primary's IP address referenced for streaming replication.

*IP addresses listed in pgbouncer or pgpool-II configurations.

*IPTables or other firewall rules on your servers.

*Application configurations.

*Remote backup scripts.
These are just highlights.
A comprehensive list will require you going patiently through everything in your setup. Creating a good checklist of what needs to be changed in the event of a failover (and keeping it up to date!) will help you immensely in the future, and improve your disaster recovery and high-availability readiness.
Hope that helps. =)


text:
Q: Prove that for all real numbers x and y we have $| |x| - |y| | \leq |x-y|$. This is my second attempt at proving this inequality, the first one went terribly so hopefully I did a better job this time.
Firstly we are given as fact (by the examiner). $||x|-|y|| = |x| - |y| $ for all $|x| \geq |y|$ and $||x|-|y|| = |y| - |x|$ for all $|x| \leq |y|$.
Let...
$$ |x| \leq |y| \iff |x|-|y| \leq 0 \leq|x-y|  $$
Let..
$$ |y| \leq |x| \iff 0\leq|x| - |y| = |x-y| = |y-x| \leq|x-(-y)| = |(-y)-x|| $$
Therefore for any real number $x$ and $y$ the inequality $||x|-|y|| \leq |x-y|$ holds.
Any feedback would be much appreciated.

A: Your proof is incorrect. In the first case, you actually have to show $|y|-|x|\leq |x-y|.$ In the second case, you write $|x|-|y|=|x-y|,$ which is incorrect.
A correct proof can be found here, or here or for an arbitrary metric.


text:
Q: How to mock multiple functions of a typescript class? Suppose, I have a typescript class
a.ts
export class A {
    constructor() {
         this.__functionA()
    }

    private __functionA(){
        this.__functionB()
    }

    private __functionB(){
    }

}

Now, I have some tests for my Class
import { A } from "./a"

describe("Class A",() => {

    it(`__functionB should Have been called`,() => {

        A.proptotype.__functionB = jest.fn()
        A.proptotype.__functionA = jest.fn()

        let instance = new A()

        expect (instance.__functionB).toHaveBeenCalled()
        expect (instance.__functionA).toHaveBeenCalled()

    })
})

the tests fail with an error
expect(jest.fn()).toHaveBeenCalled()

Now, when I mock only the __functionA of ClassA and run my assertions against only that function, i.e. expect (instance.__functionA).toHaveBeenCalled(), my test pass. Why so?
And How can I mock more than one functions of a Class?
Correct me, if I am doing something wrong here.
N.B.:- I am using jest to run my tests.

A: Found the answer,
I just had to replace
A.proptotype.__functionB = jest.fn()
A.proptotype.__functionA = jest.fn()

with
jest.spyOn(A.proptotype,__functionA)
jest.spyOn(A.proptotype,__functionB)

and everything works fine.
Hope, this helps someone.


text:
Q: Computed property returning state variable isn't reactive For a hangman game I have a Word.vue component in which I'm trying to initialise an array named wordToGuessAsArray containing n empty items (n = number of letters in word to guess):
<template>

</template>

Below is the content of my store relevant to this question:
state: {
  wordToGuessAsArray: [],
},
mutations: {
  SET_WORD_AS_ARRAY_PUSH (state) {
    state.wordToGuessAsArray.push('')
  },
  SET_WORD_AS_ARRAY (state, value) {
    state.wordToGuessAsArray[value.i] = value.letter
  }
}

My problem is the following. In my Keyboard.vue component, when user picks a letter that does indeed belong to the word to guess, I update my state thus:
this.$store.commit('SET_WORD_AS_ARRAY', { letter, i })

I expect this mutation to update the word in my Word.vue component here:

Yet it doesn't. wordToGuessAsArray seems non reactive, why?

A: It is because state.wordToGuessAsArray[value.i] = value.letter is not reactive.
Because Vue.js only watch array methods like push or splice.
You need to do this.$set(state.wordToGuessAsArray, value.i, value.letter);
Or in Vuex :
Vue.set(state.wordToGuessAsArray, value.i, value.letter); and import Vue in your file.
Read more here :
https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
Vuejs and Vue.set(), update array


text:
Q: Fetch data from XML file located in sdcard (Android) This is my first post here :-). I am developing an application for android in eclipse.
My question is I have put an XML file in sdcard with some elements like id,First name and lastname.
Form my UI i have one textbox and button. User will enter ID in the textbox and on click event of button I should fetch the data based on that ID. and display in TextView.
Any help please??
Thanks in advance. :-)
Here is a sample of XML file which is given to me,
<tblInsurees xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1">
  <ID>1</ID>
  <LastName>Family 1 (1-42-167)</LastName>
  <OtherNames>FamMem1</OtherNames>
  <DOB>01-01-85</DOB>
  <PhotoFileName xsi:nil="true" />
  </tblInsurees>
- <tblInsurees xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1">
  <ID>2</ID>
  <LastName>Family 2 (1-4-16)</LastName>
  <OtherNames>FamMem1</OtherNames>
  <DOB>01-01-85</DOB>
  <PhotoFileName xsi:nil="true" />
  </tblInsurees>
- <tblInsurees xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1">
  <ID>3</ID>
  <LastName>Family 3 (1-4-16)</LastName>
  <OtherNames>FamMem3</OtherNames>
  <DOB>01-01-98</DOB>
  <PhotoFileName xsi:nil="true" />
  </tblInsurees>

SO is it possible that somehow I can pass an ID as a parameter and I can just display the rest of the information like name and dob etc on my screen?

A: Here is a complete example with source. You just to get the File using
 File file = new File(Environment.getExternalStorageDirectory()
                    + "your_path/your_xml.xml");

Then do the further processing.
If you need example for different types of XML Parsers you can download complete example from here.


text:
Q: PrestaSitemap bundle generates localhost on production server I'm using Presta SiteMap Bundle for generating sitemaps on my site, but when it generates to me sitemaps on prod server path to sitemaps looks like below:
http://localhost/sitemap.holidayideas.xml
What should I write in config or anywhere in my app to generate correct url's for my sitemaps.
P.S. I'm using Symfony 3.3.2 for my app

A: I found the solution - need to specify url and protocol in parameters.yml as below:
# app/config/parameters.yml
parameters:
    router.request_context.host:   your-domain.com
    router.request_context.scheme: http


text:
Q: how could i decrypt the below payload into human readable text?? kindly suggest me the algorithms and decoders 0x0000:  4500 00bc 0000 4000 4011 281d c0a8 c801  E.....@.@.(.....
0x0010:  c0a8 c8c1 0035 2f16 00a8 bf52 1a74 8183  .....5/....R.t..
0x0020:  0001 0000 0001 0000 0136 0139 0161 0163  .........6.9.a.c
0x0030:  0161 0136 0163 0135 0166 0130 0137 0137  .a.6.c.5.f.0.7.7
0x0040:  0162 0138 0138 0135 0130 0130 0130 0130  .b.8.8.5.0.0.0.0
0x0050:  0130 0130 0130 0130 0130 0130 0130 0130  .0.0.0.0.0.0.0.0
0x0060:  0130 0138 0165 0166 0369 7036 0461 7270  .0.8.e.f.ip6.arp
0x0070:  6100 000c 0001 c04c 0006 0001 0000 0e10  a......L........
0x0080:  003a 0162 0b69 7036 2d73 6572 7665 7273  .:.b.ip6-servers
0x0090:  c050 0a68 6f73 746d 6173 7465 7205 6963  .P.hostmaster.ic
0x00a0:  616e 6e03 6f72 6700 781c 5634 0000 0708  ann.org.x.V4....
0x00b0:  0000 0384 0009 3a80 0000 0e10            ......:.....

The above format is normal text encrypted with some algorithm and converted as payload. How to decrypt and read it as normal form.And please exaplain me what are all these.I assumed all these as a payload.

A: This is not encrypted. This is a normal dump of an IP packet. Let's try to read it.
First 4 bits say ip version 4, next 4 bits: header length 5 (5 * 4 = 20 bytes), TOS = 0, total length = 0xBC (which matches the length of the dumped packet so we're on the right track), ID = 0, offset has the "don't fragment" flag set, TTL = 0x40 (64), protocol = 0x11 (UDP), checksum 0x281d, source address = 192.168.200.1, destination address = 192.168.200.193.
Then the UDP packet follows, source port = 53 (which is DNS), destination port = 12054, length = 168, checksum 0xbf52, the rest is the payload which I can't be bothered to decode but it looks like a reverse lookup of an ipv6 address.


text:
Q: Socket not open correctly when using Threads c++ Hey in trying to parctice with sockets and threading.
Im trying to do a little program that accept clients from one thread and add messages from client into queue. and from another thread print the messages to console.
but for some reason when i split the proccess to 2 threads, the socket not opened correctly and the listen function return 10022 error on WSAGetLastError.
the source code:
void SlaveThread(queue<char*>* tasks);
void MasterThread(queue<char*>* tasks);

int _tmain(int argc, _TCHAR* argv[])
{
    queue<char*>* tasksQueue = new queue<char*>();

    thread SecondThread(MasterThread,tasksQueue);
    thread FirstThread(SlaveThread,tasksQueue);

    FirstThread.join();
    SecondThread.join();
    return 0;
};

void SlaveThread(queue<char*>* tasks)
{
    while (true)
    {
        if (!tasks->empty())
        {
            cout << tasks->front() << " Queue size : " << tasks->size() << endl;
            tasks->pop();
        }

        Sleep(1000);
    }
};

void MasterThread(queue<char*>* tasks)
{
    WSAData WinSockData;
    WORD Version = MAKEWORD(2, 1);

    WSAStartup(Version, &WinSockData);

    /* Create socket structure */
    SOCKADDR_IN Server;
    Server.sin_addr.s_addr = inet_addr("10.0.0.7");
    Server.sin_family = AF_INET;
    Server.sin_port = htons(27015);

    SOCKET ListenSock = socket(AF_INET, SOCK_STREAM, NULL);
    SOCKET Connect;
    bind(ListenSock, (SOCKADDR*)&Server, sizeof(Server));
    listen(ListenSock, 1);
    int errno1 = WSAGetLastError();
    cout << "Listening on port 27015" << endl;
    //char buffer[200];
    int size = sizeof(Server);
    while (true)
    {
        if (Connect = accept(ListenSock, (SOCKADDR*)&Server, &size)){
            int errno1 = WSAGetLastError();
            cout << "Connection established.. " << endl;
        }
        //if (recv(ListenSock, buffer, 200, 0) > 0)
        //{
        //  tasks->push(buffer);
        //}
    }

    WSACleanup();
};

any suggestion why it's break when i add threads to program? because on empty program just opening the socket with the same code it's work properly.

A: 1) Use INADDR_ANY
2) Use ::bind instead of bind.  The name is ambiguous to an standard template library call.  This is why using namespace std is bad.
void MasterThread(queue<char*>* tasks)
{
    WSAData WinSockData;
    WORD Version = MAKEWORD(2, 1);

    WSAStartup(Version, &WinSockData);

    /* Create socket structure */
    SOCKADDR_IN Server;
    Server.sin_addr.s_addr = INADDR_ANY;//inet_addr("10.0.0.7");
    Server.sin_family = AF_INET;
    Server.sin_port = htons(27015);

    SOCKET ListenSock = socket(AF_INET, SOCK_STREAM, NULL);
    SOCKET Connect;
    ::bind(ListenSock, (SOCKADDR*)&Server, sizeof(Server));
    int errno0 = WSAGetLastError();
    listen(ListenSock, 1);
    int errno1 = WSAGetLastError();
    cout << "Listening on port 27015" << endl;
    //char buffer[200];
    int size = sizeof(Server);
    while (true)
    {
        if (Connect = accept(ListenSock, (SOCKADDR*)&Server, &size)){
            int errno1 = WSAGetLastError();
            cout << "Connection established.. " << endl;
        }
        //if (recv(ListenSock, buffer, 200, 0) > 0)
        //{
        //  tasks->push(buffer);
        //}
    }

    WSACleanup();
};


text:
Q: Contour Integral with Real Singularity So, if I'm working in spherical coordinates, how would I evaluate the following integral?  I know that I'm supposed to use contour integration and Jordan's lemma, but the fact that the singularity is located on the real axis is really throwing me off.  Any advice for solving this improper integral via contour integration only?
$$\int_0^\infty{\frac{r \sin{(r\rho)}}{r^2-\alpha^2}} dr$$ where alpha is a real number

A: Hint: begin by noting that
$$
\int_0^\infty{\frac{r \sin{(r\rho)}}{r^2-\alpha^2}}\,dr =
\Im\left\{
\int_0^\infty{\frac{r e^{(ir\rho)}}{r^2-\alpha^2}}\,dr
\right\}
$$
For the indentation contour around $\alpha$: let $\gamma_\epsilon$ be a semicircle of radius $\epsilon$ that goes counterclockwise around $\alpha$.  We wish to evaluate
$$
\int_{\gamma_\epsilon} \frac{z e^{(iz\rho)}}{z^2-\alpha^2}\,dz =
\int_{\gamma_\epsilon} \frac{1}{z - \alpha} \cdot \frac{z e^{(iz\rho)}}{z+\alpha}\,dz
$$
Noting that $g(z) = \frac{z e^{(iz\rho)}}{z+\alpha}$ is continuous around $z = \alpha$, we can take $\epsilon$ sufficiently small so that $g(z) \approx g(\alpha)$ when $|z- \alpha| < \epsilon$.  We conclude
$$
\lim_{\epsilon \to 0^+} \int_{\gamma_\epsilon} \frac{g(z)}{z-\alpha}\,dz =
\int_{\gamma_\epsilon} \frac{g(\alpha)}{z-\alpha}\,dz = \pi i g(\alpha)
$$

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
$\ds{\int_{0}^{\infty}{r\sin\pars{r\rho} \over r^{2} - \alpha^{2}}\,\dd r:\
     {\large ?}.\quad}$
These integrals are very common in Quantum Mechanics as related to scattering theory. In that cases, $\ds{\alpha}$ has a 'small' imaginary part which indicates whether a wave is going to a scattering center or is leaving the scattering center.

The 'history' is more or less like this:
  \begin{align}
&\color{#c00000}{\int_{0}^{\infty}{r\sin\pars{r\rho}\over
r^{2} - \pars{\verts{\alpha} \pm \ic 0^{+}}^{2}}\,\dd r}
\\[3mm]&=\int_{0}^{\infty}r\sin\pars{r\rho}\,
{1 \over 2\pars{\verts{\alpha} \pm \ic 0^{+}}}\bracks{%
{1 \over r - \pars{\verts{\alpha} \pm \ic 0^{+}}}
-{1 \over r + \pars{\verts{\alpha} \pm \ic 0^{+}}}}\,\dd r
\\[3mm]&={1 \over 2\pars{\verts{\alpha} \pm \ic 0^{+}}}\,2\ic\,
\Im\int_{0}^{\infty}{r\sin\pars{r\rho} \over r - \verts{\alpha} \mp \ic 0^{+}}\,\dd r
\\[3mm]&={\ic \over \verts{\alpha} \pm \ic 0^{+}}
\int_{0}^{\infty}r\sin\pars{r\rho}
\bracks{\pm\,\pi\,\delta\pars{r - \verts{\alpha}}}\,\dd r
={\ic \over \verts{\alpha} \pm \ic 0^{+}}
\,\bracks{\pm\pi\verts{\alpha}\sin\pars{\verts{\alpha}\rho}}
\\[3mm]&=\pm\ic\pi\verts{\alpha}\sin\pars{\verts{\alpha}\rho}\,
\bracks{\pp{1 \over \verts{\alpha}} \mp \ic\pi\delta\pars{\verts{\alpha}}}
\end{align}
  where $\ds{\delta\pars{x}}$ is the
  Dirac Delta 'Function' and we used the identities ( 'under' the integral sign )
  $\ds{{1 \over x \pm \ic 0^{+}} = \pp{1 \over x} \mp \ic\pi\delta\pars{x}}$. $\ds{\pp}$ denotes the Principal Value.

$$
\color{#00f}{\large\int_{0}^{\infty}
{r\sin\pars{r\rho} \over r^{2} - \pars{\verts{\alpha} \pm \ic 0^{+}}^{2}}\,\dd r
=\pm\,\ic\pi\sin\pars{\verts{\alpha}\rho}}
$$


text:
Q: How can I implement transfert learning with tensorflow I am currently working on a deep neural network, and I want to make a transfer learning to my model, I have founded a ckpt who where generated from another model, and I want to use this ckpt in my own model, the problem is that my model is completely different "numbre of layer, number of output", my question is how can I use the ckpt in my lowest layer ?
I use Tensorflow
Thanks

A: What you need is tf.train.Saver class. There is var_list parameter which you could use to set up a correspondence between saved weights and variables in the current graph.


text:
Q: std::unordered_map - Implicit instantiation of undefined template? I've done lots of languages, but I'm new to C++ and I'm completely stumped about how to initialize class instances. The following code gets an error at
class MyClass
{
   public:

    //Hash map variable

    //ERROR BELOW
    std::unordered_map<int, float, std::hash<int>, std::equal_to<int>, std::allocator<int>> myUnorderedMap;

}

I think I'm filling in the template incorrectly. Any help would be fantastic.

A: You need to include the library header:
#include <unordered_map>

and you don't need to put default types in your declaration:
std::unordered_map<int, float> myUnorderedMap;