Sorting Gridview not working with Linq

Hi and thanks in advance,

I am trying to sort a gridview with linq and nothing is happening. I am not getting an error, but no sorting is happening in the view either. I am also using firebug for debugging as well.

asp:

  <asp:GridView ID="GridViewRangeSetup" runat="server" AllowSorting="True" OnSorting="Gridview_Sort"
                        PagerStyle-Mode="NumericPages" AutoGenerateColumns="false" Width="100%" CssClass="gridView"
                        OnPageIndexChanging="GridViewRangeSetup_PageIndexChanging" AllowPaging="True"
                        PageSize="20" DataKeyNames="RangeId" OnRowCommand="GridViewRangeSetup_RowCommand"
                        OnRowEditing="GridViewRangeSetup_RowEditing" OnRowCancelingEdit="GridViewRangeSetup_CancelEditRow"
                        OnRowUpdating="GridViewRangeSetup_UpdateRow" OnRowDataBound="GridViewRangeSetup_RowDataBound">
                        <RowStyle CssClass="rowStyle"></RowStyle>
                        <HeaderStyle CssClass="headerBar" ForeColor="#ffffff"></HeaderStyle>
                        <AlternatingRowStyle CssClass="altRow" />
                        <Columns>
                            <asp:TemplateField HeaderText="Edit" HeaderStyle-Width="5%" HeaderStyle-ForeColor="#f2f2f2"
                                HeaderStyle-Font-Bold="false" HeaderStyle-Font-Size="Small">
                                <ItemTemplate>
                                    <asp:ImageButton ID="imgEdit" runat="server" ImageUrl="~/images/icon_edit.png" CausesValidation="false"
                                        CommandArgument='<%#Eval("RangeId") %>' CommandName="Edit" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:ImageButton ID="imgUpdate" runat="server" ImageUrl="~/images/icon_update.png"
                                        CausesValidation="false" CommandArgument='<%#Eval("RangeId") %>' CommandName="Update" />
                                    <asp:ImageButton ID="ImageCancel" runat="server" ImageUrl="~/images/icon_cancel.png"
                                        CausesValidation="false" CommandArgument='<%#Eval("RangeId") %>' CommandName="Cancel" />
                                </EditItemTemplate>
                                <HeaderStyle Font-Bold="False" Font-Size="Small" ForeColor="#F2F2F2" Width="5%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Delete" HeaderStyle-Width="3%" HeaderStyle-ForeColor="#f2f2f2"
                                HeaderStyle-Font-Bold="false" HeaderStyle-Font-Size="Small">
                                <ItemTemplate>
                                    <asp:ImageButton ID="imgDelete" runat="server" CausesValidation="false" OnClientClick="return DeleleAlert();"
                                        CommandArgument='<%#Eval("RangeId") %>' CommandName="Remove" ImageUrl="~/images/icon_delete.png" />
                                </ItemTemplate>
                                <HeaderStyle Font-Bold="False" Font-Size="Small" ForeColor="#F2F2F2" Width="3%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Description" SortExpression="Description">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtDescription" runat="server" CssClass="textbox" Text='<%# Eval("Description") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Country" SortExpression="Country.CountryName">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="ddlCountry" runat="server" CssClass="dropdown" AutoPostBack="True"
                                        AppendDataBoundItems="true" DataTextField="CountryName" DataValueField="CountryId">
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="State/Province" SortExpression="GeographicRegion.RegionName">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="ddlRegion" runat="server" CssClass="dropdown" AutoPostBack="True"
                                        AppendDataBoundItems="true" DataTextField="RegionName" DataValueField="GeographicRegionId">
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblRegion" runat="server" Text='<%# Bind("RegionName") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Base/Facility" SortExpression="Base.BaseName">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="ddlFacility" runat="server" CssClass="dropdown" AutoPostBack="True"
                                        AppendDataBoundItems="true" DataTextField="BaseName" DataValueField="BaseId">
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblFacility" runat="server" Text='<%# Bind("BaseName") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Map Name" SortExpression="RangeMap.MapName">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtMapName" runat="server" CssClass="textbox" Text='<%# Eval("MapName") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblMapName" runat="server" Text='<%# Eval("MapName") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Map">
                                <HeaderStyle HorizontalAlign="center" />
                                <ItemTemplate>
                                    <asp:HyperLink ID="HyperLink_Map1" runat="server" NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"MapPath") %>'
                                        Text="">
                                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"MapPath") %>'
                                            Width="50px" Height="50px" />
                                    </asp:HyperLink>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Low Latitude" SortExpression="RangeMap.LowLat">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtLowLat" runat="server" CssClass="textbox" Text='<%# Eval("LowLat") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblLowLat" runat="server" Text='<%# Eval("LowLat") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Low Longitude" SortExpression="RangeMap.LowLong">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtLowLong" runat="server" CssClass="textbox" Text='<%# Eval("LowLong") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblLowLong" runat="server" Text='<%# Eval("LowLong") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="High Latitude" SortExpression="RangeMap.HighLat">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtHighLat" runat="server" CssClass="textbox" Text='<%# Eval("HighLat") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblHighLat" runat="server" Text='<%# Eval("HighLat") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="High Longitude" SortExpression="RangeMap.HighLong">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtHighLong" runat="server" CssClass="textbox" Text='<%# Eval("HighLong") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblHighLong" runat="server" Text='<%# Eval("HighLong") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Status">
                                <ItemTemplate>
                                    <asp:Button ID="RangeSetup_Status" CssClass="page-btn blue" CausesValidation="false"
                                        CommandArgument='<%#Eval("RangeId") %> ' runat="server" Text="Status" OnClick="btnRangeStatus_Click">
                                    </asp:Button>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

c#

protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
    {

    //Label2.Text = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
    WISSModel.WISSEntities context = new WISSModel.WISSEntities();

    String column = e.SortExpression;

    IQueryable<dynamic> sortedGridview = ConvertSortDirectionToSql(e.SortDirection) == "ASC" ?
                                                (from r in context.Ranges.AsEnumerable()
                                                 where r.isDeleted == false
                                                 orderby typeof(WISSModel.Range).GetProperty(column).GetValue(r, null) ascending
                                                 select new
                                                 {
                                                     r.RangeId,
                                                     r.Description,
                                                     r.Country.CountryName,
                                                     r.GeographicRegion.RegionName,
                                                     r.Base.BaseName,
                                                     r.RangeMap.MapName,
                                                     r.RangeMap.MapPath,
                                                     r.RangeMap.LowLat,
                                                     r.RangeMap.LowLong,
                                                     r.RangeMap.HighLat,
                                                     r.RangeMap.HighLong
                                                 }).AsQueryable<dynamic>() :
                                                  (from r in context.Ranges.AsEnumerable()
                                                   where r.isDeleted == false
                                                   orderby typeof(WISSModel.Range).GetProperty(column).GetValue(r, null) descending
                                                   select new
                                                   {
                                                       r.RangeId,
                                                       r.Description,
                                                       r.Country.CountryName,
                                                       r.GeographicRegion.RegionName,
                                                       r.Base.BaseName,
                                                       r.RangeMap.MapName,
                                                       r.RangeMap.MapPath,
                                                       r.RangeMap.LowLat,
                                                       r.RangeMap.LowLong,
                                                       r.RangeMap.HighLat,
                                                       r.RangeMap.HighLong
                                                   }).AsQueryable<dynamic>();

    //var sortedGridview = context.Ranges.Where("it.isDeleted == false").OrderBy(column);

    GridViewRangeSetup.DataSource = sortedGridview.ToList();

    //var test = sortedGridview.ToList();

    //System.Diagnostics.Debugger.Break();

    GridViewRangeSetup.DataBind();

}


Power 3.3v board using analog pin

What would be the reasons not to use one of the analog pins, set at 3.3v, to power a child board running at 3.3v?

I suspect this is bad, but can't figure out why...

Obviously I'm using a nano board that doesn't have a 3.3v pin...


Manually register a user in Laravel

Is it possible to manually register a user (with artisan?) rather than via the auth registration page?

I only need a handful of user accounts and wondered if there's a way to create these without having to set up the registration controllers and views.


Date(value) and new Date(value)

Possible Duplicate:

  Difference between Date(dateString) and new Date(dateString)

What is the difference between

Date(1356567322705)
"Thu Dec 27 2012 03:13:37 GMT+0300 (Kaliningrad Standard Time)"

and

new Date(1356567322705)
Thu Dec 27 2012 03:15:22 GMT+0300 (Kaliningrad Standard Time)

and why there is a gap of about 2 minutes?


Using a $.get() in .Net MVC without a controller

In .Net MVC if I'm using the JQuery .get() method to grab a file from the server would I still need to write up a RenderAction on a controller method to display its contents? Example JQuery:

function RenderPartialView(view, contentcontainer, maskcontainer, params) {
    $.get(view, params, function (data) {
        $("#" + contentcontainer).html(data);
        $(maskcontainer).unmask();
    });
}

   function displayExpandedView() {
       $('.expand-btn').on('click', function () {
           $(".expanded-view").modal();
           RenderPartialView("../some_dir/SomeView", "expanded-view", "#expanded-view", null);
       })
   }

So when I run the displayExpandedView() function I want to fill a div that is acting as a modal with the contents of the SomeView file. When I currently try to do this with in my application the server responds back with a 404 error saying the file cannot be found, even thought he path to it is correct. Using this method would I still need to have a controller return PartialView()? I was under the impression I would not.


How can i design a DB where the user can define the fields and types of a detail table in a M-D relationship?

My application has one table called 'events' and each event has approx 30 standard fields, but also user defined fields that could be any name or type, in an 'eventdata' table. Users can define these event data tables, by specifying x number of fields (either text/double/datetime/boolean) and the names of these fields. This 'eventdata' (table) can be different for each 'event'.

My current approach is to create a lookup table for the definitions. So if i need to query all 'event' and 'eventdata' per record,  i do so in a M-D relaitionship using two queries (i.e. select * from events, then for each record in 'events', select * from 'some table').

Is there a better approach to doing this? I have implemented this so far, but most of my queries require two distinct calls to the DB - i cannot simply join my cluster manager 'events' table with different 'eventdata' tables for each record in in 'events'.

I guess my main question is: can i join my cluster manager table with different detail tables for each record?

E.g.

SELECT E.*, E.Tablename
FROM events E
LEFT JOIN 'E.tablename' T ON E._ID = T.ID

If not, is there a better way to design my database considering i have no idea on how many user defined fields there may be and what type they will be.


PHP: How to display date time in following format (2015-01-05T06:27:50.000Z )?

I want to show the datetime in the following format

2015-01-05T06:27:50.000Z

How I can achieve this ?


Visual Studio 2010 runs awful - can't find solution

I have a problem with my Visual Studio 2010 Professional - I'm working on a project at work, and everything in VS runs slow (maybe except IntelliSense). I know that start-up times usually are quite bad, and I can live with that.

But building a medium sized solution (7 projects, a few hundred files) takes from 3 to even 10 minutes... After building the solution VS says that it's ready, but I have to wait for the localhost to respond up to 5 minutes... That's up to 15 minutes in total!
To keep things short:

after turning on everything I still have at least 1Gb of free RAM (4 total) and only 20-25% of processor usage

I have uninstalled every plugin

The project builds and works fine on my teammate's computer

The project works and builds even better when I work on a server using my computer and a virtual desktop

My computer works just fine

I have just finished the painful re-installation of VS (after removing VS cleaning it's leftovers - or so I think)

EDIT: After cleaning up my solution my build times are blazing fast! :) Plus, I was able to find out that I have some kind of problem with my processor, which didn't show up in the process manager until now... Anyway, I think my problem has been solved somehow...
THANK YOU!


Joining Lists using Linq returns different result than corresponding SQL query?

I have 2 tables

TableA:

TableAID int,
Col1 varchar(8)

TableB:

TableBID int
Col1 char(8),
Col2 varchar(40)

When I run a SQL query on the 2 tables it returns the following number of rows

SELECT * FROM tableA (7200 rows)
select * FROM tableB (28030 rows)

When joined on col1 and selects the data it returns the following number of rows

select DISTINCT a.Col1,b.Col2 FROM tableA a
join tableB b on a.Col1=b.Col1 (6578 rows)

The above 2 tables on different databases so I created 2 EF models and retried the data separately and tried to join them in the code using linq with the following function. Surprisingly it returns 2886 records instead of 6578 records. Am I doing something wrong?
The individual lists seems to return the correct data but when I join them SQL query and linq query differs in the number of records.

Any help on this greatly appreciated.

// This function is returning 2886 records
public List<tableC_POCO_Object> Get_TableC()
{
    IEnumerable<tableC_POCO_Object> result = null;
    List<TableA> tableA_POCO_Object = Get_TableA(); // Returns 7200 records
    List<TableB> tableB_POCO_Object = Get_TableB(); // Returns 28030 records
    result = from tbla in tableA_POCO_Object
         join tblb in tableB_POCO_Object on tbla.Col1 equals tblb.Col1
         select new tableC_POCO_Object
         {
         Col1 = tblb.Col1,
         Col2 = tbla.Col2
         };
    return result.Distinct().ToList();
}


CustomControl with shapes

I would like to create a custom control in order to display a pie chart.
I have a PieSlice class (which I got from the WinRT toolkit project) :

public class PieSlice : Path
{
    #region StartAngle
    public static readonly DependencyProperty StartAngleProperty =
        DependencyProperty.Register(
            "StartAngle",
            typeof(double),
            typeof(PieSlice),
            new PropertyMetadata(
                0d,
                new PropertyChangedCallback(OnStartAngleChanged)));

    public double StartAngle
    {
        get { return (double)GetValue(StartAngleProperty); }
        set { SetValue(StartAngleProperty, value); }
    }

    private static void OnStartAngleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var target = (PieSlice)sender;
        var oldStartAngle = (double)e.OldValue;
        var newStartAngle = (double)e.NewValue;
        target.OnStartAngleChanged(oldStartAngle, newStartAngle);
    }

    private void OnStartAngleChanged(double oldStartAngle, double newStartAngle)
    {
        UpdatePath();
    }
    #endregion

    #region EndAngle
    public static readonly DependencyProperty EndAngleProperty =
        DependencyProperty.Register(
            "EndAngle",
            typeof(double),
            typeof(PieSlice),
            new PropertyMetadata(
                0d,
                new PropertyChangedCallback(OnEndAngleChanged)));

    public double EndAngle
    {
        get { return (double)GetValue(EndAngleProperty); }
        set { SetValue(EndAngleProperty, value); }
    }

    private static void OnEndAngleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var target = (PieSlice)sender;
        var oldEndAngle = (double)e.OldValue;
        var newEndAngle = (double)e.NewValue;
        target.OnEndAngleChanged(oldEndAngle, newEndAngle);
    }

    private void OnEndAngleChanged(double oldEndAngle, double newEndAngle)
    {
        UpdatePath();
    }
    #endregion

    #region Radius
    public static readonly DependencyProperty RadiusProperty =
        DependencyProperty.Register(
            "Radius",
            typeof(double),
            typeof(PieSlice),
            new PropertyMetadata(
                0d,
                new PropertyChangedCallback(OnRadiusChanged)));

    public double Radius
    {
        get { return (double)GetValue(RadiusProperty); }
        set { SetValue(RadiusProperty, value); }
    }

    private static void OnRadiusChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var target = (PieSlice)sender;
        var oldRadius = (double)e.OldValue;
        var newRadius = (double)e.NewValue;
        target.OnRadiusChanged(oldRadius, newRadius);
    }

    private void OnRadiusChanged(double oldRadius, double newRadius)
    {
        this.Width = this.Height = 2 * Radius;
        UpdatePath();
    }
    #endregion

    private void UpdatePath()
    {
        var pathGeometry = new PathGeometry();
        var pathFigure = new PathFigure();
        pathFigure.StartPoint = new Point(Radius, Radius);
        pathFigure.IsClosed = true;

        // Starting Point
        var lineSegment =
            new LineSegment
            {
                Point = new Point(
                    Radius + Math.Sin(StartAngle * Math.PI / 180) * Radius,
                    Radius - Math.Cos(StartAngle * Math.PI / 180) * Radius)
            };

        // Arc
        var arcSegment = new ArcSegment();
        arcSegment.IsLargeArc = (EndAngle - StartAngle) >= 180.0;
        arcSegment.Point =
            new Point(
                    Radius + Math.Sin(EndAngle * Math.PI / 180) * Radius,
                    Radius - Math.Cos(EndAngle * Math.PI / 180) * Radius);
        arcSegment.Size = new Size(Radius, Radius);
        arcSegment.SweepDirection = SweepDirection.Clockwise;
        pathFigure.Segments.Add(lineSegment);
        pathFigure.Segments.Add(arcSegment);
        pathGeometry.Figures.Add(pathFigure);
        this.Data = pathGeometry;
        this.InvalidateArrange();
    }
}

And now I am trying to create a control which can contains multiple pie slices

public class Pie : Control
{
    #region Items Source
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register(
            "ItemsSource",
            typeof(IEnumerable),
            typeof(Pie),
            new PropertyMetadata(
                null,
                new PropertyChangedCallback(OnItemsSourceChanged)));

    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    private static void OnItemsSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var target = (Pie)sender;
        var oldItemsSource = (IEnumerable)e.OldValue;
        var newItemsSource = (IEnumerable)e.NewValue;
        target.OnItemsSourceChanged(oldItemsSource, newItemsSource);
    }

    private void OnItemsSourceChanged(IEnumerable oldItemsSource, IEnumerable newItemsSource)
    {
        UpdatePieSlices();
    }
    #endregion

    public Pie()
    {
        this.DefaultStyleKey = typeof(Pie);
    }

    private void UpdatePieSlices()
    {
        double startAngle = 0;
        foreach (KeyValuePair<string, double> item in ItemsSource)
        {
            PieSlice slice = new PieSlice()
            {
                Fill = new SolidColorBrush(Colors.Red),
                Radius = 100, StartAngle = startAngle,
                EndAngle = (item.Value / 100.0) * 360
            };
            startAngle = (item.Value / 100.0) * 360;
        }
    }
}

The ItemsSource is a collection of KeyValuePair<string, int> which represents the name of the slice and the percentage. I would like to display the slices but I have no idea how...

EDIT :

I have tried this but it doesn't work

<Style TargetType="control:Pie">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="control:Pie">
                    <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">

                        <ItemsControl
                            AutomationProperties.AutomationId="ItemGridView"
                            AutomationProperties.Name="Grouped Items"
                            ItemsSource="{Binding Path=ItemsSource}">

                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <ContentControl Content="{Binding}"/>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <Grid></Grid>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                        </ItemsControl>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


Navbar growing wider than bootstrap column width

I am trying to position navbar fixed to the left-hand side of the screen effectively in a sidebar with the rest of the page content rendering to the right.

Currently, I have tried to split the page into two using bootstrap columns like so:

html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

/********************************************
*                                           *
*                                           *
*               WRAPPERS                    *
*                                           *
*                                           *
********************************************/

#sidebarWrapper {
  height: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}

/********************************************
*                                           *
*                                           *
*             SIDEBAR NAV STYLE             *
*                                           *
*                                           *
********************************************/

.sidebar-nav {
  margin: 0;
  padding: 0;
  top: 0;
  list-style: none;
  position: absolute;
}

.sidebar-nav>li {
  display: inline-block;
  line-height: 20px;
  position: relative;
  width: 100%;
}

/********************************************
*                                           *
*                                           *
*                  DIV STYLE                *
*                                           *
*                                           *
********************************************/

.container-fluid {
  height: 100%;
}

.container-fluid h1 {
  padding: 0;
  margin: 0;
}

/********************************************
*                                           *
*                                           *
*              PAGE BODY STYLE              *
*                                           *
*                                           *
********************************************/

.header {
  height: 10%;
  background-color: yellow;
}

.contentBody {
  height: 80%;
  background-color: green;
}

.footer {
  height: 10%;
  background-color: blue;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-2">
      <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="sidebarWrapper">
        <ul class="nav sidebar-nav">
          <li>
            <a class="firstChild" href="/">Dashboard</a>
          </li>
        </ul>
      </nav>
    </div>
    <div class="col-lg-10">
      <div class="header">
        <h1>Header</h1>
      </div>
      <div class="contentBody">
        <h1>Content</h1>
      </div>
      <div class="footer">
        <h1>Footer</h1>
      </div>
    </div>
  </div>
</div>

However, as you can see from the snippet my navbar seems to brute force over any bootstrap column restrictions and takes the width of the whole page.

How can I prevent it from doing so, so that it takes 100% of the width of the bootstrap column but no more and no less?


Calling an instance method in designated initializer of a Swift class

In Swift programming language, it is mandatory that

“A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.” source of quote from another s/o

Otherwise, an error similar to the following would be displayed

Property 'self.baz' not initialized at super.init call

I would like to implement the following Objective-C code in Swift:

@interface FooBar : NSObject

@property (nonatomic, readonly) NSString *baz;

@end

@implementataion FooBar

@synthesize baz = _baz;

- (instancetype)initWithString:(NSString *)string {
    self = [super init];
    if (self) {
        _baz = [self parseString:string];
    }
    return self;
}

- (NSString *)parseString:(NSString *)string {
    // Perform something on the original string
    return ...;
}

@end

The following implementation would have thrown a compiler error as described above:

class FooBar: NSObject {
    let baz: NSString?

    init(string: NSString?) {
        super.init()
        baz = parseString(string)
    }

    private func parseString(string: NSString?) -> NSString? {
        // Perform something on the original string
        return ...;
    }
}

And if I did the following, I would get an error that says

Use of self in method call 'parseString' before super.init initialises self

class FooBar: NSObject {
    let baz: NSString?

    init(string: NSString?) {
        baz = parseString(string)
        super.init()
    }

    private func parseString(string: NSString?) -> NSString? {
        // Perform something on the original string
        return string;
    }
}

So my solution, presently, is to use a private class method:

class FooBar: NSObject {
    let baz: NSString?

    init(string: NSString?) {
        baz = FooBar.parseString(string)
        super.init()
    }

    private class func parseString(string: NSString?) -> NSString? {
        // Perform something on the original string
        return ...;
    }
}

My question is whether there is a better way to achieve the same or is private class method the best approach?


Change drop folder of Visual Studio Team Services / Visual Studio Online Build to Assembly Version

I want my Visual Studio Team Services Build to use the Assembly Version of my Executable. Is there any simple way to achieve that?

I know it is possible to pass parameters into the build process, but how can i define a parameter in one step and consume it later ?


aptana javascript code assistance (Some code assistances are missing)

I'm currently learning and playing around with javascript on Aptana 3 IDE. I love Aptana's code completion and template features of it but I'm having trouble with getting full code assistance for my javascript development. For instance, if I have a new Image instance like

var imgSprite = new Image();

and if I call it by saying imgSprite, it wouldn't suggest me code suggestion for like:

imgSprite.addEventListener('load', loadImage, false);

but it does suggest me code suggestions including imgSprite.src

So are there any extensions or plugin that I can install to get all those code assistance features working in my Aptana 3 IDE? or perhaps you can suggest me other IDE with all these features embedded? Thanks


Possible to create custom urls with RESTful routing in Laravel 4

Is it possible to have custom urls without renaming controller methods when using RESTful routing with Route::controller?

With Route::controller('users', 'UsersController'); I want the url to be users/registration instead of users/create without renaming getCreate method in UsersController.


tastypie: filter many to many tables with multiple, ANDed values

I have two tables (Movie and Genre) that are connected with a many to many relation using a crosstable (MovieGenre).

My models.py file looks like this:

class Genre( models.Model ):

    sName = models.CharField( max_length=176)
    [ .. ]

class Movie( models.Model ):

    sTitle = models.CharField( max_length=176)
    genre = models.ManyToManyField( Genre )
    [ .. ]

class MovieGenre( models.Model ):

    idMovie = models.ForeignKey( Movie )
    idGenre = models.ForeignKey( Genre )

I want to use tastypie to filter all movies of certain genres. E.g. show me all movies that are of genre Action, Thriller and SciFi.

My api.py looks like this:

class GenreResource(ModelResource):
    class Meta:
        queryset = Genre.objects.all()
        resource_name = 'genre'
        always_return_data = True
        include_resource_uri = False
        excludes = ['dtCreated', 'dtModified' ]
        authorization= Authorization()
        authentication = SessionAuthentication()
        filtering = {
            "id" : ALL,
        }

class MovieResource(ModelResource):
    genre = fields.ManyToManyField( 'app.api.GenreResource', 'genre', full=True )
    class Meta:
        queryset = Movie.objects.all()
        resource_name = 'movie'
        authorization= Authorization()
        authentication = SessionAuthentication()
        always_return_data = True
        include_resource_uri = False
        excludes = ['dtCreated', 'dtModified' ]
        filtering = {
            "sTitle" : ALL,
            "genre" : ALL_WITH_RELATIONS,
        }

My test data:
Two movies (with genre ids)
Matrix (1 & 3 )
Blade Runner (1 & 2 )

First I make a query on the title, as expected below query returns 1 result (namely Matrix):

   http://localhost:8000/api/v1/movie/?format=json&sTitle__icontains=a&sTitle__icontains=x

However, I get three results with the URL that should query the related genre table (two times Matrix and once Blade Runner) with this query:

    http://localhost:8000/api/v1/movie/?format=json&genre__id__in=3&genre__id__in=1

I would expect to get back only Matrix

I also tried to override apply_filters like so:

def apply_filters(self, request, applicable_filters):
    oList = super(ModelResource, self).apply_filters(request, applicable_filters)
    loQ = [Q(**{'sTitle__icontains': 'a'}), Q(**{'sTitle__icontains': 'x'})]
    # works as intended: one result
    loQ = [Q(**{'genre__id__in': '3'}) ]
    # results in one result (Matrix)

    loQ = [Q(**{'genre__id__in': '1'}), Q(**{'genre__id__in': '3'}) ]
    # results in no results!

    loQ = [Q(**{'genre__id__in': [ 1, 3]}) ]
    # results in two results Matrix and Blade Runner which is OK since obviously ORed
    oFilter = reduce( operator.and_, loQ )
    oList = oList.filter( oFilter ).distinct()
    return oList

Any idea to make this work?

Thanks for any idea...


Search Outlook contacts by email using AppleScript and mdfind

Is there a more-efficient way to determine if a contact doesn't exist than this:

set theAddress to "foo@bar.com"

set found to false

repeat with aContact in contacts

  if email addresses of aContact contains theAddress then
    set found to true
    exit repeat
  end if

end repeat

if not found then
  ...
end if

This will create a new contact if it isn't found (and return true):

set found to open contact email address "foo@bar.com"

** edit **

Search Outlook contacts by category suggests that I should be able to do this using a Spotlight query:

-- the address to be found
set theEmailAddress to "foobar@acme.com"

-- search identity folder
set currentIdentityFolder to quoted form of POSIX path of (current identity folder as string)

--perform Spotlight query
set theContacts to words of (do shell script "mdfind -onlyin " & currentIdentityFolder & "  'kMDItemContentType == com.microsoft.outlook14.contact && [metadata element that represents an email address] == " & theEmailAddress & "' | xargs -I % mdls -name com_microsoft_outlook_recordID '%' | cut -d'=' -f2 | sort -u | paste -s -")

-- process results
...

What is the metadata element that represents a contact's email address?


Regex for matching some characters that should be left out later

I will try to explain my situation with an example, consider the following string:

03 - The-Basics-of-Querying-the-Dom.mov

I need to remove all -s (hyphens) excluding the one after the digits. In other words, all hyphens in between the words.

This is the REGEX I created: /([^\s])\-/. But the problem is, when I try to replace, the character before the space is also removed.

Following the result I am aiming for:

03 - The Basics of Querying the Dom.mov

Think, I can use something like exclude groups? I tried to use ?: & ?! in the capture group to avoid it from being matched, but didn't give any positive results.


Chronos setting environment variable leads to error

I tried this both on the chronos config and in my job definition:

    "environmentVariables": [
        {
            "name": "DOCKER_API_VERSION",
            "value": "$(docker version --format '{{.Server.Version}}')"
        }
    ],

It always fails with:

docker: Error response from daemon: 404 page not found.
See 'docker run --help'.

The reason I'm trying to set that variable is because I'm running docker in docker and the client docker API sometimes has a different version than the server docker version and it has to be started with the DOCKER_API_VERSION env set in order to work.

I'm suspecting it's because of the computed value being set instead of a string value.

In the logs I can see it runs as supposed and I don't know why it crashes to be honest:

docker run ... -e DOCKER_API_VERSION=$(docker version --format '{{.Server.Version}}') ...


Java : How to include a .properties file that is outside of jar into classpath?

We would like to keep the .properties file out of the jar so that we can change the properties used in a module and we do not have to re-install the module.

Before Java 8, we used to run a script and include the .properties file in the way below and it worked. But since when we updated to Java 8 , this way of including .properties file in classpath is not working, means java program fails not finding the .properties file.

My script to run the java project:

/usr/java/latest/bin/java -d64 -Xms1G -Xmx16G -XX:MaxPermSize=128m -XX:-UseGCOverheadLimit -cp "/online/sand/lib/client-api-1.0.0.jar:/online/sand/oap_pub/lib/*:/online/sand/oap/oap_dw/run/client_api/application.properties" team.online.client.api.ClusterManagerProcessor  | tee -a client_api.log

We are using Sping context to pick up the properties file this way:

<util:properties id="app_props"
                 location="classpath*:/application.properties" />

Then a property in that appilcation.properties files is being used ( in many different files) this way:

@Value( "#{app_props[\"SERVICE_PATH_GET_METADATA\"]?:''}" )
private String metadataServicePath;

Looking for a way to keep the.properties file out of the jar and in classpath so that Spring context finds that file.

Is their any other way than using ? We need to keep the properties file excluded from jar

class.getClassLoader( ).getResourceAsStream( "application.properties" );

Thanks in advance.


Is it possible to use Aero Peek for MDI children within a winforms application?

I've seen from the Windows API Code Pack that it is possible to enable custom glass in a winforms application, but I've been unable to ascertain how to get child windows to show as separte thumbnails for aero peek (in much the same manner that IE displays the contents of its tabs as separate windows)

Is it possible to do this from a Winforms application, or will it involve lots of P/Invoke voodoo?


Resetting animation in Android without starting it

I have an AnimationDrawable that is running. How to stop & reset it so that it does not start again until start() is called? Calling setVisible(true, true) resets it, but also immediately starts animation, and I'd like to avoid it.


Android - How to display an ImageView as a header in a listactivity?

I'm trying to display an image before the list in a listactivity.

If I put an ImageView before the ListView, then only the list is displayed... still quite an android n00b so any pointers appreciated :)

Heres my main.xml which lays out the list activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView android:id="@+id/header"
      android:src="@drawable/header"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_gravity="top"
      android:scaleType="fitStart"
      />

    <ListView android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitEnd"
        />
</LinearLayout>


How to avoid `require` and Access the controller of the parent component in transclusion

I'm trying to build a form component that receives an object as input and use the template defined into the object to ng-include the right template to render the form defined in the model.

The problem I have is the object might be defined in the above component. For example this:

   <somecomponent>
     <formx object="$ctrl.settings"></formx>
   </somecomponent>

Unfortunately, it doesn't seem to work. From what I read the transcluded block should be using the scope of the above controller. Is there a way to access the scope of the component somecomponent?

By the way, what I'm looking for is to do the same as:

 <div ng-controller="SomeController as ctrl">
   <formx object="ctrl.settings"></formx>
 </div>

But instead of using a plain controller I'd like to use a component without using an explicit require as the parent component might be different from time to time.


How to make RuboCop inspect a file in a folder that starts with dot

I want to run RuboCop for VisualEditor repository. At the moment, the only Ruby file I could find in the repository is .docs/CustomTags.rb.

$ find . | grep rb
./.docs/CustomTags.rb

If I run only rubocop, it does not find any files:

$ rubocop
Inspecting 0 files
0 files inspected, no offenses detected

I guess it ignores files in folders that start with dot (.docs).

RuboCop documentation on including files says:

If you'd like it to check other files you'll need to manually pass
  them in, or to add entries for them under AllCops/Include.

If I provide path to the file from the command line, RuboCop finds the file:

$ rubocop .docs/CustomTags.rb
Inspecting 1 file
W
(...)
1 file inspected, 26 offenses detected

Our continuous integration just runs rubocop for the repository, so I can not provide path to the file from the command line. I have to use AllCops/Include, but I can not figure out how to do it.

If I create a .rubocop.yml in the root of the repository:

AllCops:
  Include:
    - '.docs/CustomTags.rb'

and run Rubocop, it does not find the file:

$ rubocop
Inspecting 0 files
0 files inspected, no offenses detected

I have tried several variations of the .rubocop.yml file, including:

AllCops:
  Include:
    - '**/CustomTags.rb'

and

AllCops:
  Include:
    - '.docs/**/*'

But none of them are finding the file.


Creating CSS at rules (@rules) on the fly in Javascript

I'm creating CSS animations on the fly, so I need to insert a CSS timing function into my document.  As in:

@-webkit-keyframes slide
{
    from {
    -webkit-transform: translateX(-100px) translateY(-100px);
    -webkit-animation-timing-function: ease-in;
    }

    33% {
    -webkit-transform: translateX(-100px) translateY(-50px);
    -webkit-animation-timing-function: linear;
    }

    66% {
    -webkit-transform: translateX(-50px) translateY(0px);
    -webkit-animation-timing-function: linear;
    }

    to {
    -webkit-transform: translateX(0px) translateY(0px);
    -webkit-animation-timing-function: ease-out;
    }
}

Any idea how to pull this off (the insertion) using Javascript?  I can add regular classes without any trouble, but this seems to be a special case.


How to simplify complicated if then conditions?

I have a situation where I have to exclude an ever growing list of conditions in an if statement that started out rather simple

I've thought of looping an list/array and I use RegEx when possible.

I would just like to know what others have done to try and simplify these situations.

here's a quick example:

if (!DataField.Contains(strText) & (strOtherText.IndexOf(strFindThis) < 0) || Regex.isMatch(strWithLetters, @"[A-Z]"))
{
    //Do things;
}
else
{
    //Do Other Things;
}

Still learning the RegEx but I'm working on it

So far it's been strings of several words or simply certain characters.

For example:

"#, &, ^, @, and more.."

"Form 9999-99 invalid client name"

Can't start with "https" or "http"

In some case if it contains a string like "Error Code" then it would be saved in an alternate file instead of simply being ignored for processing

I have 23 of these so far


Flash AS3 - Colorized username list box different colors

I have found several tutorials regarding CellRenderer that will change an entire list or selected item, but Im not all that good with AS3 yet and need some help. I am loading a userlist from an xml file. Everything loads fine and well, but what Im looking to do is actually colorize it by the group.

Again, it loads to the list just fine, what I am looking to do is in the loop that adds them from the xml file, if its admin make it red font, green font for mod, black for member.

Any help please?


MySQL query combining several tables

Background

In order to obtain data for my thesis I have to work with a large, fairly
complicated MySQL database, containing several tables and hundreds of GBs of
data. Unfortunately, I am new to SQL, and can't really figure out how to
extract the data that I need.

Database

The database consists of several tables that I want to combine. Here are the
relevant parts of it:

> show tables;
+---------------------------+
| Tables_in_database        |
+---------------------------+
| Build                     |
| Build_has_ModuleRevisions |
| Configuration             |
| ModuleRevisions           |
| Modules                   |
| Product                   |
| TestCase                  |
| TestCaseResult            |
+---------------------------+

The tables are linked together in the following manner

Product ---(1:n)--> Configurations ---(1:n)--> Build

Build ---(1:n)--> Build_has_ModuleRevisions ---(n:1)--> ModuleRevision ---(n:1)--> Modules

Build ---(1:n)--> TestCaseResult ---(n:1)--> TestCase

The contents of the tables are

> describe Product;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| name    | varchar(255) | NO   | UNI | NULL    |                |
+---------+--------------+------+-----+---------+----------------+

> describe Configuration;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| Product_id | int(11)      | YES  | MUL | NULL    |                |
| name       | varchar(255) | NO   | UNI | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

> describe Build;
+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| id               | int(11)      | NO   | PRI | NULL    | auto_increment |
| Configuration_id | int(11)      | NO   | MUL | NULL    |                |
| build_number     | int(11)      | NO   | MUL | NULL    |                |
| build_id         | varchar(32)  | NO   | MUL | NULL    |                |
| test_status      | varchar(255) | NO   |     |         |                |
| start_time       | datetime     | YES  | MUL | NULL    |                |
| end_time         | datetime     | YES  | MUL | NULL    |                |
+------------------+--------------+------+-----+---------+----------------+

> describe Build_has_ModuleRevisions;
+-------------------+----------+------+-----+---------+----------------+
| Field             | Type     | Null | Key | Default | Extra          |
+-------------------+----------+------+-----+---------+----------------+
| id                | int(11)  | NO   | PRI | NULL    | auto_increment |
| Build_id          | int(11)  | NO   | MUL | NULL    |                |
| ModuleRevision_id | int(11)  | NO   | MUL | NULL    |                |
+-------------------+----------+------+-----+---------+----------------+

> describe ModuleRevisions;
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| Module_id | int(11)      | NO   | MUL | NULL    |                |
| tag       | varchar(255) | NO   | MUL |         |                |
| revision  | varchar(255) | NO   | MUL |         |                |
+-----------+--------------+------+-----+---------+----------------+

> describe Modules;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| name    | varchar(255) | NO   | UNI | NULL    |                |
+---------+--------------+------+-----+---------+----------------+

> describe TestCase;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| TestSuite_id | int(11)      | NO   | MUL | NULL    |                |
| classname    | varchar(255) | NO   | MUL | NULL    |                |
| name         | varchar(255) | NO   | MUL | NULL    |                |
| testtype     | varchar(255) | NO   | MUL | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

> describe TestCaseResult;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| Build_id    | int(11)      | NO   | MUL | NULL    |                |
| TestCase_id | int(11)      | NO   | MUL | NULL    |                |
| status      | varchar(255) | NO   | MUL | NULL    |                |
| start_time  | datetime     | YES  | MUL | NULL    |                |
| end_time    | datetime     | YES  | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

As you can see the tables are linked with *_id fields. E.g. TestCaseResult
is linked to a Build by the Build_id field, and to a TestCase by the
TestCase_id field.

Problem Desciption

Now to my problem. Given a specific Configuration.name and Product.name as
input, I need to find all modules+revisions and failed testcases, for every
Build, sorted by Build.start_time.

What I Have Tried

The following query gives me all the Builds given a Configuration.name of
config1 and a Product.name of product1

SELECT
    *
FROM
    `database`.`Build` AS b
        JOIN
    Configuration AS c ON c.id = b.Configuration_id
        JOIN
    Product as p ON p.id = c.Product_id
WHERE
    c.name = 'config1'
        AND p.name = 'product1'
ORDER BY b.start_time;

This doesn't even solve half of my problem, though. Now, for every build I
need to

Find all Modules linked to the Build

Extract the Modules.name field

Extract the ModuleRevision.revision field

Find all TestCases linked to the Build

Where TestCaseResult.status = 'failure'

Extract the TestCase.name field linked to the TestCaseResult

Associate the Build with the extracted module name+revisions and testcase
names

Present the data ordered by Build.start_time so that I can perform
analyses on it.

In other words, of all the data available, I am only interested in linking the
fields Modules.name, ModuleRevision.revision, TestCaseResult.status, and
TestCaseResult.name to a particular Build, order this by Build.start_time
and then output this to a Python program I have written.

The end result should be something similar to

Build Build.start_time    Modules+Revisions               Failed tests
    1         20140301    [(mod1, rev1), (mod2... etc]    [test1, test2, ...]
    2         20140401    [(mod1, rev2), (mod2... etc]    [test1, test2, ...]
    3         20140402    [(mod3, rev1), (mod2... etc]    [test1, test2, ...]
    4         20140403    [(mod1, rev3), (mod2... etc]    [test1, test2, ...]
    5         20140505    [(mod5, rev2), (mod2... etc]    [test1, test2, ...]

My question

Is there a good (and preferrably efficient) SQL query that can extract and
present the data that I need?

If not, I am totally okay with extracting one or several supersets/subsets of
the data in order to parse it with Python if necessary. But how do I extract
the desired data?


IFERROR INDEX/MATCH formula having application-defined or object-defined error

I am trying to create a macro allowing me to autofill data from another workbook using INDEX MATCH. I have used the exact code for another formula and it works but when i simply replace for formula in the code below, it gives me a "application-defined or object-defined error"

Below is my code. The formula in question starts after .formula. The rest of the code exists for me to autofill empty cells and it has already worked with another macro.

Sub FillOrderType()
Dim LR As Long
LR = ActiveSheet.UsedRange.Find("*", SearchDirection:=xlPrevious,
SearchOrder:=xlByRows).Row
With Range("H2:H" & LR)
With .SpecialCells(xlCellTypeBlanks)
.Formula = "=IFERROR(INDEX('C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]EXP'!N:N, MATCH(G:G,'C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]EXP'!L:L,0)), IFERROR(INDEX('C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]AOG'!N:N,MATCH(G:G,'C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]AOG'!L:L,0)),IFERROR(INDEX('C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]SCHED'!M:M,MATCH(G:G,'C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]SCHED'!K:K,0)),"")))"
End With
.Value = .Value
End With

End Sub

Any help identifying the problem would be greatly appreciated. And I apologise for the long formula, I have tried to wrap it by using _ but it just didn't work.

EDIT:

I believe that the issue lies solely on the formula itself since it highlights whenever I try debugging

=IFERROR(INDEX('C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]EXP'!N:N, MATCH(G:G,'C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]EXP'!L:L,0)), IFERROR(INDEX('C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]AOG'!N:N,MATCH(G:G,'C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]AOG'!L:L,0)),IFERROR(INDEX('C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]SCHED'!M:M,MATCH(G:G,'C:\Users\wwxuan\Desktop\KPI OUTBOUND 23.08.16\[KPI  Outbound - ( Aug ) Rev5.xlsx]SCHED'!K:K,0)),"")))

But I have little clue on how to convert it into VBA code. In the formula, the value i want lies in different worksheets in another workbook and I use IFERROR and INDEX MATCH to get the values I want.


tkinter: How can I get the users choice of filetype in the asksaveasfilename-dialog?

currently, I'm programming a GUI, which should allow the user to save a file and select the filetype (lets say: jpg, bmp). I'm using tkinter with Python 3.4.

Unfortunately, I am unable figure out, which filetype the user has selected: I'm using the asksaveasfilename-dialog and all I can get is the path:

from tkinter import filedialog
path = filedialog.asksaveasfilename(filetypes = [('Bitmap', '.bmp'),('jpg', '.jpg')])

I can try to extract the extension from the path, but that can leed to unexpected behaviour:

if the user doesn't provide the extension in the filename but selects the filetype, "path" doesn't contain any extension

if the user first decides to use the filename "example.bmp" but afterwards selects jpg as filetype, the extension is not updatet (as it normally is in window). So "path" will still be: C:\ ... \example.bmp

Is there a way to get the filetype, that the user selected?
Is there any other way around?


Googlemaps v3 groundoverlays loop

I wrote a script to load weather 10 radar maps into an array and want to display an animation on a Google map or the last image.
My idea was to display one image and clear it after a delay, and go to the next one.
I can't figure out why the following code fails... Any guess ?

My test page : http://www.egloff.eu/rsmaptest/rsmap.php

My code :

function nextRadarMap() {
    // delete overlays
    deleteOverlays();
    // push the new images into an array of overlays
    for (i = 0; i < 10; i++) {
        radarMap = new google.maps.GroundOverlay(images[i], boundaries, {
            clickable: false
        });
        imagesArray.push(radarMap);
    }
    // choose to display fixed or animated image
    if (animToggle == true) {
        l = imagesArray.length;
        for (i = 0; i < l; i++) {
            imagesArray[i].setMap(map);
            // erase previous image. use of modulus to foolproof when i=0
            //setTimeout( function() {imagesArray[(i+l-1)%l].setMap(null)},500);
            setTimeout(function () {
                clearOverlays()
            }, 500);
        }
    } else {
        // display most recent image
        imagesArray[0].setMap(map);
    }
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (imagesArray) {
//   for (i in imagesArray) {
    for (i=0; i<imagesArray.length; i++) {
      imagesArray[i].setMap(null);
    }
  }
}


For loop: save results of function in separate vector for each i

I have a dataframe with two columns. One for mean, one for std. deviation.
I'd like to run a for loop and safe the results of

rnorm(1000,dataframe[i,1],dataframe[i,2])

in a vector with associated i in the name.

Like: vector_i, vector_i+1, vector_i+2.....

Any idea?


mod_rewrite - exclude urls

I need a mod_rewrite to redirect all http requests to https, but I want do exclude some URLs

#   force https
RewriteCond %{HTTPS}            off
RewriteCond %{HTTP_HOST}        ^secure\. [NC]
RewriteCond %{REQUEST_URI}      !gateway_callback [NC]
RewriteRule ^.                  https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,QSA]

All URLs which match gateway_callback must be excluded

This URL should not be redirected, but it does!?

http://secure.localhost/da/gateway_callback/29/

Have tried to flush DNS cache in the browser, but the URL is still redirected to https


Where is the error in my Conditional Statement (PHP)?

The challenge is:

If n is odd, print "Weird".

If n is even and in the inclusive range of 2 to 5, print "Not Weird".

If n is even and in the inclusive range of 6 to 20, print "Weird".

If n is even and greater than 20, print "Not Weird".

And My Code is:

<?php
$N=5;

if($N%2==0 && $N>20){
    echo "Not Weird";
}else{
    echo "Weird";
}
?>

And the problem is:

When I rut it locally it's okay. But when I submit it to HackerRank then it fails their test when comes to $N=5; case. Do I have any problems in my conditional according to the challenge?


How can I import python libraries with .pyx and .c files without installing on the computer?

I am writing code for a number of other people, none of whom are particularly computer savvy. I installed python 2.7 for all of them, but I really do not want to have to install anything else.

To get around installing every library that I wanted to use, I've simply been including the library source code in the same folder as my project source code. Python automatically searches for the necessary files in the working directory, and all goes well.

The problem came when I tried to install pandas. Pandas is a library that includes .pyx and .c files that are compiled on install. I cannot just include these files in with my source code, because they are not in the proper form.

How can I either compile these on launch or pre-compile them for ease of transfer? (And the kicker, I need a solution that works cross platform--I work on Windows 7, my colleagues work on OSX.)

Thank you in advance.


how to recognise a zebra crossing from top view using opencv?

you can get all the details about the problem from this pdf document: www.shaastra.org/2013/media/events/70/Tab/422/Modern_Warfare_ps_v1.pdf

how to recognize a zebra crossing from top view using opencv ??
it is not a straight zebra crossing it has some twists and turns
i have some ideas,
1. parallel line detection but the available techniques only works to find straight parallel not the ones that has curve in it.
2. template matching to match a template of back to back white and black stripes but it becomes tedious since i cant find any pattern matching techniques with scaling and rotation.

in fact a idea on any single part of the problem will be so helpful!!
it is driving me crazy someone please help!!!!
any help is appreciated
thanks in advance ....

NOTE:
 the zebra crossing i am talking about has the inside lines perpendicular to the border lines, just like a normal zebra crossing. only difference is that the path has curves like a river


Android Spinner look and feel like ICS

I like the look and feel of the Spinner in Android ICS. I support a minimum of android 2.1 so i want the Spinner to have an ICS look on the Android 2.1. Is this possible.

Kind Regards,


Append JavaScript or StyleSheet from View_Helpers called inside a Layout

is it possible to make it happen?
My view helper works fine if in a view that was a result of a controll. But I would like to have some dinamic layout, for example, to render a jquery menu according to the state I'm in.

If I call the helper from layout headScript never happens to echo the appendScript command I did inside the helper.

thanks!


AngularJS 1.6 Routing

I'm setting up my routing for a AngularJS v1.6 app, but I am running into a slight problem.

I am getting the following error, and I can't seem to figure out what is wrong. I hope you guys can shed some light into my error.

Uncaught Error: [$injector:modulerr] <http://errors.angularjs.org/1.6.1/$injector/modulerr?p0=app&p1=Error%3A%20%…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.1%2Fangular.min.js%3A21%3A332>)
    at angular.js:38
    at angular.js:4759
    at q (angular.js:357)
    at g (angular.js:4720)
    at eb (angular.js:4642)
    at c (angular.js:1838)
    at Mc (angular.js:1859)
    at pe (angular.js:1744)
    at angular.js:32977
    at HTMLDocument.b (angular.js:3314)

Below is my code:

app.js;

(function () {
    "use strict";

    angular.module("app", [
        "ngRoute",
        "app.home",
        "app.products",
        "app.contact"
    ])

    .config(function ($routeProvider) {

        $routeProvider
            .when("/",
            {
                controller: "homeController",
                templateUrl: "app/components/home/home.html"
            })
            .when("/products",
            {
                controller: "productsController",
                templateUrl: "app/components/products/products.html"
            })
            .when("/contact",
            {
                controller: "contactController",
                templateUrl: "app/components/contact/contact.html"
            });
    });

})();

This is one of my controller (All 3 are the same) ...

(function() {
    "use strict";

    angular
        .module("app.home", [])
        .controller("homeController", homeController);

    function homeController() {
        this.helloWorld = "Hello World";
    }

});


Simple email regex, make sure user includes dot domain?

I don't mess around with Regex too much but have been able to get this one online. /.+@.+/. This will return true with both joe@joe and joe@joe.com. I want to make it so a user must supply a domain extension otherwise I want it to fail, I presume this is quite simple but I just can't figure it out. I've tried /.+@.+.\S/ but that didn't work. Any help would be great, thanks!

This will be used in both PHP and javascript. The current one works in both, the new will need to also.


How to store output of os.system() in a variable

I wrote a small code:

import os
os.system('users')
os.system('w')

This prints

ubuntu
 09:27:25 up 9 days, 21:23,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
ubuntu   pts/0    42.99.164.66     09:06    5.00s  0.10s  0.00s sh -c w

But when i try :

import os
from pyslack import SlackClient

user_name = os.system('users')
login_details = os.system('w')

print user_name
print login_details

It has the following output:

ubuntu
 09:28:32 up 9 days, 21:24,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
ubuntu   pts/0    42.99.164.66     09:06    0.00s  0.11s  0.00s w
0
0

Now i am not sure why i am not able to store the result in the varible , i.e why is it printing 0 ? And what should be the correct way to get rid of it?


Android Studio Gradle Option Error

When I went to re-sync my project to gradle, the option is grayed out. Why is this? How can I prevent this? I have tried opening new projects and the option is grayed out there as well. Additionally it worked earlier in the day.


Firefox and owl carousel issue

I'm not 100% sure if this is the correct spot to post this question.
In a website I'm using owl carousel 2. This plugin works perfectly however I noticed a weird issue in FireFox.

It looks like either owl-carousel or Firefox adds black lines around an owl-item.
This only happens (as far I can see) on 4k screens.

Does anybody experienced the same issue? Does anybody know what that can be and how to fix that?

This has probably something to do with 3d rendering??


Split Screen In Two (Horizontally or Vertically)

I am trying to build a screen that is split down the middle horizontally when in landscape and vertically when in portrait.  I have tried the below, but it does not work like I was expecting.  Any help would be greatly appreciated!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="fill_parent" android:layout_gravity="left"
        android:orientation="horizontal">
        <ListView android:layout_width="fill_parent" android:id="@+id/lvChoices"
            android:layout_gravity="left" android:layout_height="fill_parent" />
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:orientation="horizontal">
        <ListView android:layout_width="fill_parent" android:id="@+id/lvOptions"
            android:layout_gravity="right" android:layout_height="fill_parent" />
    </LinearLayout>
</LinearLayout>


SelectedItem binding stops working when using custom DataTemplate on Listbox

I've got a simple ListBox which entries are bound from an ObservableCollection<T> inside the view model. Additionally, I got a binding to a SelectedItem property.

<ListBox ItemsSource="{Binding Entries}" SelectedItem="{Binding SelectedEntry}" />

For some requirements I need to modify the actual list box items, so I made a custom DataTemplate like this:

<DataTemplate>
    <ListBoxItem ... />
</DataTemplate>

However, as soon as the DataTemplate is there, the SelectedItem binding stops working. It just doesn't fire at all, no matter what I do. If I take the whole DataTemplate away, it starts working again. Since I've got a custom ListBoxItem, do I have to somehow bind itself to the SelectedItem property of the ListBox? Or am I simply missing something here?

Full Code

<ListBox x:Name="Entries" ItemsSource="{Binding Entries}" Grid.Column="1" Margin="5, 5, 0, 5" SelectedItem="{Binding SelectedEntry}" >
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="Height" Value="5" />
                <Setter Property="Margin" Value="0" />
                <Setter Property="Padding" Value="0" />
                <Setter Property="BorderThickness" Value="0" />
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ListBoxItem Background="{Binding EntryColor}"
                             ToolTipService.InitialShowDelay="0"
                             ToolTip="{Binding SequenceNumber, StringFormat=Sequence {0:D12}}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>


How to center text in a div element?

I'm trying to create square element, that will have text centered both vertically and horizontally. Additionally, the whole area of the square should be a link. This is my HTML:

<div class="w1h1 medium">
    <a class="userLink" target="_blank" href="Fancybox.aspx">
        <table style="width: 100%; height: 100%">
            <tr style="vertical-align: central">
                <td style="text-align: center; font-weight: bold;">
                    text in the middle
                </td>
            </tr>
        </table>
    </a>
</div>

And this is my CSS:

div.w1h1 {
    width: 150px;
    height: 150px;
}

.medium {
    background-color: #06849b;
    color: white;
    font-family: sans-serif;
}

a.userLink
{
    width: 150px;
    height: 150px;
    display: table;
    color: #FFFFFF;
    text-decoration: none;
}

It works in Chrome and Firefox, but not in Internet Explorer. In IE the text is at the top of the square, not in the middle. Can you help me with this?

I just created playground here: http://jsfiddle.net/Tschareck/yfnnm/


dynamically create a class without a namespace

I am trying to dynamically create a class using the eval method.  It is working fine except for one small problem.  As my code shows I am creating the Browser class inside the BrowserFactory class.  When I do this the Browser class has an added namespace of BrowserFactory.  Is there anyway to evaluate the Browser class from a string without the BrowserFactory namespace being attached?

class BrowserFactory
  def self.create_browser(browser)
    super_class = nil
    case browser
    when 'IE'
      require 'watir'
      super_class = 'Watir::IE'
    when 'celerity'
      require 'celerity'
      super_class = 'Celerity::Browser'
    end

    raise StandardError.new("Browser '#{browser}' is not currentlys supported") if super_class.nil?

    eval <<EOS
class Browser < #{super_class}
include Singleton
include BrowserModification
end
EOS

    return Browser.instance
  end

end


Search and replace with shell script

I need a shell script to find and replace text that would go like:

For each line in a file
  find equation mark "="
  remove everything up to the equation mark on that line and replace it with the string cuts[Counter] where Counter counts how many times such substitutions have been made.

Could anybody help me out with getting started with a script like that?


Jekyll: Include Menu at different levels makes problems

I include an overall menu with jekyll at different pages.

So this menu is for example included in index.html but also at deeper levels like /portfolios/someportfolio.html.

Now the issue is that the menu links do not work at deeper levels.
They include the submenu path like .../<b>portfolios</b>/menuitem.html.

What can I do to address this?


why multiple background images does not work for IE?

I have this code which works nice in Chrome and Firefox, but on IE only the second background image appears... Do you know why?

    $('input[type=button]').click(function() {
    //search for the button
    var button = document.getElementsByName("contactme");
    //change the image
    button[0].style.background = "url(http://www.restorationsos.com/imgs/loader.gif) no-repeat,  url('http://www.restorationsos.com/imgs/btnBG.gif') repeat-x";
    //change the text
    button[0].value = "We Are Connecting You...";
    button[0].style.textAlign = "right";
    button[0].style.color = "#ea2400";
    //disable the button
    button[0].disabled = true;
});

Live: http://jsfiddle.net/cristiboariu/pUeue/21/


Google Analytics - Track users questionnaire scores

I'm building a questionnaire where the user completes a set of multiple choice questions which eventually scores them into one of three categorises - low/medium/high.

A click event on a 'Get score' button stores the user score into a js variable.

Is there anyway i can track (using google analytics) how many users scored under each of these categories? Would i need to use custom variables for this?

Sami.


OpenJDK Client VM - Cannot allocate memory

I am running Hadoop map reduce job on a cluster.
I am getting this error.

OpenJDK Client VM warning: INFO: os::commit_memory(0x79f20000, 104861696, 0) failed; error='Cannot allocate memory' (errno=12)

There is insufficient memory for the Java Runtime Environment to continue.

Native memory allocation (malloc) failed to allocate 104861696 bytes for committing reserved memory.

what to do ?


Force iOS Device to Download App

I wonder if it is possible to force an iOS Device to download an app.

I have a 1 Year Apple Developer Account and i can create Profiles.

I heard that if Users install your Profile Configuration you can do some actions.
Now i thought instead of connecting a Device over USB to PC and Load an IPA to the Device , to Force a Device UDID (with a Installed Profile) to download an App without having it to be connected to pc


PHP breaking URL by encoding ampersand

I'm debugging a site where this code is intended to display in image:

<a href="<?=$auction_link;?>"><img src="<? echo ((!empty($main_image)) ? 'thumbnail.php?pic=' . $main_image . '&w=' . $layout['hpfeat_width'] . '&sq=Y' : 'themes/' . $setts['default_theme'] . '/img/system/noimg.gif');?>" border="0" alt="<?=$item_details[$counter]['name'];?>"></a>

No image is displayed, evidently because the href value is being converted to:

thumbnail.php?pic=uplimg/img_A_100430_b93204949c62ffba35eb62f1b94b93c4.jpg&amp;w=0&amp;sq=Y"

When it should be:

thumbnail.php?pic=uplimg/img_A_100430_b93204949c62ffba35eb62f1b94b93c4.jpg&w=250&sq=Y

Note the &amp; where the & should be in two places. Is there anyway to stop the encoding?

Thanks - Joe


tableview header moves down when reloading. Swift -iOS

I am using a Tabbarcontroller with navigation bar.
There are two ViewControllers in the Tabbarcontroller.
There is a search bar and below it i display a table.
This table is grouped normally. It displays date based grouped customCellA, and the date is my header.
When searching I clear the header height (to zero) and and display a single section. This section contains search result displayed in customCellB.

All the above ui have been created in storyboard

When I switch between tabbars and come back to this viewController. The gap between the search bar (which includes header) and the first cell group seems to increase.

I tried different options like (mostly in viewwillappear)

Calling reloadData() twice

calling tableView.layoutSubviews()

automaticallyAdjustsScrollViewInsets

contentOffset

edgesForExtendedLayout

Should i use them in viewdidlayoutsubviews...?

I Used folllowin links

Swift ios 9: Section header change position after reload data

iOS 7 Custom TableView Is Under TabBar

Swift: Tableview scrolls under navigation bar but over status bar?

and more

Nothing seems to work. I am not sure where i am going wrong.
I am using swift3 and xcode 8.3.X

I am unable to show the error here as its official project.
Please suggest a possible solution.


Real time communication

I have the same dilemma as the one who posted this topic, Real-time communication with WCF
except that my problem is not about games programming. I would like to know what's the best method to use to be able to have a real time communication in between two windows applications (server-client). I am using visual c++/c# to date and i would like to be able to display all the Feeds that are being received by my server to the client in real time.

I have started trying to use .NET remoting but in my continuous research, it appears that it will use SOAP-http, and might affect the speed of the communication. My server and client will communicate using the internet and .NET remoting does not permit the use of TCP Channel when communicating in between a firewall or the internet.

Your inputs will be greatly appreciated.


Sorting on associated domain objects with DetachedCriteria

Having such a domain model:

package com
class Bar {
    String barName
}

package com
class Foo {

    static belongsTo = [bar: Bar]

    String fooName
    Integer fooAge

}

I'm able to construct following criteria, some context:(grails list.gsp / g:sortableColumn: being able to sort on associated domain objects):

   params.sort = 'bar.barName'
   def foos = Foo.createCriteria().list(params){
        gt 'fooAge', 10
   }

but when using DetachedCriteria it fails:

    params.sort = 'bar.barName'
    def foos =  new DetachedCriteria(Foo).build {
        gt 'fooAge', 10
    }.list(params)

exception:

could not resolve property: bar.barName of: com.Foo. Stacktrace follows:
Message: could not resolve property: bar.barName of: com.Foo
    Line | Method
->>   87 | initialize    in grails.gorm.PagedResultList
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|     50 | getTotalCount in     ''
|     26 | $tt__index .  in com.FooController$$EPB9xU8u
|    198 | doFilter      in grails.plugin.cache.web.filter.PageFragmentCachingFilter
|     63 | doFilter . .  in grails.plugin.cache.web.filter.AbstractFilter
|   1145 | runWorker     in java.util.concurrent.ThreadPoolExecutor
|    615 | run . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run           in java.lang.Thread

Is there a way around this?


how to take complete control of zend2 form styling?

I was following this guide (http://framework.zend.com/manual/2.0/en/user-guide/forms-and-actions.html) and the "zend" way of writing form fields is something like:

    $this->add(array(
        'name' => 'title',
        'attributes' => array(
            'type'  => 'text',
        ),
        'options' => array(
            'label' => 'Title',
        ),
    ));

The resulting HTML is:

<label>
<span>Surname/Faculty</span>
<input type="text" value="" name="title">
</label>

I can supply "class" parameter to the form field but supplying "class" to the label does nothing. I also want to include a "br" tag at the end of the "label" tag.

any ideas on how to make it work? I've looked at recent examples and tutorials (seems decorators have been phased out of zend2?) but I can't find what I'm looking for. thanks


GCC option to specify the filename which is being compiled

Assume there are 3 files which I need to compile, a.cpp, b.cpp and c.cpp.
When I compile the above 3 files using microsoft compiler, the compiler outputs the file name which it completed compiling.

ex: cl a.cpp b.cpp c.cpp

a.cpp

b.cpp

c.cpp

But GCC compiler doesnot output the filename which it completed compiling.

ex: g++ a.cpp b.cpp c.cpp

//no output is shown.

Is there any option in GCC and clang which will show the filename after the compilation of it.

Sorry for the terrible english.
Also I don't need any suggestions about achieving the desired result using make files.

Thanks inadvance


JetBrains IntelliJ IDEA SVN SSH configuration

I am trying to configure my JetBrains IntelliJ IDEA to integrate with SVN

I need to put in the authentication realm,

I already put it once, but I misspelled one letter, and now it wont let me change it

also I need to put in SSH credentials

if I create a new repository and try to checkout my project to that repository it asks me for username and password with no option to enter ssh credentials

how do I fix this ?

I tried looking on the jetbrains man pages, but nothing I can find there


how to call on resume when activity is destroyed?

I have activity A which creates list view and has onResume action to update adapter.

protected void onResume() {
        super.onResume();
        ma.notifyDataSetChanged();
        Log.d("resumed","true");
        }

Also I have activity B.  How can I call A's onResume, when B is destroyed or it pressed back from activity B?


How to get the value of a drop down selected value with the parent as the selected element in jQuery

History:

I'm using the children method because I'll be looping through divs that have content in them that is dynamically generated by the user, so there's no way of me knowing how many divs there will be. If there is another method I should be using, by all means, show me :)

I'm having trouble here using the following code:

$("[name = listItem]").each( function (){
var z = $(this).children("[name='dropDown'] option:selected").val();
alert(z);
});

In this example the output would be an alert box with:

undefined

It's strange because this way bellow works fine!

var z = $("[name='dropDown'] option:selected").val();
alert(z);

the output for this would be the appropriate value:

1

for the children() method, I thought you could use the standard selector syntax. What do you think?


SQL Azure DMV Reset

I was looking at a custom database for a client today and in looking at the usual DMV's for query stats ie.
SELECT *
FROM sys.dm_exec_query_stats AS s
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS q

I had a number of queries with thousands of executions. When I went to look at high execution sp's I got 0 rows. I looked at high-read sp's and got 0 rows. I then went and looked at my original high execution queries and noticed the results had changed and my highest executions were suddenly ~500. I then re-ran the sp queries and got some results, most with 1 execution. From my understanding the only thing that clears these are service/server restart and DBCC FREExxx() commands being run. Is there something else in the Azure environment that would cause this? Would low memory force these to clear out? I wouldn't expect that to be the case as I would expect to still see something in the results as it cycles but maybe there is something I'm missing. Open to any thoughts on this as I have spent most of my days on-prem.

I did read this article but I wasn't sure if Azure just randomly moves machines or if that applied.
SQL Azure Online Management Portal - What causes the 'Query Performance' Run Count to reset to zero?


How to delete all schedules in node-schedule?

I see from docs you can delete one by one by name for example ...

var schedule = require('node-schedule');

 // sample announcement

 var rule = new schedule.RecurrenceRule();
 rule.dayOfWeek = [1, 2, 3, 4, 5];
 rule.minute = 50;
 rule.hour = 12;

 var message = schedule.scheduleJob("AnnouncementOne", rule, function() {
    // make my announcement
})

AnnouncementOne.cancel();

but I would like code to get all scheduled jobs and then loop through them to delete each one. I think the following gets all the jobs ...

var jobList = schedule.scheduledJobs;

which outputs following to console ...

{ 'AnnouncementOne':
   Job {
     job: [Function],
     callback: false,
     name: 'AnnouncementOne',
     trackInvocation: [Function],
     stopTrackingInvocation: [Function],
     triggeredJobs: [Function],
     setTriggeredJobs: [Function],
     cancel: [Function],
     cancelNext: [Function],
     reschedule: [Function],
     nextInvocation: [Function],
     pendingInvocations: [Function] },
  'AnnouncementTwo':
   Job {
     job: [Function],
     callback: false,
     name: 'AnnouncementTwo',
     trackInvocation: [Function],
     stopTrackingInvocation: [Function],
     triggeredJobs: [Function],
     setTriggeredJobs: [Function],
     cancel: [Function],
     cancelNext: [Function],
     reschedule: [Function],
     nextInvocation: [Function],
     pendingInvocations: [Function] } }

how do I loop through jobList to delete each job?

Alternative Code:

var jobList = schedule.scheduledJobs;

for(jobName in jobList){
  var job = 'jobList.' + jobName;
  eval(job+'.cancel()');
}


Switching sheets in Excel VBA

I'm currently doing this Sheets("Sheet2").Range("A1").Value = 35, but I want to a way to do just this Range("A1").Value = 35, by switching the sheet on a separate line before. I tried Sheets("Sheet2").Select, but that only switches the sheet it displays at the end to sheet 2.


Transactions in Informix dbaccess here document approach

I am writing a shell script that invokes dbaccess.

I would like to begin a transaction, do some stuff (e.g. call some procedures) and then make a decision and either commit or rollback the current work. Is this possible?

Here's an example of what I am trying to accomplish

#!/bin/bash

v_value

dbaccess $DB - << SQL

unload to "abc.csv"
select value from table1 where id=1;
SQL

IFS=$'|' arr=( $(awk -F, -v OFS='\n' '{$1=$1}1' abc.csv) )
v_value=${arr[0]}

dbaccess $DB - << SQL

begin;

execute procedure progname();

-- here check everything is ok (e.g. using the previously retrieved $v_value) and either commit or rollback
-- commit|rollback
SQL


C# Displaying a Class Variable that is stored in an Array

I will try to simplify this down as much as I can to make this as understandable as I can.
I have created various classes (to be known as Person1, Person2 and Person3)
each of which has their own variables (examples being Name, Age and ID).
I created a one dimesional array which will be called PeopleArray with a maximum amount of 10 entries held in the array, each of these hold an instance of one of the Classes.

Note: when the form is loaded entries are made into the array and assigns values to each of the appropriate variables

I then created a Listbox called ListOfPeople which allows the user to select from the entries in the array.
What I want to do is take one of the Variables from the appropriate Classes and display the value held by it in a label.

For this lets say I have in the Array at position [0], the entry is of the Person1 Class and I want to find the value of the "Name" variable.
What would be the code to display that in a label.
"Label.Text = "

Note: what I would want the code to do however is account for whichever entry is selected, a method in the form of my previous example will suffice and I will work from there.

Any help you can give is much appriciated. Thank You


Center align a column in twitter bootstrap

I've started learning Bootstrap. My question is how to center align a column horizontally, bootstrap contains 12 column layout, there is no middle number. To be more clear if it was 11 column layout, the middle number would have been 6 (5 columns left, 1 column middle, 5 columns right)


Y-position issue with rect while ceating 1 SVG element per div with JQuerySVG and Raphael.js

Well, since someone downvoted this instead of trying to ask for a change, I am going to change up my question to better make sense.

so here are some pics of what's going on.

http://imageshack.com/a/img633/2685/7UYA8e.png

http://imageshack.com/a/img905/8505/u0gI9U.png

http://imageshack.com/a/img538/7152/gV5jd9.png

Basically I am trying to use SVG to create rectangles as well as images and then manipulate them with the DOM and do things like drag.

Instead of having 1 SVG Root or w/e you want to call it, I have multiple ones, as in 1 SVG per div.

On Raphael when I went from 1 "paper" to multiple ones(it seemed like doing document.create(div) was causing issues as well and that an already created div worked). I get what is going on with JQuery SVG when "configure({height})" is set, which is the positions of my objects are messed up at lower amounts i.e., if my height is 1 it will be messed up, but if it's 100 it will be in place.  It will mess up by going to positions farther down the page than it should, which can be seen in the images above.

If I have 1 paper in Raphael this doesn't happen, as well as if configure is off in JquerySVG; however if Configure is off, at some point (which can be seen in Image 1) I get my rectangles cut off, because my viewport isn't correct (thus needing configure to BE ON).

Raphael doesn't seem to have this cut off issue, which seems to be from what I gather from here http://tutorials.jenkov.com/svg/svg-viewport-view-box.html

The second example has preserveAspectRatio set to xMinYMin slice. That will preserve aspect ratio, but scale the view box according to the larger aspect ratio (the x-axis with ratio 2), resulting in an image too big to fit within the viewport. The image is said to be "sliced".

If anyone has any recommendations on what I might be doing wrong I would appreciate it, but I'm not sure why I am having these issues.

I hope the pics suffice, because this is very annoying and I just want to know how to do what I need to without having issues....

My code

   var scale = ....
      for(var i = 0; i < total; i++)
      {
       var face = document.createElement("div");

        face.id = 'face'+i;

        document.getElementById('plan').appendChild(face);

      $('#face'+i).svg();

        var faceE = $('#face'+i).svg('get');

         //   faceE.configure({width: w*scale, height: h*scale}, true);

        faceE.rect(0,0,w*scale,
                   h*scale,{fill:'black', stroke:
                   'red', strokeWidth: 0.3*scale});

    $( '#face'+i ).draggable({ snap: true});

         $('#face'+i).css({position:"absolute", left: x*scale, top:y*scale, width: w*scale, height:h*scale});

}

I'll try to make a fiddle later and hopefully I can get some results.  is JQuery SVG part of Fiddle or do I need to do something special for it?


Issue with Camera on certain devices

i have some sort of a LauncherApp(start other apps easy from my app). On some devices i mentioned that the Camera is not in the PackageManager:

List<ApplicationInfo> appInfo = pm.getInstalledApplications(PackageManager.GET_META_DATA);

This is because on this Devices the Camera is not an Application, but an Activity in the Gallery-Application!

The Problem is that my whole logic is based on ApplicationInfos and not ActivityInfos!

I managed to get the ActivityInfo of the Camera via an intent:

Intent camera = new Intent(android.provider.MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
camera.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ActivityInfo actInfoCamera = camera.resolveActivityInfo(getPackageManager(), 0);

now with actInfoCamera i can retrieve the icon of the camera and the Label. Which is all i need. But again my whole program is now based on ApplicationInfo. So i would need to cast or transform the ActivityInfo into an ApplicationInfo(For sorting, retrieving Icons and labels and so on).

When i try so with:

actInfoCamera.applicationInfo;

i am back at the beginning, the ApplicationInfo now has again the icon of the Gallery and the Label Gallery... or when i try that:

ApplicationInfo appInfoCamera = (ApplicationInfo) actInfoCamera;

it doesn't work cast from ActivityInfo to ApplicationInfo is not possible..

So i got two questions:

1) Is there a way to determine if the camera on that device is an single application or an activity within the Gallery application. Because i don't want to add two times the same camera application in my list in my app. Also please notice that it is possible that the user have some other camera apps which includes "camera" in their packagenames. I'm afraid it isn't that easy...

2) How do i get the activity of my camera within the gallery package as an ApplicationInfo to accomplish an easy way of implementing in my whole logic.

Any help is greatly appreciated.

Thanks in advance!


Package execution failed using DTEXEC /SQ

I have deployed a package through SQL Server Deployment to a Custom Folder "Folder1" under MSDB. The execution failed using DTEXEC. What is the correct syntax using DTEXEC ?


EF 6 Code First - Schema is not valid type not available

I did some refactoring to a code base, and created an abstract class SlottedHardware that held some common properties that other classes should use.

However, I am now getting the error:
 Schema specified is not valid. Errors: The relationship 'MyProject.Models.NetworkDevice_Slots' was not loaded because the type 'MyProject.Models.Models.NetworkDevice' is not available.

when trying to create the database by setting my DbContext ctor to Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>());

I have been at this for hours, and would really appreciate if someone can lend a helping hand.  Here are some of the entity classes, as well as the Fluent API mapping:

public abstract class EntityBase
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public abstract class SlottedHardware : EntityBase
{
    public int MaxSlots { get; set; }

    public virtual ICollection<Slot> Slots { get; set; }
}

public class Slot : EntityBase
{
    public string SlotIdentifier { get; set; }
    public List<Card> CompatibleCards { get; set; } = new List<Card>();
    public State State { get; set; }
    public virtual NetworkDevice NetworkDevice { get; set; }
}

public class NetworkDevice : SlottedHardware
{
    public string Vendor { get; set; }
    public string Model { get; set; }
    public List<UnpublishedConfig> UnpublishedConfigs { get; set; }
    public List<PublishedConfig> PublishedConfigs { get; set; }
    public State State { get; set; }

    /*** Constructors ***/

    public NetworkDevice()
    {
        MaxSlots = 0;
        Slots = new List<Slot>();
        UnpublishedConfigs = new List<UnpublishedConfig>();
        PublishedConfigs = new List<PublishedConfig>();
    }

    public NetworkDevice(string vendor, string model, int maxSlots) : this()
    {
        Vendor = vendor;
        Model = model;
        if(maxSlots > 0)
        {
            MaxSlots = maxSlots;
        }

    }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // NetworkDevice entity
    modelBuilder.Entity<NetworkDevice>().Map(m =>
    {
        m.MapInheritedProperties();
        m.ToTable("NetworkDevices");
    });
    modelBuilder.Entity<NetworkDevice>().HasKey(t => t.Id);
    modelBuilder.Entity<NetworkDevice>().
        HasMany(t => t.Slots).
        WithOptional(t => t.NetworkDevice);
    modelBuilder.Entity<NetworkDevice>().
        HasMany(t => t.PublishedConfigs).
        WithMany();
    modelBuilder.Entity<NetworkDevice>().
        HasMany(t => t.UnpublishedConfigs).
        WithMany();
    modelBuilder.Entity<NetworkDevice>().Property(t => t.MaxSlots).IsRequired();
    modelBuilder.Entity<NetworkDevice>().Property(t => t.Model).IsRequired();

    // Slot entity
    modelBuilder.Entity<Slot>().Map(m =>
    {
        m.MapInheritedProperties();
        m.ToTable("Slots");
    });
    modelBuilder.Entity<Slot>().HasKey(t => t.Id);
    modelBuilder.Entity<Slot>().HasOptional(t => t.NetworkDevice).WithMany(x => x.Slots);
    modelBuilder.Entity<Slot>().HasMany(t => t.CompatibleCards).WithMany(x => x.Slots);
    modelBuilder.Entity<Slot>().Property(t => t.SlotIdentifier).IsRequired();
    modelBuilder.Entity<Slot>().Ignore(t => t.Card);
}