text:
Q: Geometric interpretation of the map $SO(4) \to SO(3)$ Let me first explain the background of my question.
As is well known, the group $SO(n+1)$ acts transitively on the sphere $S^n$, and the stabilizer is the group $SO(n)$, so that we get a fibration sequence
$$ SO(n) \to SO(n+1) \to S^n.$$
Indeed this fibration is a principal-$SO(n)$-bundle and can actually be identified with the frame bundle of the tangent bundle of $S^n$, i.e., the tangent bundle $TS^n$ is the associated bundle to this principal-$SO(n)$-bundle along the tautological representation of $SO(n)$ on $\mathbb{R}^n$.
Now let us consider the special case $n = 4$. Here we get a principal-$SO(3)$-bundle
$$ SO(3) \to SO(4) \to S^3.$$
But we can identify the $S^3$ with $Sp(1)$, the symplectic group acting on the quaternions. Via this identification $S^3$ sits canonically in $SO(4)$, i.e. we have an embedding of topological groups $S^3 \cong Sp(1) \to SO(4)$.
The standard theory of principal-bundles hence tells us that the above bundle splits (topologically) which means that there is a homeomorphism
$$ SO(4) \cong SO(3)\times S^3 $$
in particular there is a continuous map $SO(4) \to SO(3)$ (which is not a morphism of lie groups).
It is well known that the homotopy type $BSO(n)$ represents the functor of $n$-dimensional oriented vector bundles, and via the clutching function construction the group $SO(n)$ itself represents the functor of $n$-dimensional vector bundles over suspensions of spaces. Hence the above map $SO(4) \to SO(3)$ tells us that there is a natural transformation between the functor of rank $4$ vector bundles over suspensions to the functor of rank $3$ vector bundles over suspensions.
Does anybody know a geometric construction of this transformation which I only understand homotopy theoretically?
Any ideas or references are greatly appreciated.

A: The double cover $\pi:S^3\times S^3\rightarrow SO(4)$ actually provides two homotopoically distinct maps from $S^3 = Sp(1)$ to $SO(4)$, given by restricting $\pi$ to either factor.  (One can easily see that these two maps induce different maps on $\pi_3$, so are not homotopic).
The following theorem is contained in

K.Grove-W.Ziller, Lifting group actions and nonnegative curvature, Trans. Amer. Math. Soc. 363 (2011) 2865-2890.

Ziller has a freely accessible version here - see the middle of page $8$.
Theorem  If $E\rightarrow M$ is a rank $4$ vector bundle over $M$ (where $M$ is a compact simply connected manifold.), then $\Lambda^2(E) = \Lambda^2(E)_+\oplus\Lambda^2(E)_-$ decomposes into self-dual and antiself dual forms.  Then $\Lambda^2(E)_{\pm}$ are the two rank $3$ vector bundles over $M$ corresponding to the two sections above.


text:
Q:  header height Whenever I have a table header going into 3 rows, the background is not able expand. When it is only 2 rows all seems to be fine. Does anybody went through this ?
Thanks in advance.
Sorry I am new to stackoverflow, couldn't attach image.
Image link http://i.stack.imgur.com/o6xNl.png
Table in xhtml
<rich:dataTable value="#{couponController.campaignSegmentVersionDtoList}"
var="campaignSegment" id="sas" rowClasses="odd-row, even-row"
styleClass="stable" style="width:1100px;" sortMode="single" rowKeyVar="myrow">
<rich:column>
<f:facet name="header">No</f:facet>
<h:outputText value="#{myrow + 1}" />
</rich:column>
<rich:column sortBy="#{campaignSegment.segmentName}" id="segmentName">
    <f:facet name="header">
        <a4j:commandLink value="Campaign Segment" onclick="#{rich:component('sas')}.sort('segmentName')" style="color:white;"/>
    </f:facet>
    <h:outputText value="#{campaignSegment.segmentName}" />
</rich:column>
<rich:column sortBy="#{campaignSegment.segmentTitle}" id="segmentTitle">
    <f:facet name="header">
        <a4j:commandLink value="MRM Segment Name" onclick="#{rich:component('sas')}.sort('segmentTitle')" style="color:white;"/>
    </f:facet>
    <h:outputText value="#{campaignSegment.segmentTitle}" />
</rich:column>
<rich:column sortBy="#{campaignSegment.sourceCode}" id="sourceCode">
    <f:facet name="header">
        <a4j:commandLink value="Source Code" onclick="#{rich:component('sas')}.sort('sourceCode')" style="color:white;"/>
    </f:facet>
    <h:outputText value="#{campaignSegment.sourceCode}">
    </h:outputText>
</rich:column>
<rich:column id="packageCode" sortBy="#{campaignSegment.packageCode}" style="width:80px;">
    <f:facet name="header">
        <a4j:commandLink value="SAS Package Code"  onclick="#{rich:component('sas')}.sort('packageCode')" style="color:white;"/>
    </f:facet>
    <h:outputText value="#{campaignSegment.packageCode}">
    </h:outputText>
</rich:column>
<rich:column id="version" style="width:80px;">
    <f:facet name="header">
        <h:outputText value="MRM Version Code" />
    </f:facet>
    <h:selectOneMenu value="#{campaignSegment.versionCode}" valueChangeListener="#{couponController.valueChangeListener}" label="Version Code" listWidth="300" immediate="true">
<f:selectItems value="#{couponController.mrmVersions}" var="version" itemLabel="#{version.versionCode}" itemValue="#{version.versionId}"/>
<a4j:ajax event="valueChange" render="stringCodeList" execute="@this" />
</h:selectOneMenu>
<rich:message for="Version"/>
</rich:column>
<rich:column id="testControlFlag" sortBy="{campaignSegment.testControlFlag}" style="width:60px">
    <f:facet name="header">
        <a4j:commandLink value="Test Control Flag" onclick="#{rich:component('sas')}.sort('testControlFlag')" style="color:white"/>
    </f:facet>
    <h:outputText value="#{campaignSegment.testControlFlag}"/>
</rich:column>
<rich:column sortBy="#{campaignSegment.publishedDate}" id="publishedDate">
    <f:facet name="header">
        <a4j:commandLink value="Published Date" onclick="#{rich:component('sas')}.sort('publishedDate')" style="color:white;"/>
    </f:facet>
    <h:outputText value="#{campaignSegment.publishedDate}">
        <f:convertDateTime type="date" pattern="MM-dd-yyyy H:m:s"/>
    </h:outputText>
</rich:column>
<rich:column sortBy="#{campaignSegment.status}" sortOrder="#{couponController.campaignSegmentsDescOrder}" id="publishStatus">
    <f:facet name="header">
        <a4j:commandLink value="Publish Status" onclick="#{rich:component('sas')}.sort('publishStatus')" style="color:white;"/>
    </f:facet>
    <h:outputText value="#{campaignSegment.status}">
    </h:outputText>
</rich:column>

A: The background image starts repeating itself, which it shouldn't do.
You can fix that with this:
.rf-dt-hdr-c {
    background-repeat: repeat-x;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return results based on a range of values ie WHERE ColA = (ColB + n OR ColB - n) I'm a little stuck on the following, may I ask you for some direction please?
I have created 2 temp tables 'compare1' and 'compare2' and I'd like to list words that are common between the tables.
However, in each of the temp tables I have a numeric field, 'chunkIdx', that represents the position of the word. I would like to limit the results I list to be within a specific range of that position.
Let me show you my results, first and an explanation of what is wrong with them ...
tSpan   wLen    aSize   c1_chunkIdx word    tSpan   wLen    aSize   c2_chunkIdx word
5       7       6       0           daa     5       7       6       43          daa
5       8       7       1           baa     5       8       7       44          baa
5       7       6       1           baa     5       7       6       1           baa

Of the results listed above, I would only want line 3. As the c2_chunkIDx value is between c1_chunkIDx - 5 and c1_chunkIDx + 5. Obviously, Lines 1 and 2 would fail this test.
I thought I could include something like ...
WHERE (c2.chunkIdx BETWEEN (c1.chunkIdx - 5) AND (c1.chunkIdx + 5))

or perhaps ...
WHERE (c2.chunkIdx >= (c1.chunkIdx - 5) OR c2.chunkIdx <= (c1.chunkIdx + 5))

In my WHERE clause, but doing so returns nothing. Literally no result tab to even view an empty dataset (I'm using HeidiSQL). It's like the query just never fired, I don't even get an error message.
Clearly I'm missing something (other than just results).
My complete query looks like the following.
SELECT c1.tSpan, c1.wLen, c1.aSize, c1.chunkIdx AS C1_ChunkIdx, c1.word,
       c2.tSpan, c2.wLen, c2.aSize, c2.chunkIdx AS C2_ChunkIdx, c2.word
FROM compare1 c1
    INNER JOIN compare2 c2 ON c1.word = c2.word
WHERE (c2.chunkIdx BETWEEN (c1.chunkIdx - 5) AND (c1.chunkIdx + 5))
    AND c1.tSpan = c2.tSpan
    AND c1.wLen = c2.wLen
    AND c1.aSize = c2.aSize

May I ask, how can I limit my results to be within a range based on the value of the c1.chunkIdx field?
Thank you for your time.

A: The answer seems to be to use variables
SELECT c1.tSpan, c1.wLen, c1.aSize, c1.chunkIdx AS C1_ChunkIdx, c1.word,
   c2.tSpan, c2.wLen, c2.aSize, c2.chunkIdx AS C2_ChunkIdx, c2.word
, @lowChunk := (c1.chunkIdx - 5)
, @highChunk := (c1.chunkIdx + 5)
FROM compare1 c1
    INNER JOIN compare2 c2 ON c1.word = c2.word
WHERE c2.chunkIdx BETWEEN @lowChunk AND @highChunk
    AND c1.tSpan = c2.tSpan
    AND c1.wLen = c2.wLen
    AND c1.aSize = c2.aSize

This seems to give me what I need. I'm not a strong SQL man, so I can't explain why this is so.


text:
Q: How to call a function from a module name that is assigned to a variable I am trying to call a function from a module. The module and the function have the same name, which is read at runtime using raw_input() and stored in a variable.
For example,
module.py
def module():
    print "x"

run.py
ent="module"
__import__(ent)
ent()

I can import that module using the variable ent. But when I call that function using that variable I get this error:
TypeError: 'str' object is not callable

How can I call that function from the module when I don't know their name until runtime?

A: As Jon mentioned, you didn't save a reference to the imported module. You need that to call its functions. To actually get to the function you can use the built-in getattr function. Eg,
ent = "module"
mod = __import__(ent)
func = getattr(mod, ent)
func()

However, using __import__ is rather unusual, and only done in special situations. Is your situation special enough to warrant its use?


text:
Q: How to read input file name in piglatin I have standard prefixes in filenames (QWERTY_123,POIUY_029 etc.,) which have same delimiters all the time. QWERTY ->, POIUY ->; I developed a udf which takes prefix and tells the delimiter. Now how to read files names in pig so that I split prefix from file name and get delimiter to load files properly.

A: Use a PigStorage clause in your LOAD statement, as outlined in item 2 of this post. It will put the filename as the first field in each record:
A = LOAD 'input' using PigStorage(',','-tagsource');
B = foreach A generate $0 as input_filename;


text: Q: Infinite periodic orbits Given a billiard cycling around a polygon, reflecting off each edge perfectly with no loss of energy, we know that there exist periodic orbits in specific classes of polygons (such as equilateral triangles).  Is it possible for an orbit of arbitrarily large period, or even infinite period to exist in some polygon?


text:
Q: Integer solution to a square root equation Given the following function: $$f(x) = \sqrt{36 x^2+16416 x +61084}$$ where x is an integer and the function also generates an integer value, is there an algorithm to determine its integer solutions?

A: You can write
$f(x) = \sqrt{(6(x-228))^2 - 1810340}$.
Now, $f(x)$ is an integer if and only if $(6(x-228))^2 - 1810340$ is a square.
Write $$k^2=(6(x-228))^2 - 1810340$$
so
$$1810340 = (6(x-228))^2 - k^2 = (6x-6*228+k)(6x-6*228-k)$$
Now you factorize $1810340 = 2^2 * 5* 7* 67* 193$.
So you have to solve $48$ linear systems of the form
$$
\left\{
\begin{matrix}
6x-6*228&+k &=& a \\
6x-6*228&-k &=& b
\end{matrix}
\right.
$$
For all possible values of $ab = 1810340$.

A: Given
$$
f(x) = \sqrt{ 36 x^2 + 16416 x + 61084}.
$$
For what integer $x$ is $f(x)$ also an integer?

We can write
$$
f(x) = \sqrt{ \Big( 6 x + 1368 \Big)^2 - 1810340 },
$$
therefore
$$
\Big( 6 x + 1368 \Big)^2 - 1810340 = \Big( 6 x + 1368 - p \Big)^2,
$$
so
$$
p \left\{  2  \Big( 6 x + 1368 \Big) - p \right\} = 1810340.
$$
Thus
$$
x = \left( \left( \frac{1810340}{p} + p \right) \Big/ 2 - 1368 \right) \Big/ 6.
$$
Note the symmetry
$$
\frac{1810340}{p} + p = \frac{1810340}{1810340/p} + 1810340/p.
$$
Using
$$
1810340 = 2^2 \times 5 \times 7 \times 67 \times 193,
$$
we can use limited values for $p$, like $p=2 \times 5 \times 7$, which is equivalent with $p= 2 \times 67 \times 193$.
We obtain the following results:
$$
\begin{array}{ccccc|c|c}
2 & 5 & 7 & 67 & 193 & p & x\\
\hline
\times &&&&& 2 &75203\\
\times & \times &&&& 10 &14859\\
\times && \times &&& 14 &10549\\
\times & \times & \times &&& 70 &1933\\
\times &&& \times && 134 &909\\
\times &&&& \times & 386 &195\\
\times & \times && \times && 670 &53\\
\times & \times &&& \times & 1930 &11\\
\end{array}
$$


text:
Q: Ошибка Базы данных sqlite3 python При попытки добавление в базу выходит ошибка о том что она якобы  закрыта.
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
File "C:/Users/dmozo/Desktop/Tester Creater/2.py", line 86, in save
    conn.commit()

sqlite3.OperationalError: database is locked

Код:
o=valueChosen.get()
n=n1.get()
t=t1.get()
y=y1.get()
h=h1.get()
va=vari.get()
t_2=(n,t,y,h,str(va))
conn = sqlite3.connect('bd/to.db')
conn.execute("INSERT INTO Test_"+o+" (vopros,otv1,otv2,otv3,pravotv)  VALUES(?,?,?,?,?)", t_2)
conn.commit()
conn.close()

Как подобную ошибку исправить?

A: Попробуйте на каждый connect вызывать close, добавьте конструкцию try...finally, где у вас работа с базой, чтобы всегда close вызывался, например:
conn = sqlite3.connect('bd/to.db')
try:
    conn.execute("INSERT INTO Test_"+o+" (vopros,otv1,otv2,otv3,pravotv)  VALUES(?,?,?,?,?)", t_2)
    conn.commit()

finally:
    conn.close()


text:
Q: A line of input How would I read a single "line" of input from the user that seperates the values by space and assign them to a certain variable? Seems quite confusing for me.
For example,
Enter 3 digits = 3 4 5

Total = 12

The input that I put, once there is a space, only prints first value when I put "3 4"
I know I should not use nextInt scanner but I can't figure out a way
    int a;
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter 3 digits:");
    a = scan.nextInt();
    System.out.println(a);

A: By doing sum in for loop:
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 digits:");

int sum=0;
for(int i=0;i<3;i++){
    sum = sum + scan.nextInt();
}
System.out.println(sum);

A: It would be best to have an array of variables, and read integers into the array one at a time like this:
int[] a = new int[3];

Scanner scan = new Scanner(System.in);

System.out.print("Enter 3 digits: ");
for(int i = 0 ; i < a.length ; i++) //loop 3 times
{
    a[i] = scan.nextInt(); //get int from input
    System.out.println(a[i]);
}
scan.nextLine(); //consume the \n

A: You just call nextInt() 2 more times.
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();

A: If you are required to read all integers in one read you can use this code. If reading one by one is ok the refer to other answers. For this code you can make a loop and use arrays as well.
    String a;
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter 3 digits:");
    a = scan.nextLine();
    Scanner stscan = new Scanner(a);
    System.out.println(a);
    int number1 = stscan.nextInt();
    int number2 = stscan.nextInt();
    int number3 = stscan.nextInt();
    System.out.println(number1+number2+number3);


text:
Q: TabLayout get stuck with viewpager when screen orientation change I am using the design support library. I've a Fragment and inside this fragment I have another fragment which has view pager with 3 new fragment
My fragment code -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:tabIndicatorColor="@android:color/white"
        app:tabIndicatorHeight="4dp"
        app:tabMode="fixed" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Fragment Java code
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);

        TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setTabTextColors(Color.parseColor("#ffffff"), Color.parseColor("#000000"));
        ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new SectionPagerAdapter(getActivity().getSupportFragmentManager()));
        tabLayout.setupWithViewPager(viewPager);
        return v;
    }

    public class SectionPagerAdapter extends FragmentPagerAdapter {

        public SectionPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new Tab1();
                case 1:
                    return new Tab2();
                case 2:
                    return new Tab3();

                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Tab 1";
                case 1:
                    return "Tab 2";
                case 2:
                    return "Tab 3";

                default:
                    return "";
            }
        }
    }

Now its all working fine but when I rotate the screen, swipe on viewpager does not work correctly. I mean it get stuck in between two tabs. Also the tab indicator also get stuck between tabs. It takes almost 6-7 swipe to go from 1st to 3rd tab. Also when swiping after rotating there is only one tab fragment which was previously choose before rotating.

A: You can use FragmentStatePagerAdapter instead of FragmentPagerAdapter

A: In your onCreateView() method, try changing this:
viewPager.setAdapter(new SectionPagerAdapter(getActivity().getSupportFragmentManager()));

to this:
viewPager.setAdapter(new SectionPagerAdapter(getChildFragmentManager()));

I had the same symptoms as you did, until I made this change.


text:
Q: How to pull variables from line of data file in Python I have a large data file where each row looks as follows, where each pipe-delimited value represents a consistent variable (i.e. 1517892812 and 1517892086 represent the Unix Timestamp, and the last pipe delimited object will always be UnixTimestamp)
264|2|8|6|1.32235000|1.33070000|1.31400000|1257.89480966|1517892812
399|10|36|2|1.12329614|1.12659227|1.12000000|148194.47200218|1517892086

How can I pull out the values I need to make variables in Python? For example, looking at a row and getting UnixTimestamp=1517892812 (and other variables) out of it.
I want to pull out each relevant variable per line, work with them, and then look at the next line and reevaluate all of the variable values.
Is RegEx what I should be dealing with here?

A: No need for regex, you can use split():
int(a.strip().split('|')[-1])

A: If all variable are only number and you want a matrix whit all your values you can simply do something like:
[int(line.strip().split('|')) for line in your_data.splitlines()]

A: You can use regex and re.search():
int(re.search(r'[^|]+$', text).group())


text:
Q: Is there an easy way to detect when a DC current flows, then close a path? A wire has two states -  20A DC flowing or no current.
Is there a simple device/relay that can let 20A flow through it and close a switch?

The device must keep a path open when no current flows.
It must close the path when current (DC 20A) flows through it.
I used this ACS712 current sensor with a comparator and managed to detect when the current flows but it is too complicated and I feel there must be a more simpler way.

*

*Over current protection is already taken care of externally. The wire has either 20A or none.

*Hysteresis is not needed as we already have a big window (0-20A). If the switch closes when more than 1A flows through the wire, it is good.

*Switch controls a 5V supply and only 10-20 mA current flows.

*We're allowed to break the wire carrying 20A and put the device in series.

*

*By simpler I mean minimum number of parts. Is there a device like a relay or something that lets 20A flow through it and closes a switch? It seems normal relays are controlled by 5V-12V DC voltage. I'm not able to find any relay that lets 20A control current flow through it and closes a switch

*I want a high-side switch to control a 5V 10mA supply. The switch must close when DC 20A current flows through the wire.

A: I think the current sensor is as simple as its going to get. You can then put the output signal into a comparator (or opamp, like LM741, acting as comparator). The other input of the comparator is coming from a potentiometer voltage divider where you can set the threshold between 0 and 5V, the output of the comparator then goes to a transistor to drive a relay coil.
Modules like this exist already, but you have specific requirements that I don't think fit any of them, so you'll have to build your own module like this.
https://www.aliexpress.com/item/4000089725866.html

A: You can wind 4-5 turns of the wire around a glass body reed contact. This contact will close at 20A.
I just tried reed contact ORD324-1015. One singe turn is enough to turn on at around 8A.
Update: sharing the picture to document the solution to the original problem

A:
Is there a simple device/relay that can let 20A flow through it and close a switch?

A range of current relays, meant for refrigerator / freezer applications, are available.
Typical operating currents in the range are as shown.

The one that suits your application may be selected from the range.


text:
Q: VB6 recordset code to VB.Net I am updating someone elses old code from a VB6 windows application to a VB.Net web application. I understand the old code, but I am not sure how I would translate it to .Net recordsets.
myStoredProcedure = "sp_WritevPayrollCurrent"
        myCurrentPast = "'N'"
    myStoredProcedure = "sp_ObtainSubClassID"
       myClassName = "Payroll Major"
       mySubClassName = "New Hire"
       Set rs = TgetReadResultsetWithParms(myClassName, mySubClassName, (myStoredProcedure))

Also, I am not sure what will happen with "myStoredProcedure" being declared twice or could that be an error?
The TgetReadResultsetWithParms function is as follows (some Cases redacted to free up space):
Dim en As rdoEnvironment
Dim cn As rdoConnection
Dim rq As rdoQuery

 rdoDefaultCursorDriver = rdUseServer
'open a connection to the tstdbexecutive database using DSNless connections
Set en = rdoEnvironments(0)
Set cn = connectionstring stuff here
Select Case myStoredProcedure
    'create reusable rdoQuery and Call SQL server stored procedure.
    Case "sp_ObtainClassID"
        Set rq = cn.CreateQuery("", "{call " & cstDatabaseName & ".dbo.sp_ObtainClassID(?)}")
    Case Else
        Set rq = cn.CreateQuery("", "{call " & cstDatabaseName & ".dbo." & myStoredProcedure & "(?)}")
End Select
'set the input argument value for the store procedure.
rq(0) = myParm1
'open the Resultset and pass it back to calling procedure
Set TgetReadResultsetWithParm = rq.OpenResultset(rdOpenKeyset, rdConcurReadOnly)

A: The VB6 code is using Remote Data Objects. I think you will have to read the documentation to understand what the VB6 is doing, and then rewrite in VB.Net using ADO.Net to achieve the same functionality. AFAIK there is no handy cheat-sheet which shows how RDO compares with ADO.Net, unfortunately. There are some for ADO-ADO.Net.
Alternatively you could add a reference to Remote Data Objects in your .Net project - you can use COM objects in .Net - and then use the same code. If there is a large amount of the old code, this could be a pragmatic way to make the task more manageable, although it makes the code harder to understand for other programmers who would probably be used to ADO.Net. It's better to rewrite if you can afford to.


text:
Q: Which Method is used during the processing of Sum Function? I am trying to find out which Method is used while evaluating the following function:
Sum[1/((n^2)), {n, 1, Infinity}]

Any help would be greatly appreciated. A more generic answer would also be helpful but it has to first unambiguously resolve this question. And the extension would be helpful if it clarifies what are the parameters being passed to a method and the syntax etc.
I am a beginner and happy to delete this question if the same is answered elsewhere. But please see below a partial list of what I tried:
I have tried the below options (perhaps with mistakes) and attempted to make sense of the material in the below pages and have been unsuccessful. I have also tried numerous searches on google with different keywords (Such as "Mathematica Sum Function Method" etc ...
How to find out which method Mathematica selected?
(Tried changing NDSolve to Sum and other variations);
Also looked at a few other questions that are trying to understand the intermediate steps in Mathematica:
Determining the default Method used in optimization and root-finding algorithms
What method does NDSolve use for solving PDEs?
Determining which rule NIntegrate selects automatically
https://reference.wolfram.com/language/ref/Sum.html
https://reference.wolfram.com/language/tutorial/SomeNotesOnInternalImplementation.html#5107
https://reference.wolfram.com/language/ref/TracePrint.html


text:
Q: Como puedo colocar un nombre a cada fila resultante de UNION en Sql Server La idea es que luego de hacer una UNION en SQL server
poder identificar con un nombre cada fila, para poder identificar de que tabla viene la data

A: Solo agrega un campo más a cada fila con el nombre de la tabla
    select dato1, dato2, 'nombre tabla' as nombreTabla from tabla1
    union all
    select dato1, dato2, 'nombre tabla 2' from tabla2

A: Lo puedes hacer usando alias las columnas de resultados
Seguido la columna o tabla que consultas agregas la palabra reservada AS, o solo agregando un espacio
Ejemplo
SELECT columna 1 AS nuevo nombre, columna 2   nuevo nombre o tabla AS nuevo nombre  FROM tabla          AS nuevo nombre
union all
SELECT  columna 1 AS nuevo nombre, columna 2  AS nuevo nombre FROM tabla2 AS nuevo nombre


text:
Q: Large primary key: 1+ billion rows MySQL + InnoDB? I was wondering if InnoDB would be the best way to format the table? The table contains one field, primary key, and the table will get 816k rows a day (est.). This will get very large very quick! I'm working on a file storage way (would this be faster)? The table is going to store ID numbers of Twitter Ids that have already been processed?
Also, any estimated memory usage on a SELECT min('id') statement? Any other ideas are greatly appreciated!

A: I'd recommend you start partioning your table by ID or date. Partioning splits a large table into several smaller table according to some defined logic (like splitting it by date ranges), which makes them much more managable performance and memory wise. MySQL 5.1 has this feature built-in, or you can implement it using custom solutions.
In implement storage in a flat-file, you lose all the advantages of a database - you can no longer perform queries involving the data.

A: The only definitive answer is to try both and test and see what happens.
Generally, MyISAM is faster for writes and reads, but not both at the same time. When you write to a MyISAM table the entire table gets locked for the insert to complete. InnoDB has more overhead but uses row-level locking so that reads and writes can happen concurrently without the problems that MyISAM's table locking incurs.
However, your problem, if I understand it correctly, is a little different. Having only one column, that column being a primary key has an important consideration in the different ways that MyISAM and InnoDB handle primary key indexes.
In MyISAM, the primary key index is just like any other secondary index. Internally each row has a row id and the index nodes just point to the row ids of the data pages. A primary key index is not handled differently than any other index.
In InnoDB, however, primary keys are clustered, meaning they stay attached to the data pages and ensure that the row contents remain in physically sorted order on disk according to the primary key (but only within single data pages, which themselves could be scattered in any order.)
This being the case, I would expect that InnoDB might have an advantage in that MyISAM would essentially have to do double work -- write the integer once in the data pages, and then write it again in the index pages. InnoDB wouldn't do this, the primary key index would be identical to the data pages, and would only have to write once. It would only have to manage the data in one place, where MyISAM would needlessly have to manage two copies.
For either storage engine, doing something like min() or max() should be trivial on an indexed column, or just checking the existence of a number in the index. Since the table is only one column no bookmark lookups would even be necessary as the data would be represented entirely within the index itself. This should be a very efficient index.
I also wouldn't be all that worried about the size of the table. Where the width of a row is only one integer, you can fit a huge number of rows per index/data page.

A: If these ID numbers are monotonically increasing and your writes only append data (never modify it), it'll probably be a lot faster to use a single file. A SELECT min('id') then just becomes reading the first line of the file, and anything else is a binary search.

A: If you have an index on your id column, select min(id) should be O(1), there shouldn't be much of a memory requirement for this.
If your primary key is on the twitter id then you have an index on it.

A: There is a good comparison of storage engines on MySQL Dev zone:

*

*MySQL Storage Engine Architecture, Part 1: An Overview

*MySQL Storage Engine Architecture, Part 2: An In-Depth Look

*MySQL Storage Engine Architecture, Part 3: Details and Comparison
From your description I would say MyISAM would be better, but it depends quite a lot on the compared reading and writing patterns of your app.

A: With one single field, being the primary key, only ever adding records, this is not really suited to a regular database.
For a start, you're storing twice as much info as you need to, with every field going into the data table and index.
As an aside, relational database are so called since, for one,  they store related data into a single row; it's hard to see how your data qualifies :-) If you were storing other stuff as well, a database would be worth it.
You don't mention whether the data will be accessed by multiple processes at once - if not, then you don't need all the advantages conferred by database ACID principles. Even if you do want ACID, that can still be achieved without a full blown database.
My first though would be to construct your own B-tree or B+-tree data file to store the twitter IDs to avoid the data duplication. The only queries I can see you doing (based on the question) are:

*

*select min(id) from tbl; and

*select id from tbl where id = ?

The first can be made O(1) by simply storing the lowest in another file outside of the B-tree structure (and replacing it when you get a lower one). I'm not sure of the business case for this one unless it's to quickly find out a certain twitter ID isn't in the table (so you'd probably want max as well in that case).
The second is standard tree searching techniques which is what a database generally uses under the covers anyway.

A: I've also seen some trading firms use tick database ie. kdb+
http://kx.com/


text:
Q: How to add the categories inside the slice and show the absolute number instead of the relative number I created a pie chart in highchart, but I am facing two difficulties at which I am stuck:

*

*How can I put the category name inside the slices?

*How can I change the relative numbers into the absolute numbers?

I searched around at different fora and and the highchart webpage, but I just can not find the solution. Can you help me how to solve it and also where you found the solution, as I am new to high chart and still learning.
Added is my basic jsfiddle. Thanks in advance
http://jsfiddle.net/uhydP/209/
$(function () {
var chart = new Highcharts.Chart({
    tooltip: {
        enabled: false
    },
    chart: {
        renderTo: 'container', //Dat is waar hij heen moet
        type:'pie', // Type die we hebben gekozen
        backgroundColor: '#281e82',
        borderColor: '#281e82',
        borderWidth: 0
    },

    xAxis: {
        categories: ['Sparen', 'Aflossen'], // De namen
        color: 'black',
    },
    credits: {
        enabled: false // Geen verwijzing naar highchart
    },

    plotOptions: {
        series: {
            dataLabels: {
                enabled: true,
                formatter: function() {
                    return Math.round(this.percentage*100)/100 + ' %';
                },
                distance: -60, // Hoe ver naar binnen de teksten staan
                color:'black' // De kleur van de percentages
            },
            animation: {
                duration: 2000
            }
        }
    },

    title: {
        text: 'Testje',
        style: {
            color: 'white',
            fontWeight: 'bold'
        }
    },

    series: [{
        data: [{y: 30, color: 'white'}, {y: 70, color: '#E50000'}]
    }]
});

});

A: The names can be added in the datalabels formatter,
 formatter: function() {
                    var cat = this.series.chart.xAxis[0].categories,
                        x = this.point.x;

                    return 'name: ' + cat[x] + '<br>' +  Math.round(this.percentage*100)/100 + ' %';
 },

http://jsfiddle.net/uhydP/214/


text:
Q: A-frame not loading materials I understand this seems to be a common problem for beginners in A-Frame but I'm struggling to get a material onto a model in this. I can successfully get the model in but it always comes out grey with the console telling me:
"Material component properties are ignored when a .MTL is provided".
Grey...
I've made this in Blender with a simple glossy material and exported it as an .obj with relative paths (that's what is recommended yes?)
I'm not familiar with .mtl or .obj files but is there something else I have to do to them to get them working in A-Frame? Or is it an issue with the code or CORS?
html
 <!DOCTYPE html>
    <html>
    <head>
        <script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
    </head>

    <body>
        <a-scene stats>
            <a-assets>

                <!--Not working-->
                <a-asset-item src="meh.obj" id="meh"> </a-asset-item>
                <a-asset-item src="meh.mtl" id="mat"> </a-asset-item>

            </a-assets>

            <a-obj-model src="#meh" mtl="#mat" position ="0 0 5"> </a-obj-model>

        </a-scene>
    </body>
    </html>

obj
    # Blender v2.78 (sub 0) OBJ File: ''
    # www.blender.org
    mtllib meh.mtl
    o Cube
    v 1.083111 0.312460 -1.083111
    v 1.083111 0.312460 1.083111
    v -1.083111 0.312460 1.083110
    v -1.083110 0.312460 -1.083111
    v 1.083111 3.724101 -1.083110
    vn 0.0000 -1.0000 0.0000
    vn 1.0000 -0.0000 0.0000
    vn -0.0000 0.5360 0.8442
    vn -0.8442 0.5360 -0.0000
    vn 0.0000 0.0000 -1.0000
    usemtl RedGloss
    s off
    f 1//1 2//1 3//1 4//1
    f 1//2 5//2 2//2
    f 2//3 5//3 3//3
    f 3//4 5//4 4//4
    f 5//5 1//5 4//5

MTL:
# Blender MTL File: 'None'
# Material Count: 1

newmtl RedGloss
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2

Appreciate the help :)

A: The three.js obj/mtl loaders don't work well, and MTL files generated by Maya ( maybe even blender ) are unreadable for the loaders, which are implemented in the a-frame material system. Multiple problems reported here, or here.

The easiest way, as I suggested in one of the links, is uploading the model to clara.io, and downloading an three JSON model, as it seem to work very good. Maybe You can try with Don McCurdy's loaders(though they seem to be more for the geometry, not for the material), but it seems, 3D formats are quite complicated.  Since You do it exactly as suggested in the official docs, I wouldn't say there's something wrong with Your code.


text:
Q: how to detect when mouse leaves the window win32 I am creating an application with the win32 api and I have a boolean isLeftClickPressed which is set to true when I receive a WM_LBUTTONDOWN message. when I receive a WM_LBUTTONUP message I set it to false. this works fine, however if I hold down the left mouse button and move my cursor out of the window and release my mouse, it never send a WM_LBUTTONUP message. I am not looking for a way to get around this rather just to find out when my mouse leaves the window and then set isLeftClickPressed to false.
any help would be appreciated.

A: Call TrackMouseEvent and check for WM_MOUSELEAVE


text:
Q: Dynamic variable names in function in R I am looking to make a function that takes a vector as input, does some simple arithmetic with the vector and call the new vector something which consists of a set string (say, "log.") plus the original vector name.
d = c(1 2, 3)
my.function <- function { x
x2 <- log(x)
...

I would like the function to return a vector called log.d (that is, not log.x or something set, but something dependent on the name of the vector input as x).

A: You can try next:
d = c(1, 2, 3)

my.function <- function(x){
    x2 <- log(x)

    arg_name <- deparse(substitute(x)) # Get argument name
    var_name <- paste("log", arg_name, sep="_") # Construct the name
    assign(var_name, x2, env=.GlobalEnv) # Assign values to variable
    # variable will be created in .GlobalEnv
}

A: One way to do this would be to store separately names of all your input vector names and then pass them to assign function. Like assign takes text string for output object name, get looks up object from string.
I will assume your vectors all follow common pattern and start with "d", to make it all as dynamic as possible.
d1 <- c(1,2,3)
d2 <- c(2,3,4)

vec_names <- ls(pattern = "^d")

log_vec <- function(x){
  log(x)
}

sapply(vec_names, function(x) assign(paste0("log.", x), log_vec(get(x)), envir = globalenv()))

This should create two new objects "log.d1" and "log.d2".


text:
Q: How to add calculated column to PowerBI datasets I have created a dataset in Power BI web, and then imported it on Power BI desktop (using File -> Get data -> Power BI datasets).
I don't see a way of adding Calculated Columns. Does the dataset need some special configuration to enable this?

A: Based on my experience you won't be able to see the columns because it using direct query. you can still add some columns and measure but your'e basically flying blind. you can just select the table in the report(visual view) and add column however you'll have to play the guessing game. But if you know your dataset you should be fine.
However a Dataflow wouldn't give the issue you're having.


text:
Q: Login page redirects back only to a naked partialview I use jquery ajax to call (get) an action which renders a partialview for creating(inputting) a new product. The content of this partialview is inserted into a vid tag in a full page which has a base _layout. The ajax code below:
 $("#Create").on('click', function (e) {
    //debugger;
    e.preventDefault();
    $.ajax({
        type: "GET",
        data: { returnUrl: String(window.location) },  <-- passing in the Url
        url: "/CreateGroup/CreateGroup",
        dataType: 'html',
        success: function (data) {
            $("#group-list").html(data);
        },
    });
})
.....
<div id="group-list">
    @Html.Partial("PagedGroupList")
</div>

The action:
// GET: /Create/
[Authorize]
public PartialViewResult CreateGroup(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    CreateGroupModel cgm = new CreateGroupModel();
    cgm.ReturnUrl = returnUrl;
    cgm.group = new Static_Group();
    return PartialView("CreateGroup", cgm);
}

Now if I login first before clicking CREATE button, eveerything is fine as expected. The problem is when CREATE button is clicked without login first. Due to [Authorize], the login page will come first and after login, it is expected to redirect back to my CREATE partialview inside the full page together. The problem is that the login page redirects back to a NAKED create partialview without any of its parent view's elements. If the CREATE page is NOT a partialview, login page redirects back to the full page perfectly.
I use MVC4 defafult login. I tried to make the login page into a ajax form submit and use OnSuccess to call document.location in both the login page and the create partialview, but I found it is an issue of returnUrl of the partialview. I also tried Request.UrlReferrer.AbsoluteUri, but it gives the same URL which is "/CreateGroup/CreateGroup?returnUrl=http%3A%2F%2Fwww.dev.com%3A22531%2F" or in full: http://www.dev.com:22531/CreateGroup/CreateGroup?returnUrl=http://www.dev.com:22531/. If you put the Url into a browser, it also displays the pure partialview.
I believe I must have missed something obvious coz this should be a common scenario but I could not find any threads from googling. Is there a URL which displays a partialview inside its parent view together? if not, then possible to redirect back to a previous view from a partialview?

Looks there is no URL for a partialview with its host page. The solution I can think of at the moment is get login redirect to the host page and pass in the partialview name in Model or viewbag or session temp to render the whole page again with the right partialview in it.

A: Here is how I work around this issue. Don't feel very comfortable with it. If anyone has a better solution, please help.
I added two string vars in LoginModel:
            public string RetUrl { get; set; }
            public string UrlReferrer { get; set; }
In get Login action:
        public PartialViewResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = Request.UrlReferrer.AbsolutePath;
        LoginModel lgm = new LoginModel();
        lgm.UrlReferrer = Request.UrlReferrer.AbsoluteUri;
        lgm.RetUrl = returnUrl;
        return PartialView(lgm);
    }

In post Login action:
        public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                model.IsLoggedIn = true;
                if (string.IsNullOrEmpty(model.RetUrl))
                {
                    model.RetUrl = Url.Action("Index", "Home");
                }
            }
            else
            {
                // If we got this far, something failed, redisplay form
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }
        return PartialView("Login", model);
    }

in Login.cshtml: put two hidden fields to retain Model preset value:
             @Html.HiddenFor(m => m.RetUrl)
             @Html.HiddenFor(m => m.UrlReferrer)

In ajax OnSuccess event handler, append a CallPartial querystring in the end of returnUrl and redirect to this returnUrl:
     <script type="text/javascript">
function logInComplete() {
    //debugger;
    if ('@Model.IsLoggedIn' == 'True' && '@Model.UrlReferrer' != '') {
        //debugger;
        var returnUrl = '@Model.UrlReferrer';
        if ('@Model.RetUrl' != '@Model.UrlReferrer') {
            if (returnUrl.indexOf('?') == -1) {
                returnUrl = returnUrl + "?CallPartial=True";
            }
            else {
                returnUrl = returnUrl + "&CallPartial=True";
            }
        }
        document.location = returnUrl;
    }
}

Now back to the CREATE partialview host page:

         $('.ifCallPartial').each(function () {
        //debugger;
        if ('@Request["CallPartial"]' == "True") {
            $(document).ready(function () {
                CallCreate();
            });
        }
    });

    function CallCreate() {
        //debugger;
        //e.preventDefault();
        var returl = String(window.location);
        var n = returl.indexOf("?CallPartial");
        if (n >= 1) {
            returl = returl.substring(0, n);
        }
        else {
            n = returl.indexOf("CallPartial");
            if (n >= 1) {
                returl = returl.substring(0, n);
            }
        }
        $.ajax({
            type: "GET",
            data: { returnUrl: returl },
            url: "/CreateGroup/CreateGroup",
            dataType: 'html',
            success: function (data) {
                $("#group-list").html(data);
            },
            error: function (xhr, status, error) {
                alert(error);
            }
        });
    }


text:
Q: Not showing li in ngFor statement I am trying to write a pager.
I would like to not put the
 element to the dom if number=-1.
I could not write ngIf inside an ngFor so if anyone could show me the way I would appreciate it.
Here is what I'd like to improve:

  {{number}}

A: Using the ng-container:

 is a logical container that can be used to group nodes
  but is not rendered in the DOM tree as a node.

<ng-container *ngFor="let number of pagerArray">

        {{number}}

</ng-container>

A: You can use array.filter() for that:
In your component:
getPagerArray(){
    return this.pagerArray.filter((num) => {
        return num >= 0;
    });
}

in your template:

    {{number}}

A: there is many ways you can implemented with.
one way you can set the *ngIf on the a tag

        {{number}}

another way you can do it is by adding your own filter as follow

        {{number}}


text:
Q: SQL Text data type deprecated? I have read that Microsoft SQL Server has deprecated the text data type in favour of varchar(max).
PostGreSQL already allows varchar (without a length) as an alternative for text.
The question is, what does the ANSI SQL standard have to say about deprecating text, and the best alternative? Also, does MySQL/MariaDB also follow this?
Thanks

A: In the ANSI SQL Standard, there is no TEXT type. There are various string types defined, like CHAR and VARCHAR and many more but no mention of a TEXT type. There is a CHARACTER LARGE OBJECT and a BINARY LARGE OBJECT.
The various TEXT types found in various DBMS (Postgres, SQL Server, MySQL) are additions and have small differences between them. Their similarity is that they can hold very large strings.
SQL Server's TEXT is being deprecated. MySQL's TEXT is not deprecated. PostgreSQL's TEXT is well supported and recommended by many to be used everywhere, in place of VARCHAR(n). From Postgres documentation, Character Types:

In addition, PostgreSQL provides the text type, which stores strings of any length. Although the type text is not in the SQL standard, several other SQL database management systems have it as well.

So, the questions:

The question is, what does the ANSI SQL standard have to say about deprecating text, and the best alternative? Also, does MySQL/MariaDB also follow this?

are simple to answer: Nothing and No. There is no deprecation of TEXT as there is no TEXT type. TEXT isn't even a reserved keyword in ANSI SQL. One DBMS (MySQL) does not have to follow another DBMS's (SQL Server) deprecation decisions for a type that isn't in the standard.

A: The ANSI SQL standard (which I assume you refer to) will nothing to say on how Microsoft (or Oracle, etc) implement and remove data types to suit their particular flavour of DBMS, and which ones take precedence.
The Microsoft standard is to use varchar in place of text, nvarchar in place of ntext, and varbinary in place of image, and this is because of the improved capabilities/performance of the data types and how it is stored in the database.
Here's a related StackOverflow question and answer that should give you more details: https://stackoverflow.com/questions/564755/sql-server-text-type-vs-varchar-data-type
Update
This is as close as you're going to get to reading the standard without buying it. You're interested in section 4.4.3.2 Character String types
http://jtc1sc32.org/doc/N1951-2000/32N1963T-text_for_ballot-FCD_9075-1.pdf
As I said earlier - the standard has no bearing on how anyone deprecates a data type, nor anything about specific data types. Just what a type itself should conform to.
I've also found that the PDF I've linked to can be found on the SQL:2011 Wiki page (which I assume you've checked before asking this question) :
https://en.wikipedia.org/wiki/SQL:2011


text:
Q: Wireshark - ignore all packages captured so far Lets say I start capturing and wait for a minute. How can I ignore all packages captured in that time so that similar packages are not showing anymore.
I need this to filter out the "boring" standard traffic e.g. Broadcasts, so that I can listen for my target.
Is this possible with wireshark? If not, is there better software which can do this? There is just too much noise and I have no time to filter it out one by one manually.


text:
Q: return value from subshell and output to local variables I've found the strange behaviour for me, which I can't explain.
The following code is work OK:
function prepare-archive {
blah-blah-blah...
_SPEC_FILE=$(check-spec-file "$_GIT_DIR/packaging/")
exit $?
blah-blah-blah...
}

means I get value which I expect:
bash -x ./this-script.sh:
++ exit 1
+ _SPEC_FILE='/home/likern/Print/Oleg/print-service/packaging/print-service.spec
/home/likern/Print/Oleg/print-service/packaging/print-service2.spec'
+ exit 1

As soon as I add local definition to variable:
local _SPEC_FILE=$(check-spec-file "$_GIT_DIR/packaging/")

I get following:
bash -x ./this-script.sh:
++ exit 1
+ local '_SPEC_FILE=/home/likern/Print/Oleg/print-service/packaging/print-service.spec
/home/likern/Print/Oleg/print-service/packaging/print-service2.spec'
+ exit 0
$:~/MyScripts$ echo $?
0

Question: Why? What has happened? Can I catch output from subshell to local variable and check subshell's return value reliably?
P.S.: prepare-archive is called in the main shell script. The first exit is the exit from check-spec-file function, the second from prepare-archive function - this function itself is executed from main shell script. I return value from check-spec-file by exit 1, then pass this value to exit $?. Thus I expect they should be the same.

A: From the bash manual, Shell Builtin Commands section:
local:
    [...]The return status is zero unless local is used outside a function, an invalid name is supplied, or name is a readonly variable.

Hope this helps =)

A: To capture subshell's exit status, declare the variable as local before the assignment, for example, the following script
#!/bin/sh

local_test()
{
    local local_var
    local_var=$(echo "hello from subshell"; exit 1)
    echo "subshell exited with $?"
    echo "local_var=$local_var"
}

echo "before invocation local_var=$local_var in global scope"
local_test
echo "after invocation local_var=$local_var in global scope"

produces the following output
before invocation local_var= in global scope
subshell exited with 1
local_var=hello from subshell
after invocation local_var= in global scope

A: As I use bash subshell parenthesis to group many echo commands I hit this strange problem.
In my case all I needed was to pass one value back to the calling shell so I just used the exit command
RET=0
echo RET: $RET
(echo hello
echo there
RET=123
echo RET: $RET
exit $RET)
RET=$?
echo RET: $RET

gives the following output
RET: 0
hello
there
RET: 123
RET: 123

without the exit command you will get this which is confusing:
RET: 0
hello
there
RET: 123
RET: 0


text:
Q: sudoers file change not working? I'm in Ubuntu 18.04LTS and I want to change the sudoers file to execute sudo shutdown -h now without the need of password (for my_username). The steps I take were:
With my user my_username open terminal:
sudo visudo
The line I added:
my_username    ALL=(ALL) NOPASSWD: /sbin/shutdown
Where there is only one tab in the first part (between user and ALL) and the rest are spaces.
The user is the one it appears after id in terminal.
After that, just in case I restart the system, and type sudo shutdown -h now but it keeps asking for password.
What I'm doing wrong?
-----EDIT------
Ok, I didn't know that the order in which you add the lines were important, so as asked I added my full file (it's a very simple sudoers config).
#
# See the man page for details on how to write a sudoers file.
#
Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on "#include" directives:
my_username ALL=(ALL) NOPASSWD: /sbin/shutdown
#includedir /etc/sudoers.d

This way it works perfectly for me. The problem was that I added the line after root line.

A: in sudoers man page (man 5 sudoers) has been mentioned

When multiple entries match for a user, they are applied in order.
  Where there are multiple matches, the last match is used (which is not
  necessarily the most specific match).

So no matter if your config is specific.
Also consider if you have sudoers group ( like wheel in Red Hat based distros) the line
%wheel  ALL=(ALL)       ALL should be before NOPASSWD

A: The configuration
my_username ALL=(ALL) NOPASSWD: /sbin/shutdown

allows the user my_username to run /sbin/shutdown with or without arguments and without giving a password, but they must use /sbin/shutdown, not just shutdown (as what executable is picked up would depend on the $PATH).


text:
Q: Relative data visualization in pandas I have some data as follows:
+---------+-------+---------+----------------+
| Machine | Event | Outcome | Duration Total |
+---------+-------+---------+----------------+
| a       |     1 | FAIL    |           1127 |
| a       |     2 | FAIL    |          56099 |
| a       |     2 | PASS    |          15213 |
| a       |     3 | FAIL    |          13891 |
| a       |     3 | PASS    |          13934 |
| a       |     4 | FAIL    |           6844 |
| a       |     5 | FAIL    |           6449 |
| b       |     1 | FAIL    |          21331 |
| b       |     2 | FAIL    |          30362 |
| b       |     3 | FAIL    |          12194 |
| b       |     3 | PASS    |           7390 |
| b       |     4 | FAIL    |          35472 |
| b       |     4 | PASS    |           7731 |
| b       |     5 | FAIL    |           7654 |
| c       |     1 | FAIL    |          16833 |
| c       |     1 | PASS    |          21337 |
| c       |     2 | FAIL    |            440 |
| c       |     2 | PASS    |          14320 |
| c       |     3 | FAIL    |           5281 |
+---------+-------+---------+----------------+

I'm trying to make a categorical scatter plot of total duration of each event and each machine. Or any other visualization to analyze them relatively.
What would be a good choice and how to go about it?

A: import matplotlib.pyplot as plt
import seaborn as sns

sns.catplot(x = 'Event', y = 'Duration', hue = 'Machine', col = 'Outcome', data = df)

Give this a try, its two scatter plots. X axis is the event, y axis is Duration, color of the dots is based on the machine, and there is two graphs, one for fail and next to it is another for pass. "df" is your dataframe. You can remove col = 'Outcome' to have both Fail and Pass on the same graph.
EDIT:
fig, ax = plt.subplots(figsize = (10,10))
g = sns.scatterplot(x = 'Event', y = 'Duration', hue = 'Machine', data = df[df['Outcome'] == 'PASS'], ax = ax)
g = sns.scatterplot(x = 'Event', y = 'Duration', hue = 'Machine', data = df[df['Outcome'] == 'FAIL'], ax = ax,
                    style = 'Machine', markers = ['x', 'x', 'x'])

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, ['Machine - Pass', 'a' ,'b', 'c', 'Machine - Fail', 'a','b','c'])

plt.show()


text:
Q: Debounce return I'm not understanding the debounce return, I understand about the rest and spread operator but my question is, when I console.log(...args) it's related to input event but how return receives it ?
    const fetchData = async (searchTerm) => {
  const response = await axios.get('http://www.omdbapi.com/', {
    params: {
      apikey: '',
      s: searchTerm,
    },
  });
  console.log(response.data);
};

const input = document.querySelector('input');

const debounce = (func) => {
  let timeoutId;

  return (...args) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func.apply(null, args);
    }, 2000);
  };
};

const onInput = debounce((event) => {
  fetchData(event.target.value);
});
input.addEventListener('input', onInput);


text:
Q: How do I "split" a string in PowerShell using a string of multiple characters? When using the .Split() operator on a string in PowerShell and trying to split using a string of more than one character, PowerShell exhibits weird behavior - it uses any of the characters in the string to split.
For example:
PS C:\Users\username> "One two three keyword four five".Split("keyword")
On
 t

 th

 f
u
 fiv

I do not know about you, but I was expecting the results to be an array like:
@("One two three "," four five")

How do I split a string, treating the "splitter" as a literal string? For those coming from VBScript, this is how the built-in Split() function behaved in VBScript.
A couple other notes:

*

*I have done some searching and found some proposed solutions that use RegEx; I would prefer not to use it if it can be avoided.

*I want a solution that works on all versions of PowerShell.

A: There is no need to create a function.
You can use the split function in two different ways. If you use:
"One two three keyword four five".Split("keyword")

every single character inside the brackets is used as splitter. But if you instead use:
"One two three keyword four five" -Split ("keyword")

the string "keyword" is used as splitter.

A: EDIT 2020-05-23: I've moved my code to GitHub, here, where I've made updates to cover a few edge cases: https://github.com/franklesniak/PowerShell_Resources/blob/master/Split-StringOnLiteralString.ps1

The -split operator expects RegEx, but can be made to do this well. However, the -split operator is only available on Windows PowerShell v3+, so it does not fit the requirements in the question.
A [regex] object has a Split() method that can handle this as well, but it expects RegEx as the "splitter". To get around this, we can use a second [regex] object and call the Escape() method to convert our literal string "splitter" into escaped RegEx.
Wrapping all this up into an easy to use function that works back to PowerShell v1 and also works on PowerShell Core v6.
function Split-StringOnLiteralString
{
    trap
    {
        Write-Error "An error occurred using the Split-StringOnLiteralString function. This was most likely caused by the arguments supplied not being strings"
    }

    if ($args.Length -ne 2) `
    {
        Write-Error "Split-StringOnLiteralString was called without supplying two arguments. The first argument should be the string to be split, and the second should be the string or character on which to split the string."
    } `
    else `
    {
        if (($args[0]).GetType().Name -ne "String") `
        {
            Write-Warning "The first argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
            $strToSplit = [string]$args[0]
        } `
        else `
        {
            $strToSplit = $args[0]
        }

        if ((($args[1]).GetType().Name -ne "String") -and (($args[1]).GetType().Name -ne "Char")) `
        {
            Write-Warning "The second argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
            $strSplitter = [string]$args[1]
        } `
        elseif (($args[1]).GetType().Name -eq "Char") `
        {
            $strSplitter = [string]$args[1]
        } `
        else `
        {
            $strSplitter = $args[1]
        }

        $strSplitterInRegEx = [regex]::Escape($strSplitter)

        [regex]::Split($strToSplit, $strSplitterInRegEx)
    }
}

Now, using the earlier example:
PS C:\Users\username> Split-StringOnLiteralString "One two three keyword four five" "keyword"
One two three
 four five

Volla!


text:
Q: ipython parallel load balanced view failing randomly Here's my code:
from IPython.parallel import Client
from sklearn.datasets import load_digits

def mytask(data, labels, id):
   # ...
   pass

engines = Client()
bview = engines.load_balanced_view()
bview.block = False

digits = load_digits()
X, y = digits.data, digits.target

job = bview.apply(mytask, X, y, 1)

while not job.ready(): # line 242
    time.sleep(2)

print job.result

Occasionally with the same input my code fails with this:
Traceback (most recent call last):
  File "task.py", line 242, in <module>
    while not job.ready():
  File "/usr/lib/python2.7/dist-packages/IPython/parallel/client/asyncresult.py", line 111, in ready
    self.wait(0)
  File "/usr/lib/python2.7/dist-packages/IPython/parallel/client/asyncresult.py", line 121, in wait
    self._ready = self._client.wait(self.msg_ids, timeout)
  File "/usr/lib/python2.7/dist-packages/IPython/parallel/client/client.py", line 844, in wait
    self.spin()
  File "/usr/lib/python2.7/dist-packages/IPython/parallel/client/client.py", line 799, in spin
    self._flush_results(self._task_socket)
  File "/usr/lib/python2.7/dist-packages/IPython/parallel/client/client.py", line 692, in _flush_results
    handler(msg)
  File "/usr/lib/python2.7/dist-packages/IPython/parallel/client/client.py", line 657, in _handle_apply_reply
    self.results[msg_id] = util.unserialize_object(msg['buffers'])[0]
  File "/usr/lib/python2.7/dist-packages/IPython/parallel/util.py", line 262, in unserialize_object
    return uncanSequence(map(unserialize, sobj)), bufs
  File "/usr/lib/python2.7/dist-packages/IPython/utils/newserialized.py", line 177, in unserialize
    return UnSerializeIt(serialized).getObject()
  File "/usr/lib/python2.7/dist-packages/IPython/utils/newserialized.py", line 161, in getObject
    result = numpy.frombuffer(buf, dtype = self.serialized.metadata['dtype'])
ValueError: offset must be non-negative and smaller than buffer lenth (0)

This seems to be unconnected to my code. I'm not sure what's going wrong.


text:
Q: lldb background execution from script? In GDB you could continue/step/etc. the debugging process in the background by attaching an & after the command (ex: continue&), allowing you access to the CLI while the process/thread runs. I have found this to be invaluable when debugging multi-process/multi-thread applications when I want to keep the "non-interesting" threads/processes running while I stepped through a single thread.
I was wondering is there anything equivalent in LLDB? Specifically, I would like to specify which execution model I want to use in a script.
An example of something I would like to do in an LLDB script:
# this is just background setup for attaching to multiple processes
# I've figured out how to do this in LLDB
attach 1
add-inferior
inferior 2
attach 2
# this is the step I don't know how to get to work consistently
continue&
inferior 1
# ... do debugging work on inferior 1, possibly switching to inferior 2 as needed

Things I've tried:
In LLDB, the closest thing I've found in the documentation are two "options" --no-stdin, or settings set target.process.disable-stdio true (I don't need stdin for my applications, though stdout would be nice). However, when I tried looking for either of these options in LLDB 6.0, they don't exist anymore, or at least not by these names.
Another thing I have found (couldn't find any documentation on this) is if I attached LLDB to an existing process ID, then when I issued process continue from the CLI it would always execute in the background. However, if I run an LLDB commands script or have LLDB run the process locally then it always executes "in the foreground" and I lose control of the CLI unless I interrupt the running command. It's important to me that I be able to do something like continue& in a script since I will have quite a few processes and manually switching to/continuing each target is very time consuming.

A: Looks like --no-stdin was changed to the (arguably more accurate) --no-stdio option to process launch without changing the overview doc.  Do help process launch to see all the options, including that one.  The equivalent setting is target.disable-stdio.
Note also, lldb's help was enhanced so that aliases that end with -- - i.e. that explicitly turn off adding options to the command - don't list the options for the underlying command.  run is an alias for process launch --, so if you do help run you won't see any options.
You can also use the --tty option to redirect the output to another terminal window.
As far as script commands go.  The way this works is that lldb can run the processes in either synchronous or asynchronous mode.  In synchronous mode, all the commands (and SB API calls) in the debugger that continue a process block till the process stops again.  In async mode, control returns immediately, and then somebody needs to watch the lldb event stream for process events to figure out when the process has stopped again.  For commands, lldb will do that for you.  For Python scripts, you have to do that by hand.
If you are using the command line, we figure out which to do for command-line commands based on whether we are also trying to field stdio from the process.
For scripts written with the SB API's, either when used as lldb command-line commands or as stand-alone scripts, lldb runs the debugger in synchronous mode by default.  That saves you the trouble of having to wait for events to know when the process has stopped.  And since there isn't currently a way to "suspend" a command mid-stream and go back to the command line (till when?), running in async mode is not generally very useful.  But it is useful in the case where you want to issue a "continue" as the last act of a python command, and want that to happen asynchronously. Then you can do:
old_async = debugger.GetAsync()
debugger.SetAsync(True)
process.Continue()
debugger.SetAsync(old_async)

Then the Python based command will exit when the process successfully continues rather than waiting for it to stop again.


text:
Q: Calculating Average length of words using while loop I am trying to solve a python textbook problem: The chapter is loops so I am pretty sure it wants me to use it and not any other advanced methods.
Write a program with a loop that repeatedly asks the user to enter a word. The user should enter nothing (press Enter without typing anything) to signal the end of the loop. Once the loop ends, the program should display the average length of the words entered, rounded to the nearest whole number.
My code:
total = 0
num_words = 0

input_word = input('Please enter a word or press enter to quit: ')

while input_word != '':
    input_word = input('Please enter a word or press enter to quit: ')
    length_word = len(input_word)
    total += length_word
    num_words += 1

avg = total/num_words

print('Average length of word is:',avg)

If I enter two words, the number of words are correctly reflecting as 2 but the total number of characters in the word are only counting for the second input. I am guess the first input to prime the while loop is not getting adding to total length of characters. How should I fix this ?

A: First of all, you are overwriting input_word as soon as it enters into the while loop.
Secondly, num_words is added 1 even when you press enter. So when you say number of words are correct, it is actually not counting the very first input_word, but rather from second input_word to press enter to quit.
Changing as follow make it work:
total = 0
num_words = 0

input_word = input('Please enter a word or press space to quit: ')

while input_word != '':
    length_word = len(input_word)
    total += length_word
    num_words += 1
    input_word = input('Please enter a word or press enter to quit: ')

avg = total/num_words

print('Average length of word is:',avg)

A: You are discarding the first value in the first step of your loop. Change the priming value to something like
input_word = "foo"

and subtract 1 from num_words not to count the empty string:
avg = total / (num_words - 1)

Sample output:
Please enter a word or press enter to quit: abc
Please enter a word or press enter to quit: de
Please enter a word or press enter to quit:
Average length of word is: 2.5


text:
Q: Entity Framework One to many relationship My EF query takes around 3 seconds to fetch 10 players because it fetches all 500k+ rows of the other table, instead of the few I need.
This is the PlayerEntity:
namespace RocketLeagueStats.Database.Entities
{
    [Table("players", Schema = "public")]
    public class PlayerEntity
    {

        [Key]
        [Column("id")]
        public int Id { get; set; }

        [Column("unique_id")]
        public string UniqueId { get; set; }

        [Column("display_name")]
        public string DiplayName { get; set; }

        [Column("platform_id")]
        [JsonIgnore]
        public int PlatformId { get; set; }

        [ForeignKey("PlatformId")]
        public PlatformEntity Platform { get; set; }

        [Column("avatar")]
        public string Avatar { get; set; }

        public PlayerStatsEntity Stats { get; set; }

        public List<PlayerRankedEntity> Ranks { get; set; }

        [Column("last_requested")]
        public DateTime LastRequested { get; set; }

        [Column("created_at")]
        public DateTime CreatedAt { get; set; }

        [Column("updated_at")]
        public DateTime UpdatedAt { get; set; }

    }
}

This is the PlayerRankedEntity:
namespace RocketLeagueStats.Database.Entities
{
    [Table("player_ranked", Schema = "public")]
    public class PlayerRankedEntity
    {

        [ForeignKey("Player")]
        [Column("player_id")]
        [JsonIgnore]
        public int PlayerId { get; set; }

        [Column("season_id")]
        [JsonIgnore]
        public int SeasonId { get; set; }

        [Column("playlist_id")]
        [JsonIgnore]
        public int PlaylistId { get; set; }

        [Column("matches_played")]
        public int MatchesPlayed { get; set; }

        [Column("rank_points")]
        public int RankPoints { get; set; }

        [Column("tier")]
        public int Tier { get; set; }

        [Column("division")]
        public int Division { get; set; }

        public PlayerEntity Player { get; set; }

    }
}

This is the PlayerStatsEntity:
namespace RocketLeagueStats.Database.Entities
{
    [Table("player_stats", Schema = "public")]
    public class PlayerStatsEntity
    {

        [Key, ForeignKey("Player")]
        [Column("player_id")]
        [JsonIgnore]
        public int PlayerId { get; set; }

        [Column("wins")]
        public int Wins { get; set; }

        [Column("goals")]
        public int Goals { get; set; }

        [Column("mvps")]
        public int Mvps { get; set; }

        [Column("saves")]
        public int Saves { get; set; }

        [Column("shots")]
        public int Shots { get; set; }

        [Column("assists")]
        public int Assists { get; set; }

        public PlayerEntity Player { get; set; }

    }
}

This is my DatabaseContext.OnModelCreating method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PlayerRankedEntity>()
        .HasKey(k => new { k.PlayerId, k.SeasonId, k.PlaylistId });
}

This is the code that takes over 3 seconds to complete (If I remove '.Include(x => x.Ranks)' it just takes a few ms):
using (var database = new DatabaseContext())
{
    var serviceProvider = database.GetInfrastructure();
    var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
    loggerFactory.AddNLog();

    var stopwatch = Stopwatch.StartNew();

    var players = database.Players
        .Include(x => x.Ranks)
        .Take(10)
        .ToArray();

    Console.WriteLine($"Took {stopwatch.ElapsedMilliseconds}ms to fetch {players.Length} players");
}

This is the output, notice that it generates two queries instead of one:
2016-10-31 22:50:18.6416 INFO Executed DbCommand (8ms) [Parameters=[@__p_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "x"."id", "x"."avatar", "x"."created_at", "x"."display_name", "x"."last_requested", "x"."platform_id", "x"."unique_id", "x"."updated_at"
FROM "public"."players" AS "x"
ORDER BY "x"."id"
LIMIT @__p_0
2016-10-31 22:50:18.7128 INFO Executed DbCommand (0ms) [Parameters=[@__p_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "p"."player_id", "p"."season_id", "p"."playlist_id", "p"."division", "p"."matches_played", "p"."rank_points", "p"."tier"
FROM "public"."player_ranked" AS "p"
WHERE EXISTS (
    SELECT 1
    FROM "public"."players" AS "x"
    WHERE "p"."player_id" = "x"."id"
    LIMIT @__p_0)
ORDER BY "p"."player_id"
Took 3991ms to fetch 10 players

I think that I messed up on the relations somewhere, causing it to select all rows. But I don't know what I messed up.
How can I fix this, and are there any other problems with my attributes?
I am using Microsoft.EntityFrameworkCore v1.0.1.
Edit: If I use .OrderBy(x => x.CreatedAt) or .Where(x => x.DiplayName.Contains("mike")) in the query, it goes a lot faster.
Generated query:
2016-11-01 00:14:15.9638 INFO Executed DbCommand (24ms) [Parameters=[@__p_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "x"."id", "x"."avatar", "x"."created_at", "x"."display_name", "x"."last_requested", "x"."platform_id", "x"."unique_id", "x"."updated_at"
FROM "public"."players" AS "x"
ORDER BY "x"."created_at", "x"."id"
LIMIT @__p_0
2016-11-01 00:14:16.0972 INFO Executed DbCommand (44ms) [Parameters=[@__p_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "p"."player_id", "p"."season_id", "p"."playlist_id", "p"."division", "p"."matches_played", "p"."rank_points", "p"."tier"
FROM "public"."player_ranked" AS "p"
INNER JOIN (
    SELECT DISTINCT "x"."created_at", "x"."id"
    FROM "public"."players" AS "x"
    ORDER BY "x"."created_at", "x"."id"
    LIMIT @__p_0
) AS "x0" ON "p"."player_id" = "x0"."id"
ORDER BY "x0"."created_at", "x0"."id"
Took 314ms to fetch 10 players

A: EF Core currently is a nightmare.
You can try the following workaround (but if you ask me, better switch back to EF6).
Instead of:
var players = database.Players
    .Include(x => x.Ranks)
    .Take(10)
    .ToArray();

use:
var players = database.Players
    .Take(10)
    .ToArray();
var playerIds = players.Select(p => p.Id);
database.PlayerRanks.Where(r => playerIds.Contains(r.PlayerId)).Load();

which should produce the same effect as Include.


text:
Q: Expectation by integral I am trying to compute the expectation of
$\mathbb{E}[XY]$ where $X$ and $Y$ are dependent on a third non-negative random variable $Z$.
I can now compute the expectation as follows
$$\mathbb{E}[XY]=\int_{0}^{\infty}\mathbb{E}[XY\mid Z=z]dF_{Z}(z)$$
I am also familiar with the equivalent representation
$$\mathbb{E}[XY]=\int_{0}^{\infty}\mathbb{E}[XY\mathbb{1}_{Z\in[z,z+dz)}]$$
where $\mathbb{1}_{A}$ is the indicator function on $A$.
I am now wondering whether I can write this expectation as follows
$$\mathbb{E}[XY]=\int_{0}^{\infty}\mathbb{E}[XY\mathbb{1}_{Z=z}]dz$$
I do not want to assume that $Z$ has a density function.
Could anyone tell me if this last representation is correct and perhaps provide a proof even?


text:
Q: Debugging - How to log the folder trees in Objective-C? I want to log my application's folder trees in Xcode debug area just like the picture below.
In command line, I can use the command tree to log directory tree of a folder.
Is there a way to log folder trees like this in Xcode? I can log a array of files and folders in a folder, but I want a readable log not just a list.
And the folder path is in a iOS Application. NSHomeDirectory(), for example.

A: As this is just for debugging just run tree, grab its output, and NSLog it. Look up system(3), popen(3) in man and NSTask in the frameworks for how to run a command.
Addendum after Comment
Apologies, when I read:

In command line, I can use the command tree to log directory tree of a folder.

I did not check the actual command. Is tree available on any version of MacOS?
Given the lack of this command you can roll your own. Look up fts(3). With these library routines you can write a simple loop which will traverse a complete folder hierarchy and print the items as you go. You will have the item kind, depth and name to use to produce your output.
HTH


text:
Q: Run application multiply times without stop previous I have a clock application that I would be able to run multiply times, but everytime I start the application again, the previous one stops. I think i should use target ? och This. But i cant figure out where in the function I should use it.
The function for the clock.
function myFunction() {
    startClock();

    function startClock() {
        var digits = new Array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine");
        var h = new Date().getHours().toString();
        var m = new Date().getMinutes().toString();
        var s = new Date().getSeconds().toString();
        var t = ((h > 9 ? h : "0" + h) + (m > 9 ? m : "0" + m) + (s > 9 ? s : "0" + s));

        hours.appendChild(hour1).className = "clock-digit-" + digits[t.substring(0, 0 + 1)];
        hours.appendChild(hour2).className = "clock-digit-" + digits[t.substring(1, 1 + 1)];
        minutes.appendChild(minute1).className = "clock-digit-" + digits[t.substring(2, 2 + 1)];
        minutes.appendChild(minute2).className = "clock-digit-" + digits[t.substring(3, 3 + 1)];
        seconds.appendChild(sec1).className = "clock-digit-" + digits[t.substring(4, 4 + 1)];
        seconds.appendChild(sec2).className = "clock-digit-" + digits[t.substring(5, 5 + 1)];

        t = setTimeout(function () {
            startClock()
        }, 1000);
    }
}

I have created a jsFiddle http://jsfiddle.net/dymond/nufwb/
But as you notice  when you press test twice the prev. clock stops...

A: Try defining variables outside of myFunction().
var t1 = setTimeout(function(){startClock()},1000);
var t2 = setTimeout(function(){startClock()},2000);

What you are doing now is overwriting the previous clock every time you run myFunction().


text:
Q: grunt, cannot get express server running I am using grunt-express-server and grunt-open to start the express server and open it in browser.  the problem is server gets started, then seems got closed by itself. after open it in browser,  you will get cannot connect to localhost:9000
'use strict';

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
process.env.PORT = process.env.PORT || 9000;
//var config = require('./lib/config/config');

module.exports = function(grunt){

    require('load-grunt-tasks')(grunt);
    require('time-grunt')(grunt);

    grunt.initConfig({
        coffee: {
            build: {
                expand: true,
                flatten: false,
                cwd: './src',
                src: ['**/*.coffee'],
                dest: './',
                ext: '.js'
            }
        },
        express: {
            options: {
                port: process.env.PORT,
                background: true
            },
            dev: {
                options: {
                    script: 'app.js',
                    debug: false
                }
            }
        },
        open: {
            server: {
                url: 'http://localhost:<%= express.options.port %>'
            }
        }

    });

    grunt.registerTask('default', ['coffee', 'express', 'open']);
};

A: I had this problem as well. Solved it by using grunt-watch to keep the server alive.
https://github.com/gruntjs/grunt-contrib-watch


text:
Q: Incorrect Output If then Else statement in R Please see the code below. the code does not show the accurate value as everything it being set to "Others" in the new var titles:
extractTitle<- function(name){
  name<-as.character(name)

  if (length(grep("Miss.",name))>0){
    return("Miss.")
  }else if (length(grep("Master.",name))>0){
    return("Master.")
  }else if (length(grep("Mrs.",name))>0){
    return("Mrs.")
  }else if (length(grep("Mr.",name))>0){
    return("Mr.")
  }else {
    return("Other")
  }
}

titles<- NULL
for (i in 1:nrow(data.combined)){
  titles<- c(titles,extractTitle(data.combined[i,"name"]))
}

data.combined$title<- as.factor(titles)

Kindly advice where is the issue.

A: Your code works for me when trying it with simple test data ("foobar", "fooMaster.bar" "Master.bar", "fooMaster.", etc.). So the issue probably lies with how you handle the dataset to the function. For example, if you misspelled the "name" column access this will handle NULL to the function, which in turn will cause "Other" be handed back.
PS: sorry for posting this as an answer but I'm still too low for comments :)


text:
Q: Trying to multipy but its only multiplying .10 to any input I type in. Also for my Scanner "resource" says its never closed I am working on this "if else" statement to multiply a range of numbers but it only multiplies to .10
Not sure what I am doing wrong. Additionally for "resource" it says its never closed.
import java.util.Scanner;
public class taxableIncome {

    public static void main(String[] args){
        {
        Scanner resource = new Scanner(System.in); //scanner object for keyboard input.
        System.out.print("Enter annual income:  ");
        {

        int input = 0;
        double ten = .10; // 10% tax
        double fifthteen = .15; // 15% tax
        double twentyfive = .25;
        double twentyeight = .28;
        double thirtythree = .33;
        double thirtyfive = .35;
        double total = 0.0;
        boolean taxes = true;

        while(taxes)
        {
        if (input >= 0 && input <= 8500){
                total = ten * resource.nextDouble();
                System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
        }else if  (input >= 8500 && input <= 34500){
                    total = fifthteen * resource.nextDouble();
                    System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
                    } else if (input >= 34500 && input <= 83600){
                        total = twentyfive * resource.nextDouble();
                        System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
                        }else if (input >= 83600 && input <= 174400){
                            total = twentyeight * resource.nextDouble();
                            System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
                        }else if (input >= 174400 && input <= 379150){
                            total = thirtythree * resource.nextDouble();
                            System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
                        }else if (input >= 379150 && input >= 379151) {
                            total = thirtyfive * resource.nextDouble();
                            System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
                            taxes = false;
                        }

        }
        }
    }
}
}

A: Your code is always evaluating for input == 0.0 because at no point does the code update this value. The program also never terminates for this reason as well.

A: Your input variable is initialized to 0.0, therefore it will always enter the first if statement and multiply by 0.10.
Take the salary input out of the if statements so the if statements will check based on your inputs.


text: Q: Как внедрить в приложение функционал, позволяющий брать определенный текст из html кода в рамках одного сайта Добрый день! Заранее прошу простить за возможно некорректную постановку вопроса, я еще неопытный андроид разработчик. Проблема такая, требуется создать приложение в котором будет возможность брать определенный текст из HTML кода страниц. Например,существует новостной сайт, на котором есть несколько статьей. Программа должна брать текст из новостных статьей и периодически обновлять его по мере публикации новых.Подскажите пожалуйста, какие средства можно использовать, чтобы реализовать это.


text:
Q: Limit of tan function This is a question from an old tutorial for a basic mathematical analysis module.
Show that $$\lim\limits_{n\to \infty}\tan^n(\frac{\pi}{4}+\frac{1}{n}) = e^2$$
My tutor has already gone through this in class but I am still confused. Is there anything wrong with the following reasoning?
Since $\frac{\pi}{4}+\frac{1}{n} \to \frac{\pi}{4}$ as $n \to \infty$,
it seems to me that $\tan(\frac{\pi}{4}+\frac{1}{n}) \to \tan(\frac{\pi}{4}) = {1}$,
and hence $\tan^n(\frac{\pi}{4}+\frac{1}{n}) \to 1^n = 1$.
Additionally, my tutor has given a hint, to use Squeeze theorem along with the definition $e = \lim\limits_{n \to \infty }(1 + {1\over n})^n$, but I can't see how these are to be used.
Edit: Here's another attempt I've made.
After using addition formula for tangent, we get
$$\frac{1 + \tan{\frac{1}{n}}}{1- \tan{\frac{1}{n}}} = 1 - \frac{2\tan{\frac{1}{n}}}{1-\tan{\frac{1}{n}}} = 1 - \frac{1}{\frac{1-\tan{\frac{1}{n}}}{2\tan{\frac{1}{n}}}} = [(1 - \frac{1}{\frac{1-\tan{\frac{1}{n}}}{2\tan{\frac{1}{n}}}})^\frac{1}{\frac{1-\tan{\frac{1}{n}}}{2\tan{\frac{1}{n}}}}]^\frac{2\tan{\frac{1}{n}}}{1-\tan{\frac{1}{n}}}$$
so given that $\lim\limits_{n \to \infty}{\frac{\tan{\frac{1}{n}}}{\frac{1}{n}}}=1$, we have
$$\lim\limits_{n\to \infty}\tan^n(\frac{\pi}{4}+\frac{1}{n}) = \lim\limits_{n \to \infty}[(1 - \frac{1}{\frac{1-\tan{\frac{1}{n}}}{2\tan{\frac{1}{n}}}})^\frac{1}{\frac{1-\tan{\frac{1}{n}}}{2\tan{\frac{1}{n}}}}]^\frac{2n\tan{\frac{1}{n}}}{1-\tan{\frac{1}{n}}} = e^\frac{2*1}{1-0} = e^2$$
I'm really hoping that this method works as well! So sorry for the ugly formatting, I couldn't figure out some parts.

A: Using the addition angle formula for the tangent function we can write
$$\tan^n\left(\frac{\pi}{4}+\frac1n\right)=\left(\frac{1+\tan\left(\frac1n\right)}{1-\tan\left(\frac1n\right)}\right)^n$$
Note that $\tan(x)=x+O(x^3)$.  Then, we have
$$\begin{align}
\left(\frac{1+\tan\left(\frac1n\right)}{1-\tan\left(\frac1n\right)}\right)^n&=\left(\frac{1+\frac1n +O\left(\frac1{n^3}\right)}{1-\frac1n +O\left(\frac1{n^3}\right)}\right)^n\\\\
&=\left(\frac{1+\frac1n }{1-\frac1n }\right)^n\left(\frac{1+\frac{O\left(\frac1{n^3}\right)}{1+\frac1n}}{1 +\frac{O\left(\frac1{n^3}\right)}{1-\frac1n }}\right)^n\\\\
&\to \frac {e}{e^{-1}}\,\frac{1}{1}\,\,\text{as}\,\,n\to \infty\\\\
&=e^2
\end{align}$$
And we are done!

A: If the only standard limit available is $$\lim_{n \to \infty}\left(1 + \frac{1}{n}\right)^{n} = e$$ then we are out of luck here. It is better to assume the following standard limits $$\lim_{x \to 0}\frac{\tan x}{x} = 1 = \lim_{x \to 0}\frac{\log(1 + x)}{x}$$ and then we can easily evaluate the desired limit. We have
\begin{align}
\log L &= \log\left\{\lim_{n \to \infty}\tan^{n}\left(\frac{\pi}{4} + \frac{1}{n}\right)\right\}\notag\\
&= \log\left\{\lim_{n \to \infty}\left(\frac{1 + \tan(1/n)}{1 - \tan(1/n)}\right)^{n}\right\}\notag\\
&= \log\left\{\lim_{n \to \infty}\left(1 + \frac{2\tan(1/n)}{1 - \tan(1/n)}\right)^{n}\right\}\notag\\
&= \lim_{n \to \infty}\log\left(1 + \frac{2\tan(1/n)}{1 - \tan(1/n)}\right)^{n}\text{ (via continuity of log)}\notag\\
&= \lim_{n \to \infty}n\log\left(1 + \frac{2\tan(1/n)}{1 - \tan(1/n)}\right)\notag\\
&= \lim_{n \to \infty}n\cdot\dfrac{2\tan(1/n)}{1 - \tan(1/n)}\cdot\dfrac{\log\left(1 + \dfrac{2\tan(1/n)}{1 - \tan(1/n)}\right)}{\dfrac{2\tan(1/n)}{1 - \tan(1/n)}}\notag\\
&= 2\lim_{n \to \infty}\dfrac{\tan(1/n)}{1/n}\cdot\dfrac{1}{1 - \tan(1/n)}\cdot\lim_{x \to 0}\dfrac{\log\left(1 + x\right)}{x}\notag\\
&= 2\cdot 1\cdot 1\cdot 1\notag\\
&= 2\notag
\end{align}
Hence $L = e^{2}$.

A: Solution
Applying $\textbf{L'Hospital's Rule}$, we have $$\begin{align*}\lim_{x \to +\infty} \left[x\ln \tan \left(\dfrac{\pi}{4}+\dfrac{1}{x}\right)\right]&=\lim_{x \to +\infty}\dfrac{\ln \tan \left(\dfrac{\pi}{4}+\dfrac{1}{x}\right)}{\dfrac{1}{x}}\\&=\lim_{x \to +\infty}\dfrac{1}{\sin\left(\dfrac{\pi}{4}+\dfrac{1}{x}\right)\cos \left(\dfrac{\pi}{4}+\dfrac{1}{x}\right)}\\&=\lim_{x \to +\infty}\dfrac{2}{ \sin\left(\dfrac{\pi}{2}+\dfrac{2}{x}\right)}\\&=\lim_{x \to +\infty}\dfrac{2}{ \cos\left(\dfrac{2}{x}\right)}\\&=2. \end{align*}$$ Hence, $$\begin{align*}\lim\limits_{n\to \infty}\tan^n\left(\frac{\pi}{4}+\frac{1}{n}\right)&=\lim\limits_{x\to +\infty}\tan^x\left(\frac{\pi}{4}+\frac{1}{x}\right)\\&=\lim\limits_{x\to +\infty} \exp\left[x\ln \tan \left(\dfrac{\pi}{4}+\dfrac{1}{x}\right)\right]\\&=\exp\left[\lim_{x \to \infty}x\ln \tan \left(\dfrac{\pi}{4}+\dfrac{1}{x}\right)\right]\\&=\mathbb{e}^2.\end{align*}$$


text:
Q: Calling a web service with no wsdl I want to write a Java program to call a web service. WSDL is not available for this web service. I have written programs to call a web service which has wsdl. Here I don't have any idea of how I can proceed. Not able to find many samples in Internet as well.
Is there any better frame work which I can use? I am getting JSON output from web service.
I am looking at options of writing a best possible case(If I could write a generalized program which could be used for many web services with out much changes, it would be great)

A: Well there are several ways to consume rest service.
Using Spring framework:
import org.springframework.web.client.RestTemplate

RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject("http://localhost:8080/users/2", User.class);
System.out.println("Username:    " + user.getUsername());

Using apache httpclient:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("http://localhost:8080/users/2");
HttpResponse response = httpClient.execute(getRequest);
HttpEntity httpEntity = response.getEntity();
String userString = EntityUtils.toString(httpEntity);
// Transform 'userString' into object using for example GSON:
Gson gson = new Gson();
User user = gson.fromJson(userString, User.class);
System.out.println("Username:    " + user.getUsername());


text:
Q: Deleting attributes and empty elements In an XSL transformation, there are two things I have not been able to figure out.
In the source XML
<Network>
  <Hosts>
    <Host modelId="1" name="H1">
      <LinPorts>
        <LinPort name="Port3" speed="100" parent="H1"/>
      </LinPorts>
      <CanPorts/>
      <EthernetPorts>
        <EthernetPort name="Port1" speed="100" parent="H1"/>
        <EthernetPort name="Port2" speed="100" parent="H1"/>
      </EthernetPorts>
    </Host>
    <Host modelId="1" name="H2">
      <CanPorts>
        <CanPort name="Port2" speed="100" parent="H2"/>
      </CanPorts>
      <EthernetPorts>
        <EthernetPort name="Port1" speed="100" parent="H3"/>
      </EthernetPorts>
    </Host>
    <Host modelId="1" name="lin">
      <LinPorts>
        <LinPort name="Port1" speed="10" parent="lin"/>
        <LinPort name="Port2" speed="100" parent="H2"/>
        <LinPort name="Port3" speed="100" parent="lin"/>
      </LinPorts>
    </Host>
  </Hosts>
  <DataFrames>
    <DataFrame bitSize="21" name="greasd" offset="0.021" period="0.021" prio="0">
      <Path name="greasd-S5" parent="greasd">
        <Node name="H1" sequenceNumber="1" parent="greasd-S5"/>
        <Node name="S5" sequenceNumber="2" parent="greasd-S5"/>
      </Path>
    </DataFrame>
    <DataFrame bitSize="23" name="hytdsg" offset="0.423" period="0.423" prio="0">
      <Path name="hytdsg-H1" parent="hytdsg">
        <Node name="H2" sequenceNumber="1" parent="hytdsg-H1"/>
        <Node name="S5" sequenceNumber="2" parent="hytdsg-H1"/>
        <Node name="H1" sequenceNumber="3" parent="hytdsg-H1"/>
      </Path>
    </DataFrame>
  </DataFrames>
</Network>

some child nodes have been incorrectly placed. I am using the attribute @parent to place them correctly. This works well using the XSLT below.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0" >
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>

<!-- Copy all nodes (that do not get a better match) as they are -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Host">
    <xsl:variable name="hostname" select="@name"/>
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <LinPorts>
            <xsl:apply-templates select="//LinPorts/LinPort[@parent=$hostname]">
                 <xsl:sort select="@name" data-type="text" />
            </xsl:apply-templates>
        </LinPorts>
        <CanPorts>
            <xsl:apply-templates select="//CanPorts/CanPort[@parent=$hostname]">
                 <xsl:sort select="@name" data-type="text" />
            </xsl:apply-templates>
        </CanPorts>
         <EthernetPorts>
            <xsl:apply-templates
                select="//EthernetPorts/EthernetPort[@parent=$hostname]">
                 <xsl:sort select="@name" data-type="text" />
            </xsl:apply-templates>
        </EthernetPorts>
    </xsl:copy>
</xsl:template>

<xsl:template match="DataFrame">
    <xsl:variable name="framename" select="@name"/>
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="//Path[@parent=$framename]">
            <xsl:sort select="@name" data-type="text" />
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<xsl:template match="Path">
    <xsl:variable name="pathname" select="@name"/>
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="//Node[@parent=$pathname]">
            <xsl:sort select="@sequenceNumber" data-type="text" />
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<!--  Do not save attributes parent and ID for child elements -->
<xsl:template match="CanPort|LinPort|EthernetPort|Node">
        <xsl:copy>
        <xsl:apply-templates select="@*[not(name()='parent') and not(name()='id')]">
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

*

*I also create elements that are empty (CanPorts, LinPorts, EthernetPorts). How do I get rid of these?

*I want to get rid of the @parent attribute. I have managed to do so for all elements except Path. How do I get rid of Path.parent?

A: For point 1, you can use an xsl:if to check the count of LinPort, CanPort, and EthernetPort before creating LinPorts, CanPorts, and EthernetPorts elements
And for 2, add another template that matches @parent and does nothing:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0" >
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Host">
    <xsl:variable name="hostname" select="@name"/>
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:if test="count(//LinPorts/LinPort[@parent=$hostname]) != 0">
            <LinPorts>
                <xsl:apply-templates select="//LinPorts/LinPort[@parent=$hostname]">
                    <xsl:sort select="@name" data-type="text" />
                </xsl:apply-templates>
            </LinPorts>
        </xsl:if>
        <xsl:if test="count(//CanPorts/CanPort[@parent=$hostname]) != 0">
            <CanPorts>
                <xsl:apply-templates select="//CanPorts/CanPort[@parent=$hostname]">
                    <xsl:sort select="@name" data-type="text" />
                </xsl:apply-templates>
            </CanPorts>
        </xsl:if>
        <xsl:if test="count(//EthernetPorts/EthernetPort[@parent=$hostname]) != 0">
            <EthernetPorts>
                <xsl:apply-templates
            select="//EthernetPorts/EthernetPort[@parent=$hostname]">
                    <xsl:sort select="@name" data-type="text" />
                </xsl:apply-templates>
            </EthernetPorts>
        </xsl:if>
    </xsl:copy>
</xsl:template>

<xsl:template match="DataFrame">
    <xsl:variable name="framename" select="@name"/>
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="//Path[@parent=$framename]">
            <xsl:sort select="@name" data-type="text" />
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<xsl:template match="Path">
    <xsl:variable name="pathname" select="@name"/>
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="//Node[@parent=$pathname]">
            <xsl:sort select="@sequenceNumber" data-type="text" />
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<!--  Do not save attributes parent and ID for child elements -->
<xsl:template match="CanPort|LinPort|EthernetPort|Node">
    <xsl:copy>
        <xsl:apply-templates select="@*">
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>
<!-- This template matches @parent and @id and does nothing -->
<xsl:template match="@parent | @id"/>
</xsl:stylesheet>