text:
Q: (UPDATED) How do I find the intersection of this involute and trochoid, given their parametric equations? I have two parametric curves. The first, an involute of a circle with parameter theta:
$$x_1(θ) = Z × \cos(α) × (\cos(θ − \tan(α) + α) + θ × \sin(θ − \tan(α) + α)),$$
$$y_1(θ) = Z × \cos(α) × (\sin(θ − \tan(α) + α) − θ × \cos(θ − \tan(α) + α)),$$
$$0 ≤ θ_{min} ≤ θ ≤ θ_{max}$$
(note that theta must always be greater than or equal to zero)
And the second, a trochoid with parameter gamma:
$$x_2(γ) = (Z − 2 × (C − X)) × \cos(γ) + (Z × γ + 2 × \tan(α) × (C − X)) × \sin(γ),$$
$$y_2(γ) = (Z − 2 × (C − X)) × \sin(γ) − (Z × γ + 2 × \tan(α) × (C − X)) × \cos(γ),$$
$$γ_{min} ≤ γ ≤ γ_{max}$$
With four independent variables:

*

*$Z$ is a positive integer,

*$X$ is a real number in the interval $[−1, 1]$,

*$C$ is a real number in the interval $[1, 1.5]$, and

*$α$ is an angle in the interval $\left[0, \arctan\left(\frac{π}{4 × C}\right)\right]$,

And where:

*

*$θ_{max} = \frac{\sec(α)}{Z} × \sqrt{(2 × X + Z + 2)² − Z² × \cos(α)²}$,

*$γ_{max} = \frac{−2}{Z} × (C − X) × \tan(α)$, and

*$θ_{min}$ and $γ_{min}$ are the parameter values at the intersection that I want to find.

I know that the curves have a touching intersection (where their tangents are the same) at the parameter values $θ = \tan(α) − \frac{4}{Z} × (C − X) × \csc(2 × α)$ and $γ = \frac{−4}{Z} × (C − X) × \csc(2 × α)$. See the red and blue curves in the following picture.

However, when the values of the four variables are such that $α < \arcsin\left(\sqrt{\frac{2}{Z} × (C − X)}\right)$, two things happen. First, the expression for theta in the previous paragraph goes negative, which makes it invalid for my purposes. Second, a transversal intersection (where the curves' tangents are distinct) appears at values of gamma and theta closer to zero than those for the touching intersection, and specifically with a positive value of theta. See the red and blue curves in the following picture.

THE PROBLEM:
I want to find the parameter values $θ_{min}$ and $γ_{min}$ for this transversal intersection in terms of $Z$, $α$, $X$, and $C$, in all cases where $α < \arcsin\left(\sqrt{\frac{2}{Z} × (C − X)}\right)$, given the stated domains of the independent variables $Z$, $α$, $X$, and $C$. Additionally, when that inequality is true, $θ_{min}$ should always be strictly greater than zero.
When that inequality is not true, the value of any new expression for $θ_{min}$ can be anything, because I already have expressions that hold when the opposite of that inequality, $α ≥ \arcsin\left(\sqrt{\frac{2}{Z} × (C − X)}\right)$, is true.
HOW THESE CURVES ARE DEVELOPED
The curve with parameter theta is the envelope of the line described by the equation $y = x × \tan(α + β) - Z × \sec(α + β) × (β × \cos(α) + \sin(α))$ as the parameter $β$ varies from $-∞$ to $+∞$, specifically tracking the point with $(x, y)$ coordinates
$$(Z × \cos(α) × (\cos(α + β) + \sin(α + β) × (\tan(α) + β)),$$
$$Z × \cos(α) × (\sin(α + β) - \cos(α + β) × (\tan(α) + β)))$$
The curve with parameter gamma is the path of a specific point on that line, with $(x, y)$ coordinates
$$((Z - 2 × (C - X)) × \cos(β) + (Z × β + 2 × (C - X) × \tan(α)) × \sin(β),$$
$$(Z - 2 × (C - X)) × \sin(β) - (Z × β + 2 × (C - X) × \tan(α)) × \cos(β))$$
I've tried to find a way to relate the envelope of the line, and its generating point, with the path of the other point, without any success so far, but I'm hopeful that some way to do so does exist.
WHAT ELSE I KNOW
I do know that on the first curve, the radius of a point for a given value of theta is $r(θ) = Z × \cos(α) × \sqrt{θ² + 1}$, and conversely the value of theta for a given radius is $θ(r) = \sqrt{\frac{r²} {Z² × \cos(α)²} − 1}$. This means that if I can find the radius of the transversal intersection point by any process, I can easily convert it into the value for $θ_{min}$, and vice versa. I also know that the angle made with the $x$-axis by a point on the curve at a given value of theta is $β(θ) = θ − \arctan(θ) + α − \tan(α)$, which is transcendental and has no closed-form inverse, so I cannot use a known angle to find the value of theta.
Similarly, I know that for the second curve, the radius of a point for a given value of gamma is $r(γ) = \sqrt{(2 × \tan(α) × (C − X) + Z × γ)² + (Z −2 ×(C − X))²}$, and conversely the value of gamma for a given radius is $γ(r) = \frac{±\sqrt{r² − (Z − 2 ×(C − X))²} − 2 ×(C − X) ×\tan(α)}{Z}$. This means that if I can find the radius of the transversal intersection point by any process, I can convert it into the value for $γ_{min}$, and vice versa. I also know that the angle made with the $x$-axis by a point on the curve at a given value of gamma is $β(γ) = γ − \arctan\left(\frac{Z (γ + \frac{2}{3} ×(C − X) ×\tan(α))}{Z −2 ×(C − X)}\right)$, which is transcendental and has no closed-form inverse, so I cannot use a known angle to find the value of gamma.
Thus, if I get either one of $θ_{min}$ or $γ_{min}$, I can use that value to find the other. If I can find the radius of the intersection separately, I can use it to find both values. Given these expressions, I know that the radius of the touching intersection is $r = \sqrt{4 ×\cot(α)² ×(C − X)² + (Z − 2 ×(C − X))²}$, or equivalently $r = Z ×\cos(α) ×\sqrt{(\tan(α) − \frac{4}{Z} ×(C − X) × \csc(2α))² + 1}$. I've attempted to find similar expressions for the transversal intersection by working backwards from numerically-calculated values, without any success yet.
For example, by plotting the two curves in graphing software and numerically calculating the parameter values of their intersections to ten decimal places, I created this plot, which shows the $γ_{min}$ value against the pressure angle $α$ (including some technically-invalid negative values of $α$ to get a broader sample size) for four different values of $Z$, all with $X = 0$ and $C = 1$:

The green lines show the known expression $γ_{min}(α) = \frac{4}{Z} × (C − X) × csc(2 × α)$, while the red points are samples of the unknown expression for which I am searching. I've been trying to fit a curve to the red points, unfortunately without any success yet.
The points appear to trace out a sine wave of the form $γ_{min}(α) = A × \sin(ω × α + φ)$, where

*

*$A$ is the amplitude,

*$ω$ is the angular frequency, and

*$φ$ is the phase.

I do know the transition point between the known and unknown functions exactly, as well as the slope of the known function at that point (which appears to also be the slope of the unknown function at said point). The point is $P = \left(\arcsin\left(\frac{\sqrt{2 × (C − X)}} {\sqrt{Z}}\right), \frac{\sqrt{2 × (C − X)}} {\sqrt{Z − 2 × (C - X)}}\right)$, and the slope of the function at that point is $m = \frac{4 × (C − X) − Z} {Z − 2 × (C − X)}$. However, as far as I can tell this isn't enough information to derive the three unknown variables in my hypothesized sine function. Additionally, my attempts to fit a sine curve to the numerically-calculated points suggest that the sampled function isn't a perfect sine wave and may be modified with some other term(s), the effect of which is particularly noticeable for small values of $Z$. At the very least, the red points for $Z = 8$ have proved much more difficult to get a sine wave to conform to than the points for higher $Z$ values. My best attempts so far are:

*

*$0.794 × \sin(1.20 × α + 1.70)$ for $Z = 8$,

*$0.664 × \sin(1.50 × α + 1.77)$ for $Z = 12$,

*$0.484 × \sin(2.18 × α + 1.83)$ for $Z = 24$, and

*$0.248 × \sin(4.30 × α + 1.89)$ for $Z = 96$.

As stated above, if I can find the equation that describes the red points and thus the value of $γ_{min}$, I can use that to also find the value of $θ_{min}$, which would completely solve my problem.
AN APPEALING BUT FLAWED APPROACH:
Another approach that has been tried to solve this is to create the new variables

*

*$A = Z × \cos(α)$,

*$B = Z − 2 × (C − X)$,

*$ψ(θ) = θ − \tan(α) + α$, and

*$ξ(γ) = 2 × \tan(α) × (C − X) + γ × Z$.

Then the parametric equations can be re-written as:
$$x_1(θ) = A × \cos(ψ(θ)) + A × θ × \sin(ψ(θ)),$$
$$y_1(θ) = A × \sin(ψ(θ)) − A × θ × \cos(ψ(θ))$$
and
$$x_2(γ) = B × \cos(γ) + ξ(γ) × \sin(γ),$$
$$y_2(γ) = B × \sin(γ) − ξ(γ) × \cos(γ)$$
Because the two curves intersect when $x_1(θ) = x_2(γ)$ and $y_1(θ) = y_2(γ)$, with these re-written equations we can see that an intersection exists when $A = B$, $A × θ = ξ(γ)$, and $γ = ψ(θ)$. This gives the following equations:

*

*$Z × \cos(α) = Z − 2 × (C − X)$

*$Z × \cos(α) × θ = 2 × \tan(α) × (C − X) + Z × γ$

*$γ = θ − \tan(α) + α$
With some rearranging, substitution, and simplification, these become:

*

*$α = \arccos\left(\frac{Z − 2 × (C − X)} {Z}\right)$

*$θ = \frac{α − \sin(α)} {\cos(α) − 1}$

*$γ = θ − \tan(α) + α$
This does produce an intersection of the two curves, but it fails for my purposes on several accounts:

*

*The first of these three equations fixes the value of alpha in relation to the other three variables $Z$, $X$, and $C$. In reality, alpha is an independent variable whose value in this problem is constrained by, but not dependent on, the values of the other variables. Moreover, for most combinations of values of the other three variables, the value produced by this equation is outside the domain of alpha that I specify at the beginning of this question.

*My problem has the specific constraint that a solution must be valid when $α < \arcsin\left(\sqrt{\frac{2}{Z} × (C − X)}\right)$, and the value of alpha from that first equation is always greater than or equal to the right side of this inequality, so it is always invalid.

*The second equation produces a value of theta that, using the value of alpha from the first equation, is always negative or zero. For my problem the value of theta must be strictly greater than or equal to zero, so this part is also almost always invalid.

I've played around a bit with this approach, but I haven't been able to modify it to make it work.
THE CONTEXT:
The curve with parameter theta is the involute face curve of a tooth on an involute gear, while the curve with parameter gamma is the trochoid root curve of the same tooth. These curves are naturally generated in real life by the gear-shaping process called hobbing, without needing any fancy math. Representing them in a computer, which I want to do, is more difficult.
The shapes of these curves are defined by four variables:

*

*$α$, the angle of the contact force between meshed gear teeth, called the pressure angle;

*$Z$, the number of teeth on the gear;

*$X$, the profile shift coefficient, specifying how far in or out the cutting tool is moved compared to cutting a standard gear profile; and

*$C$, the clearance factor, specifying how much clearance there is between the tooth roots on one gear and the tooth tips on a meshing gear as a multiple of the overall tooth height.

There is one more gear design variable, called module or pitch, which describes the overall size of the gear. Because this variable is a uniform scaling factor, it has no effect on the angles involved or on the values of theta and gamma, so I have left it out of the equations for the sake of simplicity.
When $α ≥ \arcsin\left(\sqrt{\frac{2}{Z} × (C − X)}\right)$, the involute face curve transitions smoothly into the trochoid root curve (with a touching intersection). However, when $α < \arcsin\left(\sqrt{\frac{2}{Z} × (C − X)}\right)$, the root curve cuts off some of the face curve (with a transversal intersection). This is called undercutting and is in general undesirable, as it reduces the strength of the gear. However, small amounts of undercutting are tolerated in many situations. I want to find the point on each curve where this undercutting occurs so I can accurately draw an undercut gear in software.
This question is very similar to another question on this site, but that question's answer doesn't address my particular problem.

A: Setting the parameterized coordinates equal to each other appears to give an intractable transcendental system in $\theta$ and $\gamma$, whose solution almost-certainly require numerical methods.
We can make a little progress by equating the $x^2+y^2$ expressions for each curve's parameterization, which conveniently gives an algebraic relation between $\theta$ and $\gamma$. Referring to my recent answer to a related question for the trochoid half of this discussion, we have
$$\begin{align}
x^2+y^2\,\mid_{\text{inv}}\quad&=\quad x^2+y^2\,\mid_{\text{tro}} \tag1\\[6pt]
\tfrac14 m^2Z^2 \cos^2\alpha\left(1 + \theta^2\right)\quad&=\quad\tfrac14m^2Z^2\left(1+\gamma_0\sin2\alpha+\gamma^2\cos^2\alpha+(\gamma-\gamma_0)^2\sin^2\alpha \right) \tag2  \\[6pt]
\theta^2\quad&=\quad\gamma^2+2\gamma_0\tan\alpha+\left(1+(\gamma-\gamma_0)^2\right)\tan^2\alpha \tag3  \\[6pt]
\end{align}$$
where $\gamma_0 := -4(C-X)\csc(2\alpha)/Z$. This gives us $\theta$.
So, "all we have to do" is substitute the formula for $\theta$ into this $x\mid_\text{inv}=x\mid_\text{tro}$ equation (here again referring to my previous answer for the trochoid formula) ...
$$\cos\alpha \left(\cos(\theta-\phi) + \theta \sin(\theta-\phi) \right)
= \cos\gamma + \gamma \sin\gamma + \gamma_0 \cos(\alpha + \gamma) \sin\alpha \tag4$$
... and solve for $\gamma$.
Even with numerical methods, that process looks downright painful, and I'm not sure if I've ever been happier to write: This is left as an exercise to the reader. :)

A: We have
$$
p_1(\theta) = \cases{
z \cos (\alpha ) (\theta  \sin (\alpha -\tan (\alpha )+\theta )+\cos (\alpha -\tan (\alpha )+\theta ))\\
z \cos (\alpha ) (\sin (\alpha -\tan (\alpha)+\theta )-\theta  \cos (\alpha -\tan (\alpha )+\theta ))
}
$$
$$
p_2(\gamma) = \cases{
\sin (\gamma ) (2 \tan (\alpha ) (c-x)+\gamma  z)+\cos (\gamma ) (z-2 c+2 x)\\
\sin (\gamma ) (z-2 c+2 x)-\cos (\gamma ) (2 \tan (\alpha ) (c-x)+\gamma z)
}
$$
The equations to solve are of transcendent type so numerical methods are indicated to solve them.
The intersections are when $\Delta p = p_1(\theta) - p_2(\gamma)=0$. Those intersections can be visualized with the command
gr1 = ContourPlot[{dp[[1]] == 0, dp[[2]] == 0}, {theta, -Pi/4, Pi/4}, {gamma, -Pi/4, Pi/4}]

showing the solutions dependence on $(\theta,\gamma)$, providing a good guess to give initial conditions to a numeric iterative procedure which would provide solutions. Follows a MATHEMATICA script which serves this purpose.
Clear["Global`*"]
p1[theta_] := {z Cos[alpha] (Cos[theta - Tan[alpha] + alpha] + theta Sin[theta - Tan[alpha] + alpha]),
               z Cos[alpha] (Sin[theta - Tan[alpha] + alpha] - theta Cos[theta - Tan[alpha] + alpha])}
p2[gamma_] := {(z - 2 (c - x)) Cos[gamma] + (2 Tan[alpha] (c - x) + z gamma) Sin[gamma],
               (z - 2 (c - x)) Sin[gamma] - (2 Tan[alpha] (c - x) + z gamma) Cos[gamma]}
dp = p1[theta] - p2[gamma]

z = 36;
x = 0;
c = 1.25;
alpha = 20/180 Pi;

gr1 = ContourPlot[{dp[[1]] == 0, dp[[2]] == 0}, {theta, -Pi/4, Pi/4}, {gamma, -Pi/4, Pi/4}]

The horizontal axis represents $\theta$ and the vertical $\gamma$. In light blue is the $x$ of $\Delta p$ component and in yellow follows the $y$ of $\Delta p$ component.
The black dots representing the solutions, are obtained as follows
sol1 = FindRoot[dp == 0, {{theta, -0.15}, {gamma, -0.15}}]
sol2 = FindRoot[dp == 0, {{theta, -0.2}, {gamma, 0.2}}]
sol3 = FindRoot[dp == 0, {{theta, 0.1}, {gamma, -0.2}}]
grp1 = Graphics[{Black, PointSize[0.02], Point[{theta, gamma} /. sol1]}];
grp2 = Graphics[{Black, PointSize[0.02], Point[{theta, gamma} /. sol2]}];
grp3 = Graphics[{Black, PointSize[0.02], Point[{theta, gamma} /. sol3]}];
Show[gr1, grp1, grp2, grp3]

The guess to fire the iterative procedure to find the solutions is extracted from the graph. The same method can be applied to typical values for x,c, alpha.


text:
Q: Donation roll-ups are not working on Contact and Household I'm acessing salesforce with a NSPS org. I have add manually some donations through the contact page but those won't sum up on the rool up fields in the contacts neither on households.
I just confirmed and all the triggers are active, also the household settings are configured correctly.
Can some help figuring out what possible could be wrong?
Thanks in advanced
Best regards
Susana

A: I work at the Salesforce.com Foundation with the product manager of the Nonprofit Starter Pack.  Here are the steps you should follow:

*

*Are you running the most recent version of Contacts and Organizations?  Rollups are only available in versions 2.x and above for both Contacts & Organizations, and Households.  You can find info on how to check your installed versions here:  http://www.youtube.com/watch?v=0TlVK3JBBCw&hd=1

*Are you correctly displaying the summary rollup fields, are they on your page layout?

*Have you added custom validation to your contact records? If you edit your contact and try to save, does the validation fail? When rollups are updated, any validation rules on your contact/household are run. Any contacts or households that fail those rules will not be updated with the rollups.

*Are your opportunities in a closed/won stage? Is Posted a Closed/Won stage? Note: The name of the stage may not be 'Closed Won', it may be 'Posted', or some other variant. However, that stage has to be marked as closed/won in order for the opportunity to rollup. You can find out if your Stage value is closed/won by going to Setup->Customize->Opportunities->Fields->Stage and examine the 'Type' column for your Stage names.

*When you go to the Opportunity Rollups tab, and manually run the rollups, are your values now correctly rolled up? If so, you may not have the opportunity trigger turned on. You can go to the Household Settings tab, select 'Roll Up Opps in Triggers', and then click 'Update the Households Settings'

*Are you excluding any record types from rollups? You can check this by going to Household Settings and looking at the Opportunity Rollups Record Types section.

*Do your Contacts all have a Household? Due to a bug in Salesforce, all Contacts MUST have a Household to be included as part of the rollups. This will hopefully be fixed in a future release.

*Does your opportunity have an Opportunity Contact Role?  If not, you may need to turn on OCRs in the trigger. Go to your 'Contact Settings' tab, and check the box 'Enable Opportunity Contact Role Trigger', and click 'Update the Contacts & Organizations Settings.  You'll need to add an Opportunity Contact Role for any Opportunities that do not already have one.
Hope that helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: if($bans[$i]['ip'] == $_SERVER['REMOTE_ADDR']) i have created a website with Ultimate video curator using wordpress, also buy a plugin "wp sensei" for protect this site from hacking. I have also installed this plugin, but when i clicked on activate showing me
"Plugin could not be activated because it triggered a fatal error." and
"Warning: Illegal string offset 'ip' in /home4/worldvj5/public_html/halloweencostumes/wp-content/plugins/wp-sensei/wplockup.php on line 108
Warning: Illegal string offset 'time' in /home4/worldvj5/public_html/halloweencostumes/wp-content/plugins/wp-sensei/wplockup.php on line 119
Fatal error: Cannot unset string offsets in /home4/worldvj5/public_html/halloweencostumes/wp-content/plugins/wp-sensei/wplockup.php on line 120"
so what is the main problem, and how to solve it, please solve this problem.
and when i go to this page with 108 line in wp sensei, i see that "if($bans[$i]['ip'] == $_SERVER['REMOTE_ADDR'])"
please help me.

A: Odds are, the $bans array is empty. Add a bogus IP to be banned using the plugin, and then try it again.


text:
Q: Using external deeplinks to open android app, opens chrome with 403 message I've followed the docs for adding deeplink where we use
https://mydomain.co/app or https://mydomain.co/app/details, etc to navigate to the app. So I've updated the manifest for this:
    <intent-filter android:autoVerify="true">
        <data
           android:host="mydomain.co"
           android:pathPrefix="/app"
           android:scheme="https" />

        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>

Generated the Digital Asset Links json file and added to the domain https://mydomain.co/.well-known/assetlinks.json
[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "co.myapp.app",
      "sha256_cert_fingerprints":
        ["redacted:key"]
    }
  }
]

So when I test using adb command (ex. adb shell am start -d "https://mydomain.co/app/profile/edit_profile")
it works perfectly but when I try using the link externally, it opens chrome and gives me 403. I'm not sure what I'm missing or what's wrong. Can somebody help me? Thanks in advance!

A: I found the solution: The main issue was the signature keys were not matching between Google Play and the release. That's because Google adds its own that can't be shared. So the only way to make it work was to upload the app in the Google Play Store. That means to make it work locally I need to add the signature key for the debug build into the Digital Asset Links json file.


text:
Q: Change WM_CONCAT function to LISTAGG I used WM_CONCAT in my sql query. The database has been updated to version 12c and WM_CONCAT doesn`t work.
Query had value:
Select r.product_id, count (1) how_many, wm_concat (distinct r.number) numbers From ...

How to transform it into LISTAGG functions. I try this, but it doesn`t work :
Select r.product_id, count(1) how_many, LISTAGG(r.number, ',') WITHIN GROUP (order by r.number) numbers From ...

A: you should add Group by in your query
with tab as(
  select '10' as num, 'A' as product from dual union all
  select '10' as num, 'B' as product from dual union all
  select '10' as num, 'C' as product from dual union all
  select '10' as num, 'D' as product from dual union all
  select '20' as num, 'A' as product from dual union all
  select '20' as num, 'B' as product from dual union all
  select '30' as num, 'A' as product from dual
)

select  product
, count (1) how_many
, LISTAGG(num, ',') WITHIN GROUP (order by num)
from tab
group by product

but you have to be careful, because by using listagg you can only concatenate strings up to 4K. There are also other string aggregation techniques, have a look at  the answer here.

PRODUCT | HOW_MANY | LISTAGG(NUM,',')WITHINGROUP(ORDERBYNUM)
:------ | -------: | :--------------------------------------
A       |        3 | 10,20,30
B       |        2 | 10,20
C       |        1 | 10
D       |        1 | 10

db<>fiddle here


text:
Q: How to plot a lineplot with dots on specific points with specific colors and linetypes for each line using seaborn? I have the following dataframe
import pandas as pd

 data_tmp = pd.DataFrame({'x': [0,14,28,42,56, 0,14,28,42,56],
                         'y': [0, 0.003, 0.006, 0.008, 0.001, 0*2, 0.003*2, 0.006*2, 0.008*2, 0.001*2],
                         'cat': ['A','A','A','A','A','B','B','B','B','B'],
                         'color': ['#B5D8F0','#B5D8F0','#B5D8F0','#B5D8F0','#B5D8F0','#247AB2','#247AB2','#247AB2','#247AB2','#247AB2'],
                         'point': [14,14,14,14,14,28,28,28,28,28],
                         'linestyles':['-','-','-','-','-','--','--','--','--','--']})

I would like to produce a lineplot with different color and linestyles per cat. But I would like to give the specific color and linestyles per cat as they are defined in the dataframe. Lastly I would like to mark the points on each line with the same color.
I have only tried:
sns.lineplot(x="x", y="y", hue="cat", data=data_tmp)
sns.scatterplot(x="point",y="y",hue="cat", data=data_tmp[data_tmp.point==data_tmp.x])
plt.show()

Any ideas ?

A: Maybe you want to use matplotlib directly, like
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'x': [0,14,28,42,56, 0,14,28,42,56],
                   'y': [0, 0.003, 0.006, 0.008, 0.001, 0*2, 0.003*2, 0.006*2, 0.008*2, 0.001*2],
                   'cat': ['A','A','A','A','A','B','B','B','B','B'],})

d = {"A" : {"color": '#B5D8F0', "markersize":  5, "linestyle": "-"},
     "B" : {"color": '#247AB2', "markersize": 10, "linestyle": "--"}}

for n, grp in df.groupby("cat"):
    plt.plot(grp.x, grp.y, marker="o", label=n, **d[n])

plt.legend()
plt.show()

A: This is how I could do this. You need to use the cat column to control the different plot parameters (color, style, marker size), and then create mapping objects (here dicts) that tell which parameter value to use for each category. The color is easy. The linestyle is harder, because Seaborn only offers dashes as a configurable parameter, which needs to be given in the advanced Matplotlib format of (segment, gap). The function matplotlib.lines._get_dash_pattern translates the string value (e.g. --) to this format, although the returned value needs to be handled with care. For the marker size, unfortunately lineplot does not offer the possibility to change the marker size with the category (even though you can change the marker style), so you need to use a scatterplot on top. The last bit is the legend, you probably want to disable it for the second plot, to avoid repeating it, but the problem is that the first legend will not have the markers in it. If that bothers you, you can still edit the legend manually. All in all, it could look like this:
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns

# Converts a line style to a format acceptable by Seaborn
def get_dash_pattern(style):
    _, dash = mpl.lines._get_dash_pattern(style)
    return dash if dash else (None, None)

data_tmp = pd.DataFrame({
    'x': [0,14,28,42,56, 0,14,28,42,56],
    'y': [0, 0.003, 0.006, 0.008, 0.001, 0*2, 0.003*2, 0.006*2, 0.008*2, 0.001*2],
    'cat': ['A','A','A','A','A','B','B','B','B','B'],
    'color': ['#B5D8F0','#B5D8F0','#B5D8F0','#B5D8F0','#B5D8F0',
              '#247AB2','#247AB2','#247AB2','#247AB2','#247AB2'],
    'point': [14,14,14,14,14,28,28,28,28,28],
    'linestyles':['-','-','-','-','-','--','--','--','--','--']})
# Extract plot features as dicts
feats = (data_tmp[['cat', 'color', 'linestyles', 'point']]
         .set_index('cat').drop_duplicates().to_dict())
palette, dashes, sizes = feats['color'], feats['linestyles'], feats['point']
# Convert line styles to dashes
dashes = {k: get_dash_pattern(v) for k, v in dashes.items()}
# Lines
lines = sns.lineplot(x="x", y="y", hue="cat", style="cat", data=data_tmp,
                     palette=palette, dashes=dashes)
# Points
sns.scatterplot(x="x", y="y", hue="cat", size="cat", data=data_tmp,
                palette=palette, sizes=sizes, legend=False)
# Fix legend
for t, l in zip(lines.legend().get_texts(), lines.legend().get_lines()):
    l.set_marker('o')
    l.set_markersize(sizes.get(l.get_label(), 0) / t.get_fontsize())
plt.show()

Output:

A: Here is my solution with the help of @jdehesa
I also put the legend outside of the plot here and some polishing to the labels
def get_dash_pattern(style):
    _, dash = mpl.lines._get_dash_pattern(style)
    return dash if dash else (None, None)

palette = dict(zip(data_tmp.cat, data_tmp.color))
dashes = dict(zip(data_tmp.cat, data_tmp.linestyles))
dashes = {k: get_dash_pattern(v) for k, v in dashes.items()}

ax = sns.lineplot(x="x", y="y", hue="cat", data=data_tmp, palette=palette, style='cat',  dashes=dashes)
ax = sns.scatterplot(x="point", y="y", hue="cat", data=data_tmp[data_tmp.point == data_tmp.x], palette=palette,
                     legend=False)

ax.set_title('title')
ax.set_ylabel('y label')
ax.set_xlabel('x label')
ax.legend(loc=(1.04, 0))
plt.show()


text:
Q: Printer sharing using Fedora I have to PC and netbook runs on fedora

*

*PC - Fedora 21 (Workstation)

*Netbook - Fedora LXDE

Both of these computers are connected to the same network (PC wired and netbook wireless)
My HP Deskjet 1010 printer is connected to the PC via a USB cable.
I want to enable printing over network for my netbook.

A: In Ubuntu/Linux Mint, all I have to do is go to 'Settings-printer-add a printer-find network printer'. After a few seconds, it shows my printer on the list. Fedora should have something fairly similar.

A: if there is no system configuration for printer then install it in terminal
dnf install system-config-printer.x86_64
or you can logged off your LXDE, logged into gnome (session). Went to "show applications", selected "all", clicked "utilities", then "settings", then "printers", then "unlock" and
simply add your printer


text:
Q: White Screen of Death, Twig_Node_Expression _Constant not found I had a site that I was making in XAMPP in windows environment which was and still is working fine. However I have switched it over to LAMP using linux. And now I getting a white screen of death. I read up here that I should use this code;
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

at the top of my index.php file to display errors. Which I have done but now get the error;
Fatal error: Class 'Twig_Node_Expression_Constant' not found in /var/www/vendor/twig/twig/lib/Twig/ExpressionParser.php on line 206

I am not to sure how to fix this as this file is in the vendor folder. As mentioned before it seems to work fine on XAMPP in windows but on linux I keep getting this error and a white screen. I also looked here and here but these links just seemed to say the same thing as the first link I visited to display the errors
<?php

error_reporting(E_ALL);
ini_set('display_errors',TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
require_once __DIR__.'/vendor/autoload.php';
require_once 'src/provider/AuthenticationServiceProvider.php';
require_once 'src/provider/TutorServiceProvider.php';

use Symfony\Component\HttpFoundation\Request;

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/views',
));

$app->register(new Silex\Provider\SessionServiceProvider());

$app->register(new Tutor\Provider\AuthenticationServiceProvider());

$app->register(new Tutor\Provider\TutorServiceProvider());

$app->get('/', function() use($app) {
    $tutors = $app['tutor']->get_tutors();
    return $app['twig']->render('index.twig', array('active_page' => 'home', 'is_user_logged_in' => $app['auth']->is_user_logged_in(), 'tutors' => $tutors));
});

$app->get('/about-us', function() use($app) {
    return $app['twig']->render('about-us.twig', array('active_page' => 'about-us', 'is_user_logged_in' => $app['auth']->is_user_logged_in()));
});

$app->get('/home-tuition', function() use($app) {
    return $app['twig']->render('home-tuition.twig', array('active_page' => 'home-tuition', 'is_user_logged_in' => $app['auth']->is_user_logged_in()));
});

$app->get('/group-tuition', function() use($app) {
    $groups = $app['tutor']->get_group_tuition($app['auth']->get_user()['email']);
    return $app['twig']->render('group-tuition.twig', array('active_page' => 'group-tuition', 'is_user_logged_in' => $app['auth']->is_user_logged_in(), 'groups' => $groups, 'user' => $app['auth']->get_user()));
});

$app->get('/group-tuition/{tutoremail}/{starttime}', function($tutoremail, $starttime) use($app) {
    $user = $app['auth']->get_user();
    if (null !== $user && ($user['type'] == 'admin' || $user['email'] == $tutoremail)) {
        $group = $app['tutor']->get_group_tuition_details($tutoremail, $starttime);
        return $app['twig']->render('group-tuition-details.twig', array('active_page' => 'group-tuition', 'is_user_logged_in' => $app['auth']->is_user_logged_in(), 'group' => $group));
    } else {
        return $app->redirect('/group-tuition');
    }
});

$app->get('/contact-us', function() use($app) {
    return $app['twig']->render('contact-us.twig', array('active_page' => 'contact-us', 'is_user_logged_in' => $app['auth']->is_user_logged_in()));
});

$app->get('/tutor/{username}', function($username) use($app) {
    $tutor = $app['tutor']->get_tutor($username);
    if (null !== $tutor) {
        return $app['twig']->render('tutor.twig', array('active_page' => 'tutor', 'is_user_logged_in' => $app['auth']->is_user_logged_in(), 'tutor' => $tutor));
    } else {
        return $app->redirect('/');
    }
});

$app->get('/login', function() use($app) {
    if ($app['auth']->is_user_logged_in()) {
        return $app->redirect('/');
    } else {
        return $app['twig']->render('login.twig', array('active_page' => 'login', 'is_user_logged_in' => $app['auth']->is_user_logged_in()));
    }
});

$app->post('/login', function(Request $request) use($app) {
    $email = $app['request']->get('email');
    $password = $app['request']->get('password');
    if ($app['auth']->login($email, $password)) {
        return $app->redirect('/');
    } else {
        return $app->redirect('/login');
    }
});

$app->get('/logout', function() use($app) {
    $app['auth']->logout();
    return $app->redirect('/');
});

$app->get('/register', function() use($app) {
    if ($app['auth']->is_user_logged_in()) {
        return $app->redirect('/');
    } else {
        return $app['twig']->render('register.twig', array('active_page' => 'register', 'is_user_logged_in' => $app['auth']->is_user_logged_in()));
    }
});

$app->post('/register', function(Request $request) use($app) {
    $email = $app['request']->get('email');
    $password = $app['request']->get('password');
    $name = $app['request']->get('name');
    $address = $app['request']->get('address');
    $phone = $app['request']->get('phone');
    if ($app['auth']->register($email, $password, $name, $address, $phone, 'student')) {
        return $app->redirect('/');
    } else {
        return $app->redirect('/register');
    }
});

$app->get('/reset-password', function() use($app) {
        return $app['twig']->render('reset-password.twig',array('active_page' => 'reset-password','is_user_logged_in' => $app['auth']->is_user_logged_in()));
});

$app->post('/reset-password', function(Request $request) use($app){
    $email = $app['request']->get('email');
    if($app['auth']->sendEmail($email)){
        return $app->redirect('/');
    }else{
        return $app->redirect('/reset-password');
    }
});

$app->get('/admin', function() use($app) {
    $tutor = $app['tutor']->get_tutors();
    $user = $app['auth']->get_user();
    if (null !== $user && $user['type'] == 'admin' && null !== $tutor){
        return $app['twig']->render('admin.twig', array('active_page' => 'admin', 'is_user_logged_in' => $app['auth']->is_user_logged_in(), 'contacts' => $app['tutor']->get_user(), 'items' => $app['tutor']->get_user_id(), 'tutor' => $tutor));
    }else{
        return $app->redirect('/login');
    }
});

$app->post('/charge', function(Request $request) use($app) {
    $description = $app['request']->get('description');
    $tutoremail = $app['request']->get('tutoremail');
    $starttime = $app['request']->get('starttime');
    $user = $app['auth']->get_user();
    $studentemail = $user['email'];

    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here https://dashboard.stripe.com/account/apikeys
    \Stripe\Stripe::setApiKey("sk_test_fktchFYkd0XywraJftt8Z9uc");

    // Get the credit card details submitted by the form
    $token = $app['request']->get('stripeToken');

    // Create the charge on Stripe's servers - this will charge the user's card
    try {
        $charge = \Stripe\Charge::create(array(
            "amount" => 2000, // amount in cents, again
            "currency" => "gbp",
            "source" => $token,
            "description" => $description . ' paid by ' . $studentemail . ' for session ' . $tutoremail . '/' . $starttime
        ));
        $app['tutor']->add_group_tuition_booking($tutoremail, $starttime, $studentemail);
    } catch(\Stripe\Error\Card $e) {
        // The card has been declined
    }
    return $app->redirect('/group-tuition');
});

$app->run();

?>

Composer.json file
{
    "require": {
        "silex/silex": "~1.1",
        "symfony/browser-kit": "~2.3",
        "symfony/console": "~2.3",
        "symfony/config": "^3.0",
        "symfony/css-selector": "~2.3",
        "symfony/dom-crawler": "~2.3",
        "symfony/filesystem": "~2.3",
        "symfony/finder": "~2.3",
        "symfony/form": "^3.0",
        "symfony/locale": "~2.3",
        "symfony/process": "~2.3",
        "symfony/security": "~2.3",
        "symfony/serializer": "~2.3",
        "symfony/translation": "^3.0",
        "symfony/validator": "^3.0",
        "symfony/monolog-bridge": "~2.3",
        "symfony/twig-bridge": "~2.3",
        "doctrine/dbal": ">=2.2.0,<2.4.0-dev",
        "swiftmailer/swiftmailer": "5.*",
        "twig/twig": "^1.24",
        "symfony/security-csrf": "^3.0",
        "stripe/stripe-php": "3.*"
    }
}

SOLUTION:
After reading around a lot over the internet I managed to solve both problem.
1) For the first problem I was copying over the composer.json file and vendor directory just expecting them to work. However as mentioned in the comments above by @Federico I simply copied over my composer.json file and ran composer update. This solved the TWIG_NODE_EXPRESSION_CONSTANT error.
2) The second error I mentioned was that I was getting a 404 when navigating to other pages;
For this I read around the internet and learnt that you need to edit the httpd.conf file to get the htaccess file to work with apache. However as I have a different version of ubuntu which meant the apache2.conf file (/etc/apache2/apache2.conf), so I changed the code;
from this
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

to this
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

However after this I was still getting an 500 internal error. So I found out that the /etc/apache2/apache2/sites-available/000-default.conf (on some versions maybe /etc/apache2/sites-available/default this was not the case on the ubuntu 14.04 that I am using) needs to have the above code inserted into it aswell. However as I installed lamp according to ubuntu's instructions this /etc/apache2/apache2/sites-available/000-default.conf file was copied over to /etc/apache2/apache2/sites-available/mysite.conf and this is where I added in the code;
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

This finally got it to work. Not sure why apache changed their directory/files conventions around guess its to do with different version upgrades.


text:
Q: What is rockstar games phone number Need to contact rockstar game services because my vehicle was replaced with another and I can't get my car back

A: There are several ways to contact Rockstar Games. The phone number is (866) 922-8694, the website offers online support and email.


text:
Q: Android developers fee without credit card? I've created an application for android, wich took me several months to complete. I've always been thinking that when it'd be done, I could publish it on Android market.
Now I went to the website, and found I had to pay €25, wich I was prepared to do. But then I found out that I Cannot pay it without a credit card!
Does anyone have a solution for this? I worked really too hard on my program to find it will never see daylight.

A: Besides the official Android market there are many alternatives.
If you want to release your app on Android market, then there is no other way but using your credit card. If you don't care about the official market you can put your app on alternatives one such as:

*

*www.androidpit.de

*www.slideme.org

*www.handster.com

A: Theses pre-paid "credit cards" are available at gas stations throughout the US:
http://usa.visa.com/personal/cards/prepaid/index.html


text:
Q: Identifying boundaries and objects in real time (tango) Is there a possibility with a google tango camera to create a situation, that my player goes on the table and if he comes out of the table he falls? Has anyone ever done anything similar and has references or ideas on how to do it?

A: in order to implement the functionality that you described, you will need to find different planes from the real world and translate their position into Unity scene. There is a class in Tango SDK, called TangoPointCloud which contains several methods for recognizing planes and translate their position into unity scene points. By knowing the positions of the table and the floor, you might be able to implement the feature you want. In my case, TangoPointCloud helped me find the walls from a room and their position relative to unity scene units.


text:
Q: how to get username who make an request to lita I'd like to know how to get username who posted in slack channel.
It seems to possible to get user information through Slack API. (https://api.slack.com/outgoing-webhooks). In our office, we use slack to deploy via slack by using lita(https://api.slack.com/outgoing-webhooks) and jenkins.  I want to prevent non-developers can make request of deploying. However, I can't figure it out how to get username through Slack API. Any comments are welcome.

A: In lita, the sender of the message is accessible via @response.user.
You could also manage the list of users who are allowed to deploy via group authorization  as is done in lita-retro:

route /retro\s+clear/i, :clear, command: true, restrict_to: :retro_admins, help: {
  "retro clear" => t("help.clear_value")
}


text:
Q: Is it possible to trigger a function on the database level? I have a table containing the following columns:
   id                     data
 integer       timestamp without time zone
---------      ---------------------------
    1              2015-01-26 15:41:20
..........................................

I also have a function (stored procedure), which needs to be triggered in the date specified by the data column. Is it possible to do that with PostgreSQL 8.4 or higher?
The stored procedure has the following signature:
create or replace function delete_row(id integer) returns void as $$
begin
    delete from partner where id = id;
end $$
language plpgsql

and is going to delete the row from the table with an id passed as the parameter.
The function have to be triggered at every date existing in the data column. So if I add a new row, I also need to trigger the function in that date.

A: Triggers don't run when a particular date happens. Loosely speaking, triggers run before or after an INSERT, UPDATE, or DELETE statement happens.
To run some code on a particular date, you would usually run an external process that periodically checks your table for a date, and then runs some other code if it finds a matching date. The external process could be controlled by cron, or it could be controlled by pgAgent.
That "some other code" could be a stored procedure (function) in the database, or it could be code written in another language that connects to the database to do its work.

A: What You are explaning seems to be best done with writing SQL job in sql sever agent . It should compare actual date with date in 'data' column in your table. If actual date is greater than one in your table it should delete that row.
Do something like that:
In SQL Server Management Studio, expand the SQL Server Agent, right click on "Jobs" and select "New Job..."
in "Steps", create a "New..." one and enter this:
DELETE table WHERE data

U can change the "occurs" there to 10 sec, or 30 sec, depends on how frequently u want to check for that dates.


text:
Q: scorm 1.2 + declaring objectives I have been looking all over the internet for resources but I cannot seem to find any that describe what I am looking for. I am trying to find out how to create learning objectives ("cmi.objectives.n.id") in scorm 1.2. I dont know whether they need to be declared in the imsmanifest file like they do in scorm 2004 or whether they are created at run time. Either way desperately need to know how to create them. I have found lots of resources on how to do this for scorm 2004 but I cannot find any for scorm 1.2.
Help is greatly appreciated.

A: if I am not mistaken in SCORM 1.2 you don't declare objectives in the imsmanifest.xml file, you can only LMSSetValue() them at runtime. Keep in mind that the LMS is not required to store them permanently, but only during the SCORM session (between LMSInitialize() and LMSFinish()).
The same holds for interaction in SCORM 1.2


text:
Q: How to schedule Jenkins build in pipeline script with custom parameters I have a Jenkins job with several parameters, each with default value, for example:
SUITE_NAME: business/common.xml
BROWSER_NAME: ff

I need the job to be started 2 times by cron, with different input parameters, like:
1st launch: 5AM
SUITE_NAME: business/common.xml
BROWSER_NAME: ff

2st launch: 7AM
SUITE_NAME: events/some-other.xml
BROWSER_NAME: ff

So SUITE_NAME and probably some other parameters could vary.
How can I set this in the pipeline scrip of in job settings via Jenkins interface?
The only solution I see now is to trigger the build each hour, get current time, and change the value of SUITE_NAME depending on whether it's 5AM or 7AM but this really looks weird.
thanks in advance.

A: Solved by using this answer and plugin:
add build parameter in jenkins build schedule
https://github.com/jwmach1/parameterized-scheduler
00 05 * * 1-5 %SUITE_NAME=business/common.xml
05 05 * * 1-5 %SUITE_NAME=events/some-other.xml

etc...


text:
Q: Android Studio Vector Asset Import Error - Tags Not Supported I've been testing out Andorid Studio with the new gradle plugin - 1.4.0-beta3.
I've been trying to import my own vector assets, made in Inkscape. However I keep getting import errors. The error message includes lots of tags in the svg that arn't supported.
In mm_card.svg:
ERROR@ line 54 <defs> is not supported
ERROR@ line 56 <linearGradient> is not supported
ERROR@ line 58 <stop> is not supported
ERROR@ line 62 <stop> is not supported
ERROR@ line 66 <stop> is not supported
ERROR@ line 70 <stop> is not supported
ERROR@ line 74 <stop> is not supported
ERROR@ line 78 <stop> is not supported
ERROR@ line 83 <linearGradient> is not supported
ERROR@ line 85 <stop> is not supported
ERROR@ line 89 <stop> is not supported
ERROR@ line 93 <stop> is not supported
ERROR@ line 97 <stop> is not supported
ERROR@ line 102 <linearGradient> is not supported
ERROR@ line 104 <stop> is not supported
ERROR@ line 108 <stop> is not supported
ERROR@ line 113 <linearGradient> is not supported
ERROR@ line 115 <stop> is not supported
ERROR@ line 119 <stop> is not supported
ERROR@ line 123 <stop> is not supported
ERROR@ line 127 <stop> is not supported
ERROR@ line 131 <stop> is not supported
ERROR@ line 135 <stop> is not supported
ERROR@ line 139 <stop> is not supported

Does anyone know the cause of this? Is it an error in the vector asset tool? Or perhaps a problem with svgs created by Inkscape? Or are more complicated svgs not supported?
Thanks!

A: The SVG import feature in Android Studio has only limited support for some SVG features.
They state as much in their announcement video.  They say they intend to improve the importer.
But also note that gradients are not supported in VectorDrawables anyway.


text:
Q: I used to wget the "historical" from the original coinbase api - cant find it with v2 api I used to use a simple wget to https://api.coinbase.com/api/v1/prices/historical to get a file of past and current buy prices from coinbase on Bitcoin. Now with the new v2 API i am unable to find documentation to lead me to this file in the new system. Anyone know what i should do?

A: Notice that https://developers.coinbase.com/api/v2#get-spot-price has a section labeled ARGUMENTS that describes how you can add an argument. "Specify date for historic spot price in format YYYY-MM-DD (UTC)"
Alternatively, you can use this URL for historic prices within the last month: http://api.coinbase.com/v2/prices/BTC-USD/historic?period=month


text:
Q: Hadoop 2.4.1 and Google Cloud Storage connector for Hadoop I am trying to run Oryx on top of Hadoop using Google's Cloud Storage Connector for Hadoop:
https://cloud.google.com/hadoop/google-cloud-storage-connector
I prefer to use Hadoop 2.4.1 with Oryx, so I use the hadoop2_env.sh set-up for the hadoop cluster I create on google compute engine, e.g.:
.bdutil -b <BUCKET_NAME> -n 2 --env_var_files hadoop2_env.sh \
--default_fs gs --prefix <PREFIX_NAME> deploy

I face two main problems when I try to run oryx using hadoop.
1) Despite confirming that my hadoop conf directory matches what is expected for the google installation on compute engine, e.g.:
$ echo $HADOOP_CONF_DIR
/home/hadoop/hadoop-install/etc/hadoop

I still find something is looking for a /conf directory, e.g.:
Caused by: java.lang.IllegalStateException: Not a directory: /etc/hadoop/conf

My understanding is that ../etc/hadoop should be the /conf directory, e.g.:
hadoop: configuration files
And while I shouldn't need to make any changes, this problem is only resolved when I copy the config files into a newly created directory, e.g.:
sudo mkdir /etc/hadoop/conf
sudo cp /home/hadoop/hadoop-install/etc/hadoop/* /etc/hadoop/conf

So why is this? Is this a result of using the google hadoop connector?
2) After "resolving" the issue above, I find additional errors which seem (to me) to be related to communication between the hadoop cluster and the google file system:
Wed Oct 01 20:18:30 UTC 2014 WARNING Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Wed Oct 01 20:18:30 UTC 2014 INFO Namespace prefix: hdfs://BUCKET_NAME
Wed Oct 01 20:18:30 UTC 2014 SEVERE Unexpected error in execution
java.lang.ExceptionInInitializerError
    at com.cloudera.oryx.common.servcomp.StoreUtils.listGenerationsForInstance(StoreUtils.java:50)
    at com.cloudera.oryx.computation.PeriodicRunner.run(PeriodicRunner.java:173)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: java.net.UnknownHostException: resistance-prediction
    at org.apache.hadoop.security.SecurityUtil.buildTokenService(SecurityUtil.java:373)
    at org.apache.hadoop.hdfs.NameNodeProxies.createNonHAProxy(NameNodeProxies.java:258)
    at org.apache.hadoop.hdfs.NameNodeProxies.createProxy(NameNodeProxies.java:153)
    at org.apache.hadoop.hdfs.DFSClient.(DFSClient.java:602)
    at org.apache.hadoop.hdfs.DFSClient.(DFSClient.java:547)
    at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:139)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:89)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2625)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2607)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:368)
    at com.cloudera.oryx.common.servcomp.Store.(Store.java:76)
    at com.cloudera.oryx.common.servcomp.Store.(Store.java:57)
    ... 9 more
Caused by: java.net.UnknownHostException: BUCKET_NAME
    ... 22 more
What seems relevant to me is that the namespace prefix is hdfs:// when I set the default file system to gs://
Perhaps this is leading to the UnkownHostException?
Note that I have "confirmed" the hadoop cluster is connected to the google file system, e.g.:
    hadoop fs -ls
yields the contents of my google cloud bucket and all the expected contents of the gs://BUCKET_NAME directory.  However, I am not familiar with the google manifestation of hadoop via the hadoop connector, and the traditional way I usually test to see if the hadoop cluster is running, i.e.:
    jps
only yields
    6440 Jps
rather than listing all the nodes.  However, I am running this command from the master node of the hadoop cluster, i.e., PREFIX_NAME-m, and I am not sure of the expected output when using the google cloud storage connector for hadoop.
So, how can I resolve these errors and have my oryx job (via hadoop) successfully access data in my gs://BUCKET_NAME directory?
Thanks in advance for an insights or suggestions.
UPDATE:
Thanks for the very detailed response.  As a work-around I "hard coded" gs:// into oryx by changing:
  prefix = "hdfs://" + host + ':' + port;
} else {
  prefix = "hdfs://" + host;

to:
  prefix = "gs://" + host + ':' + port;
} else {
  prefix = "gs://" + host;

I now get the following errors:
Tue Oct 14 20:24:50 UTC 2014 SEVERE Unexpected error in execution
java.lang.ExceptionInInitializerError
at com.cloudera.oryx.common.servcomp.StoreUtils.listGenerationsForInstance(StoreUtils.java:50)
        at com.cloudera.oryx.computation.PeriodicRunner.run(PeriodicRunner.java:173)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: Class com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem not found
        at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:1905)
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2573)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2586)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:89)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2625)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2607)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:368)
        at com.cloudera.oryx.common.servcomp.Store.(Store.java:76)
        at com.cloudera.oryx.common.servcomp.Store.(Store.java:57)
As per the instructions here: https://cloud.google.com/hadoop/google-cloud-storage-connector#classpath I believe I have added connector jar to Hadoop's classpath; I added:
HADOOP_CLASSPATH=$HADOOP_CLASSPATH:'https://storage.googleapis.com/hadoop-lib/gcs/gcs-connector-1.2.9-hadoop2.jar

to /home/rich/hadoop-env-setup.sh. and (echo $HADOOP_CLASSPATH) yields:
/contrib/capacity-scheduler/.jar:/home/hadoop/hadoop-install/share/hadoop/common/lib/gcs-connector-1.2.9-hadoop2.jar:/contrib/capacity-scheduler/.jar:/home/hadoop/hadoop-install/share/hadoop/common/lib/gcs-connector-1.2.9-hadoop2.jar
Do I need to add more to the class path?
I also note (perhaps related) that I still get the error for /etc/hadoop/conf even with the export commands.  I have been using the sudo mkdir /etc/hadoop/conf as a temporary work around.  I mention this here in case it may be leading to additional issues.

A: There appear to be a couple of problems; the first of which is that normally, when things are run under hadoop jar, hadoop imbues the various system environment variables and classpaths, etc., into the program being run; in your case, since Oryx runs without using hadoop jar, instead using something like:
java -Dconfig.file=oryx.conf -jar computation/target/oryx-computation-x.y.z.jar

then $HADOOP_CONF_DIR doesn't actually make it into the environment so System.getenv in OryxConfiguration.java fails to pick it up, and uses the default /etc/hadoop/conf value. This is solved simply with the export command, which you can test by seeing if it makes it into a subshell:
echo $HADOOP_CONF_DIR
bash -c 'echo $HADOOP_CONF_DIR'
export HADOOP_CONF_DIR
bash -c 'echo $HADOOP_CONF_DIR'
java -Dconfig.file=oryx.conf -jar computation/target/oryx-computation-x.y.z.jar

The second, and more unfortunate issue is that Oryx appears to hard-code 'hdfs' rather allowing any filesystem scheme set by the user:
private Namespaces() {
  Config config = ConfigUtils.getDefaultConfig();
  boolean localData;
  if (config.hasPath("model.local")) {
    log.warn("model.local is deprecated; use model.local-data");
    localData = config.getBoolean("model.local");
  } else {
    localData = config.getBoolean("model.local-data");
  }
  if (localData) {
    prefix = "file:";
  } else {
    URI defaultURI = FileSystem.getDefaultUri(OryxConfiguration.get());
    String host = defaultURI.getHost();
    Preconditions.checkNotNull(host,
        "Hadoop FS has no host? Did you intent to set model.local-data=true?");
    int port = defaultURI.getPort();
    if (port > 0) {
      prefix = "hdfs://" + host + ':' + port;
    } else {
      prefix = "hdfs://" + host;
    }
  }
  log.info("Namespace prefix: {}", prefix);
}

It all depends on whether Oryx intends to add support for other filesystem schemes in the future, but in the meantime, you would either have to change the Oryx code yourself and recompile, or you could attempt to hack around it (but with potential for pieces of Oryx which have a hard dependency on HDFS to fail).
The change to Oryx should theoretically just be:
    String scheme = defaultURI.getScheme();
    if (port > 0) {
      prefix = scheme + "://" + host + ':' + port;
    } else {
      prefix = scheme + "://" + host;
    }

However, if you do go this route, keep in mind the eventual list consistency semantics of GCS, where multi-stage workflows must not rely on "list" operations to find immediately find all the outputs of a previous stage; Oryx may or may not have such a dependency.
The most reliable solution in your case would be to deploy with --default_fs hdfs, where bdutil will still install the gcs-connector so that you can run hadoop distcp to move your data from GCS to HDFS temporarily, run Oryx, and then once finished, copy it back out into GCS.


text:
Q: uninstalling pip3 on mac I am trying to get the installation right with python 3, pip and pip3. I am working on a mac and by default. I have Python 2.7.10
python -V

Python 2.7.10
python3 -V

Python 3.5.1

What is the correct order of installation commands to install python3 pip and pip3 so that both pip and pip3 can be linked to python3?
This what I get when I try to see what versions I already have:
$ pip -V
-bash: /usr/local/bin/pip: No such file or directory
$ pip3 -V
pip 7.1.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)

I need to get this right so that I can install numpy afterward because now with what I have above this is what I get:
$ pip3 install numpy
Collecting numpy
  Could not find a version that satisfies the requirement numpy (from versions: )
No matching distribution found for numpy

A: I have Solved it. as @keithpjolley suggested. I installed anaconda, launched it, and I used the command:
conda install numpy

I let it solve the environment. It gave me an older version of numpy at first so I upgraded:
conda install numpy=1.13

Now everything is working with my code.


text:
Q: Deleting orders works, deleting coffees doesn't. Identical functions I have to build a CRUD in nodejs+express+mongodb and I have a function to delete orders, which is successfully deleting orders by a parameter, and a copy of this function adapted to "coffees" MongoDB collection.
The second returns undefined, or simply {}.
First I modified the collection and then different sources as arguments.
Here is server.js
// This code works.
app.delete('/orders/:coffee_id', (req, res) => {
 db.collection('orders').findOneAndDelete({name: req.body.coffee_id}, (err, result) => {
    if (err) return res.send(500, err)
    res.json('Order deleted')
  })
})

// Orders Collection. This means visiting localhost:3000/orders/Delta returns Order deleted

// Code not working as expected:
app.delete('/coffees/:id', (req, res) => {
db.collection('coffees').findOneAndDelete({'name': req.body.name}, (err, result) => {
    console.log(res.body)  // returns undefined.
    if (err) return res.send(500, err)
    res.json(req.body)
  })
})

Coffees collection. Can't delete from this table. Postman DELETE to localhost:3000/coffees/Jamaica returns {} and console.log(res.body) returns undefined

Does anybody see something wrong? Please let me know if you require more code.
Thanks in advance.

A: A couple of things to note here.
1) Your routes are configured with path parameters, but you're trying to reference properties from req.body. I'm not sure how this is working in the first route, but I expect that it should not. You should be using req.params to access the path parameters.
app.delete('/orders/:coffee_id', (req, res) => {
 db.collection('orders').findOneAndDelete({name: req.params.coffee_id}, (err, result) => {
    ...
  })
})

2) In the second route you've declared a path parameter id, but you're attempting to access a property called name. This is where the implementation differs from the "working" route. It's not clear at face value if you want to use the ObjectId of document to perform deletions, or if you were planning using the name of the document.
Using the ObjectId:
app.delete('/coffees/:id', (req, res) => {
  db.collection('coffees').findOneAndDelete({_id: req.params.id}, (err, result) => {
    ...
  })
})

Using the name:
app.delete('/coffees/:name', (req, res) => {
  db.collection('coffees').findOneAndDelete({name: req.params.name}, (err, result) => {
    ...
  })
})

The takeaway here is that you must use the same value to reference the path param as the value declared in the path param.
/coffees/:id => req.params.id (not req.params.name)

A: Apparently I had to define a ObjectId like
var ObjectId = require('mongodb').ObjectID; //Include ObjectId

//then
app.delete('/coffees/:id', (req, res) => {
     db.collection('coffees').findOneAndDelete({'_id': ObjectId(req.params.id)}, (err, result) => {
        console.log(result)
        if (err) return res.send(500, err)
        res.json(result.body)
      })
    })


text:
Q: writing an unique php function to be used on my website I'm using a custom php code to translate my date format on my wordpress website, using get_the_time. I have to use this code on various spaces on my website, sometimes more than one time on a page.
here is my code I'm adding inside my custom page templates when needed :
<?php
$date  =  get_the_time('l j F Y');
$interdit = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday","January","February","March","April","May","June","July","August","September","October","November","December");
$replace   = array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado","Domingo", "Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");

$date_espagnole = str_replace($interdit, $replace, $date);
echo ($date_espagnole);
?>

what I want to know is how can I only declare this code once, maybe in my function.php, and then just add this code when needed : <?php echo ($date_espagnole);?>
Here is what I've tried in my function.php :
function date_translation(){
$date  =  get_the_time('l j F Y');
$interdit = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday","January","February","March","April","May","June","July","August","September","October","November","December");
$replace   = array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado","Domingo", "Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");

$date_espagnole = str_replace($interdit, $replace, $date);
return $date_espagnole;
}

and then in my custom pages when needed : <?php date_translation();?>
but it's not working. Is it possible to do this ? and if yes, what am I doing wrong ?
thanks a lot for your help,

A: You are returning the translation in your function, not printing it. Using <?php echo date_translation(); ?> should solve the problem.
(given that functions.php is initiated at the time you use the function)
Edit: In order to follow Wordpress convention, you should call the function get_date_translation(). If you want the function to echo the result instead, you should call it the_date_translation()


text:
Q: Error was encountered Severity: ilegal string offset Codeigniter in view, I try to call kriteria and sub kriteria:
I try to call id_kriteria, nama_kriteria kriteria from tb_kriteria for tittle, and then I call id_kriteria, namasubkriteria for option sub kriteria
Model:
public function GetSubKriteria() {
        $this->db->select('*');
        $this->db->from('tb_kriteria');
        $query = $this->db->get();
        $krit = $query->result();
        $data = array();
        $index = 0;
            foreach($krit as $kr_key => $x){
                $data[$kr_key] = array(
                    'id_kriteria'           => $x->id_kriteria,
                    'nama_kriteria'         => $x->nama_kriteria,
                );
                $id_kriteriax = $this->db->where('id_kriteria', $x->id_kriteria);
                $this->db->select('*');
                $this->db->from('tb_subkriteria');
                $query = $this->db->get();
                $id_kriteriax = $query->result();
                foreach($id_kriteriax as $z){
                    // $idKriteriaKey = $z->id_kriteria;
                    $data[$kr_key]['subkriteria'] = array(
                        // 'id_kriteria'           => $x->id_kriteria,
                        // 'nama_kriteria'         => $x->nama_kriteria,
                        'id_subkriteria'        => $z->id_subkriteria,
                        'namasubkriteria'       => $z->namasubkriteria,
                        'value'                 => $z->value
                    );
                }
                $index++;
            }
            return $data;
            // var_dump($data);
    }

view:
<?php
    $index =0;
    foreach ($subkriteria_ as $kr_key => $kriteria) {
    ?>

        <?php echo $kriteria['nama_kriteria'] ?>

                <input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
                <input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">
            <select class="form-control"  name="isi_kriteria[]" required>
                <option>Pilih Sub Kriteria</option>
                <?php $no = 1; foreach ($kriteria['subkriteria'] as $data)     { ?>
                <option value="<?php echo $data['value'] ?>"><?php echo $data['namasubkriteria'] ?></option> // this my error
                <?php  $no++; } ?>
            </select>

    <?php } ?>

but i try this code, now show the error at the view, Error was encountered Severity: ilegal string offset 'value' blabla
and if i try to var_dump($data); this array is just show one subkriteria, not all subkriteria data show in the array
thx for your response...

A:
You should check whether data occurs or not using empty() in controller and view

public function GetSubKriteria() {
    $this->db->select('*');
    $this->db->from('tb_kriteria');
    $query = $this->db->get();
    $krit = $query->result();
    $data = array();
    $index = 0;
        foreach($krit as $kr_key => $x){
            $data[$kr_key] = array(
                'id_kriteria'           => $x->id_kriteria,
                'nama_kriteria'         => $x->nama_kriteria,
            );
            $id_kriteriax = $this->db->where('id_kriteria', $x->id_kriteria);
            $this->db->select('*');
            $this->db->from('tb_subkriteria');
            $query = $this->db->get();
            $id_kriteriax = $query->result();
            if(!empty($id_kriteriax)){
            foreach($id_kriteriax as $z){
                // $idKriteriaKey = $z->id_kriteria;
                $data[$kr_key]['subkriteria'] = array(
                    // 'id_kriteria'           => $x->id_kriteria,
                    // 'nama_kriteria'         => $x->nama_kriteria,
                    'id_subkriteria'        => $z->id_subkriteria,
                    'namasubkriteria'       => $z->namasubkriteria,
                    'value'                 => $z->value
                );
            }
            }
            $index++;
        }
        return $data;

View

<?php
$index =0;
foreach ($subkriteria_ as $kr_key => $kriteria) {
?>

    <?php echo $kriteria['nama_kriteria'] ?>

            <input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
            <input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">
        <select class="form-control"  name="isi_kriteria[]" required>
            <option>Pilih Sub Kriteria</option>
            <?php $no = 1;
            foreach ($kriteria['subkriteria'] as $data)     {
            if(!empty($data)){
            echo '<option value="'.$data['value'].'">'.$data['namasubkriteria'].'</option>
            <?php  $no++; } } ?>
        </select>

<?php } ?>


text:
Q: Error restoring spatial database. ERROR : could not load library "/builds/postgresql-9.6.3/lib/rtpostgis-2.3.so" I am trying to restore a backup of a database. I am running postgresql-9.6.3 with postgis-2.3.3
I run the following restore command
.../myw_db new_db restore /path/to/database.backup
I get the following error message:

ERROR: could not load library
  ".../builds/postgresql-9.6.3/lib/rtpostgis-2.3.so":
  .lib64/libresolv.so.2: symbol __h_errno, version GLIBC_PRIVATE not defined in > file libc.so.6 with link time reference

I am very new at working with postgreSQL and working in the linux environment in general. I did try looking for a solution in the forums before posting.


text:
Q: Unable to dual boot windows 7,8, and ubuntu using w8 bootloader I had a sony vaio running windows 7 and Ubuntu but I had given it to my friend as he needed it,
I bought  a new desktop with windows 7 and windows 8 dual booted using w8 boot loader,
Now I am trying to boot Ubuntu but I want to boot it from windows 8 boot loader can anyone please help so I can boot all 3 oses from same boot screen.Please help,
thank you.

A: Is there any particular reason you want to use the Windows bootloader? GRUB is installed by default when you install Ubuntu and it does the same thing.


text:
Q: Implementing a callback without AIDL How can I implement a callback using LocalBinder without AIDL?
I've seen the examples of android LocalService.java but it only binds to the Service, there is not callback to the activity. The only callbacks example I see in the examples is the RemoteBinder.java but this uses AIDL and I want to avoid AIDL.
Thanks!


text:
Q: Is $( E^c)^o =(E^o)^c ?$ true/false Given $X= \mathbb{R}$ and    $E \subset \mathbb{R}$
Now my question is that
Is $( E^c)^o =(E^o)^c ?$
where  $o$ denote the interior and $c$ denote the complement
I think this is not true
take $E= \emptyset$
Now $\emptyset^c= \mathbb{R}$ and $\mathbb{R}^0=\mathbb{R}$
This implies $( E^c)^o \neq (E^o)^c$

A: This is not true in general.
Consider $E = (0,1)$. Then $E^{c} = (-\infty,0]\cup[1,+\infty)$.
Hence $\text{int}(E^{c}) = (-\infty,0)\cup(1,+\infty)$ and $(\text{int}(E))^{c} = (-\infty,0]\cup[1,+\infty)$.
Hopefully this helps.


text:
Q: Retrofit - optimal coding approach I am integrating Retrofit in my Android project. I have successfully made a request and received the response. But, I have two questions. Following is my code before I write my questions:
Retrofit API Interface:
public interface GetSensorData {

    @GET("data/normal/{station}/{type}/{period}/{duration}")
    Call<SensorData> getSensorDetails(
        @Path("station") String station,
        @Path("type") String type,
        @Path("period") String period,
        @Path("duration") String duration
    );

    @GET("user/stations")
    Call<List<Station>> getStationList();

    Gson gson = new GsonBuilder()
        .setLenient()
        .create();

    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS);
    OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request original = chain.request();
        Request.Builder requestBuilder = original.newBuilder()
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + Common.TOKEN_ACCESS)
                .method(original.method(), original.body());

        Request request = requestBuilder.build();
        return chain.proceed(request);
        }
    }).build();

    public static final Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(API_BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();
}

And the asynchronous calls to Service:
public class RetroCall {

final GetSensorData gitHubService = GetSensorData.retrofit.create(GetSensorData.class);
private SensorData contributors = new SensorData();
private ArrayList<ContributorsListener> listeners = new ArrayList<>();

public void requestSensorData() {

    final Call<SensorData> call = gitHubService.getSensorDetails("00000146", "hourly", "last", "5");
    call.enqueue(new Callback<SensorData>() {
        @Override
        public void onResponse(Call<SensorData> call, Response<SensorData> response) {
            if (response.isSuccessful()) {
                contributors = response.body();
                Log.e("Response Body:", response.raw().toString());
            } else {
                for (ContributorsListener listener : listeners) {
                    listener.onContributorsLoadFailed(response.message());
                    System.out.println(response.message());
                }
            }
        }

        @Override
        public void onFailure(Call<SensorData> call, Throwable t) {
            System.out.println(t.getMessage());
            for (ContributorsListener listener : listeners) {
                listener.onContributorsLoadFailed(t.getMessage());
            }
        }
    });
}

public interface ContributorsListener {

    void onContributorsLoaded(List<SensorData> contributors);
    void onContributorsLoadFailed(String message);
    void onContributorLoaded(SensorData contributor);
}
}

Question:
In my interface, I have defined two interfaces to my API and that is not the end. I have much more calls to the server. So, I do not want to write a asynchronous call against each interface and retrieve data. I want to write it the optimal way so that I just write one asynchronous call and it can handle everything. So, Can someone tell me how can I do that with Retrofit?


text:
Q: When calling microsoft graph api, I get exception AADB2C90086: The supplied grant_type [client_credentials] is not supported I am trying to delete a user from my AD B2C directory like so:
public static async Task<bool> DeleteUserAsync2(string userId)
{
    var clientapp = ConfidentialClientApplicationBuilder.Create(Globals.ClientId)
        .WithClientSecret(Globals.ClientSecret)
        .WithRedirectUri(Globals.RedirectUri)
        .WithB2CAuthority(Globals.B2CAuthority)
        .Build();

    ClientCredentialProvider authProvider = new ClientCredentialProvider(clientapp);

    var graphClient = new GraphServiceClient(authProvider);

    try
    {
        await graphClient.Users[userId]
            .Request()
            .DeleteAsync();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

Not sure why I am getting this not supported error because this is similar to what my code uses when signing in or signing up users in my application.

A: Because Azure AD B2C does not support the Client Credential Flow, we must sign in with a user when using Azure AD B2C. Client credential flow can be used for Azure AD.
Azure AD B2C supports authorization code flow and implicit flow.
Code samples: https://learn.microsoft.com/en-us/azure/active-directory-b2c/code-samples#single-page-apps


text:
Q: Incompatible version constraints on barback: Dart Editor version 1.10.0.release (STABLE)
Dart SDK version 1.10.0
pubspec.yaml
name: project
description: A sample Polymer application
dependencies:
  browser: any
  polymer: any
  observe: any
  bwu_datagrid: any
transformers:
- polymer:
   entry_points: web/project.html

Run pub get
--- 19:11:03 Running pub get on C:\Users\Toshiba\Documents\Dart\project ... ---
Pub get failed, [1] Resolving dependencies...
Incompatible version constraints on barback:
- observe 0.9.1+1 depends on version >=0.9.0 <0.11.0
- pub itself depends on version >=0.13.0 <0.15.3

** Warning: Application may fail to run since packages did not get installed.Try running pub get again. **

I can't understand what connection is between observe which i use in my project and pub itself.
Do you have any idea?


text:
Q: Screenshot of contents of Safari from share extension In the Share Extension for Safari, is it possible to take a screenshot and save it to Userdefaults so my app can access it ?
Would this be a recommended way of capturing a screenshot of the browser from an app extension ?

A: You do not have access to Safari when your extension opens. Extensions run in their own processes, and their view context is outside that of Safari.
An interesting workaround would be to use NSExtensionJavaScriptPreprocessingFile with a JS file that uses something like html2canvas to obtain a screenshot from within Javascript, and then pass that as an input to your native extension. The JS file provided with the extension is executed in the context of the Safari page.


text:
Q: How to add new Metadata options (Date, Author, etc.) for Posts? I would like to know if it's possible and how to create new Metadata options (like Date, Author, etc.) to show about a Post.
I tried using Advanced Custom Fields, but I can't seem to use the custom fields created as new Metadata options.
For example, I would like to create a new Metadata called Location, where i can put the desiderd location maybe linked to the dynamic custom field created with ACF.
Thanks in advance.


text:
Q: Using SIGUSR1 and SIGUSR2 as signals in pthread_kill() I would like to use SIGUSR1 and SIGUSR2 as arguments to pthread_kill() to suspend the execution of the running thread(i.e thread sends signal to itself) and resuming a suspended thread by a peer thread when a condition is met.
  Would be gratefull for any pointers like example code or views about it.
Thanks

A: Signalling is used as the following example. However, in your case though, you need Condition variables
https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal has an example
 pthread_cond_wait (condition,mutex)
 pthread_cond_signal (condition)
 pthread_cond_broadcast (condition)

Example with the correct usage of the signals with pthread_kill() is demonstrated below
 /* ptsig.c
   This program illustrates the use of signals in threads.

   Three threads including the main thread.
   main thread
     a. Set up a signal mask to block all signals.
     b. Set up signal handlers for SIGINT and SIGUSR1.
     c. Create thread_1, detached.
     d. Create thread_2, nondetached.
     e. Send SIGINT & SIGUSR1 to thread_1.
     f. Quit.

   thread_1
     a. Unblock all to embrace all signals.
     b. Wait for signals.
     c. Send SIGINT and SIGUSR1 to thread_2
     d. Wait for thread_2 to terminate
     e. Print thread_2 return status.
     f. Quit

   thread_2
     a. Unblock SIGUSR1 -- all others blocked due to inheritance.
     b. Wait for signals.
     c. Quit

   Note: There is hardly any error checking in this example -- not a good
   idea, but to make the program a bit more easier to explain.

   To compile:  gcc  ptsig.c -lpthread
                                                   Sam Hsu (11/19/10)
*/

#define _POSIX_C_SOURCE 199506L
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

pthread_t tid2;
static void int_handler(int signo), usr1_handler(int signo);

void millisleep(int milliseconds)
{
      usleep(milliseconds * 1000);
}

main()
{
   pthread_t tid1;
   pthread_attr_t attr_obj;             /* a thread attribute variable */
   void *thread_1(void *), *thread_2(void *);
   sigset_t sigmask;
   struct sigaction action;

   /* set up signal mask to block all in main thread */
   sigfillset(&sigmask);                /* to turn on all bits */
   pthread_sigmask(SIG_BLOCK, &sigmask, (sigset_t *)0);

   /* set up signal handlers for SIGINT & SIGUSR1 */
   action.sa_flags = 0;
   action.sa_handler = int_handler;
   sigaction(SIGINT, &action, (struct sigaction *)0);
   action.sa_handler = usr1_handler;
   sigaction(SIGUSR1, &action, (struct sigaction *)0);

   pthread_attr_init(&attr_obj);        /* init it to default */
   pthread_attr_setdetachstate(&attr_obj, PTHREAD_CREATE_DETACHED);
   pthread_create(&tid1, &attr_obj, thread_1, (void *)NULL);
   printf("TID(%u) created\n", (unsigned int)tid1);

   pthread_attr_setdetachstate(&attr_obj, PTHREAD_CREATE_JOINABLE);
   pthread_create(&tid2, &attr_obj, thread_2, (void *)NULL);
   printf("TID(%u) created\n", (unsigned int)tid2);
   millisleep(1000);     /* for some reason a sleep is needed here */

   printf("main(%u) sending SIGINT to TID(%u)\n", (unsigned int)pthread_self(), (unsigned int)tid1);
   pthread_kill(tid1, SIGINT);          /* not blocked by tid1 */
   printf("main(%u) sending SIGUSR1 to TID(%u)\n", (unsigned int)pthread_self(), (unsigned int)tid1);
   pthread_kill(tid1, SIGUSR1);         /* not blocked by tid1 */

   printf("main(%u) is terminating\n", (unsigned int)pthread_self());
   pthread_exit((void *)NULL);          /* will not terminate process */
}  /* main */

void *thread_1(void *dummy)
{
   int sig, status, *status_ptr = &status;
   sigset_t sigmask;

   sigfillset(&sigmask);                /* will unblock all signals */
   pthread_sigmask(SIG_UNBLOCK, &sigmask, (sigset_t *)0);
   sigwait(&sigmask, &sig);
   switch(sig) {
     case SIGINT:
         int_handler(sig);
         break;
     default:
         break;
   }
   printf("TID(%u) sending SIGINT to %u\n", (unsigned int)pthread_self(), (unsigned int)tid2);
   pthread_kill(tid2, SIGINT);          /* blocked by tid2 */
   printf("TID(%u) sending SIGUSR1 to %u\n", (unsigned int)pthread_self(), (unsigned int)tid2);
   pthread_kill(tid2, SIGUSR1);         /* not blocked by tid2 */

   pthread_join(tid2, (void **)status_ptr);
   printf("TID(%u) exit status = %d\n", (unsigned int)tid2, status);

   printf("TID(%u) is terminating\n", (unsigned int)pthread_self());
   pthread_exit((void *)NULL);          /* calling thread will terminate */
}  /* thread_1 */

void *thread_2(void *dummy)
{
   int sig;
   sigset_t sigmask;

   sigemptyset(&sigmask);               /* to zero out all bits */
   sigaddset(&sigmask, SIGUSR1);        /* to unblock SIGUSR1 */
   pthread_sigmask(SIG_UNBLOCK, &sigmask, (sigset_t *)0);
   sigwait(&sigmask, &sig);
   switch(sig) {
     case SIGUSR1:
         usr1_handler(sig);
         break;
     default:
         break;
   }
   printf("TID(%u) is terminating\n", (unsigned int)pthread_self());
   pthread_exit((void *)NULL);          /* calling thread will terminate */
}  /* thread_2 */

static void int_handler(int dummy)
{
   printf("SIGINT received by TID(%u)\n", (unsigned int)pthread_self());
}  /* int_handler */

static void usr1_handler(int dummy)
{
   printf("SIGUSR1 received by TID(%u)\n", (unsigned int)pthread_self());
}  /* usr1_handler */

pthread_cancel() is safer relative to pthread_kill()
An example of pthread_cancel() below
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

#define handle_error_en(en, msg) \
       do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

static void *
thread_func(void *ignored_argument)
{
    int s;
    s = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    if (s != 0)
        handle_error_en(s, "pthread_setcancelstate");

    while (1) {
        printf("sleeping\n");

        sleep(1);        /* Should get canceled while we sleep */

    }

    /* sleep() is a cancellation point */

    /* Should never get here */

    printf("thread_func(): not canceled!\n");
    return NULL;
}

int
main(void)
{
    pthread_t thr;
    void *res;
    int s;

    /* Start a thread and then send it a cancellation request */

    s = pthread_create(&thr, NULL, &thread_func, NULL);
    if (s != 0)
        handle_error_en(s, "pthread_create");

    sleep(10);           /* Give thread a chance to get started */

    printf("main(): sending cancellation request\n");
    s = pthread_cancel(thr);
    if (s != 0)
        handle_error_en(s, "pthread_cancel");

    /* Join with thread to see what its exit status was */

    s = pthread_join(thr, &res);
    if (s != 0)
        handle_error_en(s, "pthread_join");

    if (res == PTHREAD_CANCELED)
        printf("main(): thread was canceled\n");
    else
        printf("main(): thread wasn't canceled (shouldn't happen!)\n");
    exit(EXIT_SUCCESS);
}

A: While I agree with Nemo, there are some valid use cases for suspending threads via signals.  The susp.c code in PWPT is certainly a good base but you can also find it used in GLIBC.  You might also wish to break the thread out of a blocking-IO system call (see this question) or interrupt a semaphore wait (see this question).


text:
Q: Finding the most visited place at a particular time in SQL I have a user's table that has info about user_id, places user purchased tickets, and the time user had purchased the ticket.
Users:
|------------|-------------|----------------------|
|  user_id   |  place      | purchase_time        |
|------------|-------------|----------------------|
|     1      |  New York   | 2021-11-27:17:00:21  |
|     1      |  Chicago    | 2021-11-25:19:00:21  |
|     1      |  Chicago    | 2021-11-23:03:00:21  |
|     1      |  Washington | 2021-11-21:07:00:21  |
|     1      |  Washington | 2021-11-19:12:00:21  |
|     1      |  Washington | 2021-11-17:00:00:21  |
|     1      |  Washington | 2021-11-15:23:00:21  |
|     1      |  Washington | 2021-11-12:21:00:21  |
|     2      |  Chicago    | 2021-09-25:01:00:21  |
|     2      |  Milwaukee  | 2021-09-24:02:00:21  |
|     2      |  Milwaukee  | 2021-09-23:03:00:21  |
|     2      |  New York   | 2021-09-22:19:00:21  |
|     2      |  Chicago    | 2021-09-21:01:00:21  |
|     3      |  Milwaukee  | 2021-10-27:12:31:21  |
|     3      |  Washington | 2021-10-24:07:01:23  |
|     3      |  Chicago    | 2021-10-21:01:78:89  |
|------------|-------------|----------------------|

I want to add a new column that shows the user's most visited place at the time of purchasing ticket. The table would like (Snowflake):
|------------|-------------|----------------------|---------------------|
|  user_id   |  place      | purchase_time        | most_visited_place  |
|------------|-------------|----------------------|---------------------|
|     1      |  New York   | 2021-11-27:17:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     1      |  Chicago    | 2021-11-25:19:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     1      |  Chicago    | 2021-11-23:03:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     1      |  Washington | 2021-11-21:07:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     1      |  Washington | 2021-11-19:12:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     1      |  Washington | 2021-11-17:00:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     1      |  Washington | 2021-11-15:23:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     1      |  Washington | 2021-11-12:21:00:21  |    Washington       | <--- Washington, because at purchase_time This place was most visited by the user
|     2      |  Chicago    | 2021-09-21:01:00:25  |    Chicago          | <-- tie, break. Both Chicago and Milwaukee were most visited then take the recent most visited
|     2      |  Milwaukee  | 2021-09-21:02:00:24  |    Milwaukee        | <--- Milwaukee, because at purchase_time This place was most visited by the user
|     2      |  Milwaukee  | 2021-09-21:03:00:23  |    Milwaukee        | <--- Milwaukee, because at purchase_time This place was most visited by the user
|     2      |  New York   | 2021-09-21:19:00:22  |    New York         | <-- tie, break. Both Chicago and New York were most visited then take the recent most visited
|     2      |  Chicago    | 2021-09-21:01:00:21  |    Chicago          | <--- Chicago, because at purchase_time This place was most visited by the user
|     3      |  Milwaukee  | 2021-10-27:12:31:21  |    Milwaukee        |
|     3      |  Washington | 2021-10-24:07:01:23  |    Washington       |
|     3      |  Chicago    | 2021-10-21:01:78:89  |    Chicago          |
|------------|-------------|----------------------|---------------------|

A: You want to use a WINDOW version of COUNT to get the "prior rows count" and then join to all the prior counted rows, and filter out the "best" via a QUALIFY
WITH prior_user AS (
    SELECT
        user_id,
        place,
        purchase_time,
        COUNT(place) OVER (PARTITION BY user_id, place ORDER BY purchase_time ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS place_count
    FROM users
)
SELECT
    u.user_id,
    u.place,
    u.purchase_time,
    p.place AS most_visited_place
FROM users u
JOIN prior_user p
    ON u.user_id = p.user_id AND u.purchase_time >= p.purchase_time
QUALIFY row_number() OVER (partition by u.user_id, u.purchase_time ORDER BY place_count DESC, p.purchase_time DESC) = 1

*this sql has not been run.

A: You can just do a lateral join in Snowflake. The use of distinct is kind of ugly but I think you could substitute that for a qualify and possibly even get a better plan. I'd be curious to see if this is equivalent to the other answer from an execution standpoint.
select *
from Users u, lateral (
    select distinct first_value(place) over ()
        order by count(*) desc, max(u2.purchase_time) desc) as most_visited_place
    from Users u2
    where u2.user_id = u.user_id and u2.purchase_time <= u.purchase_time
    group by place
    --qualify row_number() over (order by u2.user_id) = 1
) as mr
order by user_id, purchase_time desc

https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=02784df13affab8027f7b052ad942d70


text:
Q: CSS Menu aligntment acting odd in safari? For some reason the menu of my site is appearing all mis-aligned when using Safari.. site is at http://penarthpc.com/~redvaner/
I've been staring at it for hours and I cant figure it out. It's driving me crazy. Below is an image of how it looks when displayed 'improperly'
http://i.imgur.com/t3hXjry.png
Below is the CSS I've written for the Navbar (element has issues)
(http)pastebin.com/kLDBGnsU
Your help is much appreciated! I'm at a wits end :(

A: the only difference I can notice on first look is that your links are underlined in Safari. Everything else looks fine and not like the supplied image. The following CSS should solve the underline issue:
a{text-decoration:none !important;}

With regard to the supplied image, perhaps try adding the following to your <li> style
#nav-bar ul li{display:inline-block;zoom: 1;*display: inline;}

this is an ie7 fix, as inline block elements dont usually render correctly in ie7


text:
Q: BPS service not starting at the launch of the app Blackberry10    if(bps_initialize() == BPS_SUCCESS){
      qDebug() << "............................................";
      netstatus_interface_details_t *details;
      if (netstatus_get_interface_details(interface, &details) == BPS_SUCCESS) {
           QString ipAddr = netstatus_interface_get_ip_address(details, 0);
          netstatus_free_interface_details(&details);
      }
   }
bps_shutdown();

I am calling this function at the launch of my app to get the ip address of the device. But ( netstatus_get_interface_details(interface, &details) ) is returning false and the application crashes when i am removing this if statement. What might be the reason. Any help? this code is working perfectly fine if I am calling this function in my app at any time apart from when i am launching the app.... Thanks in advance.


text:
Q: Pyspark convert an array of json column to a pandas list of dict column I have pyspark dataframe that I want to convert into a pandas dataframe, however I have an array of json column that gets converted into a string in pandas
my_df = (
spark
.createDataFrame(
  pd.DataFrame([['Scott', 50], ['Jeff', 45], ['Thomas', 54], ['Ann',34]], columns=['id', 'score']))
)

my_df
.groupBy('id')
.agg(
  F.to_json(
    F.sort_array(
      F.collect_list(F.col('score')), asc=False
    )
  ).alias('preds')
).toPandas

I need to execute: mypandasdf['preds'] = mypandasdf.preds.apply(eval) to cast my string column to a list of dict.
I was wondering if there was any more efficient way to do it.
Any help? Thanks.


text:
Q: setting struts property value to jsp session I want to set session as below but getting jsp exception
<input type="hidden" id="taxEngine" value="<s:property value="taxEngine"/>" />

hidden field is populating correctly but unable this to assign to session.
      <%
session.setAttribute("taxEngine", <s:property value="taxEngine"/>);
   %>

any suggesion how to set jsp element hidden value to scriptlet.


text:
Q: Flex to JavaScript library/API Flex to JavaScript library/API
I am looking for a "small" lib for exposing JavaScript objects within Flex/AS3.  I have looked at Adobe's FABridge, but that seemed to me to be more of JavaScript to Flex.  Are there any good examples of Flex using JavaScript objects with the FABridge?
...or some other Flex-JavaScript library more aligned in that direction that others know of / have used?
The only other one that I have looked at is the JSInterface ... but it is documented in Russian :-( ...
gsb

A: I'm not sure exactly what you are looking to do but if it's just simple communication between Flex and Javascript you can use the ExternalInterface class to do this. It allows a Flex app to invoke Javascript methods defined in the HTML wrapper and also allows Javascript to invoke methods in the Flex app that you expose via ExternalInterface.
http://livedocs.adobe.com/flex/3/langref/flash/external/ExternalInterface.html

A: i finished translation of documentation, Presentation and ASDoc to English. :)
You are welcome


text:
Q: Cookie PHP, чтение, запись, передача? Использую
setCookie('namecc','1234',1200,'/');

Затем
print_r($_COOKIE);

*

*выдает черти какие элементы массива, что в формате как будто кодированное:) [SESSedd5b2...] => ODnkDJhiDJHSGD .. . и т.д
print_r($_COOKIE['namecc']);
пишет Notice: Undefined index: namecc in - т.е. Куки не записалось ?,
И далее еще более сложно, мне необходимо передать эти куки стороннему скрипту, на другом домене в заголовке, т.е. полностью сємулировать браузер при передаче Куки стороннему скрипту.
Браузер Firefox 46, PHP 5.6, Appache
Как это исправить? В каком направлении искать?

A: За 3-и часа, немного покурив, нашел следующую свою ошибку, setcookie в PHP устанавливает срок действия по метке времени в секундах, т.е. не 1200 от текущего времени, а 1200 от начала наших дней ... таким образом Куки устанавливались и в течение сессии обнулялись, необходимо указывать в setcookie, 3-ий параметр time()+ количество секунд после текущего времени, например 60*60*30 - 30 мин. от момента загрузки страницы.


text:
Q: R: Quantmod to pull S&P Index with ^ symbol before ticker I am having trouble using the quantmod package to get info on the S&P (ticker = ^GSPC).
For a normal stock (example: DFS) I'd be able to run the below code:
start <- as.Date("2020-01-01")
end <- as.Date("2020-05-06")
getSymbols("DFS", src = "yahoo", from = start, to = end)
DFS <-  data.frame(date=index(DFS), coredata(DFS))
head(DFS)

The problem I have with the S&P is the ^ symbol in the name.
start <- as.Date("2020-01-01")
end <- as.Date("2020-05-06")
getSymbols("^GSPC", src = "yahoo", from = start, to = end)
SP500 <-  data.frame(date=index(^GSPC), coredata(^GSPC))

This code gives the following error:
Error: unexpected '^' in "SP500 <-  data.frame(date=index(^"
Does anyone know a good work around for this?

A: use auto.assign = FALSE. This allows you to assign your values to your own data.frame with a more appropriate name.
start <- as.Date("2020-01-01")
end <- as.Date("2020-05-06")
df <- quantmod::getSymbols("^GSPC", src = "yahoo", from = start, to = end, auto.assign = FALSE)

as a side note, this will also be the default behaviour in a future update of  quantmod.