text:
Q: Jquery event handler not firing I have a web page that is having some javascript issues. I have tried looking over everything however I have a username field and when you click it (.focus) it should bring up a pop up. I used firebug in firefox to put break points right then the .focus function is called and it it is not fired even though I do focus on the username field. I have also looked over spelling and everything. Cant seem to find the issue. Hope someone can help. One more thing, this issue is happening in all browsers.
page link: http://aliahealthcareer.com/SignUp

A: Your page has two inputs with id="username".
Repeating ids is invalid html, but the browser kind of ignores it except that $('#username') finds only the first one so your .focus() handler is bound to that one.
The first is within the "login_response" div that is hidden until you click the "Login" option, so if you click "Login" and then click the "Username/Email" field that appears you'll see that your event handler runs.

A: You have JS issues on load of that page. JS wont work properly thereafter. You need to fix those first.


text:
Q: python list of floats from text file I am trying to create a list of floats from a text file with this code:
exam_data_file = open('exam_data.txt','r')
exam_data = exam_data_file.readlines()
exam_data1 = []

for line1 in exam_data_file:
    line1 = float(line1)
    exam_data1.append(line1)

 print(exam_data1)

but the output is simply: []
Can someone please help?!
Now I get this error message regardless of the changes I make:
line1 = float(line1)

ValueError: invalid literal for float(): 3.141592654
2.718281828
1.414213562
0.707106781
0.017453293

A: Why don't use literal_eval n -(easier to use)
You can read and print a simple list or multi-dimensional lists simply with literal_eval
from ast import literal_eval

f=open("demofile.txt",'r')

for line in f:
    new_list = literal_eval(line)

print(new_list)
f.close()

A: https://stackoverflow.com/a/59717679/10151945
This answer is quit relevant.
here an example that i have done with :
from ast import literal_eval
file=open("student_list.txt",'r')
for student in file:
    student_list_final = literal_eval(student)
print(student_list_final)
file.close()

A: for line1 in exam_data_file:
should be this :
for line1 in exam_data :

you are referring to a wrong object

A: There are actually two problems in your code:

*

*The first problem is that you are actually reading the file two times. One time line 2 (exam_data_file.readlines()) and one second time line 5 while executing the for-loop. You can't read a file twice. For further information see this post.

*The second problem is that line1 is currently a whole line in your file (in your case a chain of separate floats), and not a single float as you expected it to be. That's why you get the Invalid literal error. You have to split it into separate numbers in order to call float upon them. That's why you have to call the string's split method.
Try this instead:
exam_data_file = open('exam_data.txt','r')
exam_data1 = []

for line in exam_data_file:
    exam_data1.extend([float(i) for i in line.split()])

print(exam_data1)

Output:
[3.141592654, 2.718281828, 1.414213562, 0.707106781, 0.017453293]

A: You've made an error choosing the error to iterate over in the for loop.
for line1 in exam_data: # not the file!
    line1 = float(line1)
    exam_data1.append(line1)

This could be further improved with
exam_data = []
with open('exam_data.txt','r') as open_file:
    for line1 in open_file:
        line1 = float(line1)
        exam_data.append(line1)

print(exam_data)

The context handler (with syntax) will make sure you close the file after you have processed it!

A: Since a file-like object is an iterable, you can just use map.
with open('exam_data.txt','r') as f:
    exam_data = map(float, f)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select Item in Pivot Slicer when A1 Value Changes I'm trying to select an item in Pivot Slicer when I change "A1" value.
So when I change the "A1" value to "ABC" the code should look for "ABC" in the Slicer Item and select it.
"A1" value will be same as the items in the slicer.
Here is my try, but doesn't seems to work and doesn't look right :(
Private Sub WorkSheet_Change(ByVal Target As Range)

Dim i As Integer
Dim ws As Worksheet
Set ws = ActiveSheet

If Not Intersect(Target, Range("A1")) Is Nothing Then
    For i = 1 To ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems.Count
        If ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Value = ActiveSheet.Range("A1") Then
           ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Selected = True
        Else
           ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Selected = False
        End If
    Next
End If
End Sub

Thank you in advance.

A: I was able to find something that would works.
This is not perfect but works, but still looking for a better way to do this.
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim i As Integer
    Dim ws As Worksheet
    Set ws = ActiveSheet

    If Not Intersect(Target, Range("A1")) Is Nothing Then
        ActiveWorkbook.SlicerCaches("Slicer_Test").Slicers(1).SlicerCache.ClearAllFilters
        For i = 1 To ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems.Count
            If ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Value <> ActiveSheet.Range("A1") Then
               ActiveWorkbook.SlicerCaches("Slicer_Test").SlicerItems(i).Selected = False
            End If
        Next
    End If

End Sub


text:
Q: CSS margin-left applied to incorrect class heading For some unknown reason when I add margin-left to .basic-info h1, it also applies to h1 in .bottomContent. Therefore h1 in bottomContent is also give a margin left of 80px. Meaning when I do .bottomContent h1{ padding-left:80px}, this in theory should be the only one applied but it's not, so the padding-left is doubeld on h1 in bottomContent.
As an easy solution I could just remove bottomContent h1, and leave the CSS as it is with .basic-info but clearly i'm doing something wrong.
HTML
div class = "basic-info">

 Know better. Book better. Go better.

See the latest reviews and compare the lowest hotel prices from 200+ hotel booking sites to help you make the most of your trip
        See the latest reviews and compare the lowest hotel prices from 200+ hotel booking sites to help you make the most of your trip
        See the latest reviews and compare the lowest hotel prices from 200+ hotel booking sites to help you make the most of your trip
        See the latest reviews and compare the lowest hotel prices from 200+ hotel booking sites to help you make the most of your trip
        See the latest reviews and compare the lowest hotel prices from 200+ hotel booking sites to help you make the most of your trip

 Top hotels: Recommendations

CSS
.basic-info p,h1{
    margin-left:80px;
    width:50%;
}

.bottomContent h1{
        margin-left:80px;

    }

A: The margin-left: 80px is being applied to both .basic-info p and h1 since you have a comma in there. You need to do something like this for it to work...
.basic-info p, .basic-info h1 {
    margin-left:80px;
    width:50%;
}

A: I think u want to give margin left to .inside-info h1 not .bottomContent h1
so u can give css like..
.basic-info .inside-info h1{
      margin-left:80px;
}
this is not apply on h1 in bottomContent.


text:
Q: How to fit "Buttons" into frame using "table row"? I'm making a calculator but inside frame, it's not fitting.
I'm using "Table Layout" inside it.
but it's showing this.

While I wanted to make like this.

please help, how to fix my button proper inside frame? thanks.
Here is my source code for "button".
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="#cccccc"
        android:padding="15dp"/>

    <TableLayout
        android:id="@+id/tableID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp">

        <TableRow>
             <Button
                android:id="@+id/btn7"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="7"/>

             <Button
                android:id="@+id/btn8"
                android:text="8"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>

             <Button
                 android:id="@+id/btn9"
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
                 android:text="9"
                 android:layout_weight="1"/>

             <Button
                 android:id="@+id/btnDivide"
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
                 android:text="÷"
                 android:layout_weight="1"/>
        </TableRow>

        <TableRow>

            <Button
                android:id="@+id/btn4"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="4"
                android:layout_weight="1"/>

            <Button
                android:id="@+id/btn5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="5"
                android:weight="1"/>

            <Button
                android:id="@+id/btn6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="6"
                android:weight="1"/>

            <Button
                android:id="@+id/btn7"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="7"
                android:weight="1"/>

       </TableRow>
    </TableLayout>
</LinearLayout>

A: In the last 3 buttons' xml, you write android:weight="1" which will be android:layout_weight="1"
    <TableRow>

        <Button
            android:id="@+id/btn4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="4"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/btn5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="5"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/btn6"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="6"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/btn7"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="7"
            android:layout_weight="1"/>

   </TableRow>


text:
Q: A Local Service implementation closely related to Application Life Cycle In my App. I have extended Application class, say MyApp and I have few activities say A,B,C,D where A is the default Activity or root Activity. I want to start a Service (say MyService) inside OnCreate of the MyApp and stop it when User logs out from my Application,
However I need a strong way to communicate between my Activities (A,B,C,D), MyApp and MyService. Now Application is launched second time from the Memory. OnCreate of MyApp will not be called so I would like to start the Service from OnClick of the SignIn button which is inside activity A. Now I have a number of questions :-

*

*I have tried both startService and bindService. Problem with startService is I don't get back the Service reference for future use. If I use bindService will that make my Service visible through out the Application life cycle till I explicitly stop it. Which way is applicable in my case ?

*What is the best way to implement communication between Service and MyApp / Activities and vice a verse ? By Communication I mean two type of communication, 1. that needs UI thread i.e. start some activity, show some dialog etc. 2. Something like myService.doSomehing().

*The Service has a thread which does network communication which should not be closed during the life time of the Application. START_STICKY will work for me or I need to make extra arrangements for that.
This app is supposed to run for GingerBread+ devices...

A: Bind the service inside your extended app oncreate and create a public method
(getBinding) which returns that binding object ... In your root/default activity 'A' oncreate via getBinding method on casted getApplication object retrieve .. unbind when all activities close (keep counter with each getBinding method)
check this Cleanly binding/unbinding to a Service in an Application
so for 1) Bind service
2) the binding obj
3) START STICKY would be enough


text:
Q: Where are the immune people being kept safe? I just finished the Maze Runner trilogy (the last book of the series which is The Death Cure) and I'm not really satisfied with the ending of the last book
At the end of the book all of the immunes ("munies")are to be put somewhere safe and the other people (outside) will be dead because of the Flare. But until that time, the immune ones must survive.
I really don't understand what kind of place could keep them safe. How can they provide food to avoid starvation, etc. Or is that place couldn't be a place that sick people can't get there. It can't be isolated outside of the world in the end. The place is still on Earth?
Where were they being kept and why was it safe?

A: after Thomas escapes the vivisection he rescues the immunes from the maze and takes them to the flat trans that Ava Paige has hidden in the maintenance room where Thomas and the gang used to hang out they take it to Greenland which is an isolated island that because of plate tectonics has shifted to become the perfect temperature


text:
Q: How do I Change Status Bar Color only on a Specific Page in Flutter How do I change Status Bar Color only on a Specific Page in Flutter? I tried using AnnotatedRegion but it Change the status bar Color of the Whole app.

A: I wrap my main views/screens like this.
StatusBarColorChanger(
      isDark: true ,
      child: Scaffold(

I created a widget for this, if you need more customization.
and you have wrap every pages

class StatusBarColorChanger extends StatelessWidget {
  final Widget child;

  final bool isDark;

  StatusBarColorChanger({
    Key? key,
    required this.child,
    this.isDark = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        // For Android.
        // Use [light] for white status bar and [dark] for black status bar.

        statusBarIconBrightness: isDark
            ? Platform.isAndroid
                ? Brightness.light
                : Brightness.dark
            : Brightness.dark,
        //  Platform.isAndroid? isDark ?  Brightness.light : Brightness.dark: ,

        statusBarColor: isDark ? Colors.black : Colors.white,

        // For iOS.
        // Use [dark] for white status bar and [light] for black status bar.
        statusBarBrightness: isDark
            ? Platform.isAndroid
                ? Brightness.dark
                : Brightness.light
            : Brightness.light,
      ),
      child: Platform.isAndroid
          ? SafeArea(
              child: child,
            )
          : child,
    );
  }
}


text:
Q: Inconsistent behavior of Renderscript I've written following renderscript:
ushort* curve_hth;
ushort* curve_hts;
ushort* curve_htv;
ushort* curve_sth;
ushort* curve_sts;
ushort* curve_stv;
ushort* curve_vth;
ushort* curve_vts;
ushort* curve_vtv;

uchar4 RS_KERNEL transform(uchar4 in, uint32_t x, uint32_t y)
{
    if(!isSelected(x, y)) return in;

    ushort3 in_rgb = { (ushort) in.r, (ushort) in.g, (ushort) in.b };
    ushort3 in_hsv = rgb_to_hsv(in_rgb);
    ushort in_h = in_hsv.r;
    ushort in_s = in_hsv.g;
    ushort in_v = in_hsv.b;
    ushort out_h, out_s, out_v;
    rsDebug("out1", out_s);
    if(curve_hth != NULL) out_h += curve_hth[in_h]; else out_h += in_h;
    rsDebug("out2", out_s);
    if(curve_hts != NULL) out_s += curve_hts[in_h];
    rsDebug("out3", out_s);
    if(curve_htv != NULL) out_v += curve_htv[in_h];
    rsDebug("out4", out_s);
    if(curve_sth != NULL) out_h += curve_sth[in_s];
    rsDebug("out5", out_s);
    if(curve_sts != NULL) out_s += curve_sts[in_s]; else out_s += in_s;
    rsDebug("out6", out_s);
    if(curve_stv != NULL) out_v += curve_stv[in_s];
    rsDebug("out7", out_s);
    if(curve_vth != NULL) out_h += curve_vth[in_v];
    rsDebug("out8", out_s);
    if(curve_vts != NULL) out_s += curve_vts[in_v];
    rsDebug("out9", out_s);
    if(curve_vtv != NULL) out_v += curve_vtv[in_v]; else out_v += in_v;
    rsDebug("out10", out_s);

    out_h = min((float) out_h, (float) 360);
    out_s = min((float) out_s, (float) 100);
    out_v = min((float) out_v, (float) 100);

    ushort3 out_hsv = { out_h, out_s, out_v };
    ushort3 out_rgb = hsv_to_rgb(out_hsv);
    uchar4 out = { out_rgb.r, out_rgb.g, out_rgb.b, in.a };
    return out;
}

When I run that script, I get in logcat:
D/RenderScript: out1 0  0x0
D/RenderScript: out2 0  0x0
D/RenderScript: out3 255  0xff
D/RenderScript: out4 255  0xff
D/RenderScript: out5 255  0xff
D/RenderScript: out6 255  0xff
D/RenderScript: out7 255  0xff
D/RenderScript: out8 255  0xff
D/RenderScript: out9 255  0xff
D/RenderScript: out10 255  0xff

It surprised me a lot, because all the curve_?t? pointers should be null, I don't bind them in Java code. It was strange, so I modified the debugging part of script and I got:
if(curve_hth != NULL) out_h += curve_hth[in_h]; else out_h += in_h;
rsDebug("out1", out_s);
rsDebug("out2", curve_hts == NULL);
if(curve_hts != NULL)
{
    out_s += curve_hts[in_h];
    rsDebug("out3", 1);
}
rsDebug("out4", out_s);
if(curve_htv != NULL) out_v += curve_htv[in_h];
if(curve_sth != NULL) out_h += curve_sth[in_s];
if(curve_sts != NULL) out_s += curve_sts[in_s]; else out_s += in_s;
if(curve_stv != NULL) out_v += curve_stv[in_s];
if(curve_vth != NULL) out_h += curve_vth[in_v];
if(curve_vts != NULL) out_s += curve_vts[in_v];
if(curve_vtv != NULL) out_v += curve_vtv[in_v]; else out_v += in_v;
rsDebug("out5", out_s);

The result in logcat was:
D/RenderScript: out1 0  0x0
D/RenderScript: out2 1  0x1
D/RenderScript: out4 25004  0x61ac
D/RenderScript: out5 25004  0x61ac

out2 is 1, so curve_hts is NULL. There is no out3 log, the if instruction doesn't get called, so how out_s changes its value?

A: Local variable out_h, out_s, out_v are not initialized, so the behavior is undefined.
ushort out_h, out_s, out_v;

If you initialize them to be 0, I think the problem should be gone.


text:
Q: Is it possible to use one phone number and redirect all calls to a VOIP server? I am working on a project that records incoming phone calls. I am new to VOIP and SIP technology so everything is a bit vaque.
If i understand it correctly you have to use the SIP protocol to make phone calls from a 'hard phones' to a VOIP server? if so do i only need to buy one phone number at a SIP provider? and will every call be redirected to the VOIP server that handles the call?
I am asking this, because the project has to deal with a lot of incoming callers so i want to keep the costs as low as possible.


text:
Q: Can not generate p:datatable in h:panelgrid values on ajax p:commandbutton update I am developing a project in JSF2.1 ,prettyfaces, hibernate 4 , primefaces
I am getting a problem here… I ve one p:commandbutton which calls ajax request where condition checks that, financial year is opened or not

There are 3 value… if financial year is opened then '1' if financial year is closed then '0' if invalid then ' -1'
If financial year is closed or invalid then an image is loaded with some text ,but problem is here
If financial year is opened then I want to generate a p:dataTable
<h:panelGrid columns="2" id="isFinancialYearBooleanPanelGridId" styleClass="panelGridCenter" >
<h:column>
<ui:fragment rendered="#{budgetAnalysisAction.budgetFinancialYearBean.financialYearForProposalsBean == '-1'}">
<ui:fragment rendered="#{budgetAnalysisAction.util.errorCode == '-1'}" >
<h:outputText  value="<div class='n_error'><p>Error . #{budgetAnalysisAction.util.errorMessage}</p></div>" escape="false"/>
</ui:fragment>
</ui:fragment>
<ui:fragment rendered="#{budgetAnalysisAction.budgetFinancialYearBean.financialYearForProposalsBean == '0'}">
<ui:fragment rendered="#{budgetAnalysisAction.util.errorCode == '-1'}" >
<h:outputText  value="<div class='n_error'><p>Error . #{budgetAnalysisAction.util.errorMessage}</p></div>" escape="false"/>
</ui:fragment>
</ui:fragment>
</h:column>
<h:column>
<ui:fragment rendered="#{budgetAnalysisAction.budgetFinancialYearBean.financialYearForProposalsBean == '1'}">

… HERE ARE SOME COLUMNS

</ui:fragment>
</h:column>
</h:panelGrid>

When I submit the command button update=" isFinancialYearBooleanPanelGridId scenarioTabViewId:budgetAnalysisDataTableId"
It will process successfully when financial year is closed or invalid
But it will not generate p:dataTable id="budgetAnalysisDataTableId values when financial year is opened
but when i put

… HERE ARE SOME COLUMNS

outside the
<h:panelGrid columns="2" id="isFinancialYearBooleanPanelGridId" styleClass="panelGridCenter" >

p:dataTable works fine for me
Any idea thanks (Y)
Here is my full xhtml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <h:outputStylesheet name="style.css" library="css" target="head"/>
    <h:outputScript name="validate.js" library="js" target="head"/>
    <h:outputScript name="jsf.js" library="javax.faces" target="head" />
    <h:outputStylesheet name="login.css" library="css" target="head"/>

</h:head>

<h:body >

hello

<ui:composition template="/template/mastertemplate.xhtml">

    <ui:define name="content">
<f:view>

Formation's Proposal

                    <h:form styleClass="form" prependId="false" id="anaForm">

                                                            <h:panelGrid columns="4" id="isFinancialYearPanelGridId">
                                                                        <h:column>
                                                                                <h:outputLabel value="Enter financial year " />
                                                                        </h:column>
                                                                        <h:column>

 -
                                                                        </h:column>
                                                                        <h:column>

                                                                        </h:column>
                                                                        <h:column>

                                                                        </h:column>
                                                            </h:panelGrid>

                                                <h:panelGrid columns="2" id="isFinancialYearBooleanPanelGridId" styleClass="panelGridCenter" >
                                                        <h:column>
                                                                <ui:fragment rendered="#{budgetAnalysisAction.budgetFinancialYearBean.financialYearForProposalsBean == '-1'}">
                                                            <ui:fragment rendered="#{budgetAnalysisAction.util.errorCode == '-1'}" >
                                                                    <h:outputText  value="<div class='n_error'><p>Error . #{budgetAnalysisAction.util.errorMessage}</p></div>" escape="false"/>
                                                            </ui:fragment>
                                                        </ui:fragment>
                                                        <ui:fragment rendered="#{budgetAnalysisAction.budgetFinancialYearBean.financialYearForProposalsBean == '0'}">
                                                            <ui:fragment rendered="#{budgetAnalysisAction.util.errorCode == '-1'}" >
                                                                    <h:outputText  value="<div class='n_error'><p>Error . #{budgetAnalysisAction.util.errorMessage}</p></div>" escape="false"/>
                                                            </ui:fragment>
                                                        </ui:fragment>

                                                        </h:column>
                                                        <h:column>

                                                             <ui:fragment rendered="#{budgetAnalysisAction.budgetFinancialYearBean.financialYearForProposalsBean == '1'}">

                                                                            <h:outputText value="#{budgetScenarioHescoProposalList.budgetSubHeadOfAccountsBean.subHeadOfAccountNameBean}" />

                                                             </ui:fragment>

                                                        </h:column>
                                                </h:panelGrid>

                    </h:form>

</f:view>
    </ui:define>

</ui:composition>
</h:body>

A: I would like to add this as comment, but maybe I found what is your problem:
In p:commandbutton you have:
update="isFinancialYearBooleanPanelGridId scenarioTabViewId:budgetAnalysisDataTableId"

Shouldn't it be (did you eat colon?)
update="isFinancialYearBooleanPanelGridId:scenarioTabViewId:budgetAnalysisDataTableId"

A: i ve solved my problem using
.java
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.addCallbackParam("budgetFinancialYearBean", this.budgetFinancialYearRefObj);

.xhtml

.js
function handleComplete(xhr, status, args) {

var financialYearForProposalsBeanVar = args.budgetFinancialYearBean.financialYearForProposalsBean;
    if(financialYearForProposalsBeanVar == 1) {
        //rendering data table
    //  alert('value: '+financialYearForProposalsBeanVar);
        document.getElementById("budgetAnalysisDataTableDivId").style.display = "block";
    }

}


text:
Q: How to access browser console in AIDE for error checking Is there an equivalent of the browser console in AIDE? It took me trial and error to find out that it doesn't seem to support local storage (or at least the library that I'm usings implementation of it)
Should I wrap everything in one big try Catch block? I've googled and searched, I suspect I should be doing better error handling.

A: Here's what I ended up doing. You can share the published web app from aide when you're running it. Open it in Firefox for Android after downloading the console add-on. It's not as fully featured as a desktop version but it's close
It feels like  poor form to answer ones own question, I earnt the tumbleweed badge for this so perhaps I can be forgiven!


text:
Q: Running npm test in a debug terminal in VSCode I'm trying to create a configuration in my launch.json which will run npm test in the folder in which the .js file resides.  Running npm test manually in a terminal works fine, taking the relevant command from the scripts part of my package.json:
"scripts": {
    "start": "node --experimental-json-modules nodeserver.js",
    "test": "export MY_VAR=abc && node --experimental-json-modules nodeserver.js"
},

In particular, when running npm test directly in a terminal, the env var specified in the test script line takes effect and the --experimental-json-modules flag is passed to node.
This is my launch.json:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "command": "npm test",
            "name": "Run npm test",
            "request": "launch",
            "type": "node-terminal"
        }
    ]
}

This is pretty much as-is from one of the predefined options suggested in the editor, and is very similar to this.
But when I run this configuration on the nodeserver.js file, I get:

It seems to be running node without the flag I specified in the configuration?  What am I misunderstanding about how this launch.json scheme works?
EDIT the more I've played around, the more it seems as if the configuration is just being completely ignored, so that it is using the default node.js configuration... I'm selecting the config from the drop-down and pressing the play icon:

Should that work?
Apart from running npm start in a terminal, the only "automatic" way of getting this to work is by opening the package.json and clicking on the little Debug button which appears by the scripts tag:

But I'd like to figure out how to use launch.json properly so that I can pass environments variables etc via that instead.

A: launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\\index.js"
        },
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Run Test",
            "skipFiles":
            [
                "<node_internals>/**"
            ],

            // You can specify enviorment variables per config here
            // using key value pairs
            "env":
            {
                "test_variable": "test value"
            },

            // You can also specify a .env file that contains them
            "envFile": "${workspaceFolder}/.env",

            // Here you specify the file you want launched
            "program": "${workspaceFolder}\\test.js",

            // add args to nodejs here
            "runtimeArgs":
            [
                "--experimental-json-modules"
            ],
        }
    ]
}

For reference:
https://code.visualstudio.com/docs/nodejs/nodejs-debugging

A: You can try to create the npm test script directly in your launch.json as above:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "name": "Run npm test",
        "request": "launch",
        "type": "node",
        "args": ["--experimental-json-modules", "${workspaceFolder}/nodeserver"],
        "env": {
           "MY_VAR": "abc"
        }

    }
]
}


text:
Q: Custom Validationattribute not client-side working I ValidationAttribute below, which validates the information in two fields. It works, but always doing post. In client-side is not working.
What should I switch to ValidationAttribute work on client-side?
[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class SexoComTipoPessoa : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectInstance.GetType().GetProperty("TipoPessoaID");

        if (property == null)
            return new ValidationResult("Propriedade desconhecida: 'TipoPessoaID'");

        var propertyValue = property.GetValue(validationContext.ObjectInstance, null);

        /* Tipo de pessoa 2 - é pessoa juridicia */
        if (Convert.ToInt32(propertyValue) == 2)
        {
            if (Convert.ToInt32(value) != 3)
                return new ValidationResult("Para o tipo de pessoa 'Juridíca', deve ser selecionado o sexo 'Não aplicavél'!");
        }
        else if (Convert.ToInt32(propertyValue) == 1)
        {
            if (Convert.ToInt32(value) == 3)
                return new ValidationResult("Para o tipo de pessoa 'Física', deve ser selecionado o sexo 'Masculino' ou 'Feminino'!");
        }

        return ValidationResult.Success;
    }
}

A: Do you need create a method in jquery.validation for this.
Look this example for helping:
Jquery Validation - Condition Method


text:
Q: Skype and Google+ on Ubuntu 13.10 I am thinking about installing Ubuntu 13.10 in my computer, but I am afraid because I must use vídeo chat with Skype... I've seen few pictures of someone's image using Skype, but does it really work easily? And what about Google+?
Thank you!

A: In my experience skype works pretty well without issue. If you want to use google's version you can download the chrome browser for linux here: https://www.google.com/intl/en/chrome/browser/?platform=linux

A: Skype work flawless in Ubuntu.
you can download & install it with
wget http://download.skype.com/linux/skype-ubuntu-precise_4.2.0.11-1_i386.deb
sudo dpkg -i skype-ubuntu-precise_4.2.0.11-1_i386.deb

If you get any unmet dep's
sudo apt-get install -f

thats it.It will install Skype in your Ubuntu.
Google+ and hangouts are works flawlessly with Firefix , Google Chrome, chromium. you can use any of these browsers.


text:
Q: Is there a Python function that can iterate through a dataset and calculate the Euclidean distance from a given initial point? For example, if my initial point is [2.4524 6.52424], how can I iterate through an array of 20 other points and find the 4 furthest points?

A: Use math.hypot:
point = [2.4524, 6.52424]
sorted(points, key=lambda p: math.hypot(p[0] - point[0], p[1] - point[1]))[-4:]


text:
Q: Execute In Query For ResultSet Zend Framework 2? I want to get 3 separate row from 'cms' table.but all time i only got first row why?
My Cms.php page is:
    <?php
    namespace Front\Model;
    use Zend\Db\TableGateway\AbstractTableGateway;

    class Cms extends AbstractTableGateway {

        public function __construct($adapter) {
            $this->table = 'cms';
            $this->adapter = $adapter;
        }
        public function getCmsContent($id){
            $id  = (int) $id;
            $rowset = $this->select(array('id'=>$id));
            if (!$row = $rowset->current()){
                throw new \Exception ('Row not found');
            }
            return $row;
        }
    }

My Controller is :FrontController.php is:

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Front\Model\Cms;
use Front\Model\Setting;
use Front\Model\Slider;
class FrontController extends AbstractActionController
{
    public function indexAction()
    {

        $this->layout()->slider_data = $this->getSlider()->fetchAll();
        $this->layout()->setting_data = $this->getSetting()->getSettingContent(1);
        return array('cms_data'=>$this->getCms()->getCmsContent('1,2,3'));
    }
    public function getSlider(){
        return $this->getServiceLocator()->get('Front/Model/Slider');
    }
    public function getCms(){
        return $this->getServiceLocator()->get('Front\Model\Cms');
    }
    public function getSetting(){
        return $this->getServiceLocator()->get('Front/Model/Setting');
    }
}

My Model is:

namespace Front;

class Module
{
    public function getAutoloaderConfig()
    {
        return array('Zend\Loader\StandardAutoloader' =>
            array('namespaces' =>
                array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
    // Add this method:
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Front\Model\AlbumTable' =>  function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $table     = new \Front\Model\AlbumTable($dbAdapter);
                    return $table;
                },
                'Front\Model\Cms' =>  function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $table     = new \Front\Model\Cms($dbAdapter);
                    return $table;
                },
                'Front\Model\Setting' =>  function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $table     = new \Front\Model\Setting($dbAdapter);
                    return $table;
                },
                'Front\Model\Slider' => function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $table     = new \Front\Model\Slider($dbAdapter);
                    return $table;
                },
            ),
        );
    }
}
?>

My View:index.php Page is:
 <?php print_R($cms_data); ?>

A: try this code block and change the $condition according to you
public function getCmsContent($id){
    $id  = (int) $id;
    $select = new Select();
    $select->from(array('t' => $this->table))
            ->where(array($condition));

    $statement = $this->adapter->createStatement();
    $select->prepareStatement($this->adapter, $statement);
    $result = $statement->execute();

    $rows = array();
    if ($result->count()) {
         $rows = new ResultSet();
         return $rows->initialize($result)->toArray();
    }

}

A: You try:
class Cms extends AbstractTableGateway {

    public function __construct($adapter) {
        $this->table = 'cms';
        $this->adapter = $adapter;
    }
    public function getCmsContent($id){
        return $this->select(array(
                new Expression('id IN (?)', array($id)),
        ));
    }
}

Get contents
$contents = $this->getCms()->getCmsContent(array(1, 2, 3));

$results = array();
foreach($contents as $content){
     $results[] = $content;
}
print_r($results);


text:
Q: Using Property Placeholder for Bean ID In Spring 3.1, is it possible to use a property placeholder to resolve the 'id' attribute of a bean?
I would like, for example, to do the following in my context.xml file:
<context:property-placeholder/>

<int:channel id="${channel.name}"/>

A: No, not for the id and the name attributes - this is based on what I have seen of how PropertySourcesPlaceholderConfigurer resolves the placeholders.


text:
Q: How do you send an email using PHP and also include a CC? This question has been asked many times. I have looked at the other ones. I think my problem is different.
The code works without the CC header. However when I put the CC header my Mac Mail application acknowledges the CC and it says "Downloading 2 mails" aka the mail that was sent in the $to and the new mail in the Cc... but the email in the CC never comes.
    <?php
       $to = "myEmail@gmail.com";
       $subject = "Test Email";
       $body = "Hi, This is a Test Email";
       $headers = "From: Test@MyWebsite.com \r\n";
       $headers .= 'Cc: myOtherEmail@gmail.com' . "\r\n";

       if ( mail($to, $subject, $body, $headers)) {
          echo("Email successfully sent to $to");
       } else {
          echo("Email sending failed...");
       }
    ?>

A: Ok guys...  I solved it... hopefully this helps somebody......
It only seems to work gmail to gmail. I don't know why. Hopefully someone with more experience can say why. But I tried @yahoo, @hotmail, @myWebsite emails in the $to and $from.


text:
Q: @PostMapping vs @DeleteMapping "Required String parameter 'name' is not present" I am using REST client for testing. I use exact same query, just changing method from POST to DELETE. I have same method in Spring Boot 2.0.1 - just changing annotation from @PostMapping to @DeleteMapping.
@DeleteMapping(value = "/receiver")
public ResponseEntity<Response> doOperation(@RequestParam(value = "name") String name) {
    return new ResponseEntity<>(HttpStatus.OK);
}

As soon as I change to DELETE I am getting error:
"Required String parameter 'name' is not present"

I have tested it with @PutMapping - works as well.
I am doing something wrong??
UPDATE 1
DELETE request:
DELETE /api/v1/wud/receiver?action=something HTTP/1.1
Cookie: PHPSESSID=e6b750be296f28174196817f126b367a
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: somehost:9443
Connection: close
User-Agent: Paw/3.1.7 (Macintosh; OS X/10.13.4) GCDHTTPRequest
Content-Length: 10

name=ASDEF

response is mentioned error
POST request:
POST /api/v1/wud/receiver?action=something HTTP/1.1
Cookie: PHPSESSID=e6b750be296f28174196817f126b367a
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: somehost:9443
Connection: close
User-Agent: Paw/3.1.7 (Macintosh; OS X/10.13.4) GCDHTTPRequest
Content-Length: 10

name=ASDEF

Response is 200
UPDATE 2
I was able to reproduce it in really simple setup using original spring example gs-rest-service. I have forked it on github HERE It's interesting that MockMvc test passes, but it doesn't work in reality.
I will fill a bug with Spring boot

A: This is not a problem with Spring but the embedded tomcat itself as the body of DELETE requests are usually ignored.
Here is a way around it.
For spring-boot 2.0+,
@Configuration
public class TomcatConfig implements TomcatConnectorCustomizer
{

    @Override
    public void customize(Connector connector) {
        connector.setParseBodyMethods("POST,PUT,DELETE");
    }
}

same can be done in spring-boot 1.5+ as shown below.
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
    return new TomcatEmbeddedServletContainerFactory(){
        @Override
        protected void customizeConnector(Connector connector) {
            super.customizeConnector(connector);
            connector.setParseBodyMethods("POST,PUT,DELETE");
        }
    };
}

But this is a bad practice. Because you ended up performing a POST but calling it a DELETE api.

A: One should not send payload with DELETE requests. DELETE request is like rm command where you ask server to remove the resource.
Sending a payload is undefined and may differ from server to server
From RFC:
A payload within a DELETE request message has no defined semantics;
sending a payload body on a DELETE request might cause some existing
implementations to reject the request.

Source: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5

A: From your question, it looks like you are using @RequestBody for your @PostMapping but on your @DeleteMapping you are using @RequestParam.
Also you are invoking your DELETE api with request body instead of a url parameter. From your request info, I see:
DELETE /api/v1/wud/receiver?action=something HTTP/1.1

But you have to invoke your delete API like this:
DELETE /api/v1/wud/receiver?action=something&name=something
                              Here ---------^^^^^

With curl you can use:
curl -X DELETE '{{url}}/api/v1/wud/receiver?action=something&name=something'

On the other hand, if name param is not mandatory, then you can use:
@RequestParam(value = "name", required = false) String name


text:
Q: Outlook Refresh Interval for iCal subscriptions (webcal://) When Outlook 2007 and 2010 subscribe to an internet calendar (via a webcal:// link to an iCalendar or vCalendar file), how often do they auto-update?  Is there a way to configure this, either in the file downloaded or in Outlook preferences?  I know the file can specify a minimum refresh interval (via the X-PUBLISHED-TTL field), but I don't see a way to explicitly specify a recommended interval.

A: With many calendars being integrated into the Cloud, these settings (X-PUBLISHED-TTL and REFRESH-INTERVAL) no longer work on Google Calendar and many newer versions of Outlook. I've tested this myself.
If you think about it, Google and Outlook likely and intentionally ignore any specified refresh rate to prevent DNS attacks. Basically, with millions of integrated calendars in their systems, some people could set a refresh rate every second and if they obey these settings, it could crash their servers. So, it's likely that they refresh whenever they feel like it.

A: I have Outlook 2017. Under "Send/Receive" you can select "Send/Receive Groups" and then define a new group for the internet calendar with a unique sync time.

A: For Outlook 2013 if you hit send/receive that will sync the calendars as well.
To adjust that interval go to File > Options > Advanced then scroll down to find Send/Receive. The options to adjust the intervals for auto Send/Receive are found there.

A: Outlook relies on the custom property X-PUBLISHED-TTL to set the download frequency but unless set in the file you subscribe to, there is no way to force within outlook an update frequency (nor in google calendar).

A: (My answer from Mar 2014 doesn't work anymore.)
To trick Outlook into refreshing an Internet Calendar, go to
File:: Account Settings:: Account Settings (button):: Internet Calendars (tab)
Then choose the calendar you wish to refresh, click "Change...", stick a space in the description (or remove a space), then click OK.
Your calendar should now be refreshed.


text:
Q: Apache Cordova : Office 365 API SharePointClient | How To download one drive files? I am able to list all the files that i have for my one drive account but need to know how I could download them to my Android or Windows mobile phone.
I tried using the weburl that I receive from the item but looks like it will need the token.
Current JavaScript code :
var AuthenticationContext = new O365Auth.Context();
var discoveryContext = new O365Discovery.Context(); // new DiscoveryServices.Context(new AuthenticationContext(authUrl), appId, redirectUrl);
discoveryContext.services(AuthenticationContext.getAccessTokenFn('Microsoft.SharePoint')).then(function (capabilities) {
    capabilities.forEach(function (v) {
        if (v.capability === 'MyFiles') {
            var msg = "";
            var sharePointnew = new Microsoft.CoreServices.SharePointClient(v.resourceId + '/_api/v1.0/me/',
                        AuthenticationContext.getAccessTokenFn(v.resourceId));

            Microsoft.FileServices.FileFetcher

            var elementInfo = document.getElementById('popup_body');
            document.getElementById('popup_header').innerHTML = "My One Drive Files";
            /* This should open a popup */
            document.getElementById('popup_div').style.display = "block";
            document.getElementById('popup_overlay').style.display = "block";
            elementInfo.innerHTML += 'One Drive Files:';

            var fileName = 'demo.txt';

            var store = cordova.file.dataDirectory;

            var fileTransfer = new FileTransfer();
                console.log("About to start transfer");

           sharePointnew.files.getItems().fetch().then(function (result) {
                msg = '';
                result.currentPage.forEach(function (item) {

                    elementInfo.innerHTML += "
" + item.name + "
";
                    fileTransfer.download(item.webUrl, store + fileName,
                    function (entry) {
                        console.log("Success!");

                    },
                        function (err) {
                            console.log("Error");
                            console.dir(err);
                        });

                    msg += item._odataType + ' "' + item.name + '"\n';
                    var s = "";
                });

                console.log('All file system items: \n' + msg);
            }, function (error) {
                console.error(error);
            });
        }
    });


text:
Q: transition rate diagram for M/M/1 queue I do not know how to   create the following diagram by using tikz.

How do I create this?

A: You can draw arrows with the command
\draw[->] (0,0)--(1,0);

You can add the greek letters with nodes
\node[below] at (0,0) {\lambda};

You can draw the dots with
\draw[fill] (0,0) circle (2pt);

With these elements you can create your diagramm.


text:
Q: Filter on second left join - SQL I have three tables. One consists of customers, one consists of products they have purchased and the last one of the returns they have done:
Table customer
CustID, Name
  1,     Tom
  2,     Lisa
  3,     Fred

Table product
CustID, Item
  1,     Toaster
  1,     Breadbox
  2,     Toaster
  3,     Toaster

Table Returns
CustID, Date, Reason
  1,     2014, Guarantee
  2,     2013, Guarantee
  2,     2014, Guarantee
  3,     2015, Guarantee

I would like to get all the customers that bought a Toaster, unless they also bought a breadbox, but not if they have returned a product more than once.
So I have tried the following:
SELECT * FROM Customer
 LEFT JOIN Product ON Customer.CustID=Product.CustID
 LEFT JOIN Returns ON Customer.CustID=Returns.CustID
WHERE Item = 'Toaster'
AND Customer.CustID NOT IN (
Select CustID FROM Product Where Item = 'Breadbox'
)

That gives me the ones that have bought a Toaster but not a breadbox. Hence, Lisa and Fred.
But I suspect Lisa to break the products on purpose, so I do not want to include the ones that have returned a product more than once. Hence, what do I add to the statement to only get Freds information?

A: How about
SELECT * FROM Customer
LEFT JOIN Product ON Customer.CustID=Product.CustID
WHERE Item = 'Toaster'
AND Customer.CustID NOT IN (
    Select CustID FROM Product Where Item = 'Breadbox'
)
AND (SELECT COUNT(*) FROM Returns WHERE Customer.CustId = Returns.CustID) <= 1

A: The filter condition goes in the ON clause for all but the first table (in a series of LEFT JOIN:
SELECT *
FROM Customer c LEFT JOIN
     Product p
     ON c.CustID = p.CustID AND p.Item = 'Toaster' LEFT JOIN
     Returns r
     ON c.CustID = r.CustID
WHERE c.CustID NOT IN (Select p.CustID FROM Product p Where p.Item = 'Breadbox');

Conditions on the first table remain in the WHERE clause.
As a note:  A table called Product that contains a CustId seems awkward.  The table behaves more likes its name should CustomerProducts.

A: You use conditional COUNT
SELECT C.CustID, C.Name
FROM Customer C
JOIN ( SELECT CustID
       FROM Products
       GROUP BY CustID
       HAVING COUNT(CASE WHEN Item = 'Toaster' THEN 1 END) > 1
          AND COUNT(CASE WHEN item = 'Breadbox' THEN 1 END) = 0
     ) P   -- Get customer with at least one Toaster and not Breadbox
  ON C.CustID = P.CustID
JOIN ( SELECT CustID
       FROM Returns
       HAVING COUNT(*) < 2
     ) R   -- Get only customers with less than 2 returns
  ON C.CustID = R.CustID


text:
Q: Cypress element in for loop changes after first iteration I want to have a cypress test that duplicates for different values in an array. This is simple enough but in this particular case I also have a for loop inside...
let extraString = [
   ['X', 'X'],
   ['Y', 'XY'],
   ['Z', 'XY']
]

let fieldLimits = [
   ['Disputed delivery', 'Additional information', 2000],
   ['Request to redeliver', 'Special instructions', 60]
]

var element = cy.get('[cy=additionalInfo]')
if (field[1] == 'Special instructions') {
   element == cy.get('[cy=specialInstructions]')
}

element.should('be.visible').and('have.text', '')

//pastes a block of text in the field
element.then($span => {
   $span.text(generatedTextString)
})

for (let i = 0; i < 3; i++) {
   element
     .type(extraString[i][0])
     .should('have.text', generatedTextString + extraString[i][1])

   var remaining = 1 - i
   if (i == 2) {
     remaining = 0
   }

   cy.get('[class*=charsRemaining]')
     .should('contain.text', 'Characters remaining: ' + remaining)
}

The first pass of the for loop is fine where i=0 but when it comes to the second pass when i=1, the wrong element is being typed in. Instead of 'element' it actually tries to type in cy.get('[class*=charsRemaining]'). If I take out the assertion so the loop becomes...
for (let i = 0; i < 3; i++) {
  element
   .type(extraString[i][0])
   .should('have.text', generatedTextString + extraString[i][1])

}

... then this works fine. Also if I do away with the 'element' substitute...
for (let i = 0; i < 3; i++) {
   cy.get('[cy=additionalInfo]')
     .type(extraString[i][0])
     .should('have.text', generatedTextString + extraString[i][1])

   var remaining = 1 - i
   if (i == 2) {
     remaining = 0
   }

   cy.get('[class*=charsRemaining]')
     .should('contain.text', 'Characters remaining: ' + remaining)
}

... then this also works. Newish to JS so wondering if it's something to do with passing in the 'element' from outside the loop or the substitute of 'element' specifically?
Thanks

A: Okay so this seems to be to do with Cypress not using variable in the way I thought it would work... Cypress: Variables and Aliases
The code now works with he following change...
element.then($el => {
  for (let i = 0; i < 3; i++) {
      cy.wrap($el)
        .type(extraString[i][0])
        .should('have.text', generatedTextString + extraString[i][1])

      var remaining = 1 - i
      if (i == 2) {
        remaining = 0
      }

      createQueryPage
        .charactersRemaining()
        .should('contain.text', 'Characters remaining: ' + remaining)
  }
})


text:
Q: How to do fadeIn in jquery, and how to fit to all resulotions? I've had a little practice in HTML, CSS, etc. I've done a little ticker.
In this ticker you can write in a text box, press on a button, and what you wrote will appear under. you can write as much as you want but in the screen we can see only the last three messages.
All the code is in this jsfiddle.
JavaScript code:
$(document).ready(function(){

$("#send").click(function(){
    var removed = false;
    var d = new Date();

    var year = d.getFullYear();
    var month = d.getMonth()+1;
    var day = d.getDate();

    var outputDate = ((''+day).length<2 ? '0' : '') + day + '/' +
        ((''+month).length<2 ? '0' : '') + month + '/' +
         year ;

           var outStr = ((''+d.getHours()).length<2 ? '0' : '') + d.getHours() +':'+
        ((''+d.getMinutes()).length<2 ? '0' : '') + d.getMinutes();

    $(".element").animate({
        top:'+=3%'
    } , 400,  function(){
        if(removed == false)
    {
            removed=true;
            $('.third').remove();
            var temp1 = $('.first').html();
            var temp2 = $('.second').html();

            $('.first').remove();

            $('.elements .second').before('
'+
                ''+
                '
'+ outputDate +'
'+
                '
'+ outStr +'
'+
                '
'+ $('#input1').val()+
                '
'+ "Nina Pnina"+'
'+
                '
');

            $('.second').html(temp1);
            $('.elements .second').after('
'+temp2+'
');

        }
    $(".element").removeAttr("style");
        //$(".second").css("top","3%");
    });

  });
});

function clearContents(element) {
  element.value = '';
}

For now it's local on my pc so the photos will not appear in the jsfiddle, but it's quite understandable.
Now I want to do it more nice, so when a new message been sent, it will fade in and not just pop to the screen.
My second problem is that when I checked it on my laptop, all the ticker was a mess, I guess it's because the resolution. Does anyone know how can I fit the ticker to work on all resolutions?
Thanks!

A: use jquery .fadeIn(): http://api.jquery.com/fadeIn/
you apply this to the created element, such as:
$(".element").fadeIn('slow');

it depends on what you want to fadein, etc. i edited your fiddle: http://jsfiddle.net/addiktedDesign/2mDmC/3/
and added $(".first").fadeIn('slow');
as well as hiding the added element (display:none;) on : $('.elements .second').before('
'
on the resolution, i suppose you mean screen size, for which the background is an image, so is a bit complicated, would be better if you used css gradients, or flat color and use percentages for the widths, etc.


text:
Q: Using Ajax with PHP to send image to the page The user will enter some dimensions, click a button and see an image created with PHP (without a page refresh). The code I have so far is not putting the  image on the page, any idea would be greatly appreciated.
draw.html:

    <title>PHP Draw Test</title>

Test the PHP GD module

    Height:
    <input type="number" id="height" min=36 max=42 step=6 required />
    Width:
    <input type="number" id="width" value="50"/>
    <button id="SubmitRailing" type="button">Draw!</button>
    <button type="reset">Reset</button>

draw.js:
$(document).ready(function() {

    $('#SubmitRailing').click(function(){

        $.post("draw.php",
            {Height: $('#Height').val(), Width: $('#Width').val()},
            function(data){
                $('#DrawBox').html(data);
            }
        );
    });

});

draw.php:
<?php

$height = $_POST['Height'];
$width = $_POST['Width'];
$im = imagecreatetruecolor($width, $height);
$sand = imagecolorallocate($im, 222, 184, 135);
$white = imagecolorallocate($im, 255, 255, 255);

imagefill($im, 0, 0, $white);
imagecolortransparent($im, $white);
imagefilledrectangle($im, 4, 4, 50, 25, $sand);

imagepng($im, './drawtest.png');
imagedestroy($im);

echo '';
?>

UPDATE
syntax syntax syntax
I finally got this to work, modified from @gibberish example
data: { Height : Height, Width : Width},
success: function(data) {alert('This was sent back: ' + data);}

But when I tried to substitute my original statement:
function(data){$('#DrawBox').html(data);}

it would kill the script.
Finally this worked, I didn't think it should be neccessary but there you have it:
success: function(data){$('#DrawBox').html(data);}

A: This is because your inputs IDs are different from the ones retrieved in your $.post call: you've set your IDs to be both width and height and yet, you are retrieving them as #Width and #Height.
Have your jQuery code like so:
jQuery(function($) {
    $('#SubmitRailing').on('click', function(){

        $.post("draw.php",
            {Height: $('#height').val(), Width: $('#width').val()}, // note #height and #width
            function(data){
                $('#DrawBox').html(data);
            }
        );
    });

});

or have your HTML like so:

    Height:
    <input type="number" id="Height" min=36 max=42 step=6 required />
    Width:
    <input type="number" id="Width" value="50"/>
    <button id="SubmitRailing" type="button">Draw!</button>
    <button type="reset">Reset</button>

One of either solution will work.

A: This is not an answer, just some tips:
(1) Divide and conquer. Break up the problem into simple examples, and get each part working independently. For example, first just get the button to reveal a hidden div -- that shows that jQuery and the code are loaded and working properly.
$('#SubmitRailing').click(function(){
    $("hiddenDIV").show()
});

(2) Next, mod your draw.php page just to echo out the drawing to the screen. Ensure it is doing what you expect.
(3) Use the full $.ajax() format, instead of shorthand forms such as $.post(), $.get() or $.load().  Not only is the structure easier to troubleshoot, but you get additional capabilities.
See these posts for simple examples of AJAX:
A simple AJAX example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

UPDATE:
Further to your question, refactor your code thus:
<?php
    $ht = $_POST['height']; //initially, very good idea to keep the 3 vars different, for ease of reference
    echo $ht;
?>

$(document).ready(function() {
    $('#SubmitRailing').click(function(){
        var Height = $('#height').val(); <-- missing ending semi-colon
        var Width = $('#width').val(); <-- missing ending semi-colon
        $.ajax({
            type: "POST",
            url: "draw.php",
            data: 'height='+Height+ '&width=' +Width, // <=== changes
            success:function(data){
                alert('This was sent back: ' + data);
            }
        });
    });
});

NOTE THAT: AJAX cannot post to the same page -- it must post to a different PHP page. See this SO question.

Also ensure that you have loaded the jQuery libraries, usually in the head tags something like this:

If you use a CDN to load jQuery, as in the above example, it is probably already pre-loaded from other websites - especially if you load from googleapis or jquery.com CDN sites.

If you want some fast, free, 10-min refresher lessons on jQuery, find free video tuts here:
https://www.thenewboston.com/videos.php?cat=32
or at
https://phpacademy.org/videos/jquery-basics


text:
Q: "Uninitialized constant A::MyModule" error when include MyModule I'm getting this error when trying to use include MyModule "Uninitialized constant"
Here is my implementation:
a.rb
class A
  include MyModule

  puts ARRAY
end

my_module.rb
module MyModule
  ARRAY = [1,2,3]
end

A: Ruby doesn't know about MyModule because it doesn't read my_module.rb
Add at the top of a.rb
require_relative 'my_module'

if these files are in the same folder (or correct path to the file if not)


text:
Q: Net Link Linux User code bind socket call always fail for multicast group Id (non zero value) Hi am trying to implement net link user code and kernel code every thing works fine for unicast (src_addr.nl_groups = 0;). For mulicast, user code bind call always fails for non zero src_addr.nl_groups value. Really am not sure what value to put for multicast and how to proceed further. I checked the usage of netlink_broadcast in kernel source tree, so I put the same group Id value (RTMGRP_LINK) here. For unicast I found good number of help in internet but for multicast I don't think so . So Please help me to proceed further.
Error am getting is:
bind: No such file or directory
./a.out: can't bind socket (3)and err : -1: No such file or directory
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdio.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#define NETLINK_TEST 28
#define GROUP_IB 1
#define MAX_PAYLOAD 1024
struct sockaddr_nl src_addr, dst_addr;
struct nlmsghdr *nlh = NULL;
struct msghdr msg;
struct iovec iov;
int sock_fd;

int main(int argc, char ** argv)
{
    int err;
    sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TEST);
    if (sock_fd<0) {
            char s[BUFSIZ];
            sprintf( s, "%s: can't assign fd for socket", argv[0] );
            perror(s);
            return -1;
    }

    memset(&src_addr, 0, sizeof(src_addr));
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid();
    src_addr.nl_groups = 0; // Unicast
    //src_addr.nl_groups = RTMGRP_LINK; /* Multicast, bind call always fails for non zero values */

    err = bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr));
    perror("bind");
    if (err<0) {
            char s[BUFSIZ];
            sprintf( s, "%s: can't bind socket (%d)and err : %d", argv[0], sock_fd,err );
            perror(s);
            return -1;
    }

    memset(&dst_addr, 0, sizeof(dst_addr));
    nlh = (struct nlhmsghdr *) malloc(NLMSG_SPACE(MAX_PAYLOAD));
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));

    iov.iov_base = (void *)nlh;
    iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);
    msg.msg_name = (void *)&dst_addr;
    msg.msg_namelen = sizeof(dst_addr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    printf("pid : %d\n Waiting for messages from kernel...\n",getpid());
    recvmsg(sock_fd, &msg, 0);
    printf("Message : %s\n", NLMSG_DATA(nlh));
    close(sock_fd);

    return 0;

}

A: Netlink socket binds are sensitive to what USER you are- I've seen them reliably fail if you are not running the program in question as 'root', at least on RedHat 6.
Try running as root 1st, before changing your logic. If you get the same failure as you do in normal operation, then you know it isn't (necessarily) a permissions issue.

A: The issue is
sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TEST);
Does you kernel module define the NETLINK_TEST family? your own family might must be supported at kernel module and it should post the message in the proper group using nlmsg_multicast()
RTMGRP_LINK is group defined in NETLINK_ROUTE.
This sample code is example for multicast
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <sys/socket.h>
 #include <linux/netlink.h>
 #include <unistd.h>

 #define MYPROTO NETLINK_USERSOCK
 #define MYMGRP 21

 int open_netlink(void)
 {
    int sock;
    struct sockaddr_nl addr;
    int group = MYMGRP;

    sock = socket(AF_NETLINK, SOCK_RAW, MYPROTO);
    if (sock < 0) {
        printf("sock < 0.\n");
        return sock;
    }

    memset((void *) &addr, 0, sizeof(addr));
    addr.nl_family = AF_NETLINK;
    addr.nl_pid = getpid();

    /* addr.nl_groups = MYMGRP; */

    if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        printf("bind < 0.\n");
        return -1;
    }

    if (setsockopt(sock, 270, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) < 0) {
        printf("setsockopt < 0\n");
        return -1;
    }

    return sock;
}

void read_event(int sock)
{
    struct sockaddr_nl nladdr;
    struct msghdr msg;
    struct iovec iov;
    char buffer[65536];
    int ret;

    iov.iov_base = (void *) buffer;
    iov.iov_len = sizeof(buffer);
    msg.msg_name = (void *) &(nladdr);
    msg.msg_namelen = sizeof(nladdr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    printf("Ok, listening.\n");
    ret = recvmsg(sock, &msg, 0);
    if (ret < 0)
        printf("ret < 0.\n");
    else
        printf("Received message payload: %s\n", NLMSG_DATA((struct nlmsghdr *) &buffer));
}

int main(int argc, char *argv[])
{
    int nls;

    nls = open_netlink();
    if (nls < 0)
        return nls;

    while (1)
        read_event(nls);

    return 0;
}

kernel module:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netlink.h>
#include <net/netlink.h>
#include <net/net_namespace.h>

#define MYPROTO NETLINK_USERSOCK

#define MYGRP 21

static struct sock *nl_sk = NULL;

static void send_to_user(void)
{
    struct sk_buff *skb;
    struct nlmsghdr *nlh;
    char *msg = "Hello from kernel";
    int msg_size = strlen(msg) + 1;
    int res;

    pr_info("Creating skb.\n");
    skb = nlmsg_new(NLMSG_ALIGN(msg_size + 1), GFP_KERNEL);
    if (!skb) {
        pr_err("Allocation failure.\n");
        return;
    }

    nlh = nlmsg_put(skb, 0, 1, NLMSG_DONE, msg_size + 1, 0);
    strcpy(nlmsg_data(nlh), msg);

    pr_info("Sending skb.\n");
    res = nlmsg_multicast(nl_sk, skb, 0, MYGRP, GFP_KERNEL);
    if (res < 0)
        pr_info("nlmsg_multicast() error: %d\n", res);
    else
        pr_info("Success.\n");
}

static int __init hello_init(void)
{
    pr_info("Inserting hello module.\n");

    nl_sk = netlink_kernel_create(&init_net, MYPROTO, NULL);
    if (!nl_sk) {
        pr_err("Error creating socket.\n");
        return -10;
    }

    send_to_user();

    netlink_kernel_release(nl_sk);
    return 0;
}

static void __exit hello_exit(void)
{
    pr_info("Exiting hello module.\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");


text:
Q: How to redirect to non-zend link from zend application My application is mixture of simple PHP webpages and zend application. Sometime I need to redirect to simple PHP webpage from zend application's Action.
For example:
I want to redirect from example.com/module/controller/action to example.com/simplephp.php.
I tried header("Location: example.com/simplephp.php"); but it is not working.
Thanks

A: Yes, the basic redirect action helper allows you to redirect to any URL.
class MyController extends Zend_Controller_Action {
    public function indexAction() {

        $this->_redirect('/path/to/any/page.php');
        // or
        $this->_redirect('http://example.com/anypage.php');
    }
}

A: HTTP/1.1 requires an absolute URI as argument. Request should contain http:// or https://

A: You should manipulate the request object, which sends HTTP headers.
If you want to do:
header("Location: example.com/simplephp.php");

you need:
$request->setHeader('Location', 'example.com/simplephp.php', true);

Then you need to turn off the layout, view rendering and any other things which are not needed etc.
The easy way to handle the redirects without worrying too much about the details is the Redirector action helper. You may use it even outside the controller retrieving it's static instance from Helper Broker.
Note, that even if shortened URLs work in almost all of the browsers, you always should specify full URL for location (including protocol and domain name) as specified in HTTP 1.1.


text:
Q: Symfony2: inject security context into model classes I have propel classes that implement the preSave method. This is a hook where some fields can be automatically updated at each saving operation. This is needed in order to save the date of last update and the user of the last update.
The problem is that the model classes have no access to the service container, where I can get the user id (to set into the last update user field). Model classes cannot (at my knownledge) be declared as service, as these are kind of entities, instancied by propel itself and not by the service container.
The only solution I see is to have a "real" singleton (with a static instance) holding the user object, that I would instanciate during the bootstrap of the application, then any model class could access it.
Any better idea?

A: For anyone having the same propel, the given bundle only adds the EventDispatchor behavior to Propel, which means that you can manage propel events in the same as Symfony does, but it is separated from the Symfony container (it seams it is using it own container).
But glorpen/propel-bundle is doing this job very well, you can really define service that listen to Propel events, using simple tags.


text:
Q: Masstransit configuring a generic consumer I'm in the process of integrating a messaging broker within our existing application using MassTransit.
We had already implemented a kind of command handler that had generic implementations, like this:
public class MyCommandHandler: CommandHandlerBase<MyCommand>

Now it was relatively easy to make a generic Consumer that would do some boiler plating and would hand off the work to the ready command handler, requested from the DI container.
public class CommandConsumer<TCommand> : IConsumer<TCommand>

Which I could then easily register through the Microsoft DI thusly:
cfg.AddConsumer<CommandConsumer<MyCommand>>(x => some configuration...);

This all worked great, so I moved on to the next step, namely to extract the consumer registration(s) to a common helper method and this is where I'm a bit stumped. The method (currently) looks a bit like this
public static IServiceCollection ConfigureMassTransit(this IServiceCollection services, params Type[] consumerTypes)
{
        return
            services.AddMassTransit(cfg =>
            {
                foreach (var consumerType in consumerTypes)
                {
                    cfg.AddConsumer(consumerType);
                }
                // or cfg.AddConsumers(consumerTypes);
                cfg.AddBus(context => Bus.Factory.CreateUsingRabbitMq(config =>
                {
                    var host = config.Host("localhost", "/",
                        h =>
                        {
                            h.Username("guest");
                            h.Password("guest");
                        });
                    config.ConfigureEndpoints(context);
                }));

            });
    }

which would be called as services.ConfigureMassTransit(typeof(CommandConsumer<MyCommand>));
This again works, but what I can't figure out is how to add the additional configuration to the registration; the overload that takes an Action is only available when using the generic signature, which you can't use directly when you only have the Type available. I tried adding a marker class CommandConsumer: IConsumer to the CommandConsumer<TCommand> and making CommandConsumerDefinition : ConsumerDefinition<CommandConsumer>, and changing the above to cfg.AddConsumer(consumerType, typeof(CommandConsumerDefinition));, but that doesn't work as the ConfigureConsumer override is never hit.
How am I supposed to add additional configuration to a Consumer for which I don't know the type at compile time?

A: Chris' answer put me on the path to a working solution. Making the CommandConsumerDefinition generic allowed me to use reflection to construct both types in the same way at runtime. This allowed MassTransit to wire up the configuration in the expected manner.
In the end, I also used a "marker" attribute that would hold the type of the command contract, so they could be discovered rather than having to be entered as a parameter at startup.
public static IServiceCollectionConfigurator ConfigureMassTransitConsumers(this IServiceCollectionConfigurator serviceConfigurator, Assembly assembly)
    {
        foreach (var type in assembly.GetTypes())
        {
            var attributes = type.GetCustomAttributes(typeof(RegisterCommandConsumerAttribute), false);
            if (attributes.Length <= 0) continue;
            foreach (var attribute in attributes)
            {
                if (attribute is RegisterCommandConsumerAttribute registerCommandConsumerAttribute)
                {
                    Type consumerType = typeof(CommandConsumer<>).MakeGenericType(registerCommandConsumerAttribute.CommandType);
                    Type consumerDefinitionType = typeof(CommandConsumerDefinition<>).MakeGenericType(registerCommandConsumerAttribute.CommandType);
                    serviceConfigurator.AddConsumer(consumerType, consumerDefinitionType);
                }
            }
        }
        return serviceConfigurator;
    }

Because of the automatic discovery, we were already in the realm of reflection, so this seemed like an acceptable solution. This way we can have generic consumers and definitions without having to add a new class for every command contract we have.


text:
Q: Fixed point for a function. Numerical Analysis. how might g defined such that the root of $f(x)=x^3-3x-1$ is a fixed point of $g$, for $x$ in the closed interval between $-\frac{1}{2}$ and $0$. Find two distinct functions $g_1$ and $g_2$ and investigate the rate of convergence for each case.
I can find three different such functions for $g$, do I just pick one or do I have an extra one by mistake?
My functions:
$g_1(x)=(x^3-1)/3$, $g_2(x)=(1+3x)^{1/3}$ and $g_3(x)=1/(x^2-3)$.
(also because I'm new to this website, can someone please link me a guide to use latex so that my question will look less confusing hopefully!)

A: $g_1$ converges linearly (in the nomenclature used in Numerical recipes) with a constant of about $0.1206$ (that is, if $x_0$ is the fixed point, then for small $\delta$
$$
g_1 : x_0 + \delta \rightarrow x_0 + 0.1206 \,\delta
$$
$g_3$ does a bit better but still converges linearly:
$$
g_3 : x_0 + \delta \rightarrow x_0 + 0.0838 \,\delta
$$
There is a linear combination of $g_1$ and $g_3$ that converges super-linearly:
$$
g_4(x) = 3.274316\ldots g_3(x) - 2.274316\ldots g_1(x) \\
g_4 : x_0 + \delta \rightarrow x_0 + 0.3288 \,\delta^2
$$

A: All three of these functions are good ones to have a fixed point where you want.  Yes, you can pick any two.  The root of interest is about $-0.3473$.  It might be nice to choose one stable and one unstable fixed point, but the question does not require that.

A: Hint: For a $g$ with quadratic convergence, try Newton's method for $f$.


text:
Q: responsive 2 columns don't line up at top I would like to create a simple 2-column responsive page - no footer or header, just the columns.  When I use the below code, the right column starts below and to the right of the first column. Surely I am missing something simple - not a tough thing for being pretty new to responsive design. (BTW, the columns will differ much in length than in this sample.)
CODE:

.container {
  max-width: 100%;
}
.lcol {
  float: left;
  padding: 1%;
  width: 33%;
  top: 0;
}
.rcol {
  float: right;
  padding: 1%;
  width: 65%;
  top: 0;
}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
@media screen and (max-width: 480px) {
  .lcol,
  .rcol {
    float: none;
    width: auto;
  }

    ---contentLEFT--- Lorem ipsum dolor sit amet,

    ---contentRIGHT--- Lorem ipsum dolor sit amet,

A: because your are not summing the width + padding correctly, therefore overflowing, it should be no more than 100%
You can use box-sizing:border-box so the padding and the border won't interfere in the calculations,

border-box
The width and height properties include the content, the padding and border, but not the margin. This is the box model used by Internet
  Explorer when the document is in Quirks mode. Note that padding and
  border will be inside of the box e.g.  .box {width: 350px; border:
10px solid black;} leads to a box rendered in the browser of width:
350px. The content box can't be negative and is floored to 0, making
  it impossible to use border-box to make the element disappear.

*,
*::before,
*::after {
  box-sizing: border-box
}
body {
  margin: 0
}
.container {
  max-width: 100%
}
.container > div {
  float: left;
  padding: 1%;
  border: 1px dotted red;
}
.lcol {
  width: 35%;
  background: lightgreen
}
.rcol {
  width: 65%;
  background: lightyellow
}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
@media screen and (max-width: 480px) {
  .lcol,
  .rcol {
    float: none;
    width: auto;
  }
}

    ---contentLEFT--- Lorem ipsum dolor sit amet,

    ---contentRIGHT--- Lorem ipsum dolor sit amet,

A:

.left{
  background-color:red;
  height:50vh;
}
.right{
  background-color:green;
  height:50vh;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    This is the left column.

    This is the right column.

Since you are new to the responsive design, I would suggest you to use Bootstrap. It is very easy to manage alignments using the column method that it provides. You can either download Bootstrap from here.  http://getbootstrap.com/getting-started/
Or use this CDN in the head tag of ur html file.
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
You can also learn the basics from www.w3schools.com.
This is the code that I've modified(using bootstrap)..


text:
Q: What is the fastest way to get "specific" combinations of different lists? My final goal is building a football squad (squad = 11 players)
And all these 11 players are connected to some others. To put it simply, you can just think it as "neural network architecture with 11 nodes".
Now imagine that I have a seperate list for each spot (node_area). GoalKeeper_List, LeftBack_List, CenterMid_List ... and so on.
Each list has 15 players. So a node area can only be filled by the corresponding 15 players.
There is just this rule: When a node has it's neighbours ready (meaning IT'S NEIGHBOURS are filled/not empty) then there is a function going... Function checks if that node is do well with it's neighbours. It either returns "OK", or "Not-OK".
If function returns "OK", then it's okay and I can continue adding players. But if function ever returns "Not-OK", then that means this squad is not going to work. Regardless of the other node statuses.
Remember that this function is going to run for every node, with parameters as its neighbours. But it can only run when that node's neighbours are ready.
So what I want is, given 11x15 players (11 seperate lists), I want my program to give me all possible squads. If there was no rule, it would be 15^11 possible squads. Which is 8.6~ trillion squads and impossible to compute. But with all those rules, it limits the options greatly. So when code runs it give results around 1-30000 usually. So it's very countable by computers. I know these numbers because I did many practices. But the problem is, my program runs so slow. It's because in my code I have 11 for loops inside each other. It's just grow like trees, and calculating all these stuff takes time. My code sometimes give results in 40 seconds, sometimes 10 minutes, and sometimes never... (even though there are some possible squads)
And I'm sure there must be a smarter way to work this code faster, I need a new approach to this problem.
Here is my code so you can have a better understanding whats going on:
let working_squads = []

let current_full_squad = []
for (gk of GK_List){

  for(cb1 of CB1_List){
    current_full_squad = [gk]

    for(cb2 of CB2_List){
      current_full_squad = [gk, cb1]

      let GK_status = get_player_status(gk, [cb1, cb2])
      if(GK_status === "Not-OK") continue

      for (lb of LB_List){
        current_full_squad = [gk, cb1, cb2]

        for (cm1 of CM1_List){
          current_full_squad = [gk, lb, cb1, cb2]

          let LB_status = get_player_status(lb, [cb1, cm1])
          if(LB_status === "Not-OK") continue

          for (cm2 of CM2_List){
            current_full_squad = [gk, lb, cb1, cb2, cm1]

            let CB1_status = get_player_status(cb1, [gk, cb2, lb, cm1, cm2])
            if(CB1_status === "Not-OK") continue

            for (cm3 of CM3_List){
              current_full_squad = [gk, lb, cb1, cb2, cm1, cm2]

              for (rb of RB_List){
                current_full_squad = [gk, lb, cb1, cb2, cm1, cm2, cm3]

                let RB_status = get_player_status(rb, [cm3, cb2])
                if(RB_status === "Not-OK") continue

                let CB2_status = get_player_status(cb2, [gk, cb1, cm2, cm3, rb])
                if(CB2_status === "Not-OK") continue

                for (cam of CAM_List){
                  current_full_squad = [gk, lb, cb1, cb2, rb, cm1, cm2, cm3]

                  let CM2_status = get_player_status(cm2, [cb1, cb2, cm1, cm3, cam])
                  if(CM2_status === "Not-OK") continue

                  for (st1 of ST1_List){
                    current_full_squad = [gk, lb, cb1, cb2, rb, cm1, cm2, cm3, cam]

                    let CM1_status = get_player_status(cm1, [lb, cb1, cm2, st1])
                    if(CM1_status === "Not-OK") continue

                    for (st2 of ST2_List){
                      current_full_squad = [gk, lb, cb1, cb2, rb, cm1, cm2, cm3, cam, st1]

                      let CM3_status = get_player_status(cm3, [cb2, rb, cm2, st2])
                      if(CM3_status === "Not-OK") continue

                      let CAM_status = get_player_status(cam, [cm2, st1, st2])
                      if(CAM_status === "Not-OK") continue

                      let ST1_status = get_player_status(st1, [cm1, cam, st2])
                      if(ST1_status === "Not-OK") continue

                      let ST2_status = get_player_status(st2, [cm3, cam, st1])
                      if(ST2_status === "Not-OK") continue

                      current_full_squad = [gk, lb, cb1, cb2, rb, cm1, cm2, cm3, cam, st1, st2]

                      working_squads.push(current_full_squad)

                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

}

console.log(working_squads.length.toString() + " squads found! Here are they...... ")

A: This method is not faster ( in theory ), but more elegant. It also returns varying sizes of the teams if one of the lists is completely rejected. If you want only the squads with a certain size, you will have to filter them out either after or in the function.
The approach is to recursively ask the same question: Given this team and a set of lists of other players, what are all the possible teams? The method itself asks of every player if they want to join and if the squad is okay with it, for every remaining player, but just one in a given list. If its okay, it adds it to the team and runs itself again with that team, except without the list of players it choose from.
class Player {
    constructor ( name ) {
        this.name = name;
        this.wontPlayWith = [];
    }

    AddRejectedPlayers ( ...player ) {
        this.wontPlayWith.push( ...player );
        return this;
    }

    WillPlayWith ( player ) { // just an example, you can implement this any way you want.
        return !this.wontPlayWith.includes( player );
    }
}

class Squad {
    constructor ( players ) {
        this.players = [ ...players ];
    }

    static MakeAllPossibleSquads ( acceptedPlayers, remainingPlayerLists ) {
        let result = ( remainingPlayerLists.length == 0 ) ? [ new Squad( acceptedPlayers ) ] : [];
        remainingPlayerLists = [ ...remainingPlayerLists ]; // just so we don't destroy the input list

        while ( remainingPlayerLists.length != 0 ) {
            let nextList = remainingPlayerLists.pop();

            for ( let i = 0; i < nextList.length; i++ ) {
                let nextPlayer = nextList[ i ];

                if ( acceptedPlayers.every( x => x.WillPlayWith( nextPlayer ) && nextPlayer.WillPlayWith( x ) ) ) {
                    result.push( ...Squad.MakeAllPossibleSquads( [ acceptedPlayers, nextPlayer ], remainingPlayerLists ) );
                }
            }
        }

        return result;
    }
}

console.log( Squad.MakeAllPossibleSquads( [], yourListOfPlayerLists ) );


text:
Q: How to specify labels per facet in ggplot2? I am using ggplot and I would like to label the scales in each facet of a plot manually. The concept is discussed here:
http://groups.google.com/group/ggplot2/browse_thread/thread/d2044ed0f91de98a
The solutions provided there work but I am still wondering if ggplot yet supports the option to provide scale labels per facet.
Thanks,

A: The answer is no. However, as you saw in the link you posted, there is grid.arrange::gridExtra. Another option is to use something that's originally from the ggplot2 book (I think that's the source, but examples abound on the internet)
p1 <- ggplot(diamonds, aes(depth, carat)) + geom_point()
p2 <- ggplot(diamonds, aes(price, carat)) + geom_point()
vplayout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
grid.newpage()
pushViewport(viewport(layout=grid.layout(4,6)))
print(p1,vp=vplayout(1:4,1:3))
print(p2,vp=vplayout(1:4,4:6))

This setup essentially plots a "dashboard". And you can control each plot individually, yet, keep them "beside eachother in any arrangement that you feel reasonable by changing the squares they fill (mess with the numbers 4, 6, 1:4, 1:3, 4:6)

A: You can use labeller option to specify labels for each facet.
See this link
Question


text:
Q: dojo.xd.js not recognizing dojox.data.CsvStore When I use an import such as
<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.2.3/dojo/dojo.xd.js"
      djConfig="parseOnLoad:true, isDebug: true"></script>

I get the error
dojox.data.CsvStore is not a constructor

for lines such as
var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"});

but the error vanishes if I use an import from a local installation of dojo such as
<script type="text/javascript" src="dojo-release-1.2.3/dojo/dojo.js"
     djConfig="parseOnLoad:true, isDebug: true"></script>

I would really want to be able to use a CDN hosted dojo installation. Is there a known problem between the DojoX libraries and dojo.xd.js?
Thanks in advance,
Animesh
P.S. The dojo.require("dojox.data.CsvStore"); declarations are in place.
P.P.S The full "working code" is below. Replacing the CSS and JS references with those from the CDN breaks it.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
        @import "dojo-release-1.2.3/dijit/themes/tundra/tundra.css";
        @import "dojo-release-1.2.3/dojo/resources/dojo.css"
    </style>
    <script type="text/javascript" src="dojo-release-1.2.3/dojo/dojo.js"
         djConfig="parseOnLoad:true, isDebug: true"></script>
    <script>
        dojo.require("dojox.data.CsvStore");
        dojo.require("dijit.Tree");
        dojo.require("dojo.parser");
    </script>
    <script type="text/javascript">
        var stateStore = new dojox.data.CsvStore({url: "states.csv", label: "name"});
    </script>

</head>
<body class="tundra">
    <div dojoType="dijit.Tree" store="stateStore" labelAttr="name" label="States">
    </div>
</body>
</html>

A: Are you running that code inside dojo.addOnLoad()?  As in:
dojo.addOnLoad(function(){
   dojo.require("dojox.data.CsvStore");
   var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"});
});

Also, are you using FireFox 3?  If so, try putting your <script></script> block at the very end of the <body> section, just before the closing </body> tag.  (I know that is not standard practice, but it's related to Firefox's bug 444322, which should be fixed in release 3.0.6.)
Other than that, your code seems to be fine, and such strange discrepancies usually boil down to issues of timing with the loading of dojo modules.

A: Reacting to your update:
I strongly think you should try with dojo.addOnLoad().  Together, the last two <script> sections of your <head> would become:
<script>
   dojo.addOnLoad(function(){
      dojo.require("dojox.data.CsvStore");
      dojo.require("dijit.Tree");
      dojo.require("dojo.parser");  /* I don't think you really need this line */
      var stateStore = new dojox.data.CsvStore({url: "states.csv", label: "name"});
   });
</script>

The problem with your original code is that you cannot guarantee that the constructor function dojox.data.CsvStore has been read by the time you are about to create your stateStore instance of it.  That's where dojo.addOnLoad() comes in, giving you a guarantee that the rest of the javascript was loaded prior to executing the abstract function passed as parameter of addOnLoad().
Because it's an issue of timing, your own original code may work sometimes, maybe not others:  it would depend on the download speed and the order in which your browser pieces together the various javascript bits.  That's why using dojo's remote library may occasionally give different results from using your own local copy of the dojo library.
That said, if you are using Firefox 3 (earlier than 3.0.6), then bear in mind what I said about the known bug.  In that case, you may want to put that <script> block immediately before the closing </body> tag...  (That option would work on other browsers as well.)

A: Pierdeux was correct on that that addOnLoad is the key, but it should have been after dojo.requires, not before. In addition, one has to switch from automatic djConfig.parseOnLoad (it fires before addOnLoad) to manually initiating parser. When you still change that store URL to point to some sensible location (on your site), this works:
<script>
   dojo.require("dojox.data.CsvStore");
   dojo.require("dijit.Tree");
   dojo.require("dojo.parser");
   dojo.addOnLoad(function(){
      stateStore = new dojox.data.CsvStore({url: "states.csv", label: "name"});
      dojo.parser.parse();
   });
</script>

Note: there's another very similar case: Grid, stores, XD.


text:
Q: Linux process monitoring daemon I'm often issuing commands that take some time. For example downloading something using a console download app. If I want to be noticed when the command has finished, I usually do something like this:
$ <do something>; echo '<do something> has finished' | osd_cat

Then I can switch to another window and do something else meanwhile. When it's done, I'll be noticed.
Now my problem is that I'm lazy. Oh well. I just don't want to type this everytime. So I wonder if there's a daemon that could watch running processes and trigger some actions when the processes finish.
I would like config options so I could have control on:

*

*filtering the processes to be watched (for example, watch processes that run at least for a minute)

*customizing the command to perform when a process has finished

A: You could try using Bash's "wait" command to write a little wrapper script
Something like:
#!/bin/bash
command=$*

$command &
wait
osd_cat "$command has finished"

The wait command causes the script to pause until all child processes have returned an exit code.
You could also add a little timeout to make sure that you don't wait too long

A: How about just a simple shell script that does the long command for you. Maybe something like this:
#!/bin/sh
# tellme: run a command and tell me when it's done
if [ $# -gt 0 ]; then
    if $*; then
        echo "'$*' has finished" | osd_cat
    else
        echo "'$*' has finished with errors" | osd_cat
    fi
else
    echo "usage: $0 <command>"
fi

Then, you would just run this command:

tellme <do something>

Granted, it isn't a daemon, so I don't think it will help you for things started in the background (e.g. from cron), but it should do the job for interactive commands.

A: Maybe it's not a daemon, but it serves the same purpose for me. zsh has scriptable hooks executed right before and right after executing any command. You can make them measure wallclock time and run any action (here: notify-send) if the last executed command was long enough. The following in an excerpt from my ~/.zshrc:
preexec () {
  ZSH_CMD_START_TIME="$(date +%s)"
  ZSH_CMD_NAME="$1"
}
precmd () {
  [[ -n "$ZSH_CMD_NAME" ]] && {
    ZSH_LAST_TIME=$(($(date +%s) - $ZSH_CMD_START_TIME))
    [[ $ZSH_LAST_TIME -gt 60 ]] && [[ -n "$DISPLAY" ]] && { which >/dev/null notify-send } && {
      notify-send --urgency=low --category=zsh --expire-time 1500 "ZSH:" '`'"$ZSH_CMD_NAME"'`'" took $ZSH_LAST_TIME seconds."
    }
    ZSH_CMD_NAME=
  }
}


text:
Q: C++ string.empty not working I'm trying to use .empty() so pressing enter in the following code will not execute the if statement and the do-while loop will break. When I try this code, hitting enter does nothing: it just continues indenting until I enter more data. I looked up .empty() and I think I am using it correctly. Why isn't this code working?
void Student::read()
{
string g = " ";

cout << "Enter the students name: ";
getline(cin, new_name);
cout << endl;

do
{
    cout << "Please enter a letter grade <E to quit>: ";
    cin >> g;

    if(!g.empty())
    {
        addGrade(g);
    }
}while(!g.empty());
}

A: The problem is nothing to do with string.empty(), it is this line:
cin >> g;

That operation is whitespace delimited. That is to say, it skips all leading whitespace, and then once it has started consuming non-whitespace characters, it stops on the next whitespace if finds. So you can just press enter all day long, and it will be ignored, because pressing enter causes a newline character ('\n'), which is whitespace.
If you want line oriented input, use getline instead of operator>>.
getline(cin, g);

A: std:;string:empty() is working as expected in this. As Benjamin pointed out instead if you use getline(cin, g); in place of cin>>g you can achieve what you are expected:
int main()
{
string g = " ";
std::string new_name;
cout << "Enter the students name: ";
getline(cin, new_name);
cout << endl;

do
{
    cout << "Please enter a letter grade <E to quit>: ";
    getline(cin, g);

    if(!g.empty())
    {
        std::cout<<"here";
        //addGrade(g);
    }
}while(!g.empty());

return 0;
}


text:
Q: why does grep '\;.' expand to grep '\''\;.'\''' when executed over ssh? $cat test.sh
ssh HOST -l root -o StrictHostKeyChecking=no -q "/bin/bash -l -c /bin/env | grep -w PATH | grep '\;.'"

$bash -x test.sh
+ ssh HOST -l root -o StrictHostKeyChecking=no -q '/bin/bash -l -c /bin/env | grep -w PATH | grep '\''\;.'\'''

A: It's nothing to do with SSH.  The -x argument to bash is that of bash's set command, which displays the command's arguments in expanded form. This is why the double quoted strings are displayed as single quoted strings.
$ cat test.sh
echo "here are 'some single quotes' inside double quotes"

$ bash -x test.sh
+ echo 'here are '\''some single quotes'\'' inside double quotes'
here are 'some single quotes' inside double quotes


text:
Q: Gitlab pipeline deploy using rsync I'm trying to deploy all the content of the current git repository (including branch and commit) and deploy that to a remote server using rsync.
Now I have I gitlab-ci file that has the following content in it:
image: ubuntu:18.04

.init_development_ssh: &init_development_ssh |
    eval $(ssh-agent -s)
    mkdir -p ~/.ssh
    chmod 700 ~/.ssh
    [[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    ssh-add <(echo "$STAGING_PRIVATE_KEY")

.tag: &tag
  tags:
    - pixel-rp

stages:
  - lint
  - deploy

linting code:
  # Use the LUA image
  image: mhndev/docker-lua
  <<: *tag
  stage: lint
  before_script:
    - luarocks install luacheck
  script: luacheck fx-server-data
  allow_failure: true

deploy to testing:
  <<: *tag
  stage: deploy
  before_script:
    - apt -y update && apt -y upgrade && apt install -y openssh-client rsync sshpass
    - *init_development_ssh
  script:
    - sshpass -p "$SSH_PASS" -e "ssh -p 2222" rsync -rav --exclude='.git/' --exclude='.gitlab-ci.yml' --delete-excluded /builds/pixel-rp/pixel-server/ user@IP:/home/user/FXServer/server-data/

The error I get is
> Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
    -f filename   Take password to use from file
    -d number     Use number as file descriptor for getting password
    -p password   Provide password as argument (security unwise)
    -e            Password is passed as env-var "SSHPASS"
    With no parameters - password will be taken from stdin
    -P prompt     Which string should sshpass search for to detect a password prompt
    -v            Be verbose about what you're doing
    -h            Show help (this screen)
    -V            Print version information
 At most one of -f, -d, -p or -e should be used
 Conflicting password source

Now I'm not a linux expert, but the parameters that are "required" to keep in mind are the following:

*

*SSH port: 2222

*SSH key is (as far as I know) successfully imported

Anyone who knows how I can take all the content (exclude some files) and "push" that to my remote server as "continious delivery"?

A: According to the manpage of sshpass, you can specify the password in the command line using the option -p and tell sshpass to use the password from the environment variable SSHPASS when using the option -e.
As you can only specify the password once but you used both options, sshpass does not know where to take the password from (from the command line or the environment variable) and therefor fails.
The options -f (to read from a file) and -d (to read from a file descriptor) also can't be used in combination with any of the other options.