text:
Q: triple-dot notation for git diff works strangely Suppose I have the following branch structure:
            E -- F (topic)
           /
A -- B -- C -- D (master)

I have tried the following:
git diff master..topic

and
git diff master...topic

According to the gitrevisions documentation, the double-dot notation is supposed to include (in this case) only revisions in the topic branch.
The way I visualize this is that when you use the master..topic notation, think of moving from master to topic like moving a board piece in a board game. As you move to each node (commit) you only include the commits that involve moving the piece in a forward direction. Forward here is towards the tip of topic, which means we include commits E and F.
Triple dot, in this case, is supposed to include commits in both branches. So this will be commits F, E, and D.
I expect the FIRST git diff above to show me commits E and F, but instead it shows me E, F, D (which should be triple-dot based on the rules above). The SECOND git diff shows me commits E and F when I expect it to show me E, F, G. Why are these behaving completely opposite? I understand that the git diff documentation clearly states in the examples section that the triple-dot notation behaves as expected, but I suppose when you look at how git log works and also the descriptions in the git revisions documentation, git diff seems inconsistent and doesn't follow normal patterns.

A: For git diff you should be looking at the git diff documentation instead of the revisions specs documentation.

git diff [options] blob blob
    This form is to view the differences between the raw contents
    of two blob objects.
git diff [--options] commit..commit [--] [path...]
    This is synonymous to the previous form. If  on one side
    is omitted, it will have the same effect as using HEAD instead.

When you invoke git diff master..topic it is expected to get the outcome of the raw difference between the raw content of the commits pointed by master and topic, respectively. Thus git correctly shows you the content difference between (E,F) and (D).

The simple interpretation for git diff master...topic is all the changes that happened on topic since it was branched off master ignoring changes on the latter (ie., the difference for topic starting from the merge-base of the two), and in this case the shown difference would be (E,F) without (D).

A: [Edit to fix brain-o]
The double- and triple-dot notation has that meaning for git rev-list (and all the commands that use it, which is quite a few of them), but not for git diff.
As a special-case hack, when you run git diff and use the double-dot notation, it simply diffs the commit named by the left-hand name, against the commit named by the right-hand name.  So git diff x..y is really just git diff x y.  Meanwhile, git diff x...y is a different special case, that takes the merge-base of x and y as the starting point: it means git diff $(git merge-base x y) y.
In short, you're right: git diff does not follow the normal patterns.  (There is a good excuse, as it were, in that diffs are done pair-wise, rather than across a series of commits.  But git knows how to do combined diffs for merge commits, so it's not a great excuse. :-) )


text:
Q: Adding dynamic columns to an ASP.NET Gridview I'm having a problem dynamically adding columns to a GridView.  I need to change the layout -- i.e. the included columns -- based on the value in a DropDownList.  When the user changes the selection in this list, I need to remove all but the first column and dynamically add additional columns based on the selection.
I have only one column defined in my markup -- column 0, a template column, in which I declare a Select link and another application specific LinkButton.  That column needs to always be there.  When the ListBoxSelection is made, I remove all but the first column and then re-add the desired columns (in this sample, I've simplified it to always add a "Title" column).  Here is a portion of the code:
RemoveVariableColumnsFromGrid();
BoundField b = new BoundField();
b.DataField = "Title";
this.gvPrimaryListView.Columns.Add(b);
this.gvPrimaryListView.DataBind();

private void RemoveVariableColumnsFromGrid() {
    int ColCount = this.gvPrimaryListView.Columns.Count;
    //Leave column 0 -- our select and view template column
    while (ColCount > 1) {
        this.gvPrimaryListView.Columns.RemoveAt(ColCount - 1);
        --ColCount;
    }
}

The first time this code runs through, I see both the static column and the dynamically added "Title" column.  However, the next time a selection is made, the first column is generated empty (nothing in it).  I see the title column, and I see the first column to its left -- but there's nothing generated within it.  In the debugger, I can see that gvPrimaryListView does indeed still have two columns and the first one (index 0) is indeed a template column.  In fact, the column even retains it's width which is set as 165px in the markup below (for debugging purposes).
Any ideas?
<asp:GridView ID="gvPrimaryListView" runat="server" Width="100%" AutoGenerateColumns="false"
    DataKeyNames="Document_ID" EnableViewState="true" DataSourceID="odsPrimaryDataSource"
    AllowPaging="true" AllowSorting="true" PageSize="10" OnPageIndexChanging="activeListView_PageIndexChanging"
    AutoGenerateSelectButton="False" OnSelectedIndexChanged="activeListView_SelectedIndexChanged"
    Visible="true" OnRowDataBound="CtlDocList_RowDataBound" Font-Size="8pt" Font-Names="Helvetica">
    <Columns>
        <asp:TemplateField ShowHeader="false">
            <ItemTemplate>
                <asp:LinkButton EnableTheming="false" ID="CtlSelectDocRowBtn" runat="server" Text="Select"
                    CommandName="Select" CssClass="gridbutton" OnClick="RowSelectBtn_Click" />
                <asp:ImageButton EnableTheming="false" ID="DocViewBtn" runat="server" ImageUrl="../../images/ViewDoc3.png"
                    CssClass="gridbutton" CommandName="Select" OnClick="DocViewBtn_Click" />
            </ItemTemplate>
            <ItemStyle Width="165px" />
        </asp:TemplateField>
    </Columns>
    <EmptyDataTemplate>
        <asp:Label ID="Label6" runat="server" Text="No rows found." SkinID="LabelHeader"></asp:Label>
    </EmptyDataTemplate>
</asp:GridView>

Just some additional information.
It has nothing to do with the fact that it is the first column but everything to do with the fact that it is a TemplateField.  If I put a normal column to the left (in the markup) and shift the TemplateField column to the right, the first column renders fine, and the (now second) TemplateField column disappears.
Another strange thing -- the problem doesn't happen the first postback -- OR THE SECOND -- but it starts on the third postback and then continues for subsequent postbacks.  I'm stumped.

A: I recently conquered silmilar issues with dynamic columns in gridviews, perhaps this will help.
First turn the viewstate off
Second add the columns programatically in a function fired in the oninit event
Lastly I used the following helper class to cause the checkboxes to instantiate when the RowDataBound event kicked off.  Yes some of it is hard coded.
Heck here is all the code.  Have at it :)  Warrenty as is, blah blah blah...
Finally since I am just getting my feet wet DotNet any tips would be appreciated [IE don't rip me too much :) ].  And yes 'borrowed' the initial code from the web somewhere, sorry I cant remember off the top of my head :(
-- Fire this off in protected override void OnInit
    private void GridViewProject_AddColumns()
    {
        DataSet dsDataSet = new DataSet();
        TemplateField templateField = null;

        try
        {
            StoredProcedure sp = new StoredProcedure("ExpenseReportItemType_GetList", "INTRANETWEBDB", Context.User.Identity.Name);
            dsDataSet = sp.GetDataSet();

            if (sp.RC != 0 && sp.RC != 3000)
            {
                labelMessage.Text = sp.ErrorMessage;
            }

            int iIndex = 0;
            int iCount = dsDataSet.Tables[0].Rows.Count;
            string strCategoryID = "";
            string strCategoryName = "";
            iStaticColumnCount = GridViewProject.Columns.Count;

            // Insert all columns immediatly to the left of the LAST column
            while (iIndex < iCount)
            {
                strCategoryName = dsDataSet.Tables[0].Rows[iIndex]["CategoryName"].ToString();
                strCategoryID = dsDataSet.Tables[0].Rows[iIndex]["CategoryID"].ToString();

                templateField = new TemplateField();
                templateField.HeaderTemplate = new GridViewTemplateExternal(DataControlRowType.Header, strCategoryName, strCategoryID);
                templateField.ItemTemplate = new GridViewTemplateExternal(DataControlRowType.DataRow, strCategoryName, strCategoryID);
                templateField.FooterTemplate = new GridViewTemplateExternal(DataControlRowType.Footer, strCategoryName, strCategoryID);

                // Have to decriment iStaticColumnCount to insert dynamic columns BEFORE the edit row
                GridViewProject.Columns.Insert((iIndex + (iStaticColumnCount-1)), templateField);
                iIndex++;
            }
            iFinalColumnCount = GridViewProject.Columns.Count;
            iERPEditColumnIndex = (iFinalColumnCount - 1); // iIndex is zero based, Count is not
        }
        catch (Exception exception)
        {
            labelMessage.Text = exception.Message;
        }
    }

-- Helper Class
public class GridViewTemplateExternal : System.Web.UI.ITemplate
{
    #region Fields
    public DataControlRowType DataRowType;
    private string strCategoryID;
    private string strColumnName;
    #endregion

    #region Constructor
    public GridViewTemplateExternal(DataControlRowType type, string ColumnName, string CategoryID)
    {
        DataRowType = type; // Header, DataRow,
        strColumnName = ColumnName; // Header name
        strCategoryID = CategoryID;
    }
    #endregion

    #region Methods
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (DataRowType)
        {
            case DataControlRowType.Header:
                // build the header for this column
                Label labelHeader = new Label();
                labelHeader.Text = "<b>" + strColumnName + "</b>";
                // All CheckBoxes "Look Up" to the header row for this information
                labelHeader.Attributes["ERICategoryID"] = strCategoryID;
                labelHeader.Style["writing-mode"] = "tb-rl";
                labelHeader.Style["filter"] = "flipv fliph";
                container.Controls.Add(labelHeader);
                break;
            case DataControlRowType.DataRow:
                CheckBox checkboxAllowedRow = new CheckBox();
                checkboxAllowedRow.Enabled = false;
                checkboxAllowedRow.DataBinding += new EventHandler(this.CheckBox_DataBinding);
                container.Controls.Add(checkboxAllowedRow);
                break;
            case DataControlRowType.Footer:
                // No data handling for the footer addition row
                CheckBox checkboxAllowedFooter = new CheckBox();
                container.Controls.Add(checkboxAllowedFooter);
                break;
            default:
                break;
        }
    }
    public void CheckBox_DataBinding(Object sender, EventArgs e)
    {
        CheckBox checkboxAllowed = (CheckBox)sender;// get the control that raised this event
        GridViewRow row = (GridViewRow)checkboxAllowed.NamingContainer;// get the containing row
        string RawValue = DataBinder.Eval(row.DataItem, strColumnName).ToString();
        if (RawValue.ToUpper() == "TRUE")
        {
            checkboxAllowed.Checked = true;
        }
        else
        {
            checkboxAllowed.Checked = false;
        }
    }
    #endregion
}

A: best solution for add dynamic column to grid view (ASP) placed on code project by below address :
please check it out :
http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view

A: diningphilanderer.myopenid.com has a similar approach to what I would recommend.
The problem is that you have to rebind the grid each time a postback occurs and consequently you have to rebuild the columns.  I like to have a method called BindGrid() that first clears the Columns GridView1.Columns.Clear(); then adds them programatically, then sets the datasource and calls databind.  Make sure you have viewstate disabled for the grid and you have autogeneratecolumns = false;

A: I found this earlier today: TemplateField in a GridView doesn't have its ViewState restored when BoundFields are inserted.
Looks like a bug that Microsoft doesn't plan on fixing, so you'll have to try one of the solutions above. I'm having the same problem -- I have some DataBoundFields and some TemplateFields, and after a postback, the TemplateField based columns lose their controls and data.

A: I have written a short article on the similar topic that deal with dynamically populating GridView column based on the columns selected by the user in the CheckBoxList control. Hope this will help to those looking for simple demonstration How to generate GridView columns dynamically based on user selection?.

A:     void Page_PreRenderComplete(object sender, EventArgs e)
    {
        // TemplateField reorder bug: if there is a TemplateField based column (or derived therefrom), GridView may blank out
        // the column (plus possibly others) during any postback, if the user has moved it from its original markup position.
        // This is probably a viewstate bug, as it happens only if a TemplateField based column has been moved.  The workaround is
        // to force a databind before each response. See https://connect.microsoft.com/VisualStudio/feedback/details/104994/templatefield-in-a-gridview-doesnt-have-its-viewstate-restored-when-boundfields-are-inserted
        //
        // This problem is also happening for grid views inside a TabPanel, even if the TemplateField based columns have not
        // been moved.  Also do a databind in that case.
        //
        // We also force a databind right after the user has submitted the column chooser dialog.
        // (This is because the user could have moved TemplateField based column(s) but ColChooserHasMovedTemplateFields()
        // returns false -- ie when the user has moved all TemplateField based columns back to their original positions.
        if ((!_DataBindingDone && (ColChooserHasMovedTemplateFields() || _InTabPanel)) || _ColChooserPanelSubmitted || _ColChooserPanelCancelled)
            DataBind();

        // There is a problem with the GridView in case of custom paging (which is true here) that if we are on the last page,
        // and we delete all row(s) of that page, GridView is not aware of the deletion during the subsequent data binding,
        // will ask the ODS for the last page of data, and will display a blank.  By PreRenderComplete, it will somehow have
        // realized that its PageIndex, PageCount, etc. are too big and updated them properly, but this is too late
        // as the data binding has already occurred with oudated page variables.  So, if we were on the last page just before
        // the last data binding (_LastPageIndex == _LastPageCount - 1) and PageIndex was decremented after the data binding,
        // we know this scenario has happened and we redo the data binding.  See http://scottonwriting.net/sowblog/archive/2006/05/30/163173.aspx
        // for a discussion of the problem when the GridView uses the ODS to delete data.  The discussion also applies when we
        // delete data directly through ClassBuilder objects.
        if (_LastPageIndex == _LastPageCount - 1 && PageIndex < _LastPageIndex)
            DataBind();

        if (EnableColChooser)
        {
            if (!_IsColChooserApplied)
                ApplyColChooser(null, false, false);
            else
            {
                // The purpose of calling ApplyColChooser() here is to order the column headers properly.  The GridView
                // at this point will have reverted the column headers to their original order regardless of ViewState,
                // so we need to apply our own ordering.  (This is not true of data cells, so we don't have to apply
                // ordering to them, as reflected by the parameters of the call.)

                // If we have already processed column reordering upon the column chooser panel being submitted,
                // don't repeat the operation.
                if (!_ColChooserPanelSubmitted)
                    ApplyColChooser(null, false, true);
            }
        }
    }

A: I found this little nugget in the documentation, under the DataControlFieldCollection Class.
If you are using the GridView or DetailsView control, the DataControlField objects that are automatically created (for example, when the AutoGenerateColumns property is true) are not stored in the publicly accessible fields collection. You can only access and manipulate DataControlField objects that are not automatically generated.
I guess the answer is to do all of your column manipulation in code, and then your approach should work fine.

A: Instead of dynamically adding columns, could you define them at the outset and hide/show them as needed (either with Visible="false" or setting the CssClass of the control/header/footer to a class with "display: none;")? I use this method in some of my code, including template columns, with no issues.

A: Sorry, Decker.  I missed a few key points obviously.. :)
If this is still a problem for you, I wonder if it makes a difference what you have in your item template?  If you just put some text in there, then refresh the page a few times, does the text appear on the first load, then not on the second?
Also, when the problem arises is there any html markup at all in the cells or are they completely empty?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cordova: How to set different package names per platform using the cordova-cli? I have an app for iOS and Android that I am upgrading from PhoneGap 2.x to Cordova 4.0.
As the iOS and Android apps were created using PhoneGap 2.x I have two separate projects (i.e. a  project for iOS and a project for Android). These projects have a shared www directory (using symbolic links) for the HTML/CSS/JavaScript assets. When I upgrade to Cordova 4.0 I can have a single Cordova project and use the Cordova CLI to create projects for each platform in the platforms directory.
The package name that is used to for each platform in Cordova is set in shared a config.xml file though. The Cordova CLI uses the package name set in the config.xml for the perpare, build and add platform commands.
Unfortunately the package names that were used for the PhoneGap 2.x apps are not the same (i.e. the package name for the Android app is different to the package name of the iOS app).
For example: the Android app has a package name like com.example.applongname but the iOS app has a package name like com.example.AppShortName. The beginning of the package name (i.e. reverse company domain name) is the same for each app but the application names differ. The iOS application name also contains capital letters.
I need to keep the package names that were used for the initial PhoneGap 2.x builds so that the apps can be updated (i.e the end users can receive an update that will replace their existing install of my app).
How I can set the package name per platform without creating two separate projects?

A: Write widget this way:
<widget id="com.company.app" android-packageName="com.company.androidapp" ios-CFBundleIdentifier="com.company.iosapp" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

see my other answer for more details.


text:
Q: Do different CPUs with same architecture use same complier? For example, do different processors with the same armv8 architecture use one same compiler?
More specifically, do Qualcomm and MTK processors use the same compiler?

A: Assuming the processors are capable of compiling from the same target triple, code generated for one of the processors should be capable of running on the other.
A Target Triple is a specifier for a set of properties a target has, such as its architecture (x86_64, armv8, armhf etc), vendor and its ABI. Clang has a decent description of how a target triple is determined and which properties are relevant. A link to that article can be found here: https://clang.llvm.org/docs/CrossCompilation.html#target-triple


text:
Q: i want to locate pageview in listview @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.purpleAccent.shade200,
        title: Text_Button(),
        actions: [IconButton(onPressed: () {}, icon: Icon(Icons.menu))],
      ),
      body: ListView(
        children:[ PageView(
          children: [
            Image.asset(
              "asset/img/1.PNG",
            ),
            Image.asset(
              "asset/img/2.PNG",
            ),
          ],
        )],
      ),
    );
  }

I don't know why it does no work.
I think maybe the problem from the relationship between ListView and Pageview
or my image.
i want to upload the error name but the code is too long to upload.
please help me
the ultimate my purpose is it.
it : locate my images on the top of my app under the appbar with pageview function.
The reason I want to use a list view is because my app is vertically long, so it doesn't fit on the screen all at once. at the same time
as a pageview under the app bar
I want to add slideable photos. How the hell can I do that? Because I am Korean, my English is poor. Please understand. handsome friends.
few days ago
in the column
with pageview
put textbutton
I have a memory.
So I know that a Pageview can be put inside a Colmn.
therefore
Put Pageview in Colmn,
I tried to align upwards with mainaxis but this also
error pops up
So I thought about it, a few days ago
I used a long photo vertically, but this time I used a long photo horizontally.
Perhaps this is the problem.

A: You can use carousel_slider: ^4.2.1  package to set slidable photos under appbar


text:
Q: 6x6 sudoku puzzle, Finding what sector you're in I'm making a Sudoku solver, and I need to check if a number is free in the current sector, I already check the rows and columns of the number, so what's left is sectors.
The whole puzzle is 6x6 and has 3 (2rows per sector) row sectors and 2 (3 colums per sector) column sectors.
I check the rows and columns like this:
for (int i = 0; i < 6; i++)
{
    if (Matrica[i][column] == CurrentNumber) return 0;
    if (Matrica[row][i] == CurrentNumber) return 0;
}

and since it's a 6x6 matrix, and the sectors are 2x3(or 3x2 don't know the format)
only 2 numbers in the sector remain, and i need to find out from my row and column numbers, what places i should check, but the solution escapes me, I've no idea how to do it.
SOLUTION:
For anyone interested, I've worked the checking out like this:
int Tikrinimas(int number, int Matrica[][6], int row, int column)
{
int sectorRow = 2 * (row / 2);
int sectorCol = 3 * (column / 3);
int row1 = (row + 1) % 2;
int col1 = (column + 2) % 3;
int col2 = (column + 4) % 3;

/* Check for the value in the given row and column */
for (int i = 0; i < 6; i++)
{
    if (Matrica[i][column] == number) return 0;
    if (Matrica[row][i] == number) return 0;
}

/* Check the remaining two spaces in this sector */
if (Matrica[row1 + sectorRow][col1 + sectorCol] == number) return 0;
if (Matrica[row1 + sectorRow][col2 + sectorCol] == number) return 0;
return 1;
}

in a function this will check if current set number is viable in that position

A: If you have a grid that is divided into sectors you can find a corner of that sector and then base all or indexes of of that corner.  Assuming [0][0] is the top left corner of your puzzle then the top left corner sector you are in if you are at [3][5] would be
rows_per_sector (2) * (current_row (3) / rows_per_sector (2)) = 2

cols_per_sector (3) * (current_col (5) / cols_per_sector (3)) = 3

Now you can use 2,3 as the top left corner and you can code in the offsets need to get the rest of the sector.


text:
Q: Trouble unmarshaling text into struct Trying to unmarshal a json text into my own struct. My struct definitions seem correct but json.Unmarshal doesn't return anything.
package main

import (
    "encoding/json"
    "fmt"
)

type CmdUnit struct {
    Command     string
    Description string
}

type CmdList struct {
    ListOfCommands []CmdUnit
}

type OneCmdList struct {
    Area    string
    CmdList CmdList
}

type AllCommands struct {
    AllAreas []OneCmdList
}

func main() {
    jsonTxt := `
    {
        "Area1": [{
                "Command": "cmd1",
                "Desc": "cmd1 desc"
        }, {
                "Command": "cmd2",
                "Desc": "cmd2 desc"
        }],
        "Area2": [{
                "Command": "cmd1",
                "Desc": "cmd1 desc"
        }]

}
`
    cmds := AllCommands{}
    if err := json.Unmarshal([]byte(jsonTxt), &cmds); err != nil {
        fmt.Println("Failed to unmarshal:", err)
    } else {
        fmt.Printf("%+v\n", cmds)
    }
}

$ go run j.go
{AllAreas:[]}

A: Your structs have a different structure from the json you're providing. Marshalling the structs in your example would result in json that looks like:
{
  "AllAreas": [
    {
      "Area": "Area1",
      "CmdList": {
        "ListOfCommands": [
          {
            "Command": "cmd1",
            "Description": "cmd1 desc"
          },
          {
            "Command": "cmd2",
            "Description": "cmd2 desc"
          }
        ]
      }
    }
  ]
}

The json in your example can be unmarshaled directly into a map[string][]CmdUnit{} with the minor change of CmdUnit.Description to CmdUnit.Desc.
cmds := map[string][]CmdUnit{}
if err := json.Unmarshal(jsonTxt, &cmds); err != nil {
    log.Fatal("Failed to unmarshal:", err)
}
fmt.Printf("%+v\n", cmds)

https://play.golang.org/p/DFLYAfNLES


text:
Q: Mouse coordinates action Is there a way to do it in Flex to say:
if mouseClick x<300&y<200 currentState='';

Thanks,

A: Many objects dispatch a click event; and in that click event properties you can access the x and y position using stageX and stageY properties.
http://livedocs.adobe.com/flex/3/langref/flash/events/MouseEvent.html
However, I do not think it is possible to listen for a click event at a specific location without their being a UI Element at that spot.
I also question whether hard coding the x and y position for such a state change is a good idea; as different machines and different screen sizes and resolutions may size your content differently.

A: You can add a listener to the stage to capture all clicks:
package
{

import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;

[SWF(width='500', height='300', backgroundColor='#ffffff', frameRate='30')]
public class ClickTest extends Sprite
{
    public function ClickTest()
    {
        addEventListener(Event.ADDED_TO_STAGE, addedToStage);
    }

    private function addedToStage(event:Event):void
    {
        stage.addEventListener(MouseEvent.CLICK, handleClick);
    }

    private function handleClick(event:MouseEvent):void
    {
        if((stage.mouseX < 300) && (stage.mouseY < 200)
        {
            trace("CLICKED WHERE I WANT");
        }
    }
}

}

This seems to work even when Sprites are placed on top of the interface.


text:
Q: Issue in loading JSP page using JQuery-struts -ajax Hi I have one select option tag in page. I need to change the content of this select box depending upon the value of other select box. We are using AJAX to do this.
Select tag of which value is supposed to get change is.

        <s:text name="tempName"/>:

            <s:select   name="vo.indexId"
                        id="vo.indexId"
                        list="indexList"
                        listKey="id"
                        listValue="name"
                        size="1"
                        required="true"
                        onchange="someFunction();"/>

This is a ajax call to load new value of select option tag.
$("#indexDiv").load(url, "key="+value, function(){
        someOtherFunction();
    });

This is the JSP page that is supposed to get loaded in IndexDiv
<s:select name="vo.indexId"
    id="vo.indexId" list="indexList" listKey="id" listValue="name" size="1"
    required="true" onchange="someFunction();" />

After ajax call the content of indexDiv tag is as follows.

        Index :

                    <select name="vo.indexId" size="1" id="vo.indexId" onchange="someFunction();">
                        <option value="1">someValue1</option>
                        <option value="2">someValue2</option>
                    </select>

So 'indexDiv' should contain only select option tag. But it contains table row instead. This issue arises only when JQuery is used to make ajax call. But when plane javascript is used this issue is not observed.
If this is issue related to struts2 then it should have also appeared when I used non-jquery way to make ajax call.

A: Ah! dont blame jQuery. Did you try using <s:set name="theme" value="'simple'" scope="page" /> on the top of the source JSP page. Or, in struts.xml:
<struts>
   <constant name="struts.ui.theme" value="simple" />
</struts>


text:
Q: Post variables to php file and load result on same page with ajax I have tried searching quite a bit but can't seem to make anything work.
I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.
What I have so far:
HTML:

      <form id="form">
        <input id="info" type="text" />
        <input id="submit" type="submit" value="Check" />
      </form>

JS:

PHP:
<?php

  $url = '/api.php?&info='.$_POST['info'];

  $reply = file_get_contents($url);

   echo $reply;

?>

When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.
I cannot get any solutions to work.

A: Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:
$('#submit').click(function (){
 $.ajax({
    type: "POST",
    url: "/api.php",
    data: dataString,
    success: function(res) {
        $('#result').html(res);
    }
 });

 return false;

});

Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(

A: Thanks everyone for your help, I have it working now.
I was doing a few things wrong:

*

*I was using single quotes in my php file for the URL and also for the $_POST[''] variables.

*I needed to add return false; as Steve pointed out.

*I did not have a "name" for the input elements, only an ID.

A: I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax. The code below.
/* ... */

$('#submit').click(function (){
    $.ajax({
        var info= $('#info').val();
        var dataString = "info="+info;

/* ... */


text:
Q: JUnit throwing IllegalArgumentException I'm trying to Parameterize a JUnit4 test, but I keep receiving IllegalArgumentExcpetion: Wrong number of arguments, though I've triple checked my constructors. My code is like (please notice that variables are defined in top of classes as same type):
@RunWith(Parameterized.class)
public class OrderTest {

private Order order;

public OrderTest(byte id, byte coffee, byte cafelatte, byte smoothie, byte iceCoffee) {
    order = new Order(new byte[] {id, coffee, cafelatte, smoothie, iceCoffee});
}

@Parameters
public static Collection order() {
    return Arrays.asList(new byte[][] {
        {1, 1, 0, 0, 0},
        {2, 1, 1, 0, 0},
        {3, 1, 1, 1, 1},
        {14, 80, 127, 127, 127}
    });
}

And my Order class is
public class Order {

public Order(byte[] orders) {
    id = orders[0];
    coffee = orders[1];
    cafeLatte = orders[2];
    smoothie = orders[3];
    iceCoffee = orders[4];
}

A: Let's make it simple and clean:
@RunWith(Parameterized.class)
public class OrderTest {

    @Parameterized.Parameter
    public Order order;

    @Parameterized.Parameters
    public static Collection<Order> orders() {
        return Arrays.asList(
            new Order(1, 1, 0, 0, 0),
            new Order(2, 1, 1, 0, 0),
            new Order(3, 1, 1, 1, 1),
            new Order(14, 80, 127, 127, 127)
        );
    }

If you implement a toString() method to Order, you can replace @Parameterized.Parameters with @Parameterized.Parameters(name = "{index}: {0}") in order to have a better idea of what is currently tested.

A: You can use a workaround with boxed Byte-s:
public OrderTest(Byte id, Byte coffee, Byte cafelatte, Byte smoothie, Byte iceCoffee) {
    order = new Order(new byte[] {id, coffee, cafelatte, smoothie, iceCoffee});
}

@Parameters
public static Collection order() {
    return Arrays.asList(new Byte[][] {
        {1, 1, 0, 0, 0},
        {2, 1, 1, 0, 0},
        {3, 1, 1, 1, 1},
        {14, 80, 127, 127, 127}
    });
}


text:
Q: Is the increased proper time of earth due to its orbital motion around the sun equal the increased proper time due to GR? The proper time $d\tau$ and coordinate time $dt$ are connected by
 $$\gamma d \tau=dt$$
where
$$\gamma=\frac{1}{\sqrt{1-\frac {{v}^2} {{c}^2}}}$$
This is, for example, the reasons that muons can travel much farther through our atmosphere than expected because their proper time increases.
Now if we fill in for $v$ in $\gamma$ the velocity of the earth around the sun, will this give the same result as predicted by the general theory of relativity, which is to say, will the increased time be the same as GR predicts for points at the same distance as the earth is orbiting the sun (assuming the earth orbit is circular?


text:
Q: Kendo UI grid binding error I am working with kendo UI grid here is my code
JAVASCRIPT
 $("#logs").kendoGrid({
                    dataSource: {
                        type: "json",
                        transport: {
                            read: {
                                url: "https://localhost:1153/v3.svc/auditlog",
                                dataType: "json",
                                data: '?&tableName=' + table + '&userId=' + userId + '&fromDate=' + dateFrom + '&toDate=' + dateto + '&isSearchForClient=' + true,
                                type: "GET",
                                contentType: "application/json; charset=utf-8"
                            }
                        },
                        pageSize: 10, //page size
                        schema: {
                            data: "d", //root element that contains data array
                            total: "d.length" //total amount of records
                        }
                    },
                    pageable: true, //enable paging
                    columns: [{ field: "d.TransactionId", title: "TransactionID", width: "30px" }, { field: "d.Log", title: "Audit Logs", width: "110px" }]
                });

And whats coming from server is something like this
[ { "TransactionId" : "185492010250010630", "Log" : "Administrator  Super has updated jobdescmanagement on 1/28/2015 4:24:03 PM"}]

Its giving error in console is
Uncaught Sys.ParameterCountException: Sys.ParameterCountException: Parameter count mismatch.

A: According to your JSON data structure fields configuration should be
columns: [{
    field: "TransactionId",
    title: "TransactionID",
    width: "30px"
}, {
    field: "Log",
    title: "Audit Logs",
    width: "110px"
}]

in this case you don't need schema configuration as you don't have root JSON element.
The schema
schema: {
    data: "d"
}

implies that data has the following format:
{d: [{"TransactionId": "185492010250010630", "Log": "Administrator Super has updated jobdescmanagement on 1/28/2015 4:24:03 PM"}]}

however this is not your case.


text:
Q: No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate I am getting an error as No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. for the following code, My base class is "com.springmvc"
My Controller Class is
package com.springmvc.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.springmvc.dao.UserDAO;
import com.springmvc.dao.UserDAOImpl;
import com.springmvc.type.User;

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private UserDAO usrdao;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {

        logger.info("Welcome home! The client locale is {}.", locale);

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        String formattedDate = dateFormat.format(date);
        model.addAttribute("Date", formattedDate );
        return "index";
    }
    /*
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String welcome(Locale locale,Model model,@ModelAttribute("LoginBean")LoginBean login){

        if(login != null && login.getUserName() != "" && login.getPassword() != ""){

            if(login.getUserName().equals("ajith") && login.getPassword().equals("123")){

                model.addAttribute("msg","Welcome "+login.getUserName());
                return "welcome";
            }
            else{

                model.addAttribute("error","Invalid Login Details");
                return "index";
            }
        }
        else{

            model.addAttribute("error","Please Enter Login Details");
            return "index";
        }
    }
    */
    @RequestMapping(value="/checkLogin",method = RequestMethod.POST)
    public String CheckUser(Model model,@ModelAttribute("User")User user){

        if(user != null && user.getUserName() != "" && user.getPass() != ""){

            boolean isActive            = usrdao.isActiveUser(user.getUserName(), user.getPass());

            if(isActive){
                List<User> usrLst   = usrdao.ListAllUsers();
                model.addAttribute("message",user.getUserName());
                model.addAttribute("usrLst",usrLst);
                return "home";
            }
            else{
                model.addAttribute("error","Invalid Login Details");
                return "index";
            }
        }
        return "index";
    }
    @RequestMapping(value="/createUser", method = RequestMethod.GET)
    public String RedirectCreateUser(Model model){

        return "createUser";
    }

    public String createUser(Model model, @ModelAttribute User user){

        usrdao.CreateOrUpdateUser(user);
        return "";
    }
}

UserDAO
package com.springmvc.dao;

import java.util.List;

import com.springmvc.type.User;

public interface UserDAO {

    public void CreateOrUpdateUser(User user);
    public void DeleteUser(int uid);
    public User GetUser(int uid);
    public List<User> ListAllUsers();
    public boolean isActiveUser(String userName,String pass);
}

UserDAOImpl
package com.springmvc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import com.springmvc.type.User;

@Repository("UserDAO")
public class UserDAOImpl implements UserDAO {

    private JdbcTemplate jdbc;
    /*
    public void setJdbc(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }
    */
    public UserDAOImpl(DataSource DS) {
        jdbc = new JdbcTemplate(DS);
    }

    @Override
    public void CreateOrUpdateUser(User user) {

        if(user.getUid() == 0){
            String query    = "INSERT INTO userdetails(UserName,Name,Pass) VALUES(?,?,?)";
            jdbc.update(query,user.getUserName(),user.getName(),user.getPass());
        }
        else{
            String query    = "UPDATE userdetails SET UserName = ?,Name = ?,Pass = ?,isActive = ? WHERE id = ?";
            jdbc.update(query, user.getUserName(),user.getName(),user.getPass(),user.getIsActive(),user.getUid());
        }
    }

    @Override
    public void DeleteUser(int uid) {

        String query    = "DELETE FROM userdetails WHERE id = ?";
        jdbc.update(query, uid);
    }

    @Override
    public User GetUser(int uid) {

        String query    = "SELECT * FROM userdetails WHERE id = ?";
        return  jdbc.query(query, new ResultSetExtractor<User>() {

            @Override
            public User extractData(ResultSet rs) throws SQLException, DataAccessException {

                if(rs.next()){

                    User user = new User();
                    user.setUid(rs.getInt("id"));
                    user.setUserName(rs.getString("UserName"));
                    user.setName(rs.getString("Name"));
                    user.setIsActive(rs.getInt("isActive"));
                    return user;
                }
                return null;
            }
        });
    }

    @Override
    public List<User> ListAllUsers() {

        String query        = "SELECT * FROM userdetails";
        List <User> usrLst  = jdbc.query(query, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {

                User user   = new User();
                user.setUid(rs.getInt("id"));
                user.setUserName(rs.getString("UserName"));
                user.setName(rs.getString("Name"));
                user.setIsActive(rs.getInt("isActive"));
                return user;
            }
        });
        return usrLst;
    }

    @Override
    public boolean isActiveUser(String userName, String pass) {

        String query    = "SELECT id FROM userdetails WHERE UserName = ? AND Pass = ? AND isActive = 1";
        SqlRowSet rs    = jdbc.queryForRowSet(query,userName,pass);
        if(rs.next())
            return true;
        else
            return false;
    }

}

Thank You

A: UserDAOImpl do not have default constructor. either add default constructor or autowire the construction arg.

A: Spring is using a strong naming convention.
Try to use as a variable userDao as the autowired variable and use the same string  in the @repository.
See this little explanation here:
https://www.tutorialspoint.com/spring/spring_beans_autowiring.htm


text: Q: Why android realm's greaterThan not support String, while comon sql support it, how can I make greaterThan method support String parameter? I store date in string in realm, now I need to query future days which need to use greater Than method.


text:
Q: Running SQL Server Profiler 24/7 I have low-level traces that I used to SQL Profiler to create and I would like to run these traces 24/7.
So for I have the trace result imported to a table in the database and It stop running when I close the SQL Profiler instance.
Is there a way to make this runs 24/7 in the background?


text:
Q: GWT like perfect caching for non-GWT resources Perfect Caching
Perfect Caching allows the browser to cache resources forever and guarantees that changed resources are propagated immediately to the browser. In GWT this is accomplished by naming a file like the hash code of its content. As this leads to a new file name each time the content of a file changes, the browser can cache these files forever without having to ask the server whether or not there is a new version available. More about perfect caching can be found here.
As this concept works very well I would like to apply it to all of my non-GWT resources (some JS, CSS and image files).
As my build process is Maven based it would be great if there was a plugin which could automatically rename the files according to their hash code and which could adjust all of the references to this file.
Here's an example
Renaming

*

*foo.css -> foo_39757cec04498955db62043f7ecfefc2.cache.css

*logo.png -> logo_35bcdbbabe1944afc75eeeb16f06d1ad.cache.png

Update references in files

*

*Replace all occurances of "foo.css" by "foo_39757cec04498955db62043f7ecfefc2.cache.css"

*Replace all occurances of "logo.png" by "logo_35bcdbbabe1944afc75eeeb16f06d1ad.cache.png"

Does anybody know whether something like that already exists?
Many thanks in advance,
Michael

A: If you're using Apache (httpd) you can setup mod_pagespeed to do that. Since GWT does some of that stuff already, be careful to properly configure mod_pagespeed so that performance doesn't degrade.

A: mod_pagespeed indeed disables HTML caching by default, as typically HTML is dynamic.  However, you can override that behavior.
There is a new option in the most recent binary release (0.10.21.*) that provides the behavior you want: explicitly control of your HTML caching headers:
  ModPagespeedModifyCachingHeaders off

http://code.google.com/speed/page-speed/docs/install.html#ModifyCachingHeaders


text:
Q: How do I deploy .net core rc2 projects via msbuild / msdeploy? Currently we deploy our web application projects (csproj's) via a call to MSBuild.exe with the DeployOnBuild=true and PublishProfile=Whatever parameters to deploy our projects to one of the following:

*

*IIS on premisis

*Azure Web Apps

*Web Deployment Packages

We'd like to begin using the new .net core rc2 projects, but we're really not sure how to deploy them.  Can we use the older publish profiles / publish methods?
When going thru the Visual Studio Publishing UI, I only see File System and Microsoft Azure App Service as options.  The File System doesn't make a web deployment package and we'd like to continue using the deployment package technique, especially for promoting the same build between different environments.
In general, any advice on deploying .net core rc2 apps via msbuild in a manner similar to what we previously did, would be fantastic.  However, specifically, I'd like to know how to deploy .net core rc2 projects to web deployment packages via msbuild.  Thanks for any advice!

A: Just as a note: The tooling around .NET Core and ASP.NET Core is in "Preview 1" not finished yet and my proposed solution could change with the next version.
Anyway. msdeploy.exe is still working but needs some knowledge about the msdeploy CLI.
I just configured a continuous deployment process using FAKE (F# Make) but it should also work with MSBuild, if you have some deeper knowledge of it.
The first step is to use "dotnet publish" to deploy to a specific folder using arguments like this:
"dotnet publish " + webPath + " --framework net461 --output " + publishFolder +
    " --configuration " + buildConf + " --no-build"

Than you need to call msdeploy.exe with arguments similar to this:
"msdeploy.exe -source:contentPath=" + publishFolder + " -dest:contentPath=" + targetFolder +
    ",ComputerName=" + computerName + ",UserName='" + username + "',Password='" + publishPassword +
    "',IncludeAcls='False',AuthType='Basic' -verb:sync -enablerule:AppOffline -enableRule:DoNotDeleteRule -retryAttempts:20"

Visual Studio does exactly the same, if you publish to Azure. If you try it with Visual Studio, you'll see that in the publish output window.

A: thx a lot! worked for me!
i have used:
$website = Get-AzureWebsite -Name [AzureWebsiteName]

# get the SCM URL to use with MSDeploy.
# by default this will be the second in the array.
$msDeployHost = $website.EnabledHostNames[1]

and then i've created the -dest:contentPath like this
$destPath="$($website.Name),ComputerName='https://$msDeployHost/msdeploy.axd',UserName='$($website.PublishingUsername)',Password='$($website.PublishingPassword)',IncludeAcls='False',AuthType='Basic'"


text:
Q: "TypeError: Object(...) is not a function" error when trying to use react hooks (alpha) When I try to use the new React hooks feature I run into this annoying error message for some reason.
I followed the instructions on the documentation and upgraded react to the latest alpha version with yarn add react@next.

A: I actually solved this issue! Most likely what you did to start using hooks was just updated react using yarn add react@next or something similar, but you probably didn't upgrade react-dom which is why you're getting this error.
TLDR; Upgrade react-dom!!


text:
Q: Does quickfix store received messages somewhere? I know that quickfix stores outgoing messages to .body file, but I am curious does it store incoming messages somewhere (i.e. file) and what should be set up to get that functionality?
Best,
D

A: If you use FileLogFactory, then all incoming messages will be logged into a file in your logs folder (that you set at FileLogPath).

A: if you set FileStorePath=\path\ quickfix will save a .messages.current file there with the messages in raw format in it


text:
Q: What is the control flow and recursion tree in python I have a simple doubt:
I have found the power of number code using recursion as:
def power(x, y):

    if(y == 0): return 1
    temp = power(x, int(y / 2))
    print("outside loop:",temp)

    if (y % 2 == 0):
        print("inner loop y%2==0:",temp*temp)
        return temp * temp
    else:
        if(y > 0):
            print(" loop y > 0:",x*temp*temp)
            return x * temp * temp
        else: return (temp * temp) / x
power(2,3)

What would be the control flow and recursive diagram of the above code?
Is temp=power(x, int(y / 2)) called 3 times first and then the control reaches to else:  if(y > 0):?
Any help would be great. Simple printing will not help.


text:
Q: Receive input in specific time I'm writing a testing system and i all i want to do is to count how many seconds had user spent on this question. i.e. i print question(standard System.out.println), then wait 5 seconds and if within these 5 seconds user answered(through standard input), i want to keep this value.
If user hasn't provided an answer in 5 seconds, it must skip this question and continue.
The problem is I'm reading user answers via Scanner object, and something like in.nextInt() is uncontrollable, I suppose.
How can I solve this problem? Here is fragment of my code without that functionality, can you give me some hints what to add?
    public void start() {
    questions.prepareQuestions(numQuestions);
    Scanner in=new Scanner(System.in);
    boolean playerIsRight=false,botIsRight=false;
    int playerScore=0,botScore=0;
    for (int i = 0; i < numQuestions; i++) {
        questions.askQuestion(i);
        System.out.print("Your answer(number): ");
        playerIsRight=questions.checkAnswer(i,in.nextInt()-1); //in.nextInt() contains the answer
        botIsRight=botAnswersCorrectly(i + 1);
        if(playerIsRight){ playerScore++; System.out.println("Correct!");}
        else System.out.println("Incorrect!");
        if(botIsRight) botScore++;
        System.out.print("\n");
    }
    if(botScore>playerScore) System.out.println("Machine won! Hail to the almighty transistors!");
    else if(playerScore>botScore) System.out.println("Human won! Hail to the power of nature!");
    else System.out.println("Tie. No one ever wins. No one finally loses.");
}

A: I would use two threads in this case. The main thread writes questions, waits for answers, and keeps score. A child thread reads standard input and sends the answers to the main thread, perhaps via a BlockingQueue.
The main thread can wait for five seconds for an answer by using the poll() method on the blocking queue:
…
BlockingQueue<Integer> answers = new SynchronousQueue();
Thread t = new ReaderThread(answers);
t.start();
for (int i = 0; i < numQuestions; ++i) {
  questions.askQuestion(i);
  System.out.print("Your answer (number): ");
  Integer answer = answers.poll(5, TimeUnit.SECONDS);
  playerIsRight = (answer != null) && questions.checkAnswer(i, answer - 1);
  …
}
t.interrupt();

If this call returns null, the main thread knows that the child thread didn't receive any input during that time, and can update the score appropriately and print the next question.
The ReaderThread would look something like this:
class ReaderThread extends Thread {

  private final BlockingQueue<Integer> answers;

  ReaderThread(BlockingQueue<Integer> answers) {
    this.answers = answers;
  }

  @Override
  public void run() {
    Scanner in = new Scanner(System.in);
    while (!Thread.interrupted())
      answers.add(in.nextInt());
  }

}

Used on System.in, the Scanner will block until the user presses Enter, so it might happen that the user has entered some text but not yet pressed Enter when the main thread times out and moves on to the next question. The user would have to delete their pending entry and enter a new answer for the new question. I don't know of a clean way around this awkwardness, since there's not a reliable way to interrupt the nextInt() call.


text:
Q: refresh filter text bootstrap 4 So i have an input element with filter and list. After i choose any list item,it changes name of default text written in the input into the text written in the chosen list item.I want to refresh the default text written in the input after i press some button.
I tried doing it using innerHTML and .text(),but it failed.
HTML

   <input type="text" class="region formClear" id="myInput"
      onkeyup="myFunction()" value="regions" title="Type in a name">

region1

region2

<button onclick="defaultChange()">refresh</button>

Javascript
function defaultChange(){
    //$('#myInput').text("regions");
    $('#myInput').innerHTML="regions";
}

A: You need to use the .val() function for this:
function defaultChange(){
    $('#myInput').val("regions");
}

An input doesn't have any HTML value, it's a replaced element, so you need to set its value.

A: You will need to use jQuery val() function to get the value of input like
$('#myInput').val("regions")

innerHTML is used to change the inner html of the element.
Stack Snippet

function defaultChange() {
  $('#myInput').val("regions");
}

  <input type="text" class="region formClear" id="myInput" onkeyup="" value="regions1" title="Type in a name">

<button onclick="defaultChange()">refresh</button>


text:
Q: only fire workflow when value changes I have a workflow that I've created that will populate a text field with a URL when the record is updated.
My workflow rule evaluation criteria is:  Evaluate the rule when a record is created, and every time it's edited
my rule criteria is:
AND
(
MyField__c <> "MyValue"
)
I'm trying to use an "AND" condition to only fire the workflow when "MyField" is not equal to "MyValue" and "MyField" has changed either from Null or blank to a value or the value has changed.
"MyField" is not set on the record creation.  It only gets populated on update thru APEX.  I've tried using ISCHANGED and PRIORVALUE, but neither of those work.  Any ideas?  I'm trying to prevent my workflow from firing every single time the record is updated.
Thanks for any help.

A: There is function ISCHANGED
Try this:
AND (
ISCHANGED(MyField__c),
ISBLANK(PRIORVALUE(MyField__c)),
MyField__c <> "MyValue" )

A: You can try to change your workflow criteria to everytime a record is created or edited to subsequently meet your criteria.

A: Like @ankush said, change your evaluation criteria to 'created, and any time it's edited to subsequently meet criteria'.
Then,

*

*Run this rule if the following 'Criteria are met'

*

*Field: MyField__c

*Operator: not equal to

*Value: MyValue

*If the record is created with MyField__c <> "MyValue", the workflow will fire.

*If the record is created with MyField__c = "MyValue", the workflow will not fire.

*If it is then edited so that MyField__c <> "MyValue", the workflow will fire.

However, if MyField__c is changed from one value that is <> MyValue to a different value that is <> MyValue it will not fire.


text:
Q: c++ define directive on class in header file I am somewhat aware of what the #define directive does and its conveniences but what does it mean when using it on a class such as:
#ifndef SAVINGS_H
#define SAVINGS_H
#include "account.h"

class Savings
{
protected:
public:
};
#endif

If SAVINGS_H is not defined, it defines SAVINGS_H, but where is SAVINGS_H ever used? And why is the class referred to as SAVINGS_H in all capital letters?
I know when you define a variable such as
#define num 1

int arr[num]

num gets replaced with 1 but for my question, SAVINGS_H is not used any where else in the program

A: If your source code (by whatever path) did this:
  #include "savings.h"
  #include "savings.h"

then SAVINGS_H would be defined after the first #include, and would prevent a re-definition of the names in the savings.h header file. This is what is known as an "include guard", and prevents redefinition of names in header files in the same translation unit.

A: This is what is called Include Guard. It's so that you header is included only once (to avoid ODR violations, i.e. multiple definitions of the same entity).
For example if A includes B and C but B also includes C.
Basically they work this way: when compiler includes the header the 1st time it defines the include guard macro. In all the subsequent includes it just skips the file contents, since the macro is already defined (ifndef).

A: Look up "header guard" aka "include guard".
The purpose is to prevent multiple inclusion (including multiple transitive inclusion) of the header file. Which would lead to problems with the same type being defined multiple times.


text:
Q: Casting a Delphi interface to TObject* in C++ Builder and proper ClassName() function call I am trying to access Java classes dynamically from *.apk file using C++ Builder (Android development). For this purpose I have found complete guide with example in Delphi (here: http://www.pclviewer.com/android/androidJNI.html). Everything works fine in Delphi, but when I tried to rewrite Pascal source code (at the end of guide) into C++ using C++ Builder XE7, I found curious problem. How to cast Delphi interface into TObject* in C++, properly invoke ClassName() function and get JavaObjectID? I spent a lot of time, but still cannot rewrite these 3 lines of code:
var
JavaObject:JObject;
oTemp:TObject;
JavaObjectID:JNIObject;
:
oTemp:=JavaObject as TObject;                   //1. ?
JavaObjectID:=tjavaimport(otemp).GetObjectID;   //2. ?
memo1.Lines.Add(oTemp.ClassName);               //3. ?
:

I have tried differenet type casts, also using GetInterface() method of TObject class, but nothing works. As a C++ programmer I don't understand how is it possible directly cast delphi interface into TObject*.
Androidapi::Jni::Javatypes::_di_JObject JavaObject;
System::TObject* oTemp;
Androidapi::Jni::_JNIObject *JavaObjectID;
:
oTemp = (TObject*)(&JavaObject);   //Compiling ok, but segmentation fault
?
Memo1->Lines->Add(oTemp->ClassName()); // after ClassName() invoke.

Does anybody know. how to rewrite these 3 lines of Pascal code into C++ please? Thank you very much for your response.

A: Casting an interface into an object reference is a Delphi-only feature, there is no equivilent in C++ without delving into the vtable directly.  What you can do, however, is write a function in Delphi that takes an interface as input, casts it, and returns the object as output, and then call that function in C++ code. You can add a Delphi .pas file to a C++Builder project, it will generate a C++ .hpp file when compiled.
unit MyJavaHelper;

interface

uses
  Androidapi.JNI.JavaTypes;

function JObjectToTObject(JavaObject: JObject): TObject;

implementation

function JObjectToTObject(JavaObject: JObject): TObject;
begin
  Result := JavaObject as TObject;
end;

end.

#include "MyJavaHelper.hpp"

Androidapi::Jni::Javatypes::_di_JObject JavaObject;
System::TObject* oTemp;
Androidapi::Jni::_JNIObject *JavaObjectID;

JavaObject = ...;
oTemp = JObjectToTObject(JavaObject);
JavaObjectID = static_cast<TJavaImport*>(otemp)->GetObjectID();
Memo1->Lines->Add(oTemp->ClassName());


text:
Q: Group rows under condition, get all results I am working on a facebook like notification system. I want to group data, when the Entity ID and type of operation (labeled CUD) are the same. So from this:
+----+-----------------+--------+------------+--------+-----------+---------------------+---------------------+---------------------+-----+---------------+-----------+
| id | display_name    | name   | surname    | avatar | type      | last_check          | redirect            | created             | cud | notif_culprit | entity_id |
+----+-----------------+--------+------------+--------+-----------+---------------------+---------------------+---------------------+-----+---------------+-----------+
| 45 |                 | Julie  | Opletalová |        | character | Character:edit, 316 | Character:edit, 316 | 2018-02-03 00:55:04 |   2 |             5 |       316 |
| 52 | juliina postava | Julie  | Opletalová |        | character | Character:edit, 325 | Character:edit, 325 | 2018-02-03 01:22:47 |   1 |             5 |       325 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-03 23:15:39 |   2 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-03 23:51:39 |   3 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-03 23:57:23 |   3 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-04 00:05:45 |   3 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-04 00:06:02 |   3 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-04 00:06:16 |   3 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-04 00:23:50 |   3 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-04 00:30:06 |   3 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-04 00:30:36 |   3 |             3 |       326 |
+----+-----------------+--------+------------+--------+-----------+---------------------+---------------------+---------------------+-----+---------------+-----------+

I would like to have
+----+-----------------+--------+------------+--------+-----------+---------------------+---------------------+---------------------+-----+---------------+-----------+
| id | display_name    | name   | surname    | avatar | type      | last_check          | redirect            | created             | cud | notif_culprit | entity_id |
+----+-----------------+--------+------------+--------+-----------+---------------------+---------------------+---------------------+-----+---------------+-----------+
| 45 |                 | Julie  | Opletalová |        | character | Character:edit, 316 | Character:edit, 316 | 2018-02-03 00:55:04 |   2 |             5 |       316 |
| 52 | juliina postava | Julie  | Opletalová |        | character | Character:edit, 325 | Character:edit, 325 | 2018-02-03 01:22:47 |   1 |             5 |       325 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-03 23:15:39 |   2 |             3 |       326 |
| 62 | veveho postava  | Martin | Nezamysl   |        | character | Character:edit, 326 | Character:edit, 326 | 2018-02-03 23:51:39 |   3 |             3 |       326 |

I know about "having" command in mysql, so I could use group by with having specifying type. But I was able to do that with only one type (CUD). I need to display all types.
Here is SqlFiddle:
http://sqlfiddle.com/#!9/5a8361/1

A: You will have to group your result by the id, and cud.
SELECT * FROM mytable
GROUP BY id, cud;

SQL FIDDLE DEMO


text:
Q: How to Install and configure Redis on ElasticBeanstalk How do I install and configure Redis on AWS ElasticBeanstalk? Does anyone know how to write an .ebextension script to accomplish that?

A: The accepted answer is great if you are using ElastiCache (like RDS, but for Memcached or Redis). But, if what you are trying to do is tell EB to provision Redis into the EC2 instance in which it spins up your app, you want a different config file, something like this gist:
packages:
  yum:
    gcc-c++: []
    make: []
sources:
  /home/ec2-user: http://download.redis.io/releases/redis-2.8.4.tar.gz
commands:
  redis_build:
    command: make
    cwd: /home/ec2-user/redis-2.8.4
  redis_config_001:
    command: sed -i -e "s/daemonize no/daemonize yes/" redis.conf
    cwd: /home/ec2-user/redis-2.8.4
  redis_config_002:
    command: sed -i -e "s/# maxmemory <bytes>/maxmemory 500MB/" redis.conf
    cwd: /home/ec2-user/redis-2.8.4
  redis_config_003:
    command: sed -i -e "s/# maxmemory-policy volatile-lru/maxmemory-policy allkeys-lru/" redis.conf
    cwd: /home/ec2-user/redis-2.8.4
  redis_server:
    command: src/redis-server redis.conf
    cwd: /home/ec2-user/redis-2.8.4

IMPORTANT: The commands are executed in alphabetical order by name, so if you pick different names than redis_build, redis_config_xxx, redis_server, make sure they are such that they execute in the way you expect.
Your other option is to containerize your app with Redis using Docker, then deploy your app as some number of Docker containers, instead of whatever language you wrote it in. Doing that for a Flask app is described here.
You can jam it all into one container and deploy that way, which is easier, but doesn't scale well, or you can use AWS' Elastic Beanstalk multi-container deployments. If you have used docker-compose, you can use this tool to turn a docker-compose.yml into the form AWS wants, Dockerrun.aws.json.

A: AWS Elastic Beanstalk does provide resource configuration via the .ebextensions folder. Essentially you need to tell Elastic Beanstalk what you would like provisioned in addition to your application. For provisioning into a default vpc. You need to
create an .ebextensions folder
add an elasticache.config file
and include the following contents.
Resources:
  MyCacheSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Lock cache down to webserver access only"
      SecurityGroupIngress :
        - IpProtocol : "tcp"
          FromPort :
            Fn::GetOptionSetting:
              OptionName : "CachePort"
              DefaultValue: "6379"
          ToPort :
            Fn::GetOptionSetting:
              OptionName : "CachePort"
              DefaultValue: "6379"
          SourceSecurityGroupName:
            Ref: "AWSEBSecurityGroup"
  MyElastiCache:
    Type: "AWS::ElastiCache::CacheCluster"
    Properties:
      CacheNodeType:
        Fn::GetOptionSetting:
          OptionName : "CacheNodeType"
          DefaultValue : "cache.t1.micro"
      NumCacheNodes:
        Fn::GetOptionSetting:
          OptionName : "NumCacheNodes"
          DefaultValue : "1"
      Engine:
        Fn::GetOptionSetting:
          OptionName : "Engine"
          DefaultValue : "redis"
      VpcSecurityGroupIds:
        -
          Fn::GetAtt:
            - MyCacheSecurityGroup
            - GroupId

Outputs:
  ElastiCache:
    Description : "ID of ElastiCache Cache Cluster with Redis Engine"
    Value :
      Ref : "MyElastiCache"

Referenced from: "How to add ElasticCache resources to Elastic Beanstalk VPC"
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-environment-resources-elasticache.html


text:
Q: Atom Compiler for C++ gives me wrong output for converting a value to binary So I have written a code for printing first 20 Binary Numbers like
0
1
10
11
100
101 and so on...
I Tried running the code in Atom Editor it's not accurate but when I ran the same code in an Online compiler it gave me a correct answer which I expected
This is the code that I used :
#include<iostream>
#include<math.h>

using namespace std;

 int toBinary(int num){
   int ans = 0;
   int i = 0;
   while(num!=0){
     int bit = num&1;
     ans = ( bit * pow(10,i) ) + ans;

     num = num>>1;
     i++;

   }
   return ans;
 }

int main(){

  for(int i=0;i<20;i++){
    cout<<toBinary(i)<<endl;
  }

  return 0;
}

This is the output i'm getting in ATOM editor:
0 1 10 11 99 100 109 110 1000 1001 1010 1011 1099 1100 1109 1110 9999 10000 10009 10010

And this is the output I'm getting in Online Compiler (this is the output I expect):
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011

A: pow is a floating point function and should not be used for integers.
It is also not required (from efficiency point of view) to recalculate the exponent from scratch every iteration. You can just keep a variable and multiply it by 10 in each one.
You can try the code below:
#include<iostream>

int toBinary(int num)
{
    int ans = 0;
    int exp = 1;
    while (num)
    {
        int bit = num & 1;
        ans += bit * exp;
        // for next iteration:
        exp *= 10;
        num /= 2;
    }
    return ans;
}

int main()
{
    for (int i = 0; i < 20; i++)
    {
        std::cout << toBinary(i) << std::endl;
    }
}

Output:
0
1
10
...
10001
10010
10011

Note that the result will overflow pretty fast (2000 is already way to big for representing binary in an int the way you do).
A side note: Why is "using namespace std;" considered bad practice?.


text:
Q: impdp failing with ORA-01031: insufficient privileges I'm trying to import a dmp file provided by our dba to my dev database. I've been able to export the contents to a SQLFILE and the contents look ok. I tried importing the schema and it kept on failing (same errors as shown below); so I tried running the SQL directly from the sqlfile - this created all the schema objects but didn't import the data.
The export was from the expenses schema from our test database. I already have another schema by that name in my dev database that I don't want to touch; so I'm remapping expenses to expenses1.
This schema (expenses1) has READ and WRITE privilege on the data_pump_dir directory. It has, as far as I can tell, all the privileges it needs (create table, view, procedure, sequence, etc) as well as IMP_FULL_DATABASE.
[oradev@DIAS45 dpdump]$ impdp expenses1/expenses1 logfile=expenses1.log
  remap_schema=EXPENSES:EXPENSES1 directory=data_pump_dir
  dumpfile=ossarct_expenses_expdp.dmp
  content=DATA_ONLY schemas=EXPENSES include=TABLE

Import: Release 11.2.0.3.0 - Production on Tue Apr 16 09:28:21 2013

Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.

Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

UDI-31626: operation generated ORACLE error 31626
ORA-31626: job does not exist
ORA-39086: cannot retrieve job information
ORA-06512: at "SYS.DBMS_DATAPUMP", line 3326
ORA-06512: at "SYS.DBMS_DATAPUMP", line 4551
ORA-06512: at line 1

[oradev@DIAS45 dpdump]$ cat expenses1.log
;;;
Import: Release 11.2.0.3.0 - Production on Tue Apr 16 09:28:21 2013

Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.
;;;
Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
Master table "EXPENSES1"."SYS_IMPORT_SCHEMA_01" successfully loaded/unloaded
Starting "EXPENSES1"."SYS_IMPORT_SCHEMA_01":  expenses1/******** logfile=expenses1.log
  remap_schema=EXPENSES:EXPENSES1 directory=data_pump_dir
  dumpfile=ossarct_expenses_expdp.dmp content=DATA_ONLY schemas=EXPENSES include=TABLE
ORA-39097: Data Pump job encountered unexpected error -1031
ORA-39065: unexpected master process exception in DISPATCH
ORA-01031: insufficient privileges

I can't tell from the above what privilege is missing, or if my command is telling impdp to do more than I'm expecting it to. I've tried skipping the schemas and include parameters with no difference.


text:
Q: How can a register detect that the value it containes is either data, or the address of data? As far as I know, when a data is too long, the address of a data is written to a register. When it is not long for a register, the real value of the data can be written to a register. How can a register detect that the value in the register is whether a the value of a data or the address of a data? If it could not detect, it would process with the wrong value.
I have found a related question ( How is data, address and Instruction differentiated in Processor/Register/memory?). However the answers are not too satisfied. Are there more satisfied answers? (Probably, it will be too complicated )
Thanks.

A: This is what I want to learn. http://cs.oberlin.edu/~jdonalds/317/IntelEncoding.htm


text:
Q: using console escape color codes in sed I need to color lines that start with #.
I have following code in perl, which works fine:
echo 'aaa\n#bbb\nccc' | perl -pe "s/(#.*)$/\e[0;32m\1\e[0m/"

I am trying to do the same in sed, but it just prints the color codes, instead of the color:
echo 'aaa\n#bbb\nccc' | sed -r "s/(#.*)$/\e[0;32m\1\e[0m/"
aaa
e[0;32m#bbbe[0m
ccc

Why are the color codes not working in sed, and what do I have to do differently ?

A: Use '\o033' instead of '\e':
$ echo -e 'aaa\n#bbb\nccc' | sed -r "s/(#.*)$/\o033[0;32m\1\o033[0m/"


text:
Q: BigInteger in objective c
Possible Duplicate:
biginteger on Objective-c

Is there any NS* class for arbitrary size integers in objective c like BigInteger in C#? if not, is gmp a good library to import or is there a better library/way? The operations I need is addition, subtraction, multiplication and division(with truncation). Memory is a big issue for this application so the one that uses least memory will be the best. Run time is not an issue as long as it doesn't take years per operation.


text:
Q: Is it possible to VNC into a separate desktop? I'm currently running Ubuntu 15.10 on my home-theater and I'm frequently using Remmina Remote Desktop Client to manage the box. Since the home-theater is frequently in use playing it's video duties, it would be immensely helpful to remote desktop into a separate session than the current - since it's playing full screen video for the family and VNCing in and tinkering with stuff would be incredibly distracting for those watching videos.

A: I think we were working too hard.
When I ssh into a machine I enable X forwarding with the -X flag.
ssh -X nodak@192.168.0.3
Then from the terminal I call the application, thunar (or nautilus), sudo thunar, sudo gdebi-gtk, etc.
This only renders the application interface on your machine, and you will not see a full 'desktop' of another instance, but the host computer will continue to function without interrupting the video to your TV.
See if that will be suitable for you.


text:
Q: Is it possible to append code to the CakePHP-generated document.ready block? I currently use the CakePHP JsHelper as follows and I would like to run additional JavaScript code when the document is ready:
    echo $this->Js->get(':submit')->event('click', "$(':submit').attr('disabled','disabled');
        $(':submit').val(\"Saving...\");
        ",
             array('stop' => false));

The above code is in my default.ctp and is inserted into every single page in this website application. I would like to add the additional code inside 1 page. The code would  append a button with certain properties and events dangling from it. Is it possible to do so?
I have already tried having 2 documentReady functions (1 generated by CakePHP and the other inside a *.js file) to no avail.
Here are the current contents of the 2nd .js file:
//source: http://marcgrabanski.com/articles/cakephp-ajax-quick-save-jquery
$(document).ready(function() {
$('<input type="button" value="Insta-Save"/>')
.click(function(){
$(this).parents("form:first").ajaxSubmit({
success: function(responseText, responseCode) {
$('#ajax-save-message').hide().html(responseText).fadeIn();
setTimeout(function(){
$('#ajax-save-message').fadeOut();
}, 5000);
}
});
return false;
})
.appendTo('form div.submit');
});

I also tried using a code block but CakePHP insisted on stuffing the code in at the very top of the page and so naturally, IE complained.

A: Success!
Simply append to the CakePHP buffer as follows:
echo $this->Js->buffer('alert("Hello world!");');

And, just as the commenter pointed out above, everything works just fine with the 2 resulting documentReady functions.


text:
Q: "IndexError: list index out of range" when comparing object to csv file element in Python I'm new to Python and have stumbled upon a problem while trying to code a program that searches for a line in a csv file containing the put in username.
Code:
# ...
username = input("Please put in username: ")

    with open(r"C:\Users\This\Is\A\Path\user.csv", 'r') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            if username == row[0]:
                data = row
                print(data)
                line_count += 1
        f.close()
# ...

Error:
Traceback (most recent call last):
  File "C:\Users\This\Is\A\Path\main.py", line 61, in <module>
    if username == row[0]:
IndexError: list index out of range

Contents of user.csv
Username,Name,Age,Gender,Speechproblems,Speechspeed
bingus,Joe,22,m,n,f

My guess is that the datatypes of username and row[0] don't match up, but I wouldn't know how to check what they are because I'm not the brightest tool in the shed. The IDE I'm using is PyCharm using the Python 3.9 Interpreter.


text:
Q: Bind - Resolve two domains with a single server I need a bit of help with BIND (Centos 7.5)
Bit of a back story:
We are running two domains on the network. One called company.domain.com and one called comp.domain.com
company.domain.com has devices with 192.168.100.x IP Addresses
comp.domain.com has devices with 10.1.100.x IP Addresses
My problem is that when I try to resolve a name from company.domain.com with just its short name it works fine, but when I try to do the same with comp.domain.com it fails and I need to enter the full address for it to be resolved.
Is there any way of telling the DNS server that if the requested address cannot be found in company.domain.com to look in comp.domain.com instead of timing out?
(Don't ask me about why we have two domains, I would like to know too. It was done by the previous manager ;D)
Any help is highly appreciated! :)

Thanks a lot!
Yes I'm aware it's not great using short names but its near-impossible to tell engineers to do something differently after doing it for the past couple of years!
I'll play around with the windows and linux solutions and see what happens as the DNS server will serve both.
Thank you for the responses! :)

A: Using short names is bad practice and should be avoided. It's best practice to always use fully qualified domain names. A whole lot of other stuff will break, either now or in the future, if you continue using short names. If possible, convert all your existing clients to use FQDNs.
That said, this isn't a problem with the DNS server, but with the clients. They need to be configured explicitly to search multiple domain names. For instance, on Linux, you would change the search option in /etc/resolv.conf.
search company.example.com corp.example.com

A: As Michael Hampton points out, this is something that can be addressed on the clients. For Windows clients, it's the DNS Suffix Search List. It can be configured via Group Policy, or through a GUI -- Network and Sharing, select your Local Area Connection, Properties, IPv4 Properties, Advanced, DNS tab, then add company.domain.com and comp.domain.com to the list.
You can also do it programmatically, via registry editing or WMIC. See https://superuser.com/questions/198231/append-dns-suffixes-via-windows-command-prompt for some ideas.


text:
Q: Python logging overhead I'm writing my code using asyncio module with a lot of info/debug logging (logging.FileHandler). I'm concerned that extensive using of logging in asyncio will decrease the performance of my application, because logging is blocking operation.
What is the best solution for that? Didn't find any information on logging overhead.
Maybe using SocketHandler or MemoryHandler will help? For metrics I'm using statsd (which is also blocking operation, but must be very fast), but I'm more concerned with non-blocking logging.
Code example:
@asyncio.coroutine
def creator_worker(self):
    while not self.q.empty():
        with (yield from self.semaphore):
            sample = yield from self.q.get()
            logging.debug('Got new sample, processing')
            # start processing

I'm aware of
import os
os.environ['PYTHONASYNCIODEBUG'] = '1'
import asyncio

But that's not what I'm looking for.
Thank you

A: Logging document provided a solution, log through a QueueHandler, then use a QueueListener to handle log record in another thread.
https://docs.python.org/3.6/howto/logging-cookbook.html#dealing-with-handlers-that-block

A: You may create a custom log handler.
The handler will push logging record into a queue.
Another thread may read data from the queue and perform actual logging.
As an option you may use SysLogHandler -- it's pretty fast.
But, anyway, logging too much reduces performance, you can do nothing with it.


text:
Q: Is there a way to instruct pylatex to not ignore extra spaces (whitespaces) on its own? I have started using pylatex four days ago to automate report generation (I have no earlier experience in latex as well). The text that I want to enter in the latex report has been generated by an online server and stored in my file as a text file. In the text file, there exist places with more than one simultaneous space for proper formatting and aligning (Protein Sequence Alignment). Hence, while simply trying to use .append, pylatex seems to ignore all the extra spaces on its own. I searched the internet with various relevant terms, but could not find any answer for pylatex. I did find some latex answers, exploring which I tried to incorporate pylatex's NoEscape and explicitly replacing "  " (double spaces) with " \space ", it seems to work for some lines as expected, but not for others (maybe some of the places have \ (or some other special characters for latex) which are expected to be meaningful but could not understand what it actually means since it does not even exist (for example \clo). Can someone please suggest a method where I can simply allow the simultaneous existence of the spaces, which is also visible in the final document without the need to think about the existence of a possible special character that needs to be escaped. The following code snippets that I used might be of use to answer/understand my query.
i = 0
    with doc.create(Subsection('Details')):
        with open(whatcheck_detail, 'r') as fh:
            lines = fh.read().split("#")[1:]
            for line in lines:
                i += 1
                line = line.replace("  ", " \space ").replace("#", "\#") + "\n"
                if "Note:" in line:
                    print(i)
                    # doc.append(TextColor(line))
                    doc.append(NoEscape(line))
                elif "Warning:" in line:
                    print(i)
                    # line = "\color{blue} " + line
                    doc.append(NoEscape(line))
                    # doc.append(TextColor("blue", line))
                elif "Error:" in line:
                    print(i)
                    # line = "\color{red} " + line
                    doc.append(NoEscape(line))
                    # doc.append(TextColor("red", line))

And the following is the screenshot of the last part of the error report.
Error Description upon running the above script.
Following are the images of what is happening by using the simple pylatex code doc.append(TextColor("color", line)), and what is actually in the text file (which is how I want it to be on PDF generated by latex/pylatex).
What is happening to the text in the output file.
What is in the text file, or how do I want it.
Thank you!


text:
Q: Getting event default handler's result from jQuery handler Let's say there is a DIV element with an onclick event:

Now I want to get this 'Hello world' string from delegated jQuery event:
$('body').delegate('div', 'click', function(event){
    var s = ...; // Now s is 'Hello world'
});

Is it possible?
I need this as a workaround for a sophisticated IE bug, so IE-only solutions will do.
P.S. For those who wonder: the bug is that when in IE8 document mode, IE10 follows links within FORM elements even when there is return false in anchor's onclick handler.

A: var s = this.onclick(); Will do the trick, although it is not clear what your are trying to achieve...

A: A slight modification on your code:

Hello World

and
$('body').delegate('div', 'click', function(e) {
    e.preventDefault();
    exec($(this).attr('onclick'));
});

JSFiddle: http://jsfiddle.net/y7ABJ/
Another option as it's not clear what your goal is:

Hello World

and
$('body').delegate('div', 'click', function(e) {
    e.preventDefault();
    var s = $(this).data('myText');
    alert(s);
});


text:
Q: subtract days from a Calendar time stored as text in Kotlin So I take the current date in Kotlin:
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -daysAgo)

I store it as text on a label: time = calendar.time.toString()
Next, I want to subtract 2 days from the label text:
val date = LocalDate.parse(time)
val cal = Calendar.getInstance()
cal.time = java.sql.Date.valueOf(date.toString())
cal.add(Calendar.DAY_OF_YEAR, -daysAgo)

Method threw 'java.time.format.DateTimeParseException' exception after this line:       LocalDate.parse(time) any thoughts?

A: I would use the new time API which is available since JDK 8 and can be found in java.time. You should also agree on a format that is being used:
val format = DateTimeFormatter.ISO_DATE_TIME
val current = LocalDateTime.now()
val currentAsText = current.format(format)
println(currentAsText) // e.g. 2019-02-27T12:00:00.000

val fromText = LocalDateTime.parse(currentAsText, format)
val twoDaysAgo = fromText.minusDays(2)
println(twoDaysAgo) // 2019-02-27T12:00:00.000

A: From Date class:

public String toString()
  Converts this Date object to a String of the form:
  dow mon dd hh:mm:ss zzz yyyy

this results in this format:
Fri Feb 22 11:45:35 EET 2019

You need ZonedDateTime to parse this format, like this:
val date = ZonedDateTime
    .parse(time, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH))
    .toLocalDate()


text:
Q: Changing variable by html button I'm learning javascript and I decided to create simple Rock, Paper, Scissors game. I want to make it controllable by buttons. So I made this in html:

    <button onClick="user(rock)">Rock</button>
    <button onClick="user(paper)">Paper</button>
    <button onClick="user(scissors)">Scissors</button>

    <button onClick="test()">DEBUG</button>

and this in .js file.
var user = "none";
function user(choice){
    var user = choice;
}

function test(click){
    alert("You chose " + user);
}

So I thought that after I click Rock button it will change var user to rock but it doesn't. After I click rock and then Debug button I get "You chose none".

A:

    <button onClick="choose('rock')">Rock</button>
    <button onClick="choose('paper')">Paper</button>
    <button onClick="choose('scissors')">Scissors</button>

    <button onClick="test()">DEBUG</button>

and
var user;
function choose(choice){
    user = choice;
}

function test(click){
    alert("You chose " + user);
}

A: var is used for declaring a variable. You don't need to declare user variable again in user function. You just need to assign a value to declared one.
var user; //declaration
function user(choice) {
    user = choice; //assignment
}

A: One problem:
var user = "none";
function user(choice){
    var user = choice;
}

One variable of user is hiding the other variable of user.
And having a function and variable with the same name is a BAD idea.

A: The var keyword used in the scope of a function will declare a new local variable.
Hence, in the global scope, user retains the value "none".

A: Maybe try this.. cleaner markup.. uses jQuery

    <button class="user" data-name="rock">Rock</button>
    <button class="user" data-name="paper">Paper</button>
    <button class="user" data-name="scissors">Scissors</button>

    <button id="test">DEBUG</button>

$(document).ready(function() {
    var user = "none";
    $(".user").click(function() {
       user = $(this).attr("data-name");
    });

    $("#test").click(function() {
       alert(user);
    });
});

http://jsfiddle.net/rQDbe/

A: Seems like a scoping issue. Try removing the var inside the function.

A: The other answers are fixing some issues. There is also a problem with the way you're calling the functions as you're passing rock as a variable, you need to use a string:
<button onClick="user('rock')">Rock</button>

Unless you're declaring the variables somewhere but it's not shown in your code.

A: The selections should be encased in the quotes, javascript is looking for the variables named paper etc.
<button onClick="user(rock)">Rock</button>
<button onClick="user(paper)">Paper</button>
<button onClick="user(scissors)">Scissors</button>


text:
Q: A unix system programming project on windows? I was given a unix prgramming project (with of cours a use of signal handling and fork()) but i have some issues with my ubuntu and i prefer to work on windows. So is there a solution ? I installed Cygwin but i don't think it will be enough to compile and execute the files like in Linux.

A: Just do the project in Ubuntu.  You're going to have a hard enough time learning about signals and process handling without having to worry about various differences between Cygwin and actual unix/linux.
Another option is to install virtualbox and run Ubuntu within that.  There should be no differences there.  https://www.virtualbox.org/wiki/Downloads


text:
Q: Can palettes dock to notebooks? Over on Meta: A wishlist for Mathematica
I got an interesting comment on the following suggestion and thought it merited a stand alone question:

re: NOTEBOOK INTERFACE USABILITY & ORGANIZATION
Dock palettes -- When I use palettes, I'd love the ability to just
  stick them on to the side of a notebook window so I don't have to keep
  searching for them.

Comment:

This may be able to be done using docked cells.  @rcollyer

See: DockedCells in the documentation.
I recognize that Wolfram builds palettes as notebooks and I can imagine that one could create a custom palette whose cells one could dock at the top of another notebook (this would work great if one could split a notebook into panes and scroll through them separately so one always had access to the palette).  Just not certain I see a clear way to do this with a supplied palette.
So, does anyone know how to dock a palette to a notebook (or any reasonably functional equivalent)?

A: Building off of jVincent's idea here's a way to make it take up less space:
plt = NotebookGet[Notebooks[][[1]]][[1]];
CreateWindow[
 DockedCells ->
  ReplacePart[
   plt,
   {1, 1, 1, 2, 2, 1} ->
    Partition[Flatten@plt[[1, 1, 1, 2, 2, 1]], 2]
   ]
 ]

I just looked inside the thing and flattened the primary GridBox.

A: You can simply assign the content of the palette to the docked cells, however this won't give any nice results for palettes that where not designed to be used as such:
For instance, first open up a palette, I chose Basic Math input, then run
plt = Notebooks[][[1]]
CreateWindow[DockedCells -> NotebookGet[plt][[1]]]

What you then end up with is a notebook with that palette docked, in this case and with most other palettes the result is quite horrible to look at.


text:
Q: Trouble Re-order a HTML table when the user clicks on the table header I am trying to re-order a HTML table when the user clicks on the table header. Here is all I can do, but still doesn't work.
  i want to do sorting  By default it will come as event_date desc.

it works properly
Now when i click on event name then its should do  sorting as event_name desc and when i again click on event name then its should be event_name asc.
How to do this?
please help me as soon as possible...
Thanks in advance...

A: you could use
jQgrid
It is much easier to manage tables using jquery

A: If you are doing it using javascript then its better to use any external js like datatable.
Or if are using php you can append parameter (asc/desc) to Event Title link and according to that sort the result.
Plz show wht you have done to find appropriate solution.


text:
Q: How to utilize data in xml from flow monitor I want to use ns3 to calculate TCP throughput,and I think one way to track network status is using flow monitor.However,it gives out xml file and I do not know how to use it...Can anyone help how to use the data or how to find relative tutorials of utilizing data generated by flow monitor in ns3 document?

A: The data in FlowMonitor.xml can be viewed using NetAnimator.

*

*Install NetAnim, see the requirements

*Add the netanim-module libraries in your simulation code

*Configure the node animations, see the example in src/netanim/examples/grid-animation.cc
std::string animFile = "grid-animation.xml";
AnimationInterface anim (animFile);

*Run the simulation

*Open the Netanim folder and run ./NetAnim

*Open XML trace file

*On the Stats tab change the IP-MAC switch to Flow-monitor

*Select flow-monitor file and open

*Select the flows of your interest
Ready! Good simulations!


text:
Q: Unable to get USB 3.0 working in VMWare Guest Windows 7 I am having a tough time in getting USB 3 work with VMWare Player 12 on Windows 7.
Host – Gigabyte 880GM USB3 board with Etron USB 3 controller. AMD Athlon CPU, 12GB RAM, Windows 7 64
Guest – VMWare Player 12, Windows 7 64, 4GB RAM, USB 3 enabled in VM configuration and successfully installed the recommended  Intel(R)_USB_3.0_eXtensible_Host_Controller_Driver_5.0.3.42 in Guest Windows 7
The issue is when I connect a USB 2 or USB 3 pen drive at Host USB 3 port it is just not detected in the VM at all. Only once it mysteriously appeared but when I tried to connect it gave 'Host is using the device' error, but then no files or even explorer window was open on host.
I even tried installing the Etron drivers in Guest but it fails.
I think there's some incompatibility between the Etron Host device and the Intel USB 3 controller driver. There's no issue with USB 2 ports at all.
What else can I try?

A: The VMware Support article
USB 3.0 support for Windows 7 virtual machine in VMware Workstation and VMware Fusion (2128105)
lists the following conditions:

*

*The guest VM must be defined with at least VMWare Workstation 12 compatibility

*In Settings, USB Controller, the USB compatibility needs to be set to 3.0.

*In the virtual machine, download and install the USB3 drivers from the
Intel Download Center.

However, not all hardware configurations are supported.
The most recent VMware article I have managed to find is
Host and guest OS USB 3.0 and virtual xHCI support with Workstation 9 (2041591)
which lists the supported configurations,
and where the Etron USB3 controller is not listed as supported.
Even though the article is for Workstation 9 and not Workstation 12,
this might be taken as an indication that your controller is unsupported,
meaning that you meed to stay with USB2.


text:
Q: How to ignore a PC which is shut down or locked or not connected with the network? I have defined an array of strings (Names of PCs). The script will copy File 1 from a remote PC and save it locally. The grep command will read the File 1 and save the results in another file. But when a PC is shut down or not connected with the network, the script will not execute and I have to press Ctrl+C and then it will move to next PC.
How I can change this script so that whenever a PC is shut down or not connected with the network or is locked it moves to the next PC? For example when user2@PC2 is shut down or not connected with the network or locked (required password), the script should automatically move to user3@PC3. It should copy File1 from each online user@PC once and then run grep.
#!/bin/sh

word=name

declare -a arr=("user1@PC1" "user2@PC2" "user3@PC3")
for i in "${arr[@]}"
do
    for t in 1 2 3
    do
        scp ${i}:/PCpath/File1 ./File${t}
        grep -e "${word}" "File${t}" >| /home/new/File${t}`_$(date`)
    done
done

A: Use ping to test if the remote PC is up before trying to copy from it.
    for i in "${arr[@]}"
    do
        if ping -q -c 2 "$i"
        then
            for t in 1 2 3
            do
                scp ${i}:/PCpath/File1 ./File${t}
                grep -e "${word}" "File${t}" >| /home/new/File${t}`_$(date`)
            done
        else
            echo "$i down, skipping"
        fi
    done