text:
Q: About reference frame in Newton's second law? Classical physics models events occuring in the spacetime $\mathcal E\times \mathcal T$ where $\mathcal E$ is a dimension 3 euclidean point space and
$\mathcal T$ is an interval of $(\mathbb R, <)$ (an ordered set).
An observer is a fictitious human being or sensor that can infinitely precisely describs events.
A reference frame is made of a frame $R=(O, \vec e_1, \vec e_2, \vec e_3)$,
an initial time $t_0$ and a coordinate system uniquely mapping a triplet $(x,y,z)$
to a generic point $M$ in $\mathcal E$.
Point $O$ is in $\mathcal E$ and is chosen as the origin and $(\vec e_1, \vec e_2, \vec e_3)$ is a basis of the euclidean vector space $\vec E$ attached to $\mathcal E$.
It seems to me that the first purpose of such a reference frame is to quantify
(I mean with values not with symbols) the location and the instant of any event. Without it a generic point $M$ still qualifies a unique location of $\mathcal E$ and a real $t$ an instant in $\mathcal T$ and the inner product a tool for geometry...
Since we can define arbitrarily a reference frame given a point and a basis
let's suppose that $O$ is the location of the observer. The observer moves with point $O$.
It is often said that Newton's first law postulates the existence of privilegied reference frames in which a body experiencing null resultant of forces $\vec F$ have a constant velocity, that is null acceleration $\vec a$, such frames are called inertial reference frames or galilean reference frames. Then Newton's second law as the simple form $\vec F=m \vec a$ only in inertial reference frames.
In mathematics, it is taught that a vector is intrinsic in the sense that
it's existence preceeds the one of basis and it is not dependent of the basis in which it is quantified.
So my question is why the notion of reference frame is usefull in the statement of Newton's second law?
It seems to me that only point $O$ is needed, we actually don't care about the basis. Point $O$ should be an "inertial point" the basis can rotate, vectors change in norm, angles between two vectors can change as long as they stay linearly independent because we still can quantity $\vec F$ in every such basis.
Do you have an opinion on that? Any book that consider vectors as intrinsic objects?

A: You have a wrong idea of classical spacetime $V^4$. It is not the Cartesian product $\mathbb E^3 \times \mathbb R$.
It is instead a fiber bundle $$T: V^4 \to \mathbb R$$
such that each fiber $\Sigma_t = T^{-1}(t)$, the absolute space at fixed time $t$,  is isomorphic to a three dimensional Euclidean space (*) $\mathbb E^3$. The basis of the bundle, the axis $\mathbb R$, is the range of the absolute time $T$ which is defined up to an additive constant.
The difference between this notion of spacetime as a bundle $T: V^4 \to \mathbb R$ and a trivial scalar product
$\mathbb E^3 \times \mathbb R$ is fundamental: Here there is no canonical representation of $V^4$ as a Cartesian product $\mathbb E^3 \times \mathbb R$.
More precisely, every choice of a reference frame defines such a representation.
A reference frame is nothing but a (smooth) surjective map $$\pi : V^4 \to \mathbb E^3$$ such that $\pi|_{\Sigma_t} : \Sigma_t \to \mathbb E^3$ is an isomorphism of Euclidean spaces (i.e., a surjective affine isometry), for every $t\in \mathbb R$.
In this picture, $\mathbb E^3$ is viewed as the rest space of the reference frame.
This way the spacetime $V^4$ is identified with the Cartesian product $\mathbb R \times \mathbb E^3$ by means of
$$V^4 \ni p \mapsto (T(p), \pi(p)) \in \mathbb R \times \mathbb E^3$$
There are however infinitely many such identifications depending on the choice of the reference frame.
Consider two reference frames $\pi$ and $\pi'$ and fix Cartesian orthonormal coordinates in the respective rest spaces $\mathbb E^3$ and
$\mathbb E'^3$, and use the absolute time defined up to an additive constant as time coordinate.
Using the fact that  $\pi'|_{\Sigma_t}\circ (\pi|_{\Sigma_t})^{-1} : \mathbb E^3 \to \mathbb E'^3$ is  a surjective affine isometry,
 you easily see that the transformation of coordinates must be of the form
$$t'=t+c \:,\quad x'_i = \sum_{j=1}^3 R_{ij}(t) x_j + b_i(t) \tag{1}$$
where $R(t) \in O(3)$ and $b(t) \in \mathbb R$ for every $t$.
These are the most general transformation of coordinates between Cartesian coordinates at rest with different reference frames.
To define the velocity of a section $$\mathbb R \ni t \mapsto \gamma(t) \in \Sigma_t $$  you need a full reference frame as indicated not only a reference point.
Indeed, the velocity of $\gamma$ with respect to $\pi$ is computed as
$$\vec{V}_\pi(t) := \frac{d}{dt}\pi(\gamma(t))$$
and, with this definition, it is a vector in the rest space $\mathbb E^3$ of $\pi$. However it can be seen as a vector in $\Sigma_t$ using the inverse of the isomprphism  $\pi|_{\Sigma_t} : \Sigma_t \to \mathbb E^3$.
Exploiting this identification, velocities of the same section but referred to different reference frames can be compared in the absolute space $\Sigma_t$.
REMARK. It is not enough to fix a reference point, that is a section $\mathbb R \ni t \to O(t) \in \Sigma_t$ to define the velocity of another section $\mathbb R \ni t \to \gamma(t) \in \Sigma_t$. Your  idea is to take the limit $$\lim_{h \to 0} \frac{1}{h}\left[\left(\gamma(t+h) -O(t+h)\right) - \left(\gamma(t) -O(t)\right)\right]\:.$$
The point is that the difference $$\left(\gamma(t+h) -O(t+h)\right) - \left(\gamma(t) -O(t)\right)$$ does not make sense as the two vectors$\gamma(t+h) -O(t+h)$ and $\gamma(t) -O(t)$ belong to different vector spaces. In order to make sensible that difference is necessary to isometrically identify the spaces. This is exactly what the notion of reference frame does.
Inertial reference frames are defined as reference frames where every isolated body moves with constant velocity. It is easily proved that this constraint imposes a strong restriction to the form of the coordinate transformation (1) between inertial frames which therefore specialises to
$$t'=t+c \:,\quad x'_i = \sum_{j=1}^3 R_{ij} x_j + tv_i + b_i \tag{2}$$
that is a generic transformation of Galileo's group. It is nice to observe that, up to isomorphisms, there is only one affine structure in the classical spacetime such that Cartesian coordinates at rest with inertial reference frames together with absolute time as forth coordinate define affine coordinate systems of that structure. The sections of the spacetime which are right lines (geodesics) of that affine structure are all possible inertial evolutions of isolated matter points. To this respect classical physics and GR are not so different.
Statements as Newton's second law are formulated with this notion of reference frame (if one wants to be completely rigorous).

(*) An Euclidean  space $\mathbb E^n$ is an affine space whose $n$-dimensional space of vectors $T^n$ describing translations in $\mathbb E^n$ is equipped with a positive scalar product.

A:
It seems to me that only point O is needed, we actually don't care about the basis.

We actually do care about the basis, very much so. In Newtonian mechanics, the displacement vector between one point and another in $\mathbb R^3$ is indeed frame independent. This displacement vector might well have different representations in different bases, but all such displacement vectors are substantively the same vector.
The same does not apply to the time derivatives of these vectors. The time derivative of a displacement vector is a frame-dependent quantity, depending on the linear and angular velocities of the observers. This also applies to the second time derivative of a displacement vector. Since Newton's second law is a statement about second time derivatives, that displacement vectors are substantively the same to all observers is irrelevant.


text:
Q: QGIS 64-bit ODBC set up link to 32-bit Access on win7 I am trying to set up a an ODBC link to Access 2007 32-bit but not having any success.  My system is a win7 pro 64-bit and I have QGIS 64-bit installed.  Here are the steps I have already tried.

*

*Set up an ODBC link using c:\windows\syswow64\odbcad32.exe.  However, when I try to use that, the error message states that there is an architecture mismatch, which I assume means between 64- and 32-bit architecture.

*Tried to set up the ODBC link from the standard location in Control Panel, but the error is that the Microsoft Access driver isn't installed.

*Downloaded the Microsoft Access 64-bit Runtime, but when installing the error comes up that the 32-bit Access is installed and the 64-bit Runtime cannot be installed.
I am not sure where to go from here.
I know that I can change databases and go with a spatial system, but this is a regular download from a government site, which would mean a lot of extra work.  Any assistance would be much appreciated.

A: Here's the thing. Windows 64 bit stores the 64 bit odbcad.exe in the System32 folder. The one in the location that you're editing, c:\windows\syswow64\odbcad32.exe, is actually the 32 bit one. Hilarious right? 32 bit applications in the syswow64 folder, 64 bit applications in the System32 folder! There are reasons though.
Now, for QGIS, add the ODBC driver in the odbcad for the right architecture for you:

*

*for 32 bit applications, open c:\Windows\syswow64\odbcad32.exe

*for 64 bit applications, open c:\Windows\system32\odbcad32.exe

To do this quickly, you can use my reg scripts: https://gist.github.com/alexgleith/9358893

A: Try uninstalling QGIS-64 bit and re-install QGIS-32 bit. Then try the odbc link. This trick worked for me, I think that QGIS-64 is looking in the wrong folder (the system32 folder) for the ODCB link. Using QGIS-32 will cause it to look in the SysWOW64 folder.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Draw Bar/Column Chart using google app script I want to draw a chart as presented in the image using the data.
Please follow the link for image :
https://drive.google.com/file/d/0B8FL6hHjH8poakoxRlFDVWRuams/edit?usp=sharing

A: Based on your question, there are a ridiculous number of chart API's out there which may or may not suit your needs, personally I would go with the Google Charts API as it can accept multiple dataTypes and custom styles and you'll want to be looking for the column chart within the Google API Documentation.
Read the Documentation carefully or you will get lost on this one.
(Although this statement pretty much counts for anything with a documentation).

A: I don't think it is possible to do so using google charts visual api/google apps script.
As data looks to contain hierarchy under which the bars are constructed.


text:
Q: Converting 2D position / rotation to 3D I have a player-object, and a player and a camera attached to it as childs.
I would like to rotate the camera in a circle around the player so that it always faces the player (which is centered at 0,0,0).
I have a 2D approach which I need to convert 3D.
What would this script look like for 3D?
Thank you.
 using UnityEngine;
 using System.Collections;

 public class circularMotion : MonoBehaviour {

 public float RotateSpeed;
 public float Radius;

 public Vector2 centre;
 public float angle;

 private void Start()
 {
     centre = transform.localPosition;
 }

 private void Update()
 {

     angle += RotateSpeed * Time.deltaTime;

     var offset = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle)) * Radius;
     transform.localPosition = centre + offset;
 }
 }

A: Well, one approach could be to define an upwards vector and then rotate around the corresponding axis.
using UnityEngine;

public class circularMotion : MonoBehaviour
{
    public float RotateSpeed = 1;
    public float Radius = 1;

    public Vector3 centre;
    public float angle;

    public Vector3 upDirection = Vector3.up; // upwards direction of the axis to rotate around

    private void Start()
    {
        centre = transform.localPosition;
    }

    private void Update()
    {
        transform.up = Vector3.up;
        angle += RotateSpeed * Time.deltaTime;

        Quaternion axisRotation = Quaternion.FromToRotation(Vector3.up, upDirection);

        // position camera
        Vector3 offset = axisRotation * new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle)) * Radius;
        transform.localPosition = centre + offset;

        // look towards center
        transform.localRotation = axisRotation * Quaternion.Euler(0, 180 + angle * 180 / Mathf.PI, 0);
    }
}


text:
Q: Check if sequence fulfils the Central Limit Theorem Does the following sequence of independent random variables with symmetric probability:
$\mathbb{P}(X_n = 1) = \frac{1}{2} - \frac{1}{2n^2}$ and $\mathbb{P}(X_n = n) = \frac{1}{2n^2}$
fulfils the Central Limit Theorem?
Now, I wish I could show my attempt but there isn't much to show. Should I first see if $\mathbb{E}X^2 < \infty$ and then check the Lindenberg's condition?


text:
Q: Wordpress form, cannot set value with jQuery I've designed a simple form in Wordpress which I included (as HTML) in an external file [see background at the end]. In this file, an event listener is supposed to fill an input of the form. But I cannot set a value in this input, the change doesn't seem to be made.
Here is the input (as generated with Wordpress) :
<span class="wpcf7-form-control-wrap tarif-depart">
     <input name="tarif-depart" value="" size="40" class="wpcf7-form-control wpcf7-text tarif-hidden" id="tarif-depart" aria-invalid="false" type="text">
</span>

And here is the JS :
$('#tarif-depart')
    .val(places.O[0].formatted_adress)

Background
I'm working on a little script using Google Map API on a Wordpress site. The fact is including my script (and HTML elements) doesn't seem to work well when integrated. So, I chosed to include it inside an iframe. The script is related to a form that I had to add in the iframe for communication. But it doesn't work better ...
Thanks for your help.

A: If you are writing jQuery in a PHP document (like Wordpress) you need to write it as
jQuery('#tarif-depart')
    .val(places.O[0].formatted_adress)

or wrap it in a wrapper like this:
jQuery(document).ready(function($) {
    // Inside of this function, $() will work as an alias for jQuery()
    // and other libraries also using $ will not be accessible under this shortcut
});

source for the last bit


text:
Q: Gradle 'TestApp' project refresh failed I am new to android studio. I have installed android studio 2.1 and imported an eClipse project into it as my first project. After finishing import job, an error occurred with this title:

Gradle 'TestApp' project refresh failed
►Error:A problem occurred configuring project ':app'.

I notice that in Tools > Android > SDK manager > System Settings > Android SDK > SDK Update Sites there are errors with Android Repository and Legacy Android Repository.

Android Repository https://dl.google.com/android/repository/repository2-1.xml
Legacy Android Repository  https://dl.google.com/android/repository/repository-12.xml

I have reinstalled Android studio and then installed and updated all extra fields in SDK manager. I have Android 4.4.2 and 5.0.1 SDK platforms. I Have all tools items installed in SDK manager.

There are no errors in Standalone SDK Manager.

I tried creating a new project. But same error appears.
How can I resolve the issue and run this app?

A: I restarted the Android SDK Manager and at this time I noticed that I got Android SDK Platform-tools (upgrade) and Android SDK Build-tools (new).
After installing those, I was finally able to fully compile my project.
Note: The latest ADT (Version 23) should be installed.


text:
Q: How to preform loc with one condition that include two columns I have df with two columns A and B both of them are columns with string values.
Example:
df_1 = pd.DataFrame(data={
    "A":['a','b','c'],
    "B":['a x d','z y w','q m c'] #string values not a list
})
print(df_1)

#output
   A      B
0  a  a x d
1  b  z y w
2  c  q m c

now what I'm trying  to do is to preform loc in the df_1 to get all the row that col B cointain the string value in col A.
In this example the output i want is the first and the third rows:
   A      B
0  a  a x d # 'a x d' contain value 'a'
2  c  q m c # 'q m c' contain value 'c'

I have tried different loc condition but got unhashable type: 'Series' error:
df_1.loc[df_1["B"].str.contains(df_1["A"])] #TypeError: unhashable type: 'Series'
df_1.loc[df_1["A"] in df_1["B"]] #TypeError: unhashable type: 'Series'

I really don't want to use a for/while loop because of the size of the df.
Any idea how can I preform this?

A: Cute!
from operator import contains

df_1.loc[map(contains, *map(df_1.get, ['B', 'A']))]

   A      B
0  a  a x d
2  c  q m c

And without the import but with an ugly dunder ... /-:
df_1.loc[map(str.__contains__, *map(df_1.get, ['B', 'A']))]

Also, to the OP... don't accept this answer.  I was just golfing.  You should never use this in production code as it is less than transparent due to the use of 2 maps and a splat.
And just to be super duper clear...
mozway's is the better one

A: You can try:
out = df_1.loc[df_1.apply(lambda x: x['A'] in x['B'], axis=1)]
print(out)

# Output
   A      B
0  a  a x d
2  c  q m c

Alternative with numpy:
df_1.loc[np.apply_along_axis(lambda x: x[0] in x[1], axis=1, arr=df_1)]

A: When accessing two different columns in pandas you can use .apply()
df.apply(lambda row: row['A'] in row['B'], axis = 1)

This creates a Boolean Series which you can use for your loc condition which selects only the columns where 'A' is in 'B':
df.loc[df.apply(lambda row: row['A'] in row['B'], axis = 1)]

A: df_1[df_1.apply(lambda x:x['A'] in x['B'],axis=1)]

A: There is no vectorial method, to map in using two columns. You need to loop here:
mask = [a in b for a,b in zip(df_1['A'], df_1['B'])]

df_1.loc[mask]

Output:
   A      B
0  a  a x d
2  c  q m c

comparison of speed (3000 rows)
# operator.contains
518 µs ± 4.61 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# list comprehension
554 µs ± 3.84 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# numpy.apply_along_axis
7.32 ms ± 58.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# apply
20.7 ms ± 379 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: import pandas as pd

df_1 = pd.DataFrame(data={
    "A":['a','b','c'],
    "B":['a x d','z y w','q m c'] #string values not a list
})

m = df_1['B'].str.contains('|'.join(df_1['A']), case=True, regex=True)
print(df_1.loc[m])

#    A      B
# 0  a  a x d
# 2  c  q m c


text:
Q: Why does Workbook.Close trigger the UserForm_Terminate? - VBA There is some problem in the following code, which is driving me mad. I can't seem to find the reason why the code suddendly ends when an Excel Workbook gets automatically closed.
The code is executed from an Excel Workbook and works like this:

*

*It opens another Workbook (WbLOP)

*Creates a third Workbook (TargetWb)

*Copies some data from WbLOP to TargetWb

*Closes WbLOP

Whole code below:
Public WbLOP As Workbook, WsLop As Worksheet
Public AbtToEval As String

Sub Std_Ausw()

Dim OpenDialog As Object, FileName As String
Dim Ws As Worksheet
Dim Termin As Date
Dim TargetWb As Workbook, TargetWs As Worksheet
Dim i As Integer, j As Integer, k As Integer, w As Integer
Dim ZielCol As Integer, ZielNEWCol As Integer, PEPStatusCol As Integer, StatusAICol As Integer
Dim ActivityRow As Integer

' Asks user input file to read from
Set OpenDialog = Application.FileDialog(msoFileDialogFilePicker)
With OpenDialog
    .AllowMultiSelect = False
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xls, *.xlsx, *.xlsm"
    If .Show Then
        FileName = .SelectedItems(1)
    Else
        Set OpenDialog = Nothing
        Exit Sub
    End If
End With
Set OpenDialog = Nothing

' Checks if the worksheet "LOP" is contained in the file
Set WbLOP = Application.Workbooks.Open(FileName)
For Each Ws In WbLOP.Worksheets
    If UCase(Ws.Name) = "LOP" Then
        Set WsLop = Ws
        Exit For
    End If
Next
On Error Resume Next
If WsLop.Name = "" Then
    WbLOP.Close savechanges:=False
    Set WbLOP = Nothing
    MsgBox "Fail"
    Exit Sub
End If
On Error GoTo 0

' Shows a Userform to let user decide the name of the AbtToEval
Ausw.Show

I'm pasting here the code of the UserForm:
Private Sub Cancel_Click()
    End
End Sub

Private Sub UserForm_Terminate()
    End
End Sub

Private Sub UserForm_Initialize()

Dim Abt() As String
Dim i As Integer, j As Integer, k As Integer

' Searches for the PD-Abt column
i = 1
Do Until LCase(WsLop.Cells(8, i)) = "pd-abt"
    i = i + 1
Loop

' Copies the unique Abt in an array
j = 10
ReDim Abt(0)
Abt(0) = UCase(WsLop.Cells(j, i))
Do Until IsEmpty(WsLop.Cells(j, 1))
    For k = 0 To UBound(Abt)
        If Abt(k) = UCase(WsLop.Cells(j, i)) Then
            Exit For
        Else
            If k = UBound(Abt) Then
                ReDim Preserve Abt(UBound(Abt) + 1)
                Abt(UBound(Abt)) = UCase(WsLop.Cells(j, i))
            End If
        End If
    Next
    j = j + 1
Loop

' Initializes the combo-box with the Abt names
For i = 0 To UBound(Abt)
    Me.AbtBox.AddItem Abt(i)
Next
Me.AbtBox.ListIndex = 0

End Sub

Private Sub OK_Click()
    AbtToEval = Me.AbtBox.List(Me.AbtBox.ListIndex)
    Me.Hide
End Sub

And here the main Sub is resumed
' Opens a new workbook and copies the table from the template
Application.DisplayAlerts = False
Set TargetWb = Application.Workbooks.Add
Do Until TargetWb.Sheets.Count = 1
    TargetWb.Sheets(TargetWb.Sheets.Count).Delete
Loop
Set TargetWs = TargetWb.Sheets(1)
ThisWorkbook.Worksheets("Template").Range("A1:J3").Copy Destination:=TargetWs.Range("A1")
Application.DisplayAlerts = True
TargetWs.Range("A2") = AbtToEval

' Sets a standard limit of 4 weeks from today
Termin = DateAdd("ww", 4, Date)

' Searches for the Ziel-Datum columns
i = 1
Do Until InStr(1, LCase(WsLop.Cells(8, i)), "ziel-datum") <> 0
    i = i + 1
Loop
If InStr(1, LCase(WsLop.Cells(8, i)), "neu") <> 0 Then
    ZielNEWCol = i
    i = i + 1
    Do Until InStr(1, LCase(WsLop.Cells(8, i)), "ziel-datum") <> 0
        i = i + 1
    Loop
    ZielCol = i
Else
    ZielCol = i
    i = i + 1
    Do Until InStr(1, LCase(WsLop.Cells(8, i)), "ziel-datum") <> 0
        i = i + 1
    Loop
    ZielNEWCol = i
End If

' Searches for the status columns
i = 1
Do Until InStr(1, LCase(WsLop.Cells(8, i)), "pep status") <> 0
    i = i + 1
Loop
PEPStatusCol = i
i = 1
Do Until InStr(1, LCase(WsLop.Cells(8, i)), "status ai") <> 0
    i = i + 1
Loop
StatusAICol = i

' Searches for the activities to do
i = 0
j = 0
Do Until IsEmpty(WsLop.Cells(9 + i, 1))
    If Not WsLop.Cells(9 + i, PEPStatusCol) = "akt" Then GoTo Go_Forth
    If WsLop.Cells(9 + i, StatusAICol) = "ges" Then GoTo Go_Forth
    If IsEmpty(WsLop.Cells(9 + i, ZielNEWCol)) Then
        If CDate(WsLop.Cells(9 + i, ZielCol)) > Termin Then
            GoTo Go_Forth
        Else
            ActivityRow = 9 + i
        End If
    Else
        If CDate(WsLop.Cells(9 + i, ZielNEWCol)) > Termin Then
            GoTo Go_Forth
        Else
            ActivityRow = 9 + i
        End If
    End If
    ThisWorkbook.Worksheets("Template").Range("A4:J4").Copy Destination:=TargetWs.Cells(4 + j, 1)
    For w = 1 To 10
        k = 1
        Do Until TargetWs.Cells(3, w) = WsLop.Cells(8, k)
            k = k + 1
        Loop
        TargetWs.Cells(4 + j, w) = WsLop.Cells(ActivityRow, k)
    Next
    j = j + 1
Go_Forth:
    i = i + 1
Loop

' If TargetSheet is empty then shows only a message
If IsEmpty(TargetWs.Cells(4, 1)) Then
    Application.DisplayAlerts = False
    TargetWb.Close savechanges:=False
    Application.DisplayAlerts = True
    MsgBox "We have no bananas before " & Format(Termin, "dd.mm.yyyy") & " for the " & AbtToEval & "!", vbInformation, AbtToEval & " out of bananas"
Else
    ' If the activity is in the past, it is marked in red
    i = 4
    Do Until IsEmpty(TargetWs.Cells(i, 1))
        If IsEmpty(TargetWs.Cells(i, 2)) Then
            If CDate(TargetWs.Cells(i, 1)) <= Date Then TargetWs.Range(Cells(i, 1).Address(0, 0), Cells(i, 10).Address(0, 0)).Font.ColorIndex = 3
        Else
            If CDate(TargetWs.Cells(i, 2)) <= Date Then TargetWs.Range(Cells(i, 1).Address(0, 0), Cells(i, 10).Address(0, 0)).Font.ColorIndex = 3
        End If
        i = i + 1
    Loop
    ' Fixes the visual and adds filters
    TargetWs.Range("A4").Select
    ActiveWindow.FreezePanes = True
    TargetWs.Range("A3:J3").AutoFilter
    TargetWs.Cells.EntireColumn.AutoFit
End If

' Ending
Set TargetWs = Nothing
Set TargetWb = Nothing
Set WsLop = Nothing
WbLOP.Close savechanges:=False
Set WbLOP = Nothing

End Sub

I managed to find a workaround playing with if WbLOP Is Nothing Then End in the UserForm_Terminate event, which as pointed out in some comments/answers is being triggered by the Workbook.Close event, but apparently if I execute the code where TargetWb is closed instead, nothing happens.
The event is basically linked to the WbLOP.Close and I still don't get why.

A: As you haven't posted full code - run your code in debug mode. Add breakpoints at points where you want to look closely what is happening. Use F5 to run (it will stop on next breakpoint or run till end) and F8 for step mode (move to next line). Use watch table to check values of your variables or whole IF contiodions to determine when the code should branch or do something specific.
Debug mode:

EDIT
Is there any chance it might be something like the problem you had in the past in this case?

EDIT 2
According to MSDN:

Terminate event is triggered when object is unloaded. First workbook close works OK as the form hasn't been loaded. If the form is an object of that workbook when workbook close is performed it unloads the form and triggers UserForm_Terminate resulting in END - code stops execution.
Apparently this will be executed on every closure of form (even hiding it)
Private Sub userform_terminate()
'Code
End Sub

You should be using this to detect when user closed it by the x button:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = 0 Then ' =0 or = vbFormControlMenu
         'Code
    End If
End Sub

Then it will be only executed when user closed the form, but not when form has been unloaded, so replace your userform_terminate with the above alternative and it should work fine.


text:
Q: javascript datetimepicker with local support I want the user to enter an appointment date and time and send him a reminder an hour before it.
On the server I want to store the date-time in UTC, but on the client the user will enter it in his local time. Whats the best way to deal with this conversion?
Is there a plugin that natively supports this?

A: Yes, there's a plugin which detects the timezone according to the system-information (jsTimezoneDetect). Actually a date-object itself stores the information (but it's kinda wierdo!).
There's an interesting article and an interesting answer here on SO, which is worth a read!

Don't do any date-time computations in javascript. You may guess the
  browsers time zone to define it, but the definition itself and all
  date-time computations must be made in a time-zone aware system.

As you will read this article, you'll get a deeper understanding of the problem "date/dst/utc/timezones in javascript" - therefore it would be interesting if you tell us more about your server-side:

*

*Which framework do you use on your server-side?

*Do you have any logic for represeting accounts with some settings (eg custom timezone-settings)?

The "correct" approach (which is fail-safe if you have the backend behind it) will be: let the user work with a datetime - in the browser-scope it's more or less "undefined" (no need to find the timezone, offset, or anything alike!). Now you provide this "undefined" datetime information to the server (eg sending the unix-timestamp with a hiddenfield to the server), where you have the information which actual timezone the user is assigned to. So you can now translate this "undefined" datetime-information to a time-zone aware datetime-object on the server-side and assign the information of your account-scope to it (now the "undefined" datetime-object has a local time-zone - eg "Pacific Daylight Time"). Now you can easily do any conversion you want.
The only downside of this approach is, that you will have 2 scopes of defining a timezone (OS of the user and your webapp) - but anything else is fiddling and not fail-safe!

A: It may be an idea to send a timestamp to your server, using the getTimezoneOffset method to calculate the UTC date/time client side. To convert it back client side you'd send the timestamp, create a dummy date client side to determine the currend timezone offset (the user may have moved to another timezone!) and create a client side date from that information. Client side you'd do something like:
//[client side send]
var d = new Date(), //now
    offset = d.getTimezoneOffset()
    UTCTimeStamp = d.getTime()+(60000*offset); // send to server

//[client side receive]
var offset = 60000*new Date().getTimezoneOffset(),
    localDate = new Date(timestamp + (offset < 0 ? Math.abs(offset) : -offset));

Click here to do a simple test using this idea.


text:
Q: How can I read or write to json file in google storage bucket (not public access) using Go I am trying to read/write a json file to google cloud storage bucket using Golang. I know how to write to the file system. This will not work if the json file is in the bucket.

A: You can use Google's go SDK for reading and writing files to Google storage bucket. You can find the golang sdk for storage here - Golang SDK

*

*Example for reading a file - here

*Example for writing a file - here
They confirm to io.Reader and io.Writer interfaces so, once you have handle you can work with them like normal file reader/writer.


text:
Q: Breaking a kubernetes pod circular readiness dependency Suppose I have two deployments, D_a and D_b and they each have a replica of 1. Ideally this would get me two running pods P_a and P_b.
Now suppose both P_a and P_b contain gRPC services which periodically ping each other to establish their readinesss state.
I now have a circular dependency between the two and I will never be able to get them ready as each one of them won't be ready for the other one to become ready.
Is this an anti-pattern or perhaps I am completely missing the point of readiness probes?
How would I break this loop? Thank you in advance!


text:
Q: Why I can find a vector normal to the plane using it's arguments I know I can find a vector normal to the plane ax + by +cz = 0 which is (a,b,c) but I don't know why.
I would be pleased if you could explain the method used to find vectors normal to the plane.
Thank You!

A: Suppose you know  $(x_0,y_0,z_0)$ is a point on the plane, and $\left<a,b,c\right>$ is a vector normal to the plane.  Then if $(x,y,z)$ is any other point on the plane, then the two vectors $\left<a,b,c\right>$ and $\left<x-x_0,y-y_0,z-z_0\right>$ are perpendicular -- this is precisely what "normal vector" means.  That, in turn, is equivalent to
$$\left<a,b,c\right> \cdot \left<x-x_0,y-y_0,z-z_0\right> = 0$$
which is the same as
$$a(x-x_0) + b(y-y_0) + c(z-z_0) = 0$$
This can be rearranged in the form
$$ax + by + cz = d$$
where $d$ is a constant that can be expressed in terms of the other parameters ($a,b,c,x_0,y_0,z_0$).
Now this whole procedure can be run in reverse:  if you are given an equation of the form
$$ax+by+cz=d$$
then if you find any point $(x_0,y_0,z_0)$ that satisfies the equation, you would have
$$a(x-x_0) + b(y-y_0) + c(z-z_0) = 0$$
which means that if $(x,y,z)$ is any other point satisfying the condition above, then the two vectors $\left<a,b,c\right>$ and $\left<x-x_0,y-y_0,z-z_0\right>$ are perpendicular to each other, which means that $\left<a,b,c\right>$ is a normal vector.

A: The user @symplectomorphic tell you why. Your equation is one which passes through the origin, so we may take $p = (0,0,0)$ to be a point on our plane. If $(a',b',c')$ is a normal vector to your plane then $(a',b',c') \cdot ((x,y,z) - p) = 0$. And now you see that after simplifying, it is the coefficients of the remaining variables $x,y,z$ which automatically give the coordinates of the normal vector.


text:
Q: Rounding the output Vector of a Neural Network layer to prepare it for the next layer I am attempting to Round up the output Vector of a Neural Network layer to prepare it for the next layer
Ex. Layer output {.1.,2.2,3.3} and I need it to be a Vector of Integers for the next layer.
I have tried this,
Round@@LinearLayer[3]. But it does not work.
Any suggestions would be appreciated.
Thank You
Michel

A: ElementwiseLayer[Ceiling] rounds up, ElementwiseLayer[Round] rounds to the nearest integer. This layer also accepts arbitrary compositions of a subset of Mathematica functions (see documentation for more details).


text:
Q: Javascript - How to search for numbers greater than x in regex I am trying to not to include numbers greater than 26 in my input. So if a user input 27 above in the input tag, it will not show on the result. How can i do it?  Here is my code thank you!

Please separate the numbers using space, for example:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

<input type="text" id="inputNum">

<button onclick="convert()">Convert to Letters</button>

A: Just a basic validation can work:
function convert() {
  let numbers = document.getElementById("inputNum").value;
  if(isNaN(numbers) || parseInt(numbers) > 26){
      return;
  }

  let outputVal = numbers.replace("10", "J").replace("11", "K").replace(/12/gi, "L").replace("13", "M").replace("14", "N").replace("15", "O").replace("16", "P").replace("17", "Q").replace("18", "R").replace("19", "S").replace("20", "T").replace("21", "U").replace("22", "V").replace("23", "W").replace("24", "X").replace("25", "Y").replace("26", "Z").replace(/1/gi, "A").replace(/2/gi, "B").replace("3", "C").replace("4", "D").replace("5", "E").replace("6", "F").replace("7", "G").replace("8", "H").replace("9", "I");

  document.getElementById("result").innerHTML = outputVal;
}

A: I'd suggest simplifying the logic using String.split(), and Array.reduce().
We can check each number to ensure it's in range in the .reduce() call (>=0 and <= 26).
You can then use String.fromCharCode() to convert each number to a letter:

function convert() {
    let numbers = document.getElementById("inputNum").value.trim();
    let outputVal = numbers.split(/\s+/).reduce((acc, n) => {
        return acc + (((n >= 0) && (n <= 26)) ? String.fromCharCode(+n + 64) + ' ': '');
    }, '');
    document.getElementById("result").innerHTML = outputVal;
}
Please separate the numbers using space, for example:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

<input type="text" id="inputNum">

<button onclick="convert()">Convert to Letters</button>


text:
Q: What is the equivalent of OpenMP Tasks in Pthreads in this recursion example? I am studying parallel programming and I use the following OpenMP directive to parallelize a recursive function:
voir recursiveFunction()
{
  //sequential code

  #pragma omp task
  {
    recursiveFunction(); //First instance
  }                     //Independent from each other,
                        //they allow an embarrassingly parallel strategy

  recursiveFunction(); //Second instance
}

It works good enough, but I have a hard time trying to make an equivalent parallelization using only pthreads.
I was thinking something like this:
voir recursiveFunction()
{
  //sequential code

  Pthread_t thread;

  //First instance
  pthread_create(thread, NULL, recursiveFunction, recFuncStructParameter);

  //Second instance
  recursiveFunction();
}

And... I am kind of lost here... I can not grasp how to control the number of threads, if for example I want only 16 threads to by created and if all of them are "busy" then continue sequentially until one of them is freed, then do parallel again.
Could someone point me in the right direction? I have seen may examples which seem really complicated but I have a feeling that in this particular example, which allows an embarrassingly parallel strategy, there is a simle approach which I am unable to point out...


text:
Q: Tableau Personal Space 401 on Web Edit We recently upgraded to the latest version of Tableau and are encountering a serious problem. No-one in the tableau community has answered the question and even our paid Tableau support is not responding to us!
We are embedding a viz in our site and then allowing users to click on the "Edit" button which opens up a web-edit version of the workbook. We have special permissions setup that allows them to even save their changes. This has all been working fine.
As of the most recent upgrades where Tableau introduced this idea of a Personal Space we now get a 401 when trying to save in the Web Edit (now labelled "Publish as")
Clicking "Publish As" loads a modal which is meant to display a list of locations to save to but instead displays a spinner which never goes away. The console indicates an error specifically wit the new personal space - 401 - No authentication credentials were provided.
We are using trusted ticket authentication to display our embedded vizzes and have had no problems with web edit saving until now. If we log directly into Tableau the web edit saves perfectly. So it seems to be an issue of Web Edit Saving + Trusted authentication, specifically as it relates to personal spaces.
Seems clear to me that this is a Tableau bug but wondering if anyone can suggest any kind of fix or workaround.
Thank you

A: This has been confirmed by Tableau as a bug in their latest versions. Unclear when it will be fixed.
They provided us with the following workaround (which is not ideal from a security perspective) but works.

Workaround provided by Tableau. Configuration change required, setting unrestricted tickets to true.
https://kb.tableau.com/articles/issue/login-prompt-when-embedding-server
This is a temporary measure while Tableau develops a more permanent solution.


text:
Q: Change logo theme according to important events/holidays? Similar to Google, but with some important differences:

*

*It will be more like adding stuff to the logo, instead of making the logo out of stuff

*The changes should not take away your attention for more than 2-3 seconds

*The logo colors and text should never be altered

So basically, the changes will only be like adding stuff to the logo (e.g a pumpkin in Halloween)
Do you think modifying the logo according to important events or holidays will bring more positiveness than negativeness to the site?
Edit: we should use the visitors ip location to display relevant holidays to maximize positiveness (or to be more specific, minimize the negativeness)

A: I definitely agree with Al Everett's comment above:

Who gets to choose the events/holidays? A significant number of our readers are from outside the U.S. And what types of events?

Therefore the only reasonable option is:

A: Basing this on geographic location sounds like a lot of work.
To start, there'd be a one-time investment from a dev to write code to serve different logos and possibly CSS depending on visitor IP.
The real issue is that someone would have to constantly keep track of which holidays/events were coming up in which countries, including things that don't simply recur every year based on date.
Also, as sixlettervariables said, Meta will end up fielding a steady stream of posts like

"Omigerd you left out Important Day X you insensitive clods!"

Doesn't seem worth the effort, for the small amount of benefit it would provide. Not to mention that page loads would slow down, although I don't know if the effects would be noticeable.


text:
Q: Set Menu for Additional Toolbar I have an additional Toolbar in one of my Fragments in addition to the Toolbar that is used instead of the ActionBar.
<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="50dp"
            app:theme="@style/Theme.AppCompat" >
// Other View Elements, like a profile image and name
</android.support.v7.widget.Toolbar>

I want to add overflow menu for this Toolbar. These items will be specific to this Fragment and wont make sense in other Fragments.
I can access this toolbar in my Fragment with the below code.
mFragmentToolbar = (Toolbar) layout.findViewById(R.id.toolbar2);

How to inflate a menu for this Toolbar?

A: You can inflate the menu on toolbar using this.
mFragmentToolbar = (Toolbar) layout.findViewById(R.id.toolbar2);
mFragmentToolbar.inflateMenu(/*your menu resource file*/);
mFragmentToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
     @Override
     public boolean onMenuItemClick(MenuItem item) {
           return false;
     }
 });


text:
Q: Unable to infer GraphQL type from TypeScript reflection system I'm trying to create an Alert class as follows:
@ObjectType()
export class Alert {
  @Field()
  status: 'error' | 'success' | 'warning' | 'info' | undefined

  @Field(() => [String])
  messages: string[];
}

However, it gives me the following error message:

Error: Unable to infer GraphQL type from TypeScript reflection system.
You need to provide explicit type for 'status' of 'Alert' class.

A: Create a type for 'error' | 'success' | 'warning' | 'info' | undefined and add it to the field definition as such:
@Field(() => StatusType)
It's basically complaining that it can't infer the type of that field as it's not a primitive, whenever a field is an object or other user defined type you will need to provide type information like I've described

A: my work around for the problem was an enum and tuple type.
//anything after EnumStatus is optional. depends on how much control you want.
type TSuccessArray = [EnumStatus.ERROR, EnumStatus.SUCCESS,EnumStatus.WARNING,EnumStatus.INFO,EnumStatus.UNDEFINED]

export enum EnumStatus {
        ERROR = "error",
        SUCCESS = 'success',
        WARNING = 'warning',
        INFO = "info",
        UNDEFINED = "undefined"
      }

    @ObjectType()
export class Alert {
  @Field(() => [String])
  status: TSuccessArray[];

  @Field(() => [String])
  messages: string[];
}

and somewhere in your code create a table or object with those options.
`const myArr:succesArray = [EnumStatus.ERROR, EnumStatus.SUCCESS,EnumStatus.WARNING,EnumStatus.INFO,EnumStatus.UNDEFINED]`;

A: You can try adding this to your tsconfig.json file
"experimentalDecorators": true,
"emitDecoratorMetadata": true,


text:
Q: Creating a Paper on LaTeX and importing R Packages onto LaTeX I am a novice with LaTeX and R.  I am creating a report on LaTeX (under Overleaf) and want to include some R code.  I handled this fine, but when I want to include an R package, I am producing an error.  Here is what I type out as an example:
<<>>=
install.packages("rmarkdown")
install.packages("AdequacyModel")
library(AdequacyModel)
@

And here is the respective error:
Error:  <text>:2:18:  unexpected input## 1:  install.packages('rmarkdown')
2:  install.packages(<e2>##

Could somebody please explain to me (as if I am at a fourth grade level) why this occurs and a solution to this problem?


text:
Q: How to access two similar but located in different API in a single Apigility project? Suppose we do have an Apigility URL like localhost:8888/user.
But I do have two API's in a single Apigility project, ApiOne and ApiTwo.
Doing a GET request from localhost:8888/user always returns resources generated by ApiTwo. But when I want to get the same user resource rom ApiOne because it is from a different DB I can't retrieve it. I already tried to supply the Accept media type with the proper version (hoping it would help), to access ApiOne (e.g. Accept application/vnd.apione.v1+json)

A: I'm guessing based on your question that you've got ApiOne with a route to /user and ApiTwo with a route to /user?
The problem is that they are not different routes. ZF2 is going to use (I believe) the one that is defined last in the combined configuration file. If you want to be able to use both API resources, you'll need to have different routes somehow. This could be literally changing one of them to something like /user1.
You could also theoretically route to two different endpoints for entities if you provide constraints on the id that would make them differentiable. What I mean is you could have both routes like this:
/api/user[/:user_id]
/api/user[/:user_name]
As far as the ZF2 router is concerned, at this point, those routes are identical. The variable parts user_id and user_name could be the same thing.
However, you'd need something else that makes the routes different. Apigility (and ZF2) allow for constraints on the parts of the URL. So you could put a constraint on user_id of [0-9]+ and a constraint on user_name of [a-z]+. These would make the routes mutually exclusive for entities, but the collection version of the routes is still the same.
Constraints are added in the route under options like so:

'router' => array(
        'routes' => array(
            'your-api.rest.user' => array(
                'type' => 'Segment',
                'options' => array(
                    'route' => '/user[/:user_id]',
                    'defaults' => array(
                        'controller' => 'YourApi\\V1\\Rest\\User\\Controller',
                    ),
                    'constraints' => array(
                        **'user_id' => '[0-9]+'**,
                    ),
                ),
            ),
            'your-api.rest.username' => array(
                'type' => 'Segment',
                'options' => array(
                    'route' => '/user[/:user_name]',
                    'defaults' => array(
                        'controller' => 'YourApi\\V1\\Rest\\Username\\Controller',
                    ),
                    'constraints' => array(
                        **'user_name' => '[a-z]+'**,
                    ),
                ),
            ),
        ),
    ),
)

In this example, if no user_id or user_name were provided, the Username resource should be called since it is defined last.
Overall though, my recommendation would be that you change the routes so that they are different. The accept header with version is essentially used for versioning, not routing to a different API resource.


text:
Q: How to store table cell values in a jquery array? How do I store table cell values  in a jquery array?

A: iterate over each table cell and push its value in the array say for example you have table structure like

        improve your

        accept rate plz!

you can do
var arr=[];

$("td").each(function(){

arr.push($(this).text());
});

$.each(arr,function(index,value){

alert(arr[index]);
});

here is the fiddle http://jsfiddle.net/qNgST/1/

A: tableArr = new Array();
$('table td').each(function(){
    tableArr.push($(this).text());
});

A: $('#mytable').map(function() {
            var data_array = $(this);
});

Your table:

    improve your

    accept rate plz!

A: // USE: var myTableArray = table2array( $('#idTable') );
function table2array( jTable ) {
    tableArr = new Array();
    var ix = 0;
    $(jTable).find('tr').each(function(){
        tableArr[ix] = new Array();
        $(this).find('th, td').each(function(){
            tableArr[ix].push($(this).text().trim());
        });
        ix++;
    });
    return tableArr;
};


text:
Q: How to run my website as https which is running as Docker swarm cluster in AWS? I am working on docker swarm and aws. I am not having much idea in it.
Please correct me if my question is wrong and kindly help me to solve my problem.
I have my docker swarm cluster running in AWS under a loadbalancer.
I created a certificate from Amazon certificate Manager for https to my load balancer.
In loadbalancer tab under listener if I set https for load balancer protocol and http to instance protocol like below, when I type https://website-url in the browser it automatically redirects to http.
LoadBalancerProtocol LoadBalancerPort InstanceProtocol InstancePort Cipher SSL Certificate
     HTTPS              443              HTTP           80           Change 6e7528d6-8261-4d61-b1d3-3c2548e1b575 (ACM) Change
But I want the website to be run as https not as http.
So I changed like below. That is making Instance port and its protocol as 443 and https.
LoadBalancerProtocol LoadBalancerPort InstanceProtocol InstancePort Cipher SSL Certificate
     HTTPS              443              HTTPS          443          Change 6e7528d6-8261-4d61-b1d3-3c2548e1b575 (ACM) Change
But After this https://website-url is continuously running without any response in the browser.
After doing some search, I came to know that ACM certificate only works for load balancer not for backend instance.
That is for instance level I need to enable https for apache.
The docker swarm cluster has 1 manager and 3 worker nodes. All the host instance OS is Alpine OS. The containers inside the nodes are Centos-7.
The containers are running as a service in the cluster.
Please guide me on this,
Do I need to configure self signed certificate for apache inside the container or on the host instance.
I want my website to be run as https not http.
Kindly show me What are the steps required.
Thanks

A: The load balancer port is what people talk to your load balancer on, so load balancer port 80 and 443 is correct.
The instance port is what port the load balancer talks to your webserver on. In this case for you both should be 80, unless your webserver is listening on 443 with a valid SSL cert (Not the case as you are using an AWS cert.)
Then in your code or your webserver what you need to do is check the X-Forwarded-Proto header http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html and if it's not https re-direct to https.
https://www.allcloud.io/how-to/how-to-force-https-behind-aws-elb/ has a couple examples.


text:
Q: Mock/Monkeypatch BeautifulSoup html objects for Pytest I'm working on a web scraping project in Python and trying to add automated testing w/ Pytest.  I'm not new to web scraping but I'm very new to testing, and I believe the idea here is I should mock the HTTP request and replacing it with some dummy html fixture code to test if the rest of the function works without having to rely on requesting anything from the actual url.
Below is my web scraping function.
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import urlopen

def get_player_stats_data():
    """
    Web Scrape function w/ BS4 that grabs aggregate season stats
    Args:
        None
    Returns:
        Pandas DataFrame of Player Aggregate Season stats
    """
    try:
        year_stats = 2022
        url = f"https://www.basketball-reference.com/leagues/NBA_{year_stats}_per_game.html"
        html = urlopen(url)
        soup = BeautifulSoup(html, "html.parser")

        headers = [th.getText() for th in soup.findAll("tr", limit=2)[0].findAll("th")]
        headers = headers[1:]

        rows = soup.findAll("tr")[1:]
        player_stats = [
            [td.getText() for td in rows[i].findAll("td")] for i in range(len(rows))
        ]

        stats = pd.DataFrame(player_stats, columns=headers)

        print(
            f"General Stats Extraction Function Successful, retrieving {len(stats)} updated rows"
        )
        return stats
    except BaseException as error:
        print(f"General Stats Extraction Function Failed, {error}")
        df = []
        return df

And here is what I'm using to grab the raw html of the page, and pickling it so I can save it and import it for testing.
import pickle
from bs4 import BeautifulSoup
from urllib.request import urlopen

year_stats = 2022
url = "https://www.basketball-reference.com/leagues/NBA_2022_per_game.html"
html = urlopen(url)

# how you save it
with open('new_test/tests/fixture_csvs/stats_html.html', 'wb') as fp:
    while True:
        chunk = html.read(1024)
        if not chunk:
            break
        fp.write(chunk)

# how you open it
with open('new_test/tests/fixture_csvs/stats_html.html', "rb") as fp:
    stats_html = fp.read()

My question is how do I mock/patch/monkeypatch the urlopen(url) call and use the pickled html in its place to create a fixture with it?  The Pytest docs example is creating a class & monkeypatching requests.get() where get is an attribute of requests which seems a little different from what i'm doing, and I haven't been able to get mine working, I think i'm supposed to use something other than monkeypatch.setattr?  Below is what I tried.
@pytest.fixture(scope="session")
def player_stats_data_raw(monkeypatch):
    """
    Fixture to load web scrape html from an html file for testing.
    """
    fname = os.path.join(
        os.path.dirname(__file__), "fixture_csvs/stats_html.html"
    )

    with open(fname, "rb") as fp:
        html = fp.read()

    def mock_urlopen():
        return html

    monkeypatch.setattr(urlopen, "url", mock_urlopen)
    df = get_player_stats_data()
    return df

### The actual tests in a separate file
def test_raw_stats_rows(player_stats_data_raw):
    assert len(player_stats_data_raw) == 30

def test_raw_stats_schema(player_stats_data_raw):
    assert list(player_stats_data_raw.columns) == raw_stats_cols

The goal is to replace html = urlopen(url) in the web scraping function with this pickled html I've previously saved.
The other option is to turn that url into an input parameter for the function, where in production I just call the actual url as you see here (www.basketballreference.com/etc), and in testing I just read in that pickled value.  That's an option but I'm curious to learn & apply this patching technique to a real example.  If anyone has any thoughts I'd appreciate it!

A: In your test file, you could try like this:
from module.script import get_player_stats_data

@pytest.fixture(scope="session")
def urlopen(mocker):
    with open(fname, "rb") as fp:
        html = fp.read()
    urlopen = mocker.patch("module.script.urlopen")
    urlopen.return_value = html
    return urlopen

def test_raw_stats_rows(urlopen):
    df = get_player_stats_data()
    assert len(df) == 30

def test_raw_stats_schema(urlopen):
    df = get_player_stats_data()
    assert list(df.columns) == raw_stats_cols


text:
Q: Unable to see the created .xlsx file in the directory I had generated a few values and had populated them into a spreadsheet using xlsxwriter. This is how I did it:
class main1():
    .
    .
    .
    .
    def fun1():
        workbook = xlsxwriter.Workbook(self.Output_fold+'Test'+time.strftime("%H_%M_%S_%d_%m_%Y")+'.xlsx')
        worksheet_A = workbook.add_worksheet('Sheet_A')
        .
        .
        worksheet_A.write(row,col,<val>)
        .
        .
        workbook.close()

Now, since I had to make multiple writes, and added more complex logic, I decided to have another function introduced fun2 which would write the values accordingly. The new logic requires generating values in fun1 as well as fun2 (by calling another function fun3). So, I decided to replace variables workbook etc with self.workbook and likewise. My modified script looks like this :
main_file.py
import xlsxwriter
import libex
import os
import time
import sys
import string

class main_cls():
    def __init__(self):
        self.i=0
        self.t1=""
        self.t2=""
        pwd=os.getcwd().split('\\')
        base='\\'.join(pwd[0:len(pwd)-1])+'\\'
        print base
        self.Output_fold=base+"Output\\"
        self.Input_fold=base+"Input\\"
        self.workbook=xlsxwriter.Workbook(self.Output_fold+'Test_'+time.strftime("%H_%M_%S_%d_%m_%Y")+'.xlsx')
        self.worksheet_A = self.workbook.add_worksheet('Sheet_A')
        self.worksheet_A.write(self.i,self.i,"Text 1")
        self.worksheet_A.write(self.i,self.i+1,"Text 2")
        self.i+=1
    def fun1(self):
        self.t1="1"
        self.t2="2"
        self.worksheet_A.write(self.i,self.i,self.t1)
        self.worksheet_A.write(self.i,self.i+1,self.t2)
        self.i+=1
        self.eg=libex.exlib()
        self.t1=self.eg.gen(0)
        self.t2=self.eg.gen(0)
        self.fun2()
        self.workbook.close()
    def fun2(self):
        if option==1:
            self.fun3()
    def fun3(self):
        self.t1=self.eg.gen(0)
        self.t2=self.eg.gen(1)
        self.worksheet_A.write(self.i,self.i,self.t1)
        self.worksheet_A.write(self.i,self.i+1,self.t2)
        self.i+=1

option=int(sys.argv[1])
if len(sys.argv)==2:
    p=main_cls()
    if option==1:
        p.fun1()
    else:
        pass
else:
    print "Wrong command"

libex.py
class exlib():
    def __init__(self):
        self.a="duh"
    def gen(self,x):
        if int(x)==0:
            return(self.a)
        elif int(x)==1:
            self.a=str(self.a+" "+self.a+" "+self.a+" !!!")
            return(self.a)

Now, this works in this particular case but in the actual code, it doesn't. The file itself is not getting created in the output directory. Then, I added the following line:
    print "Workbook created at path : ",self.workbook.filename

to see if the file is getting created and it surprisingly showed with full path!!!
Where could I be going wrong here and how can I get this fixed?
UPDATE1: I played around a bit with it and found that removing self from self.workbook moving workbook to __init__(self) creates the file with the initial values populated.
UPDATE2: Have replicated my code in a minimal way as suggested. And this one works pretty well!!!

A: Tried to reproduce, file is being created just fine, maybe you have a problem with the self.Output_fold variable, or with file permissions or with your code editor's file explorer.


text:
Q: Incorrect tint color DatePicker swift 5 ios16 I'm using UIDatePicker with preferredDatePickerStyle = .inline and tintColor = .systemOrange. I've tried to put this settings inside ViewDidLoad, ViewWillAppear and ViewDidAppear but the result is that the tint color remains blue. How can I solve?
Following an image of the issue:


text:
Q: Phusion Passenger running with Fullstaq Ruby We're trying to use an apt-installed version of Fullstaq Ruby with Passenger and Nginx on Ubuntu 20.04 installed via the recommended process from the Passenger website.  We specifically do not want to compile Nginx to work with Passenger.
The problem we're running into is that the passenger apt package depends on Ruby and apt doesn't recognize the Ruby installs from the Fullstaq repository as valid options to meet that dependency.
We've come "close" by configurating passenger options as:
passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/lib/fullstaq-ruby/versions/2.7-jemalloc/bin/ruby;

But passenger still boots using the default OS provided Ruby rather than the specific version we install from the Fullstaq repo.  A subset of the installed packages can be found here:
$ dpkg -l | grep ruby
ii  fullstaq-ruby-2.7-jemalloc         10-ubuntu-20.04                   amd64        Fullstaq Ruby 2.7-jemalloc
ii  fullstaq-ruby-common               1.0-0                             all          Fullstaq Ruby common dependencies
ii  ruby2.7                            2.7.0-5ubuntu1.7                  amd64        Interpreter of object-oriented scripting language Ruby
ii  ruby                               1:2.7+1                           amd64        Interpreter of object-oriented scripting language Ruby (default version)

Has anyone found a successfully configuration to make Fullstaq Ruby and Passenger work together?

A: As suggested in a comment, I ended up just adding the following to the sites nginx config
passenger_ruby /home/<username>/.rbenv/shims/ruby


text:
Q: Add images and other text in QGIS 3.0.2 (Windows) Today is my second day of using a GIS software. I have imported latitude, longitudes from csv into QGIS. I want that whenever users click on any location, they can see a pop with info: Country and State only, not all the fields that I see now.

Also, I want to add a field that will contain a hyperlink. In addition, I want to that users see the locations' image post clicking (or hover over). For this I am following this tutorial, but not helpful. Working file is here.

A: Use Field Widgets to control what the user sees in the Attributes Form
Right click on layer name in Layer Panel > Properties > Attributes Form
For any fields you want to hide from the user, change the Widget Type to Hidden.

For a hyperlink, just add a text field and type the link into it.
For an image, use an Attachment Field Widget
Type the file path where it says Default Path, or put a unique file path in the field for each feature, and choose that field under data-defined settings.


text:
Q: Nonlinear second order ODE $y''+f(x)y=g(x)y^3$ I encountered the following ODE in order to find a solution for Einstein equation
$$y''+f(x)y=g(x)y^3.$$
It seems to me that it is not among the solvable nonlinear second order differential equations.
Is there any known method to solve that? Any help will be appreciated.

A: When $g(x) = 2$ (which can be achieved by a transformation in $x$) and $f(x)$ is linear in $x$, then this equation is a special case of the second Painlevé equation, which also appears in other areas of mathematical physics. It is known to be integrable by the isomonodromy method via its Lax representation and it has many other interesting properties.

A: The paper by Norbert Euler (1997) ``Transformation Properties of $\ddot{x}+f_1(t)\dot{x} + f_2(t)x + f_3(t) x^n = 0$" Journal of Nonlinear Mathematical Physics, 4:3-4, 310-337
describes in detail the "the most general conditions on the functions $f_1$, $f_2$ and $f_3$, by which the equation may be integrable, as well as conditions for the existence of Lie point symmetries."

A: While closed-form solutions will be very rare, you can get series solutions.
For example, the solution with $y(0)=0,\; y'(0)=v$ has Maclaurin series
$$ y = v x - \frac{f(0)}{6} v x^3 - \frac{f'(0)}{12} v x^4 + \left(\frac{f(0)^2 - 3 f''(0)}{120} v + \frac{g(0)}{20} v^3 \right) x^5 + \ldots $$

A: Consider the ODE
\begin{align}
y'+\frac{A'(x)}{3A(x)}y&=A(x)y^2,
\end{align}
with derivative
\begin{align}
y''+\left[\left(\frac{A'}{3A}\right)'-\left(\frac{A'}{3A}\right)^2\right]y=2A^2y^3.
\end{align}
This is equivalent to your equation if
\begin{align}
\left(\frac{A'}{3A}\right)'-\left(\frac{A'}{3A}\right)^2=f,\quad\text{and}\quad2A^2=g.
\end{align}
In other words, if $f(x)$ and $g(x)$ satisfy the equation
\begin{align}
\left(\frac{g'}{6g}\right)'-\left(\frac{g'}{6g}\right)^2=f,
\end{align}
your problem is reduced to an easily integrable Bernoulli equation.


text:
Q: Neo4j Path.reverseNodes bug I am using Neo4j 2.2.1. I am trying to use the reverseNodes method of the path class. Running this code:
logger.info("Path1: "+path.toString());
for(Node node : path.reverseNodes()){
   logger.info("Node1: "+node.toString());
}

Logger output:
INFO: Path1: (469383)--[is_a,722474]-->(469384)--[is_a,732353]-->(469382)--[is_a,722473]-->(469089)--[is_a,722737]-->(468447)--[is_a,722237]-->(467769)--[is_a,721025]-->(467627)

We never get inside the for loop. An exception is thrown first:
message: "Node[467627] not connected to this relationship[722474]"
exception: "NotFoundException"
fullname: "org.neo4j.graphdb.NotFoundException"
-stackTrace: [15]
O: "org.neo4j.kernel.impl.core.RelationshipProxy.getOtherNode(RelationshipProxy.java:189)"
1: "org.neo4j.graphalgo.impl.util.PathImpl$1$1.next(PathImpl.java:205)"
2: "org.neo4j.graphalgo.impl.util.PathImpl$1$1.next(PathImpl.java:187)"
3: "org.eihg.phevor.plugins.TextQuery.path_to_json(TextQuery.java:85)"

It looks as though we are starting from the end node but trying to go through the first relationship instead of the last.
Seems like a bug in Neo4j. Am I missing something here?


text:
Q: What does throttle exactly mean in this sentence? This is a sentence I got from CNN News and I'm struggling with the exact meaning of throttle in it. It describes the weightless experience using a jetliner.

The pilot throttles the plane and aims at 45 degrees up; then, he suddenly puts it in dive.

Does it mean speed up (which makes more sense to me based on the context but I can't find a reference to support my inference) or simply control? I found a definition online which is control (an engine or vehicle) with a throttle but it seems to be superfluous to me. I fail to understand the importance of using throttle here and not simply control or fly!

A: "Throttle" has one meaning, but it can be used in a number of different ways. A throttle "chokes down" a flow of (usually) liquid to reduce the output. So if you had a straw and sucked on it to get a drink; then if you squeezed the straw it would reduce the flow, "throttling" what you are getting to drink.
In a car, the throttle is another word for "accelerator". It's actually in the reverse sense: the more you push the accelerator, the more the engine accelerates - but this is reducing the amount of throttle on the fuel flow.
In aviation and space terms, this word is even further removed from its original meaning. "Throttling up" means pushing forward on the thrust lever to increase acceleration - but in actuality it is actually reducing the amount of throttle on the fuel lines to the engine.
In that specific article (I assume on the "Vomit Comet" to induce a zero gravity experience) it is implying that the throttle is being used to control the aircraft. To climb, you need more power, so you'd throttle up; and to descend, you'd need less power, so you'd throttle down. In short, you'd throttle the plane to control its up and down manoeuvers.
Having said that, they're also probably pulling back on the yoke to climb, and pushing it forward to dive, to more precisely control the plane's position in the climb and dive - but engine power is by far the more obvious mechanism, with the engines by turns screaming and whispering as it moves from full throttle to barely idle.


text:
Q: How do Recursive CTEs work in SQL Server? Can anyone help me understand how this recursive CTE works?
WITH
RECURSIVECTE (EMPID, FULLNAME, MANAGERID, [ORGLEVEL]) AS
    (SELECT EMPID,
            FULLNAME,
            MANAGERID,
            1
     FROM RECURSIVETBL
     WHERE MANAGERID IS NULL
     UNION ALL
     SELECT A.EMPID,
            A.FULLNAME,
            A.MANAGERID,
            B.[ORGLEVEL] + 1
     FROM RECURSIVETBL A
          JOIN RECURSIVECTE B ON A.MANAGERID = B.EMPID)
SELECT *
FROM RECURSIVECTE;

A: Recursive CTEs in SQL Server have 2 parts:
The Anchor: Is the starting point of your recursion. It's a set that will be further expanded by recursive joins.
SELECT
    EMPID,
    FULLNAME,
    MANAGERID,
    1 AS ORGLEVEL
FROM
    RECURSIVETBL
WHERE
    MANAGERID IS NULL

It seems that it's fetching all employees that don't have any managers (would be the top bosses, or roots from tree relationships).
The recursion: Linked with a UNION ALL, this set has to reference the declaring CTE (thus making it recursive). Think of it as how will you expand the result of the anchor with the next level.
UNION ALL

SELECT
    A.EMPID,
    A.FULLNAME,
    A.MANAGERID,
    B.[ORGLEVEL] + 1
FROM
    RECURSIVETBL A
    JOIN RECURSIVECTE B  -- Notice that we are referencing "RECURSIVECTE" which is the CTE we are declaring
    ON A.MANAGERID = B.EMPID

On this example, we are fetching (on a first iteration) the anchor result set (all employees with no managers) and joining them with RECURSIVETBL through MANAGERID, so A.EMPID will hold the employee of the previously selected manager. This joining goes on and on as long as each last result set can generate new rows.
There are a few limitations on what you can put on the recursive part (no grouping or another nested recursion for example). Also, as it's preceeded with a UNION ALL, it's rules also apply (amount of columns and data types must match).
About the ORGLEVEL, it starts with the anchor set at 1 (it's hard-coded there). When it's further expanded on the recursion set, it fetches the previous set (the anchor, on the first iteration) and it adds 1, as it's expression is B.[ORGLEVEL] + 1 with B being the previous set. This means that it starts with 1 (the top bosses) and it keeps adding 1 for each descendant, thus representing all the levels of the organization.
When you find an employee at ORGLEVEL = 3 means that he has 2 managers over him.

Step by step with working example
Let's follow this example:
EmployeeID  ManagerID
1           NULL
2           1
3           1
4           2
5           2
6           1
7           6
8           6
9           NULL
10          3
11          3
12          10
13          9
14          9
15          13

*

*Anchor: Employees without managers (ManagerID IS NULL). This will start with all the top badass of your company. It's crucial to note that if the anchor set is empty, then the whole recursive CTE will be empty, as there is no starting point and no recursive set to join to.
SELECT
    EmployeeID = E.EmployeeID,
    ManagerID = NULL, -- Always null by WHERE filter
    HierarchyLevel = 1,
    HierarchyRoute = CONVERT(VARCHAR(MAX), E.EmployeeID)
FROM
    Employee AS E
WHERE
    E.ManagerID IS NULL

Which are these:
EmployeeID  ManagerID   HierarchyLevel  HierarchyRoute
1           (null)      1               1
9           (null)      1               9

*Recursion N°1: Using this UNION ALL recursion:
UNION ALL

SELECT
    EmployeeID = E.EmployeeID,
    ManagerID = E.ManagerID,
    HierarchyLevel = R.HierarchyLevel + 1,
    HierarchyRoute = R.HierarchyRoute + ' -> ' + CONVERT(VARCHAR(10), E.EmployeeID)
FROM
    RecursiveCTE AS R
    INNER JOIN Employee AS E ON R.EmployeeID = E.ManagerID

For this INNER JOIN, RecursiveCTE has 2 rows (the anchor set), with employees ID 1 and 9. So this JOIN will actually return this result.
HierarchyLevel  EmployeeID  ManagerID   HierarchyRoute
2               2           1           1 -> 2
2               3           1           1 -> 3
2               6           1           1 -> 6
2               13          9           9 -> 13
2               14          9           9 -> 14

See how the HierarchyRoute starts with 1 and 9 and moves to each descendant? We also increased HierarchyLevel by 1.
Because the results are linked by a UNION ALL, at this point we have the following results (step 1 + 2):
HierarchyLevel  EmployeeID  ManagerID   HierarchyRoute
1               1           (null)      1
1               9           (null)      9
2               2           1           1 -> 2
2               3           1           1 -> 3
2               6           1           1 -> 6
2               13          9           9 -> 13
2               14          9           9 -> 14

Here is the tricky part, for each of the following iterations, recursive references to RecursiveCTE will only contain the last iteration result set, and not the accumulated set. This means that for the next iteration, RecursiveCTE will represent these rows:
HierarchyLevel  EmployeeID  ManagerID   HierarchyRoute
2               2           1           1 -> 2
2               3           1           1 -> 3
2               6           1           1 -> 6
2               13          9           9 -> 13
2               14          9           9 -> 14

*Recursion N°2: Following the same recursive expression...
UNION ALL

SELECT
    EmployeeID = E.EmployeeID,
    ManagerID = E.ManagerID,
    HierarchyLevel = R.HierarchyLevel + 1,
    HierarchyRoute = R.HierarchyRoute + ' -> ' + CONVERT(VARCHAR(10), E.EmployeeID)
FROM
    RecursiveCTE AS R
    INNER JOIN Employee AS E ON R.EmployeeID = E.ManagerID

And considering that in this step RecursiveCTE only holds rows with HierarchyLevel = 2, then the result if this JOIN is the following (level 3!):
HierarchyLevel  EmployeeID  ManagerID   HierarchyRoute
3               4           2           1 -> 2 -> 4
3               5           2           1 -> 2 -> 5
3               7           6           1 -> 6 -> 7
3               8           6           1 -> 6 -> 8
3               10          3           1 -> 3 -> 10
3               11          3           1 -> 3 -> 11
3               15          13          9 -> 13 -> 15

This set (and only this!) will be used in the following recursive step as RecursiveCTE, and it will be added to the accumulated grand total, which is now:
HierarchyLevel  EmployeeID  ManagerID   HierarchyRoute
1               1           (null)      1
1               9           (null)      9
2               2           1           1 -> 2
2               3           1           1 -> 3
2               6           1           1 -> 6
2               13          9           9 -> 13
2               14          9           9 -> 14
3               4           2           1 -> 2 -> 4
3               5           2           1 -> 2 -> 5
3               7           6           1 -> 6 -> 7
3               8           6           1 -> 6 -> 8
3               10          3           1 -> 3 -> 10
3               11          3           1 -> 3 -> 11
3               15          13          9 -> 13 -> 15

*Recursion N°3: Starting with level 3s in our working set, the result of the join is:
HierarchyLevel  EmployeeID  ManagerID   HierarchyRoute
4               12          10          1 -> 3 -> 10 -> 12

This becomes our working set for next recursive step.

*Recursion N°4: Starting with the only row level 4 from previous step, the result of the join yields no rows (no employee has EmployeeID 12 as ManagerID). Returning no rows marks the end of the iterations.

The final result set stands tall:
HierarchyLevel  EmployeeID  ManagerID   HierarchyRoute
1               1           (null)      1
1               9           (null)      9
2               2           1           1 -> 2
2               3           1           1 -> 3
2               6           1           1 -> 6
2               13          9           9 -> 13
2               14          9           9 -> 14
3               4           2           1 -> 2 -> 4
3               5           2           1 -> 2 -> 5
3               7           6           1 -> 6 -> 7
3               8           6           1 -> 6 -> 8
3               10          3           1 -> 3 -> 10
3               11          3           1 -> 3 -> 11
3               15          13          9 -> 13 -> 15
4               12          10          1 -> 3 -> 10 -> 12

Here is the complete fiddle and code:
CREATE TABLE Employee (EmployeeID INT, ManagerID INT)

INSERT INTO Employee (EmployeeID, ManagerID)
VALUES
  (1, NULL),
  (2, 1),
  (3, 1),
  (4, 2),
  (5, 2),
  (6, 1),
  (7, 6),
  (8, 6),
  (9, NULL),
  (10, 3),
  (11, 3),
  (12, 10),
  (13, 9),
  (14, 9),
  (15, 13)

;WITH RecursiveCTE AS
(
    SELECT
        EmployeeID = E.EmployeeID,
        ManagerID = NULL, -- Always null by WHERE filter
        HierarchyLevel = 1,
        HierarchyRoute = CONVERT(VARCHAR(MAX), E.EmployeeID)
    FROM
        Employee AS E
    WHERE
        E.ManagerID IS NULL

    UNION ALL

    SELECT
        EmployeeID = E.EmployeeID,
        ManagerID = E.ManagerID,
        HierarchyLevel = R.HierarchyLevel + 1,
        HierarchyRoute = R.HierarchyRoute + ' -> ' + CONVERT(VARCHAR(10), E.EmployeeID)
    FROM
        RecursiveCTE AS R
        INNER JOIN Employee AS E ON R.EmployeeID = E.ManagerID
)
SELECT
    R.HierarchyLevel,
    R.EmployeeID,
    R.ManagerID,
    R.HierarchyRoute
FROM
    RecursiveCTE AS R
ORDER BY
    R.HierarchyLevel,
    R.EmployeeID

A: If you have more than on top manager [ORGLEVEL] will always start on 1.
Without posting data cannot provide details.


text:
Q: Hiding a UIImageView in Cocoa Touch I want to toggle displaying an image in my program.  Here is my code simplified:
UIImage *newImage = [UIImage imageNamed:@"selected.png"];
UIImageView *selector = [[UIImageView alloc] initWithImage: newImage];
[selector setFrame: CGRectMake( 0, 0, 64, 64)];
[overView addSubview: selector];
[overView bringSubviewToFront: selector];
selector.hidden = TRUE;

[newImage release]

Later in the code:
-(IBAction)Button1Click
{
  selector.hidden = FALSE;
}

-(IBAction)Button2Click
{
  selector.hidden = TRUE;
}

Later still:
[selector release];

When I run and click the two buttons the "selector" image never shows up.  If I debug the program I can see the program reaches the lines under the IBActions, but it has no effect.  Here is the strange thing:  If I set the line early on to:
selector.hidden = FALSE;

Then I can see the "selected" image the whole time and it never turns off no matter what button I press.  Any ideas?
UPDATE:
I know it was unclear in the code but "selector" is in the same scope in all the code.  Adding "self." to "selector" fixed the problem.  Thank you!

A: from your code snippets it seems that you have property "selector" (accessed in IBActions) and local variable "selector" used in "main" snippet.  If this is the case, you have to do something like this:
self.selector = [[UIImageView alloc] initWithImage: newImage];

instead of
UIImageView *selector = [[UIImageView alloc] initWithImage: newImage];

A: in your case in method 'Button1Click' (and the other one) 'selector' is unknown, cause it was declared locally here: UIImageView *selector = ....
You need proper reference to it, accessible from your button click methods. You can declare it in your *.h file, then use it anywhere in your class, then release it at end (in dealloc method).
And of course you shouldn't release this UIImage. Please read Apple documentation about memory management. It will be really hard to go further without it :)
Andrei's answer is right I think, but little too short for someone fresh.

A: UIImageView *selector = [[UIImageView alloc] initWithImage: newImage];
looks like it's "shadowing" your selector ivar.  Look at your @interface and see if selector is also in the ivar list.  If so, then just remove the UIImageView * portion.
Take a look at http://en.wikipedia.org/wiki/Variable_shadowing for more information about that.  You can also turn on a warning flag in Xcode that will warn you when it encounters one. Surprisingly it's not on by default.

A: Try this
UIImageView *selector = [[[UIImageView alloc] initWithImage: newImage] autorelease];


text:
Q: What is the length of the missing distance?
The book says that the missing distance is $$\frac{L}{2} - \frac{D}{2}$$
I feel like this is something simple that I should understand but I'm just having a disconnect on how they found the distance to be that.
EDIT: added more information with context of the problem

A: This would be true if the $L$ measure and the $D$ measure are centred on the same point. Then the L measure extends $L/2$ to the right of the centre point, the $D$ measure extends $D/2$ to the right of the same point, and the gap between them is as given.

A: The key is that the sawhorses are equidistant from the center of the plank. Therefore the distances between each end of the plank and each sawhorse are also equal, and must be ${L-D \over 2}$.


text:
Q: How does this one-hot vector conversion work? When I was working on my machine learning project, I was looking for a line of code to turn my labels into one-hot vectors. I came across this nifty line of code from u/benanne on Reddit.
np.eye(n_labels)[target_vector]

For example, for a target_vector = np.array([1, 4, 2, 1, 0, 1, 3, 2]), it returns the one-hot coded values:
np.eye(5)[target_vector]
Out:
array([[ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  1.,  0.,  0.],
       ...,
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.]])

While it definitely does work, I'm not sure how or why it works.

A: It's rather simple. np.eye(n_labels) creates an identity matrix of size n_labels then you use your target_vector to select rows, corresponding to the value of the current target, from that matrix. Since each row in an identity matrix contains exactly one 1 element and the rest 0, each row will be a valid 'one hot coding'.

A: ndarray[[0]] is to select the first line in the ndarray
t = np.arange(9).reshape(3,3)
print t
print t[[1]]

Output is
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[[3 4 5]]


text:
Q: Mac OS X not booting I have dual booted my laptop with Mac OS X and Windows 7 (hackintosh) . It was working fine for some days.
But now, Windows 7 gets started properly.. But Mac OS does not boot. I can't even see the loading screen with the icon of Apple.
What might be the problem? Any idea? please help...

A: The problem is the fact that this is a Hackintosh. These are against the OS X Software License Agreement.

Subject to the terms and conditions of this License, unless you have purchased a Family Pack or Upgrade license for the Apple Software,
  you are granted a limited non-exclusive license to install, use and run one (1) copy of the Apple Software on a single Apple-branded computer at a time. You
  agree not to install, use or run the Apple Software on any non-Apple-branded computer, or to enable others to do so. This License does not allow the Apple
  Software to exist on more than one computer at a time, and you may not make the Apple Software available over a network where it could be used by multiple
  computers at the same time.

And, since the hardware isn't compatible with OS X, there could be any number of issues with this. In short, the issue you're having is because this is a Hackintosh.


text:
Q: Creating a new Partition on Centos Linux I installed a Centos and partitioned it as:
/root - 100MB
/ - rest of the disk.
I need to have a /log partition. is it possible to do it after the Linux
was already installed?
Thanks!!
Dotan.

A: Yes, this is possible, however, not while CentOS is running. You will need to boot from a live cd or other live boot method, and then partition from there, so the system doesn't use the disk for other things.

This may be more difficult on a remote server, if your hosting company doesn't support live environments, then you will have to do more complicated (and potentially dangerous) things like booting your OS in RAM, or making Grub2 boot an ISO in RAM, where the ISO has to start a ssh session on boot, and set the right ip. If you do this incorrectly though, you may end up with an unbootable server, and have to wait for your hosting company's support.

If you want to know what programs to use to partition it, you could look into gparted for a non-headless system, or fdisk or parted for commandline tools. Resizing with the latter 2 tools is a bit harder though.


text:
Q: Will using "yes" command in unix waste lot of cpu cycles? Will using "yes" command waste lot of cpu cycles ?
I have a long running script (script code not in my control) which accepts something as input just once.  Then the script runs for long time .
To automate I use "yes" command to feed the input
yes hello | myscript
Will  yes command steal/waste lot of cpu cycles ?. As per  the docs i read it keeps printing the string argument to piped program
I gave top command , i didnt see "yes" there in top

A: yes will print the string "hello" when it has the chance - this means that the receiving end (your script) must be waiting for I/O (i.e., expecting input). So: no, yes does not take any CPU when the receiving end does not wait for input, the process is blocked.
See the run state of the process yes in a ps auxf for confirmation.


text:
Q: Custom In App Keyboard in UWP I want to create a custom OnScreen keyboard in UWP. It need to be part the application because it will be used on Large Table or Board devices so full control of the keyboard placement is very important (rotation on the table).
In WPF, I already made a custom keyboard like this by creating a keyboard control whith a Target Property. When a key is pressed, it raise a KeyEvent or TextComposition on the target with UIElement.RaiseEvent(...).
But in UWP, there is no RaiseEvent function and it seems there is no way to raise routed event for the developper.
I want to use native Text Event (KeyDown event, TextComposition event, etc...) so solution which manually edit the Text property of TextBox ( like this one ) are not acceptable.
This page explains how to create a control who listen to Text Services Framework. I think one solution would be to create a custom Text service but I didn't found any documentation on this.

A: You can do at least part of what you were looking for using classes in the Windows.UI.Input.Preview.Injection namespace and the restricted inputInjectionBrokered capability.
This works for the KeyUp, KeyDown,  PreviewKeyUp, and PreviewKeyDown events, and as long as you don't need to send key strokes to anything outside of your app.
Non-latin scripts are outside the scope of what I'm working on, so I don't know if it can be extended to IME's which would generate TextComposition events.
Martin Zikmund demonstrates doing so here, with a sample solution available on github.
The key points are that you need to edit your Package.appxmanifest file (as code not via the designer) to include:
<Package>
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="rescap"
</Package>

and
<Capabilities>
    <rescap:Capability Name="inputInjectionBrokered" />
<Capabilities>

From there you can simulate typing and raise native key events by:
private async void TypeText()
{
    Input.Focus(FocusState.Programmatic);
    //we must yield the UI thread so that focus can be acquired
    await Task.Delay(100);

    InputInjector inputInjector = InputInjector.TryCreate();
    foreach (var letter in "hello")
    {
        var info = new InjectedInputKeyboardInfo();
        info.VirtualKey = (ushort)((VirtualKey)Enum.Parse(typeof(VirtualKey),
                                   letter.ToString(), true));
        inputInjector.InjectKeyboardInput(new[] { info });

        //and generate the key up event next, doing it this way avoids
        //the need for a delay like in Martin's sample code.
        info.KeyOptions = InjectedInputKeyOptions.KeyUp;
        inputInjector.InjectKeyboardInput(new[] { info });
    }
}


text:
Q: How to programmatically call a click event on list of labels I have made a 'list' of fuel weights using labels because I wanted to show the list open on iOS devices. This works fine and I can click on a label item and get the weight (100) and the moment (298.16) value.
What I want to do next and I can't figure out how, is I want to make a click event call and have the weight highlighted and pull the moment out as well into a variable.
How do I do this?
0
100
200
300
400
500

This is my code when I manually click on a fuel weight to get the weight and the moment value:
$('.fuelLoad').mousedown(function(event) {
    switch (event.which) {
        case 1:
            //Left Mouse button pressed
            $(this).val(fuel_weight);
            document.getElementById('idfuelLoadMoment').innerHTML = parseFloat(fuel_moment).toFixed(2);
            break;
        case 2:
            //Middle Mouse button pressed
            break;
        case 3:
            //Right Mouse button pressed
            $(this).val(0);// set value to 0
            return false;
            break;
        default:
    }
});

A: I rewrote the click event code, which works now to get the fuel weight and th fuel moment value:
function fuelListClick(obj) {
    fuel_weight = $(obj).text();
    fuel_moment = $(obj).data("fuel_moment");
    console.log("fuel_weight:" + fuel_weight);
    console.log("fuel_moment:" + fuel_moment);
}

Now, I need to be able to call a click event with a specific fuel weight and have it select that item in the list.


text:
Q: Binding child ember objects to handlebars class Having a binding issue with a child object of an ember.view object.  Code is as follows:
--Textbox class extended from Ember.TextField
App.TextBox = Ember.TextField.extend({
attributeBindings:['placeholder', 'autocorrect','autocapitalize'],
value:null,
isInvalid:true,
validate:function(){
    this.set('isInvalid', false);
    return false;
},
focusOut:function(event){
    this.validate();
}});

---View that uses App.Textbox
App.ViewTextBox = Ember.View.extend({
name:"viewName",
label:"View Label",
input: App.TextBox.extend({
    placeholder:function(){
        return this.get('parentView').get('label');
    }.property('label').cacheable()
})});

--Handlebars with bindings
{{#view App.ViewTextBox}}
{{label}}

{{#view input valueBinding="parentView.value"}}

{{/view}}{{/view}}

Issue is this:
1) After the initial rendering of the view, the class is properly set, but subsequent changes to the isInvalid value, through the onFocusOut call, do not change the class in the DOM.  Ideas?

A: You can't use a view block helper with Ember.TextField.


text:
Q: Handling multipart/form-data in aws lambda I'm trying to send a request with an image to a lambda function through API gateway.
I'm using this piece of code to parse the form-data-object received by my lambda function. I then upload the image to S3, but when downloading and opening the image from S3, I see that it's corrupt.
I have tried the following npm packages:

*

*parse-multipart

*parse-multipart-data
Both do not work, because I get an empty parts-array. The piece of code I use does get results in the array, but the buffers seems to be corrupt.
The problem seems to be in this line of code:
Buffer.from(item.slice(item.search(/Content-Type:\s.+/g) + item.match(/Content-Type:\s.+/g)[0].length + 4, -4), 'binary')

Does anyone has a solution for me?

A: You can use busboy to parse the multipart form data before uploading to S3 as shown below:

// This code is written in ECMAScript 6 (ES6), not CommonJS syntax.
// So, make sure you add <"type": "module"> in your package.json.
import {S3Client, PutObjectCommand} from '@aws-sdk/client-s3';
import Busboy from 'busboy';

// Initialize the clients outside the function handler to take advantage of execution environment reuse.
const s3Client = new S3Client({region: process.env.AWS_REGION});

// Function handler.
export async function handler(event) {
    const {
        ContentType: contentType = '',
        File: file = '',
    } = await FORM.parse(event['body'], event['headers']);

    try {
        // Adds an object to a bucket. We must have `WRITE` permissions on a bucket to add an object to it.
        await s3Client.send(new PutObjectCommand({
            Body: file,
            Bucket: 'BUCKET_NAME',
            ContentType: contentType,
            Key: 'SOME_KEY',
        }));

        return {
            isBase64Encoded: false,
            statusCode: 200,
            body: JSON.stringify({
                message: 'Everything is gonna be alright.',
            }),
        }
    } catch (e) {
        return {
            isBase64Encoded: false,
            statusCode: 404,
            body: JSON.stringify(e),
        }
    }
}

const FORM = {
    parse(body, headers) {
        return new Promise((resolve, reject) => {
            const data = {};
            const buffer = Buffer.from(body, 'base64');
            const bb = Busboy({
                headers: Object.keys(headers).reduce((newHeaders, key) => {
                    // busboy expects lower-case headers.
                    newHeaders[key.toLowerCase()] = headers[key];
                    return newHeaders;
                }, {}),
                limits: {
                    fileSize: 10485760, // Set as desired.
                    files: 1,
                },
            });

            bb.on('file', (name, stream, info) => {
                const chunks = [];

                stream.on('data', (chunk) => {
                    if (name === 'File') {
                        chunks.push(chunk);
                    }
                }).on('limit', () => {
                    reject(new Error('File size limit has been reached.'));
                }).on('close', () => {
                    if (name === 'File') {
                        data[name] = Buffer.concat(chunks);
                        data['ContentType'] = info.mimeType;
                    }
                });
            });
            bb.on('error', (err) => {
                reject(err);
            });
            bb.on('close', () => {
                resolve(data);
            });

            bb.end(buffer);
        });
    }
};


text:
Q: Fixed Header Blocks Scrolling through fullPage.js Sections with "scrollOverflow: true" A fixed header on my website blocks scrolling, when hovering, through sections when set scrollOverflow: true.
When fixed header is not hovered scrolling through all sections works fine.
How can I achieve the same browsing through sections, when hovering fixed header?
Isolated Reproduction:
https://jsfiddle.net/o5Lcpemw/1/
Steps to reproduce it:

*

*Hover fixed red header

*Try to scroll through blue, grey and green sections

MacOS High Sierra, latest Chrome Release

A: You could stop allowing the header to respond to mouse events by setting the element's pointer-events value to none:
#header {
  ...
  pointer-events: none;

}


text:
Q: Page not Found when I add jpeg on the filter plupload I am using plupload version: 2.1.8 and every browser works fine on my PC.
When I want to upload a picture on my website from a IPhone 6s plus, I get the extension error 601.
If I add jpeg on my script the page will not load and I get page not found? Can someone help me?
This is my script for now before I add jpeg:
<script type="text/javascript">
var uploader = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : 'pickfiles',
    container: document.getElementById('container'),
    url : '<?php echo WEBSITE_CNST_URL?>/upload.inc.php?adid=<?php echo $adid ?>',
    resize : { width : 1024, height : 768, quality : 80 },

    flash_swf_url : '<?php echo WEBSITE_URL ?>/js/Moxie.swf',
    silverlight_xap_url : '<?php echo WEBSITE_URL ?>/js/Moxie.xap',

    filters : {
        max_file_size : '4mb',
        mime_types: [
            {title : "Image files", extensions : "jpg,gif,png"}
        ]
    },

What is going wrong?


text:
Q: Variable listener in iOS Swift I am trying to make an independent class/library that runs on its own and handles errors internally, but also gives feedback (status) to the frontend for possible user interaction. In Android I'd solve this with a Listener:
    class Status(errCode:Int=0, msg:String=""){
    var errCode:Int=0
    var text:String=""
    private var listener: ChangeListener? = null

    init {
        this.errCode=errCode
        this.text=msg
    }

    fun set(errCode:Int, msg:String) {
        this.errCode=errCode
        this.text=msg
        if (listener != null) listener!!.onChange()
    }

    fun getListener(): ChangeListener? {
        return listener
    }

    fun setListener(listener: ChangeListener?) {
        this.listener = listener
    }

    interface ChangeListener {
        fun onChange()
    }
}

Whenever I want to update it, e.g. on Exception, I call:
catch (e: IOException) {
            this.status.set(109,"someException: $e")
        }

And in the MainActivity I just have to handle these changes:
myObj.status.setListener(object : Status.ChangeListener {
            override fun onChange() {
                when(myObj!!.status.errCode) {
                    //errors
                    109 -> log(myObj!!.status.text) //some Exception
                    111 -> myObj!!.restart() //another exc
                    112 -> myObj!!.checkAll() //some other error
...

In Swift I found didSet that seems similar. I read you can attach it to a struct so whenever something in the struct changes, it is called. So I added my "struct Status" to my "struct myObj" like this:
struct myObj {
var status:Status=Status(errCode: 0, msg: "Init")

struct Status {
    var errCode:Int
    var msg:String

    mutating func set(err:Int, txt:String){
        errCode=err
        msg=txt
    }
}

and in my code I initialize a new instance of myObj
var mObj:myObj=myObj.init() {
        didSet{
            switch myObj.status.errCode{
            case 1:
                promptOkay()
            case 113:
                obj.errorHandling()
            default:
                log(txt: mObj.status.msg)
            }
        }
    }

However, it never trigger didSet, even though internal functions should change the Status. I read that didSet is not triggered on init, but I do not run anything right now after initializing the class object that should run quite independently. I want to verify that the approach is okay before I go further and have to unravel everything again.

A: didSet must be declared on the property, not during initialization:
class MyObj {
    var status: Status = Status(errCode: 0, msg: "Init") {
        didSet {
            // status did change
            print("new error code: \(status.errCode)")
        }
    }

    struct Status {
        var errCode:Int
        var msg:String

        mutating func set(err:Int, txt:String){
            errCode = err
            msg = txt
        }
    }
}

let obj = MyObj()
obj.status.set(err: 10, txt: "error 10") // prints "new error code: 10"

At this point you can react to every changes made to obj.status in the didSetClosure.
Edit — React to didSet from outside the class
If you want to respond to changes from outside the MyObj, I would recommend using a closure:
class MyObj {
    var status: Status = Status(errCode: 0, msg: "Init") {
        didSet {
            statusDidChange?(status)
        }
    }

    // closure to call when status changed
    var statusDidChange: ((Status) -> Void)? = nil

    struct Status {
        var errCode:Int
        var msg:String

        mutating func set(err:Int, txt:String){
            errCode = err
            msg = txt
        }
    }
}

This way, you can assign a closure from outside to perform custom actions:
let obj = MyObj()
obj.statusDidChange = { status in
    // status did change
    print("new error code: \(status.errCode)")
}

obj.status.set(err: 10, txt: "error 10") // prints "new error code: 10"

Edit 2 — Call didSet closure directly from initialization
You also can manually call the statusDidChange closure during the init.
class MyObj {
    var status: Status = Status(errCode: 0, msg: "Init") {
        didSet {
            statusDidChange(status)
        }
    }

    // closure to call when status changed
    var statusDidChange: (Status) -> Void

    init(status: Status, statusDidChange: @escaping (Status) -> Void) {
        self.status = status
        self.statusDidChange = statusDidChange
        self.statusDidChange(status)
    }
}

let obj = MyObj(status: MyObj.Status(errCode: 9, msg: "error 09")) { status in
    // status did change
    print("new error code: \(status.errCode)")
}

obj.status.set(err: 10, txt: "error 10")

This will print
new error code: 9
new error code: 10