问:
Unity paint circular healthbar dynamically
I got a circular healthbar. It updates, when the current or max life changes.

```<code>healthBar.fillAmount = currentHealth / maxHealth;
</code>```

So this bar looks boring. There are no borders between the "pieces". When I got eight lifepoints I want to see eight parts there.

Super Mario 64 should be an excellent example

Important would be having small borders showing the lifepoints. Is this even possible?

I don't have 8 lifepoints. The lifepoints are not constant. They are set by the value X. Otherwise I could use a Texture, yes. Furthermore I want to increase the max life in the game, so everything has to work dynamically.

答:
The simplest solution would be to create a thin line in a graphics editor, import it into Unity as a sprite, then add the sprite as an Image object in your scene.

If you have eight health pieces, you need 4 border lines spaced 45 degrees apart. The code below will clone the image as many times as you need (set via the field pieces, instead of X as you said) and rotate each clone round the z-axis.

```<code>public GameObject line; //Set your line image via the inspector here
private int pieces = 8;

public void DrawLines()
{
   int linecount = pieces/2;
   float angle = 360 / linecount;

   for(int i = 0; i < linecount; i++)
   {
       GameObject clone = Instantiate(line, Vector3.zero,
       Quaternion.Euler(0,0,(angle*i)));
   }
}
</code>```

Body:
I got a circular healthbar. It updates, when the current or max life changes.

healthBar.fillAmount = currentHealth / maxHealth;

So this bar looks boring. There are no borders between the "pieces". When I got eight lifepoints I want to see eight parts there.

Super Mario 64 should be an excellent example

Important would be having small borders showing the lifepoints. Is this even possible?

I don't have 8 lifepoints. The lifepoints are not constant. They are set by the value X. Otherwise I could use a Texture, yes. Furthermore I want to increase the max life in the game, so everything has to work dynamically.

Body:
The simplest solution would be to create a thin line in a graphics editor, import it into Unity as a sprite, then add the sprite as an Image object in your scene.

If you have eight health pieces, you need 4 border lines spaced 45 degrees apart. The code below will clone the image as many times as you need (set via the field pieces, instead of X as you said) and rotate each clone round the z-axis.

public GameObject line; //Set your line image via the inspector here
private int pieces = 8;

public void DrawLines()
{
   int linecount = pieces/2;
   float angle = 360 / linecount;

   for(int i = 0; i < linecount; i++)
   {
       GameObject clone = Instantiate(line, Vector3.zero,
       Quaternion.Euler(0,0,(angle*i)));
   }
}


来源: stackexchange

问:
Windows Phone 10 Universal, how to resize and move a rectangle?
I am pretty new to C# and XAML, and I am trying to create an application that allows the user to move a rectangle, resize the rectangle using pinch, and change the color when touched. I have successfully created the application for Windows Phone 8.1 Silverlight, but I am having a lot of trouble creating it for Windows Phone 10 Universal. There is very limited literature out there in regards to handling manipulation events in Windows Phone 10.

Can someone please direct me to the appropriate information for doing this, or if you could show me where I went wrong in my code?

I would greatly appreciate it!

Thank you,

Page

Here is my MainPage.xaml

```<code><Page
x:Class="Gesture_App_UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Gesture_App_UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <TextBlock x:Name="textBlock" HorizontalAlignment="Left"
               Height="50" TextWrapping="Wrap"
               Text="Gesture Application" VerticalAlignment="Top"
               Width="360" FontSize="36" TextAlignment="Center"
               FontFamily="Bauhaus 93" Margin="0,25,0,0" >
        <TextBlock.Foreground>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF23AFE2" Offset="1"/>
            </LinearGradientBrush>
        </TextBlock.Foreground>
    </TextBlock>

    <Button x:Name="button_Info" Content="Info" HorizontalAlignment="Left"
            Height="34" Margin="35,91,0,0" VerticalAlignment="Top" Width="110"
            Click="button_Info_Click" BorderThickness="2" Foreground="#FFFA9F11"
            BorderBrush="#FF09B4F3">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
    <Button x:Name="button_Instructions" Content="Instructions"
            HorizontalAlignment="Left" Height="34" Margin="210,91,0,0"
            VerticalAlignment="Top" Width="110" BorderThickness="2"
            Foreground="#FFFA9F11" BorderBrush="#FF09B4F3" Click="button_Instructions_Click">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>

    <Border BorderBrush="Black" BorderThickness="2" HorizontalAlignment="Left"
            Height="5" Margin="10,160,0,0" VerticalAlignment="Top" Width="340"/>

    <Grid HorizontalAlignment="Left" Height="475" Margin="0,165,0,0"
          VerticalAlignment="Top" Width="360"/>

    <Canvas HorizontalAlignment="Left" Height="470" Margin="0,170,0,0"
            VerticalAlignment="Top" Width="360" >

        <Rectangle Name="touchRectangle" Fill="Green" Width="200" Height="40" Canvas.Left="80"
                   Stroke="Blue" Canvas.Top="190" RadiusX="5" RadiusY="5"
                   HorizontalAlignment="Center" VerticalAlignment="Center"
                   ManipulationMode="All"/>
    </Canvas>

</Grid>
</Page>
</code>```

Here is my MainPage.xaml.cs, I have updated it to reflect the changes mentioned below and still the rectangle does not move or resize.

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Input;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
using System.Windows.Input;

namespace Gesture_App_UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
    // Global translation transform used for changing the position of
    // the Rectangle based on input data from the touch contact.
    private TranslateTransform dragTranslation;
    private CompositeTransform deltaTransform;
    private TransformGroup rectangleTransforms;

    //Various Brushes for changing rectangle's color
    private Brush stationaryBrush;
    private SolidColorBrush greenBrush = new SolidColorBrush(Colors.Green);
    private SolidColorBrush redBrush = new SolidColorBrush(Colors.Red);
    private SolidColorBrush orangeBrush = new SolidColorBrush(Colors.Orange);

    public MainPage()
    {
        this.InitializeComponent();

        // Pointer event listeners.
        touchRectangle.PointerPressed += touchRectangle_PointerPressed;
        touchRectangle.PointerReleased += touchRectangle_PointerReleased;

        // Listener for Manipulation events
        touchRectangle.ManipulationStarted += new ManipulationStartedEventHandler(touchRectangle_ManipulationStarted);
        touchRectangle.ManipulationDelta += new ManipulationDeltaEventHandler(touchRectangle_ManipulationDelta);
        touchRectangle.ManipulationInertiaStarting += new ManipulationInertiaStartingEventHandler(touchRectangle_ManipulationInertiaStarting);
        touchRectangle.ManipulationCompleted += new ManipulationCompletedEventHandler(touchRectangle_ManipulationCompleted);

        //Initiate new instance of various Transforms
        dragTranslation = new TranslateTransform();
        deltaTransform = new CompositeTransform();
        rectangleTransforms = new TransformGroup();

        // Combine moving & resizing tranforms into one TransformGroup.
        // Rectangle's RenderTransform can only contain a single transform or TransformGroup.
        rectangleTransforms.Children.Add(dragTranslation);
        rectangleTransforms.Children.Add(deltaTransform);

        //Assign manipulation data to rectangle
        touchRectangle.RenderTransform = rectangleTransforms;
    }
    private async void button_Info_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Info = new MessageDialog("Page Lynn Potter");
        await dialog_Info.ShowAsync();
    }
    private async void button_Instructions_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Instructions = new MessageDialog("PINCH - Zoom In & Out, LONG TOUCH - Toggle Color, FLICK - Move Rectangle");
        await dialog_Instructions.ShowAsync();
    }
    //Handler for pointer released event.
    private void touchRectangle_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = greenBrush;
    }
    // Handler for pointer pressed event.
    private void touchRectangle_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }
    void touchRectangle_ManipulationInertiaStarting(object sender, ManipulationInertiaStartingRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = redBrush;
    }
    void touchRectangle_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
    {
        // Save rectangle's original color before changing color.
        stationaryBrush = touchRectangle.Fill;

        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }

    // Handler for ManipulationDelta event.
    // ManipulationDelta data loaded into translation transform & applied to Rectangle
    void touchRectangle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.Scale;

        // Move rectangle.
        dragTranslation.X += e.Delta.Translation.X;
        dragTranslation.Y += e.Delta.Translation.Y;

        // Resize rectangle.
        if (deltaTransform.ScaleX > 0 && deltaTransform.ScaleY > 0)
        {
            //Scale Rectangle
            deltaTransform.ScaleX *= e.Delta.Scale;
            deltaTransform.ScaleY *= e.Delta.Scale;
        }
    }
    //When manipulation ends, event handler restores original color to Rectangle
    void touchRectangle_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
    {
        // Restore rectangle's original color.
        touchRectangle.Fill = stationaryBrush;
    }
}
}
</code>```

答:
As Clemens said, you're assigning touchRectangle.RenderTransform twice. When you second time set the touchRectangle.RenderTransform, it will replace the first time that you set. So the TranslateTransform will not work.

We should be able to use a TransformGroup to group two or more Transform objects into a single composite Transform.

For example:

```<code>private TranslateTransform dragTranslation;
private CompositeTransform deltaTransform;
private TransformGroup myTransformGroup;

public MainPage()
{
    this.InitializeComponent();
    touchRectangle.PointerReleased += touchRectangle_PointerReleased;
    touchRectangle.ManipulationDelta += touchRectangle_ManipulationDelta;
    dragTranslation = new TranslateTransform();
    deltaTransform = new CompositeTransform();
    myTransformGroup = new TransformGroup();
    myTransformGroup.Children.Add(dragTranslation);
    myTransformGroup.Children.Add(deltaTransform);
    touchRectangle.RenderTransform = myTransformGroup;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am pretty new to C# and XAML, and I am trying to create an application that allows the user to move a rectangle, resize the rectangle using pinch, and change the color when touched. I have successfully created the application for Windows Phone 8.1 Silverlight, but I am having a lot of trouble creating it for Windows Phone 10 Universal. There is very limited literature out there in regards to handling manipulation events in Windows Phone 10.

Can someone please direct me to the appropriate information for doing this, or if you could show me where I went wrong in my code?

I would greatly appreciate it!

Thank you,

Page

Here is my MainPage.xaml

<Page
x:Class="Gesture_App_UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Gesture_App_UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <TextBlock x:Name="textBlock" HorizontalAlignment="Left"
               Height="50" TextWrapping="Wrap"
               Text="Gesture Application" VerticalAlignment="Top"
               Width="360" FontSize="36" TextAlignment="Center"
               FontFamily="Bauhaus 93" Margin="0,25,0,0" >
        <TextBlock.Foreground>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF23AFE2" Offset="1"/>
            </LinearGradientBrush>
        </TextBlock.Foreground>
    </TextBlock>

    <Button x:Name="button_Info" Content="Info" HorizontalAlignment="Left"
            Height="34" Margin="35,91,0,0" VerticalAlignment="Top" Width="110"
            Click="button_Info_Click" BorderThickness="2" Foreground="#FFFA9F11"
            BorderBrush="#FF09B4F3">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
    <Button x:Name="button_Instructions" Content="Instructions"
            HorizontalAlignment="Left" Height="34" Margin="210,91,0,0"
            VerticalAlignment="Top" Width="110" BorderThickness="2"
            Foreground="#FFFA9F11" BorderBrush="#FF09B4F3" Click="button_Instructions_Click">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>

    <Border BorderBrush="Black" BorderThickness="2" HorizontalAlignment="Left"
            Height="5" Margin="10,160,0,0" VerticalAlignment="Top" Width="340"/>

    <Grid HorizontalAlignment="Left" Height="475" Margin="0,165,0,0"
          VerticalAlignment="Top" Width="360"/>

    <Canvas HorizontalAlignment="Left" Height="470" Margin="0,170,0,0"
            VerticalAlignment="Top" Width="360" >

        <Rectangle Name="touchRectangle" Fill="Green" Width="200" Height="40" Canvas.Left="80"
                   Stroke="Blue" Canvas.Top="190" RadiusX="5" RadiusY="5"
                   HorizontalAlignment="Center" VerticalAlignment="Center"
                   ManipulationMode="All"/>
    </Canvas>

</Grid>
</Page>

Here is my MainPage.xaml.cs, I have updated it to reflect the changes mentioned below and still the rectangle does not move or resize.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Input;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
using System.Windows.Input;

namespace Gesture_App_UWP
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class MainPage : Page
{
    // Global translation transform used for changing the position of
    // the Rectangle based on input data from the touch contact.
    private TranslateTransform dragTranslation;
    private CompositeTransform deltaTransform;
    private TransformGroup rectangleTransforms;

    //Various Brushes for changing rectangle's color
    private Brush stationaryBrush;
    private SolidColorBrush greenBrush = new SolidColorBrush(Colors.Green);
    private SolidColorBrush redBrush = new SolidColorBrush(Colors.Red);
    private SolidColorBrush orangeBrush = new SolidColorBrush(Colors.Orange);

    public MainPage()
    {
        this.InitializeComponent();

        // Pointer event listeners.
        touchRectangle.PointerPressed += touchRectangle_PointerPressed;
        touchRectangle.PointerReleased += touchRectangle_PointerReleased;

        // Listener for Manipulation events
        touchRectangle.ManipulationStarted += new ManipulationStartedEventHandler(touchRectangle_ManipulationStarted);
        touchRectangle.ManipulationDelta += new ManipulationDeltaEventHandler(touchRectangle_ManipulationDelta);
        touchRectangle.ManipulationInertiaStarting += new ManipulationInertiaStartingEventHandler(touchRectangle_ManipulationInertiaStarting);
        touchRectangle.ManipulationCompleted += new ManipulationCompletedEventHandler(touchRectangle_ManipulationCompleted);

        //Initiate new instance of various Transforms
        dragTranslation = new TranslateTransform();
        deltaTransform = new CompositeTransform();
        rectangleTransforms = new TransformGroup();

        // Combine moving & resizing tranforms into one TransformGroup.
        // Rectangle's RenderTransform can only contain a single transform or TransformGroup.
        rectangleTransforms.Children.Add(dragTranslation);
        rectangleTransforms.Children.Add(deltaTransform);

        //Assign manipulation data to rectangle
        touchRectangle.RenderTransform = rectangleTransforms;
    }
    private async void button_Info_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Info = new MessageDialog("Page Lynn Potter");
        await dialog_Info.ShowAsync();
    }
    private async void button_Instructions_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Instructions = new MessageDialog("PINCH - Zoom In & Out, LONG TOUCH - Toggle Color, FLICK - Move Rectangle");
        await dialog_Instructions.ShowAsync();
    }
    //Handler for pointer released event.
    private void touchRectangle_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = greenBrush;
    }
    // Handler for pointer pressed event.
    private void touchRectangle_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }
    void touchRectangle_ManipulationInertiaStarting(object sender, ManipulationInertiaStartingRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = redBrush;
    }
    void touchRectangle_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
    {
        // Save rectangle's original color before changing color.
        stationaryBrush = touchRectangle.Fill;

        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }

    // Handler for ManipulationDelta event.
    // ManipulationDelta data loaded into translation transform & applied to Rectangle
    void touchRectangle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.Scale;

        // Move rectangle.
        dragTranslation.X += e.Delta.Translation.X;
        dragTranslation.Y += e.Delta.Translation.Y;

        // Resize rectangle.
        if (deltaTransform.ScaleX > 0 && deltaTransform.ScaleY > 0)
        {
            //Scale Rectangle
            deltaTransform.ScaleX *= e.Delta.Scale;
            deltaTransform.ScaleY *= e.Delta.Scale;
        }
    }
    //When manipulation ends, event handler restores original color to Rectangle
    void touchRectangle_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
    {
        // Restore rectangle's original color.
        touchRectangle.Fill = stationaryBrush;
    }
}
}

Body:
As Clemens said, you're assigning touchRectangle.RenderTransform twice. When you second time set the touchRectangle.RenderTransform, it will replace the first time that you set. So the TranslateTransform will not work.

We should be able to use a TransformGroup to group two or more Transform objects into a single composite Transform.

For example:

private TranslateTransform dragTranslation;
private CompositeTransform deltaTransform;
private TransformGroup myTransformGroup;

public MainPage()
{
    this.InitializeComponent();
    touchRectangle.PointerReleased += touchRectangle_PointerReleased;
    touchRectangle.ManipulationDelta += touchRectangle_ManipulationDelta;
    dragTranslation = new TranslateTransform();
    deltaTransform = new CompositeTransform();
    myTransformGroup = new TransformGroup();
    myTransformGroup.Children.Add(dragTranslation);
    myTransformGroup.Children.Add(deltaTransform);
    touchRectangle.RenderTransform = myTransformGroup;
}


问:
Entity Framework 4 relating tables with no foreign key constraint
I am working with Entity Framework for the first time.  The database that I am working with has no foreign key constraints defined (and I cannot change that, integrity is controlled at the app level, out of my hands).

There is a very strong convention in the database -- all PK's are named a specific way, and an FK field has exactly the same name as its corresponding PK.

When I draw a relation with EF, it seems to want to auto-create an FK field in the child table.  Is there any way I can teach EF to infer our relations based upon our convention?

答:
There is nothing built-in to infer FKs based on naming conventions, but you can manually add the associations to your model. Associations don't need an underlying FK constraint so you can add the associations to the model only...

Update: In the latest version of the Model Comparer for EF4, I added a feature for inferring FKs and generating associations in EFv4 models based on inferred FK constraints. Blogged about it here: http://huagati.blogspot.com/2010/12/inferring-foreign-key-constraints-in.html

I hope that helps...

ContentLicense: CC BY-SA 2.5


问:
Error while setting up openCV in VS2015
I am trying to run a project using openCV in VS2015, I have added the libraries and linked them but still got an error about the video tracker, however I didn't have an error about the cor utility. Can anybody help me?

答:
You need the video contrib download see  OpenCV where is tracking.hpp

This contains extra algorithms not part of the main distribution

Title: Error while setting up openCV in VS2015


问:
Returning a view from a method by calling its method
I have a method in a controller named AspNetAssessment_QuestionController

```<code>public ActionResult Excel_Data(HttpPostedFileBase excelfile)
{
    if ( excelfile == null )
    {
        ViewBag.Error = "Please select an excel file";
        return View("Create");
    }
    else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
    {
        return View("Index");
    }
    else
    {
        ViewBag.Error = "File type is incorrect";
        return View("Create");
    }
}
</code>```

Now when this method returns the view, the requested view needs some viewbag data to run its razor syntax, like in 'Create' and 'Index' both have:

```<code>@Html.DropDownList("ClassID", null, htmlAttributes: new { @class = "form-control" })
</code>```

As the system just return my view without hitting the method it is not able to get value of viewbag from the method of Create and Index.

I also added the routes so they hit their method in routes.config file as

```<code>routes.MapRoute(
                name: "AspNetAssessment_Question/Create",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "AspNetAssessment_Question", action = "Create", id = UrlParameter.Optional }
            );
</code>```

and same goes for index but when excel_data method return view I receive an error that Viewbag.propertyname data is missing on following url

```<code>http://localhost:1331/AspNetAssessment_Question/Excel_Data
</code>```

I even tried to call their methods like Create() instead of return view("Create") but it failed and didn't render the view.

The create method has two forms. One hits the method of Excel_data and other one call Create method

How can I hit their method and return the view from Excel_Data so that they get the viewbag data from their methods and from Excel_Data as well.

excel_data method assign viewbag.Error and in the method of create I have viewbag.ClassID and some more.

答:
Solution for your problem is very simple

Before giving the solution , we need to understand two things view and redirecttoaction and its differences:

In short return view() is like a server.Transfer() in asp.net and whereas  redirecttoaction will hit the 302 request to the browser.

Detailed info can be found in this very good  article: http://www.dotnettricks.com/learn/mvc/return-view-vs-return-redirecttoaction-vs-return-redirect-vs-return-redirecttoroute

so now solution to your problem is:

Use to return  redirectoaction() instead of return view()

your example slightly modified:

```<code>public ActionResult Excel_Data(HttpPostedFileBase excelfile)
        {
            if ( excelfile == null )
            {
                ViewBag.Error = "Please select an excel file";
                return View("Create");
            }else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
            {
                return View("Index");
            }
            else
            {

        TempData["Error"] = "File type is incorrect";  //replaced tempdata with viewbag

                return RedirectToAction("Create","AspNetAssessment_QuestionController")
            }

        }
</code>```

Note : For the error message to retain use tempdata["error"] instead of viewbag.error as mentioned in the above code.

And the data of the tempdata you can access directly in the create view like below without doing anything the create action method.

create view code ex:

```<code>@if(tempdata["error"]!= null)
{
    var result = tempdata["error"];
}
</code>```

Thats it

FYI:

if you want an additional info like how to cast the different tempdata object and difference between the viewbag, viewdata , tempdata ,kindly refer this link:http://www.binaryintellect.net/articles/36941654-8bd4-4535-9226-ddf47841892f.aspx

That article had a very good explanation

Hope it be will helpful

Thanks
Karthik

Body:
I have a method in a controller named AspNetAssessment_QuestionController

public ActionResult Excel_Data(HttpPostedFileBase excelfile)
{
    if ( excelfile == null )
    {
        ViewBag.Error = "Please select an excel file";
        return View("Create");
    }
    else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
    {
        return View("Index");
    }
    else
    {
        ViewBag.Error = "File type is incorrect";
        return View("Create");
    }
}

Now when this method returns the view, the requested view needs some viewbag data to run its razor syntax, like in 'Create' and 'Index' both have:

@Html.DropDownList("ClassID", null, htmlAttributes: new { @class = "form-control" })

As the system just return my view without hitting the method it is not able to get value of viewbag from the method of Create and Index.

I also added the routes so they hit their method in routes.config file as

routes.MapRoute(
                name: "AspNetAssessment_Question/Create",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "AspNetAssessment_Question", action = "Create", id = UrlParameter.Optional }
            );

and same goes for index but when excel_data method return view I receive an error that Viewbag.propertyname data is missing on following url

http://localhost:1331/AspNetAssessment_Question/Excel_Data

I even tried to call their methods like Create() instead of return view("Create") but it failed and didn't render the view.

The create method has two forms. One hits the method of Excel_data and other one call Create method

How can I hit their method and return the view from Excel_Data so that they get the viewbag data from their methods and from Excel_Data as well.

excel_data method assign viewbag.Error and in the method of create I have viewbag.ClassID and some more.

Body:
Solution for your problem is very simple

Before giving the solution , we need to understand two things view and redirecttoaction and its differences:

In short return view() is like a server.Transfer() in asp.net and whereas  redirecttoaction will hit the 302 request to the browser.

Detailed info can be found in this very good  article: http://www.dotnettricks.com/learn/mvc/return-view-vs-return-redirecttoaction-vs-return-redirect-vs-return-redirecttoroute

so now solution to your problem is:

Use to return  redirectoaction() instead of return view()

your example slightly modified:

public ActionResult Excel_Data(HttpPostedFileBase excelfile)
        {
            if ( excelfile == null )
            {
                ViewBag.Error = "Please select an excel file";
                return View("Create");
            }else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
            {
                return View("Index");
            }
            else
            {

        TempData["Error"] = "File type is incorrect";  //replaced tempdata with viewbag

                return RedirectToAction("Create","AspNetAssessment_QuestionController")
            }

        }

Note : For the error message to retain use tempdata["error"] instead of viewbag.error as mentioned in the above code.

And the data of the tempdata you can access directly in the create view like below without doing anything the create action method.

create view code ex:

@if(tempdata["error"]!= null)
{
    var result = tempdata["error"];
}

Thats it

FYI:

if you want an additional info like how to cast the different tempdata object and difference between the viewbag, viewdata , tempdata ,kindly refer this link:http://www.binaryintellect.net/articles/36941654-8bd4-4535-9226-ddf47841892f.aspx

That article had a very good explanation

Hope it be will helpful

Thanks
Karthik


问:
nth-child(2n) CSS after hidden tr
I have a table looks like this (below) after using css nth-child(2n).

```<code>tr:nth-child(2n) {background-color: #f0f3f5;}
</code>```

After doing some hidden on the vID,ID,MO_Sub tr

```<code><tr style="display:none">
</code>```

The table now looks like this below, with backgroung on "MO" and "MODEL".

I have done somthing like (below) and it doesn't seem to work.

```<code>tr:not(.isotope-hidden):nth-child(2n)
</code>```

Anyone got any idea applying css after the hidden tr?
Thanks for any helps! =)

EDIT: add snippet

tr:not([style*="display:none"]):nth-child(2n){
    background-color: #f0f3f5;
}

tr:hover{

    background-color: cadetblue;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <table id="form_tb">
                    <tr style="display:none">
                        <td><label>vvID :</label></td>
                        <td><input type="text" name="vvID" placeholder="vvID" readonly></td>
                    </tr>
                    <tr style="display:none">
                        <td><label>vID :</label></td>
                        <td><input type="text" name="vID" placeholder="vID" readonly></td>
                    </tr>
                    <tr style="display:none">
                        <td><label>vID_sub :</label></td>
                        <td><input type="text" name="vID_sub" placeholder="vID_sub" readonly></td>
                    </tr>
                    <tr style="display:none">
                        <td><label>ST :</label></td>
                        <td><input type="text" name="Station" placeholder="Station" readonly></td>
                    </tr>
                    <tr style="display:none">
                        <td><label>SortID :</label></td>
                        <td><input type="text" name="SortID" placeholder="SortID" readonly></td>
                    </tr>
                    <tr>
                        <td><label>MO :</label></td>
                        <td data-key='MO'><input id=MO type="text" name="MO" placeholder="MO" readonly></td>
                    </tr>
                    <tr style="display:none">
                        <td><label>MO_Sub :</label></td>
                        <td><input type="text" name="MO_Sub" placeholder="MO_Sub" readonly></td>
                    </tr>
                    <tr>
                        <td><label>PART :</label></td>
                        <td data-key='text'><input type="text" name="Part_number" placeholder="PART" readonly></td>
                    </tr>
                    <tr>
                        <td><label>MODEL :</label></td>
                        <td><input type="text" name="Model" placeholder="MODEL" readonly></td>
                    </tr>
                    <tr style="display:none">
                        <td><label>Class :</label></td>
                        <td><input type="text" name="Product_Class" placeholder="Class" readonly></td>
                    </tr>
                    <tr>
                        <td><label>Side :</label></td>
                        <td><input type="text" name="Side" placeholder="Side" readonly></td>
                    </tr>

                </table></code>```

Result for the snippet should look like this.(below)

答:
The n-th child selector only selects children that are the nth child of the parent.
In your case, it selects table.children[n] such that n is even. Counterintuitively, it doesn't match the even values of the filtered results.

To fix the :hover problem, you could add :not(:hover) to the first css selector, but this doesn't fix everything.

I think this question and this question are both questions that deal with the same issue.

Might be better to use JavaScript, in this case.

Title: nth-child(2n) CSS after hidden tr

Body:
I have a table looks like this (below) after using css nth-child(2n).

tr:nth-child(2n) {background-color: #f0f3f5;}

After doing some hidden on the vID,ID,MO_Sub tr

The table now looks like this below, with backgroung on "MO" and "MODEL".

I have done somthing like (below) and it doesn't seem to work.

tr:not(.isotope-hidden):nth-child(2n)

Anyone got any idea applying css after the hidden tr?
Thanks for any helps! =)

EDIT: add snippet

tr:not([style*="display:none"]):nth-child(2n){
    background-color: #f0f3f5;
}

tr:hover{

    background-color: cadetblue;

}

                        vvID :
                        <input type="text" name="vvID" placeholder="vvID" readonly>

                        vID :
                        <input type="text" name="vID" placeholder="vID" readonly>

                        vID_sub :
                        <input type="text" name="vID_sub" placeholder="vID_sub" readonly>

                        ST :
                        <input type="text" name="Station" placeholder="Station" readonly>

                        SortID :
                        <input type="text" name="SortID" placeholder="SortID" readonly>

                        MO :
                        <input id=MO type="text" name="MO" placeholder="MO" readonly>

                        MO_Sub :
                        <input type="text" name="MO_Sub" placeholder="MO_Sub" readonly>

                        PART :
                        <input type="text" name="Part_number" placeholder="PART" readonly>

                        MODEL :
                        <input type="text" name="Model" placeholder="MODEL" readonly>

                        Class :
                        <input type="text" name="Product_Class" placeholder="Class" readonly>

                        Side :
                        <input type="text" name="Side" placeholder="Side" readonly>

Result for the snippet should look like this.(below)


问:
I want change bezier curve's endpoint
Sorry for my paint:

I want change bezier curve's endpoint

start from s point with control points(c1, c2) to end point

when point arrive at changepoint(pink), I want change endpoint and

get the new path for new endpoint smoothly

How ? help me..

答:
I dont understand your question but I have crated a simpl program which will let u understand bezier curves.

 <title>A simple tool</title>

  <button class="controlButton" onclick="activePoint='sp'" id="sp">Start Point</button>
  <button class="controlButton" onclick="activePoint='cp1'" id="cp1">Control Point 1</button>
  <button class="controlButton" onclick="activePoint='cp2'" id="cp2">Control Point 2</button>
  <button class="controlButton" onclick="activePoint='ep'" id="ep">End Point</button>

 <canvas id="mainCanvas"></canvas>

```

click to select a control point

Title: I want change bezier curve's endpoint

Body:
I dont understand your question but I have crated a simpl program which will let u understand bezier curves.

<html>
<head>
 <title>A simple tool</title>

 <style type="text/css">
 body {
  margin: 0;
  padding: 0;
  overflow: hidden;
 }

 .controlButton {
  border: 0;
  background: #000;
  border-radius: 10px;
  outline: 0;
  position: absolute;
  margin: 1px;
  font-family: monospace;
  color: #fff;
 }

 #mainCanvas {
  background: #FFF;
 }

 #output {
  position: absolute;
  top: 0;
  left: 0;
  background: #000;
  color: #fff;
  padding: 2px 7px;
  border-radius: 10px;
  font-family: Monospace;
 }
 </style>
</head>
<body>
 <div class="controlWrapper">
  <button class="controlButton" onclick="activePoint='sp'" id="sp">Start Point</button>
  <button class="controlButton" onclick="activePoint='cp1'" id="cp1">Control Point 1</button>
  <button class="controlButton" onclick="activePoint='cp2'" id="cp2">Control Point 2</button>
  <button class="controlButton" onclick="activePoint='ep'" id="ep">End Point</button>
 </div>
 <canvas id="mainCanvas"></canvas>
 <div id="output"></div>

 <script type="text/javascript">
 var canvas = document.getElementById("mainCanvas");
 var ctx = canvas.getContext("2d");
 var width = canvas.width = innerWidth;
 var height = canvas.height = innerHeight;

 var activeCurve = {
  sp:  { x: width/2, y: height/2 },
  cp1: { x: width/2+50, y: height/2+100 },
  cp2: { x: width/2+200, y: height/2+100 },
  ep:  { x: width/2+200, y: height/2+50 }
 };

 var activePoint = "";

 addEventListener("mousemove", function(e) {
  switch(activePoint) {
   case "sp":
    activeCurve.sp.x = e.clientX;
    activeCurve.sp.y = e.clientY;
    break;
   case "cp1":
    activeCurve.cp1.x = e.clientX;
    activeCurve.cp1.y = e.clientY;
    break;
   case "cp2":
    activeCurve.cp2.x = e.clientX;
    activeCurve.cp2.y = e.clientY;
    break;
   case "ep":
    activeCurve.ep.x = e.clientX;
    activeCurve.ep.y = e.clientY;
    break;
  }
 });

 addEventListener("click", function() {
  activePoint = "";
 }, true)

 function draw() {
  var sp = document.getElementById("sp");
  sp.style.top = activeCurve.sp.y + "px";
  sp.style.left = activeCurve.sp.x  + "px";

  var cp1 = document.getElementById("cp1");
  cp1.style.top = activeCurve.cp1.y + "px";
  cp1.style.left = activeCurve.cp1.x  + "px";

  var cp2 = document.getElementById("cp2");
  cp2.style.top = activeCurve.cp2.y + "px";
  cp2.style.left = activeCurve.cp2.x  + "px";

  var ep = document.getElementById("ep");
  ep.style.top = activeCurve.ep.y + "px";
  ep.style.left = activeCurve.ep.x  + "px";

  var o = document.getElementById("output");
  o.innerHTML = "<i>context</i>.moveTo(" + activeCurve.sp.x + ", " + activeCurve.sp.y +");<br/><i>context</i>.bezierCurveTo("
   + activeCurve.cp1.x + ","
   + activeCurve.cp1.y + ","
   + activeCurve.cp2.x + ","
   + activeCurve.cp2.y + ","
   + activeCurve.ep.x  + ","
   + activeCurve.ep.y +  ");";

  ctx.fillStyle = "#FFF";
  ctx.fillRect(0, 0, width, height);

  ctx.beginPath();
  ctx.fillStyle = "#289e82";
  ctx.strokeStyle = "#16614f";
  ctx.lineWidth = 5;

  ctx.moveTo(activeCurve.sp.x, activeCurve.sp.y);
  ctx.bezierCurveTo(
   activeCurve.cp1.x, activeCurve.cp1.y,
   activeCurve.cp2.x, activeCurve.cp2.y,
   activeCurve.ep.x, activeCurve.ep.y);

  ctx.stroke()
  ctx.fill();

  ctx.closePath();

  ctx.save();
  ctx.beginPath();
  ctx.lineWidth = 2;
  ctx.strokeStyle = "#101010";
  ctx.globalAlpha = 0.2;

  ctx.moveTo(activeCurve.sp.x, activeCurve.sp.y);
  ctx.lineTo(activeCurve.cp1.x, activeCurve.cp1.y);
  ctx.moveTo(activeCurve.ep.x, activeCurve.ep.y);
  ctx.lineTo(activeCurve.cp1.x, activeCurve.cp1.y);

  ctx.moveTo(activeCurve.sp.x, activeCurve.sp.y);
  ctx.lineTo(activeCurve.cp2.x, activeCurve.cp2.y);
  ctx.moveTo(activeCurve.ep.x, activeCurve.ep.y);
  ctx.lineTo(activeCurve.cp2.x, activeCurve.cp2.y);

  ctx.stroke();
  ctx.closePath();
  ctx.restore();

  requestAnimationFrame(draw);
 }

 draw()
 </script>
</body>
</html>

click to select a control point


问:
Indexing on Local Secondary Index in Dynamo DB
Say, I have a table with 5 columns :- A, B, C, D, E. A is a hash key and B is a sort Key. Now, I also wanted to query for A and C. Then, adding C as a local secondary index would be fine, right? I am asking because local secondary index is primarily for range queries. For my case, it would be equal query on C attribute.

Any suggestions you could give would be greatful.

答: I found the answer for this. I can create a local secondary index for with A as hash key and C as range key. But I need to make sure to create this index while creating the table since one can't create LSIs after table creation. </p>


问:
How do I display the user input when user clicks submit button. Also clear the message when user clicks the clear button. (Angularjs)
How do I display the user input when user clicks submit button. Also clear the message when user clicks the clear button. (please & thank you)</p>

```<code><html>

<head>
  <title></title>

    angular.module('exampleModule', [])

    .controller('messageController', ['$scope', function($scope) {

      $scope.message = '';

    }])
  </script>
</head>

<body ng-app="exampleModule">

  <div ng-controller="messageController">

    Input:
    <input ng-model="message" />

    <button>Submit</button>

    <button>Clear</button>

    <br/>
    <div>Message: {{message}}</div>
  </div>
</body>

</html>
</code>```

答:
Give your buttons a ng-click event and handle the event in your controller.
If the submit button is pressed set the show veriable to true, so that it will display.

HTML:

```<code><div ng-app="exampleModule">
    <div ng-controller="messageController">

         Input:
        <input ng-model="message" />

        <button ng-click="display()">Submit</button>

         <button ng-click="clear()">Clear</button>

         <br/>
         <div ng-show="show">Message: {{message}}</div>
    </div>
</div>
</code>```

AngularJS Controller:

```<code>angular.module('exampleModule', [])
.controller('messageController', ['$scope', function($scope) {
    $scope.show = false;
    $scope.message = '';

    $scope.clear = function() {
        $scope.message = '';
    };

    $scope.display = function() {
        $scope.show = true;
    };
}])
</code>```

JSFiddle: https://jsfiddle.net/Anokrize/2fvtbwd2/

Body:
How do I display the user input when user clicks submit button. Also clear the message when user clicks the clear button. (please & thank you)

  <title></title>

    angular.module('exampleModule', [])

    .controller('messageController', ['$scope', function($scope) {

      $scope.message = '';

    }])
  </script>

    Input:
    <input ng-model="message" />

    <button>Submit</button>

    <button>Clear</button>

Message: {{message}}

Body:
Give your buttons a ng-click event and handle the event in your controller.
If the submit button is pressed set the show veriable to true, so that it will display.

HTML:

<div ng-app="exampleModule">
    <div ng-controller="messageController">

         Input:
        <input ng-model="message" />

        <button ng-click="display()">Submit</button>

         <button ng-click="clear()">Clear</button>

         <br/>
         <div ng-show="show">Message: {{message}}</div>
    </div>
</div>

AngularJS Controller:

angular.module('exampleModule', [])
.controller('messageController', ['$scope', function($scope) {
    $scope.show = false;
    $scope.message = '';

    $scope.clear = function() {
        $scope.message = '';
    };

    $scope.display = function() {
        $scope.show = true;
    };
}])

JSFiddle: https://jsfiddle.net/Anokrize/2fvtbwd2/


问:
call js script on every change state
i have big table with many html items such as select, textbox, radio-button, checkbox. also i have some function. i want to call this function on every change in item. for example select was changed, or some text type in textbox, or click radiobutton. how can i simply subscribes and call my js function? i can insert in any item

onchange='function()'

but may be jquery allow more simly way? any sample?

答:
In JQuery, you could use a .click() event on the items you want to change. For example:

```<code>    $("#the-element").click(function(){

//Enter your function here

});
</code>```

Hope that helps!

Title: call js script on every change state

Body:
In JQuery, you could use a .click() event on the items you want to change. For example:

    $("#the-element").click(function(){

//Enter your function here

});

Hope that helps!


问:
removing duplicates from a bool list
I am trying to get a word in a list that is followed by a word with a ''.'' in it. for example, if this is a list

```<code>test_list = ["hello", "how", "are.", "you"]
</code>```

it would select the word ''you'' I have managed to pull this off but I am trying to ensure that I do not get duplicate words.
Here is what I have so far

```<code>list = []
i = 0
bool = False
words = sent.split()
for word in words:
    if bool:
        list.append(word)
        bool = False
   # the bellow if statment seems to make everything worse instead of fixing the duplicate problem
    if "." in word and word not in list:
        bool = True
return list
</code>```

答:
Here is a different approach to the same problem.</p>

```<code>import itertools
from collections import deque

t = deque(map(lambda x: '.' in x, test_list)) # create a deque of bools
>>deque([False, False, True, False])

t.rotate(1) # shift it by one since we want the word after the '.'
>>deque([False, False, False, True])

set(itertools.compress(test_list, t)) # and then grab everywhere it is True
>>{'you'}
</code>```

Title: removing duplicates from a bool list

Body:
I am trying to get a word in a list that is followed by a word with a ''.'' in it. for example, if this is a list

test_list = ["hello", "how", "are.", "you"]

it would select the word ''you'' I have managed to pull this off but I am trying to ensure that I do not get duplicate words.
Here is what I have so far

list = []
i = 0
bool = False
words = sent.split()
for word in words:
    if bool:
        list.append(word)
        bool = False
   # the bellow if statment seems to make everything worse instead of fixing the duplicate problem
    if "." in word and word not in list:
        bool = True
return list

Body:
Here is a different approach to the same problem.

import itertools
from collections import deque

t = deque(map(lambda x: '.' in x, test_list)) # create a deque of bools
>>deque([False, False, True, False])

t.rotate(1) # shift it by one since we want the word after the '.'
>>deque([False, False, False, True])

set(itertools.compress(test_list, t)) # and then grab everywhere it is True
>>{'you'}


问:
Textmate: Remove a list of email addresses from a larger list
This feels like something that ought to be very simple, but i've been unable to find any way to accomplish it.

i have a list of over 10,000 email addresses in a text file. i have another, shorter list of 100+ addresses i need to remove from the original list. The problem is, there is an unknown number of addresses between each one to be removed.

i want to know: Is there a way to remove this list of addresses from the main list without doing a find/replace for each of the 100+ addresses individually?

答:
You can use google sheets to identify the unique values in two different list using few simple steps. Please find the below Demo.

Step 1: Create a google sheet and paste the Inputs as below.

Step 2: Use the add-on's menu choose the choose the remove duplicates add on(if you don't have it by default, you can choose Get Add on's.. and include it to your menu)

Step 3: Select the input and output column Ranges.
First List:

Second List:

Step 4: Choose the data type as unique value.

Step 5: Choose filter options to add or ignore case sensitivity.

Step 6: Choose the output options(I have included the third column for demo).

Step 7: The unique values will be filtered in the specified destination as below.


问:
Regex in JavaScript acting differently than elsewhere
I am trying to match the word ethane (preceded with nothing) while avoiding methane.  I've tried this in an online regex tester: /(?<!m)ethane/i (which works), but I get an invalid regex expression error in JavaScript.  What am I doing wrong?

答:
You can use RegExp /\bethane\b/ to match "ethane" and not "methane"

var thanes = ["ethane", "methane"];
var re = /\bethane\b/;
thanes.forEach(word => console.log(re.test(word)));
  ```

See

Difference between \b and \B in regex

How does \b work when using regular expressions?

Body:
You can use RegExp /\bethane\b/ to match "ethane" and not "methane"

var thanes = ["ethane", "methane"];
var re = /\bethane\b/;
thanes.forEach(word => console.log(re.test(word)));

See

Difference between \b and \B in regex

How does \b work when using regular expressions?


问:
Powershell Group Paramter - Count over 100 adds value to variable
I found the below article to help me group a list of IP addresses.

Using Powershell, how can i count the occurrence of each element in an array?

The command I am currently using is:

```<code>get-content c:\temp\temp3.txt | group
</code>```

This would get the following output:

```<code>> Count Name                      Group
----- ----                      -----
    3 192.168.1.1             {192.168.1.1, 192.168.1.1, 192.168.1.1}
    3 192.168.1.2             {192.168.1.2, 192.168.1.2, 192.168.1.2}
</code>```

What command can I use to find all IP's with over a count of 5?

I imagine I would need to put my orignal command as a variable like below:

```<code>$groupedoutput get-content c:\temp\temp3.txt | group
</code>```

Unsure where to go from there. Any help would be appreciated.

Thanks,

S

答:
In full:

```<code>Get-Content -Path c:\temp\temp3.txt  |
    Group-Object  -NoElement         |
    Where-Object  { $_.Count -gt 5 } |
    Select-Object -ExpandProperty Name
</code>```

In short:

```<code>gc c:\temp\temp3.txt | group |? count -gt 5 |% Name
</code>```

The -NoElement switch means the groups don't gather up all this stuff: {192.168.1.1, 192.168.1.1, 192.168.1.1} , it's not really necessary here but it saves memory if you aren't going to use the grouped items.

Body:
I found the below article to help me group a list of IP addresses.

Using Powershell, how can i count the occurrence of each element in an array?

The command I am currently using is:

get-content c:\temp\temp3.txt | group

This would get the following output:

> Count Name                      Group
----- ----                      -----
    3 192.168.1.1             {192.168.1.1, 192.168.1.1, 192.168.1.1}
    3 192.168.1.2             {192.168.1.2, 192.168.1.2, 192.168.1.2}

What command can I use to find all IP's with over a count of 5?

I imagine I would need to put my orignal command as a variable like below:

$groupedoutput get-content c:\temp\temp3.txt | group

Unsure where to go from there. Any help would be appreciated.

Thanks,

S

Body:
In full:

Get-Content -Path c:\temp\temp3.txt  |
    Group-Object  -NoElement         |
    Where-Object  { $_.Count -gt 5 } |
    Select-Object -ExpandProperty Name

In short:

gc c:\temp\temp3.txt | group |? count -gt 5 |% Name

The -NoElement switch means the groups don't gather up all this stuff: {192.168.1.1, 192.168.1.1, 192.168.1.1} , it's not really necessary here but it saves memory if you aren't going to use the grouped items.


答:
You can use a jQuery selector to wrap all the items you want the event attached to. Then, use bind method on that wrapper to attach events.

An example:

```<code>$('input').bind({
  click: function() {
    // do something on click
  },
  mouseenter: function() {
    // do something on mouseenter
  }
});
</code>```

Title: call js script on every change state

Body:
i have big table with many html items such as select, textbox, radio-button, checkbox. also i have some function. i want to call this function on every change in item. for example select was changed, or some text type in textbox, or click radiobutton. how can i simply subscribes and call my js function? i can insert in any item

onchange='function()'

but may be jquery allow more simly way? any sample?

Body:
You can use a jQuery selector to wrap all the items you want the event attached to. Then, use bind method on that wrapper to attach events.

An example:

$('input').bind({
  click: function() {
    // do something on click
  },
  mouseenter: function() {
    // do something on mouseenter
  }
});


问:
cordova create project failed,but it can run or build
I tried to reinstall the cordova and reinstall the system, but it didn't work.My cordova version is 7.0.1,node version is v6.10.3 and npm version is 3.10.10.The code for the new project error is as follows. </p>

```

 - E:\cordovaProject>cordova create myapp  com.mu myapp -d  Using
   detached cordova-create  Creating a new cordova project.  Copying
   assets."  Using cordova-fetch for
   C:\Users\Administrator\AppData\Roaming\npm\node_modules\
   cordova\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hello-world\ind
   ex.js  Running command: cmd "/s /c ""C:\Program Files\nodejs\npm.cmd"
   install C:\Users\
   Administrator\AppData\Roaming\npm\node_modules\cordova\node_modules\_cordova-app
   -hello-world@3.12.0@cordova-app-hello-world\index.js"" Command finished with error code 4294963238: cmd /s /c ""C:\Program
   Files\nodejs \npm.cmd" install
   C:\Users\Administrator\AppData\Roaming\npm\node_modules\cordov
   a\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hello-world\index.js"

   Error: Uncaught, unspecified "error" event. (  Error from Cordova
   Fetch: Error: cmd: Command failed with exit code 4294963238 Error
   output: npm ERR! not a package
   C:\Users\Administrator\AppData\Roaming\npm\node_modules\c
   ordova\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hello-world\inde x.js npm ERR! addLocal Could not install
   C:\Users\Administrator\AppData\Roaming\npm\n
   ode_modules\cordova\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hel
   lo-world\index.js npm ERR! path
   C:\Users\Administrator\AppData\Local\Temp\npm-8056-980eaa3d\unpack
   -8e52606f\package.json npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory,
   open 'C:\Users\Administrator\
   AppData\Local\Temp\npm-8056-980eaa3d\unpack-8e52606f\package.json'
   npm ERR! enoent This is most likely not a problem with npm itself npm
   ERR! enoent and is related to npm not being able to find a file. npm
   ERR! enoent

   npm ERR! A complete log of this run can be found in: npm ERR!
   C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2017-05-18T0
   2_13_23_845Z-debug.log)

```

答:
Hey I had the same issue as you described above.
And I solved the issue with the answer here.</p>

Body:
I tried to reinstall the cordova and reinstall the system, but it didn't work.My cordova version is 7.0.1,node version is v6.10.3 and npm version is 3.10.10.The code for the new project error is as follows.

 - E:\cordovaProject>cordova create myapp  com.mu myapp -d  Using
   detached cordova-create  Creating a new cordova project.  Copying
   assets."  Using cordova-fetch for
   C:\Users\Administrator\AppData\Roaming\npm\node_modules\
   cordova\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hello-world\ind
   ex.js  Running command: cmd "/s /c ""C:\Program Files\nodejs\npm.cmd"
   install C:\Users\
   Administrator\AppData\Roaming\npm\node_modules\cordova\node_modules\_cordova-app
   -hello-world@3.12.0@cordova-app-hello-world\index.js"" Command finished with error code 4294963238: cmd /s /c ""C:\Program
   Files\nodejs \npm.cmd" install
   C:\Users\Administrator\AppData\Roaming\npm\node_modules\cordov
   a\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hello-world\index.js"

   Error: Uncaught, unspecified "error" event. (  Error from Cordova
   Fetch: Error: cmd: Command failed with exit code 4294963238 Error
   output: npm ERR! not a package
   C:\Users\Administrator\AppData\Roaming\npm\node_modules\c
   ordova\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hello-world\inde x.js npm ERR! addLocal Could not install
   C:\Users\Administrator\AppData\Roaming\npm\n
   ode_modules\cordova\node_modules\_cordova-app-hello-world@3.12.0@cordova-app-hel
   lo-world\index.js npm ERR! path
   C:\Users\Administrator\AppData\Local\Temp\npm-8056-980eaa3d\unpack
   -8e52606f\package.json npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory,
   open 'C:\Users\Administrator\
   AppData\Local\Temp\npm-8056-980eaa3d\unpack-8e52606f\package.json'
   npm ERR! enoent This is most likely not a problem with npm itself npm
   ERR! enoent and is related to npm not being able to find a file. npm
   ERR! enoent

   npm ERR! A complete log of this run can be found in: npm ERR!
   C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2017-05-18T0
   2_13_23_845Z-debug.log)


问:
c# classification inside datatable
I don't know exactly what is the correct term/way to explain my question but i hope someone get my idea

My datatable are required to classify few type of sources (ex in image) and i need to calculate them according to the type.. is there any way i can perform this?

Thank you so much for your reply

Here's what i've tried so far

```<code>  for (int l = 0; l < my_datatable.Rows.Count; l++)
        {

            data_source = my_datatable.Rows[l][3].ToString();

            if (data_source.Contains("Cross Site Scripting"))
            {
                my_datatable.Rows[l][3] = "2";
            }
            else if (data_source.Contains("SQL Injection"))
            {
                my_datatable.Rows[l][3] = "3";
            }
            else if (data_source.Contains("Unicode Attack"))
            {
                my_datatable.Rows[l][3] = "4";
            }
            else if (data_source.Contains("Proxy Attack"))
            {
                my_datatable.Rows[l][3] = "5";
            }
            else
            {
                my_datatable.Rows[l][3] = "1";
            }
</code>```

current output

expected output

Code for CSV part

```<code>        string[] raw_text =
        System.IO.File.ReadAllLines("C:\\dummylog3.csv"); //Placement of the
        .CSV Files
        string[] data_col = null;
        int x = 0;

        foreach (string text_line in raw_text)
        {
            //MessageBox.Show(text_line);
            data_col = text_line.Split(' ');

            if (x == 0)
            {
                for (int i = 0; i <= data_col.Count() - 1; i++)
                {
                    my_datatable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {

                my_datatable.Rows.Add(data_col);
            }

            my_datagridview.DataSource = my_datatable;
            this.Controls.Add(my_datagridview);
        }
</code>```

答:
Make a custom class which inherits the DataTable</p>

```<code>   public class CustomDataTable : DataTable
    {
        public enum ClassificationType
        {
            IMAGE
        }
        public ClassificationType classification { get; set; }
    }
</code>```

Title: c# classification inside datatable

Body:
I don't know exactly what is the correct term/way to explain my question but i hope someone get my idea

My datatable are required to classify few type of sources (ex in image) and i need to calculate them according to the type.. is there any way i can perform this?

Thank you so much for your reply

Here's what i've tried so far

  for (int l = 0; l < my_datatable.Rows.Count; l++)
        {

            data_source = my_datatable.Rows[l][3].ToString();

            if (data_source.Contains("Cross Site Scripting"))
            {
                my_datatable.Rows[l][3] = "2";
            }
            else if (data_source.Contains("SQL Injection"))
            {
                my_datatable.Rows[l][3] = "3";
            }
            else if (data_source.Contains("Unicode Attack"))
            {
                my_datatable.Rows[l][3] = "4";
            }
            else if (data_source.Contains("Proxy Attack"))
            {
                my_datatable.Rows[l][3] = "5";
            }
            else
            {
                my_datatable.Rows[l][3] = "1";
            }

current output

expected output

Code for CSV part

        string[] raw_text =
        System.IO.File.ReadAllLines("C:\\dummylog3.csv"); //Placement of the
        .CSV Files
        string[] data_col = null;
        int x = 0;

        foreach (string text_line in raw_text)
        {
            //MessageBox.Show(text_line);
            data_col = text_line.Split(' ');

            if (x == 0)
            {
                for (int i = 0; i <= data_col.Count() - 1; i++)
                {
                    my_datatable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {

                my_datatable.Rows.Add(data_col);
            }

            my_datagridview.DataSource = my_datatable;
            this.Controls.Add(my_datagridview);
        }

Body:
Make a custom class which inherits the DataTable

   public class CustomDataTable : DataTable
    {
        public enum ClassificationType
        {
            IMAGE
        }
        public ClassificationType classification { get; set; }
    }


问:
function on nested ranked lists: comparing lists of data against combinations of another list with data R
I really need help with my script, I am not a professional in R.

Some background information about what I want to do.

There are two ranked lists of data ( drugs,diseases ). In these datasets there is information about how genes change in expression.

The drugRL(drug) dataset is a dataset which is a ranked list. The diseaseRL(disease) dataset is a dataset which in the description says it is the same ( ?diseaseRL ), but seems not to be a ranked list.

What i did was i took the absolute numbers from the diseaseRL dataset and normalized the data using the range of the data ( max - min of a vector of a particular disease in that dataset ).

So what i have now are two lists of dataframes containing the information of gene expression, as ranked lists.

Some code examples, first build the needed packages:

```<code># Compile/install packages using biocLite.
#source("https://bioconductor.org/biocLite.R")
#biocLite("DrugVsDiseasedata")
#biocLite("gespeR")
#biocLite("DrugVsDisease") # may not be needed.
</code>```

Then import packages/datasets :

```<code>#import libraries
library("DrugVsDisease")#may not be needed
library("DrugVsDiseasedata")
library("cMap2data")
library("gespeR")

#import datasets
data(diseaseRL)
data(drugRL)

> class(drugRL)
[1] "matrix"
>

> class(diseaseRL)
[1] "matrix"
>

> str(drugRL)
 num [1:11709, 1:1309] 1870 4059 2250 10284 8999 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:11709] "ZNF702P" "SAMD4A" "VN1R1" "ZNF419" ...
  ..$ : chr [1:1309] "(+)-chelidonine" "(+)-isoprenaline" "(+/-)-catechin" "(-)-MK-801" ...
>

> str(diseaseRL)
 num [1:11709, 1:45] 0.01683 -0.00112 -0.00126 0.04902 0.02605 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:11709] "LINC00115" "GOT2P1" "TP73-AS1" "PIN1P1" ...
  ..$ : chr [1:45] "wilms-tumor" "glaucoma-open-angle" "diabetes-mellitus-type-ii" "soft-tissue-sarcoma" ...
>
</code>```

Now comes the part where i created a function to normalize the datasets:

```<code>NormalizeRLData <- function(x){

data.rankedlist <- x
data.rankedlist.abs <- as.data.frame(abs(data.rankedlist))
data.rankedlist.abs.ordered <-
data.rankedlist.abs[order(data.rankedlist.abs,decreasing=T), , drop = FALSE]

data.rankedlist.abs.ordered.max <- max(data.rankedlist.abs.ordered)
data.rankedlist.abs.ordered.min <- min(data.rankedlist.abs.ordered)

data.rankedlist.abs.ordered.normalizedToOwnRange <- (data.rankedlist.abs.ordered
/
(data.rankedlist.abs.ordered.max - data.rankedlist.abs.ordered.min ))

data.rankedlist.abs.ordered.normalizedToOwnRange.ordered <-
data.rankedlist.abs.ordered.normalizedToOwnRange[order(
data.rankedlist.abs.ordered.normalizedToOwnRange,decreasing=T ), , drop =
FALSE]

return(data.rankedlist.abs.ordered.normalizedToOwnRange.ordered)
}

diseaseRL.normalized <- apply(diseaseRL,2,NormalizeRLData)
drugRL.normalized <- apply(drugRL,2,NormalizeRLData)
</code>```

There are multiple doubts/problems i have in order to proceed. I am unsure if what i did till now can be done more effectively, in particular in regards to the following, using rank-biased overlap (RBO).

RBO is a function which is able to compare two ranked lists. I want to make use of this function for the lists of normalized data, containing data.frames of the genes (for the disease and drug ranked lists). The input of this rbo function is a named vector.

example :

```<code>> a <- c(4,2,5,5)
> b <- c(1,2,3,4)
> names(a) <- c('one','two','three','four')
> names(b) <- c('one','two','three','four')
> rbo(a,b, p = 0.95)
[1] 0.9650417
</code>```

What is the most efficient way to do this, so first of all can i have a better output then what i have at the moment to provide to the rbo function ?

And second :

If not ( or similar case ), I will have a list of data.frames containing the gene information for ether a drug, and another for a disease. I want to do the rbo function for every drug against every disease.

I tried using sapply, but i could not get it to work properly, and I am unsure if it is the right way to go. I need to maintain the names of the drugs , and for the other dataset the name of the disease, but also the gene names are important. So i can later check with genes and disease and drugs are having interactions.

I really hope someone here can shed some light into this !

p.s: If any one tries to help me here, but has problem compiling the packages, I may help ! Maybe i could send an example dataset ( not sure if i can attach anything here directly ).

Best Regards,
Rick

答:
First, your user-defined method can vastly be reduced in verbosity. No need to cast into data.frame, initially order, or use drop in [] as vectors are being passed into the method. Consider the following adjustment where last line is the returned object:

```<code>NormalizeRLData <- function(x){
  rnklist <- abs(x)
  rnklist <- rnklist[order(rnklist)]

  normRng <- rnklist / (max(rnklist) - min(rnklist))
  normRng[order(normRng, decreasing = TRUE)]
}

diseaseRL.normalized <- apply(diseaseRL,2,NormalizeRLData)
drugRL.normalized <- apply(drugRL,2,NormalizeRLData)
</code>```

Secondly, your normalized matrices (not dataframes) can possibly indeed be run with sapply by passing two inputs into the method, specifically both number of columns of each matrix as arguments. When two vectors are passed in sapply a cartesian product is applied where all combinations between both sets are iterated.

Since matrices maintain named columns and rows, it should adhere to rbo requirements. The return will be a matrix M x N where dimensions are the number of columns of disease and drug matrices.

```<code># TWO-INPUT SAPPLY
rbo_mat <- sapply(seq(ncol(diseaseRL.normalized)), function(i,j) rbo(diseaseRL.normalized[,i], drugRL.normalized[,j], p = 0.95),
                  seq(ncol(drugRL.normalized)))

# EQUIVALENT WITH VAPPLY TO [V]ERIFY TYPE AND LENGTH OF OUTPUT
rbo_mat <- vapply(seq(ncol(diseaseRL.normalized)), function(i,j) rbo(diseaseRL.normalized[,i], drugRL.normalized[,j], p = 0.95),
                  numeric(seq(ncol(drugRL.normalized))),
                  seq(ncol(drugRL.normalized)))
</code>```

You might even be able to use the lesser know apply function, rapply (recursive apply):

```<code>cols_list <- list(seq(ncol(diseaseRL.normalized)), seq(ncol(drugRL.normalized)))

rbo_mat2 <- rapply(cols_list, function(i,j) rbo(drugRL.normalized[,j], diseaseRL.normalized[,i], p = 0.95),
                   how="replace")[[1]]
</code>```

TEST EXAMPLE

Because I cannot reproduce OP's data and do not have necessary packages, below is working example of above methodology with random normal data and uses the correlation function, cor as substitute for rbo:

```<code>set.seed(142)

mat1 <- sapply(1:10, function(i) rnorm(20))
colnames(mat1) <-  LETTERS[1:10]
rownames(mat1) <- letters[1:20]

str(mat1)
#  num [1:20, 1:10] 1.255 1.704 0.88 -0.582 -0.169 ...
#  - attr(*, "dimnames")=List of 2
#   ..$ : chr [1:20] "a" "b" "c" "d" ...
#   ..$ : chr [1:10] "A" "B" "C" "D" ...

mat2 <- sapply(1:5, function(i) rnorm(20))
colnames(mat2) <-  LETTERS[1:5]
rownames(mat2) <- letters[1:20]

str(mat2)
#  num [1:20, 1:5] -0.156 0.449 -0.822 -1.062 0.838 ...
#  - attr(*, "dimnames")=List of 2
#   ..$ : chr [1:20] "a" "b" "c" "d" ...
#   ..$ : chr [1:5] "A" "B" "C" "D" ...

corr_mat <- sapply(seq(ncol(mat1)), function(i,j) cor(mat1[,i], mat2[,j]),
                   seq(ncol(mat2)))

corr_mat2 <- vapply(seq(ncol(mat1)), function(i,j) cor(mat1[,i], mat2[,j]),
                    numeric(ncol(mat2)),
                    seq(ncol(mat2)))

corr_mat3 <- rapply(list(seq(ncol(mat1)), ncol(mat2)), function(i,j) cor(mat2[,j], mat1[,i]),
                    how="replace")[[1]]
</code>```

Body:
I really need help with my script, I am not a professional in R.

Some background information about what I want to do.

There are two ranked lists of data ( drugs,diseases ). In these datasets there is information about how genes change in expression.

The drugRL(drug) dataset is a dataset which is a ranked list. The diseaseRL(disease) dataset is a dataset which in the description says it is the same ( ?diseaseRL ), but seems not to be a ranked list.

What i did was i took the absolute numbers from the diseaseRL dataset and normalized the data using the range of the data ( max - min of a vector of a particular disease in that dataset ).

So what i have now are two lists of dataframes containing the information of gene expression, as ranked lists.

Some code examples, first build the needed packages:

# Compile/install packages using biocLite.
#source("https://bioconductor.org/biocLite.R")
#biocLite("DrugVsDiseasedata")
#biocLite("gespeR")
#biocLite("DrugVsDisease") # may not be needed.

Then import packages/datasets :

#import libraries
library("DrugVsDisease")#may not be needed
library("DrugVsDiseasedata")
library("cMap2data")
library("gespeR")

#import datasets
data(diseaseRL)
data(drugRL)

> class(drugRL)
[1] "matrix"
>

> class(diseaseRL)
[1] "matrix"
>

> str(drugRL)
 num [1:11709, 1:1309] 1870 4059 2250 10284 8999 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:11709] "ZNF702P" "SAMD4A" "VN1R1" "ZNF419" ...
  ..$ : chr [1:1309] "(+)-chelidonine" "(+)-isoprenaline" "(+/-)-catechin" "(-)-MK-801" ...
>

> str(diseaseRL)
 num [1:11709, 1:45] 0.01683 -0.00112 -0.00126 0.04902 0.02605 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:11709] "LINC00115" "GOT2P1" "TP73-AS1" "PIN1P1" ...
  ..$ : chr [1:45] "wilms-tumor" "glaucoma-open-angle" "diabetes-mellitus-type-ii" "soft-tissue-sarcoma" ...
>

Now comes the part where i created a function to normalize the datasets:

NormalizeRLData <- function(x){

data.rankedlist <- x
data.rankedlist.abs <- as.data.frame(abs(data.rankedlist))
data.rankedlist.abs.ordered <-
data.rankedlist.abs[order(data.rankedlist.abs,decreasing=T), , drop = FALSE]

data.rankedlist.abs.ordered.max <- max(data.rankedlist.abs.ordered)
data.rankedlist.abs.ordered.min <- min(data.rankedlist.abs.ordered)

data.rankedlist.abs.ordered.normalizedToOwnRange <- (data.rankedlist.abs.ordered
/
(data.rankedlist.abs.ordered.max - data.rankedlist.abs.ordered.min ))

data.rankedlist.abs.ordered.normalizedToOwnRange.ordered <-
data.rankedlist.abs.ordered.normalizedToOwnRange[order(
data.rankedlist.abs.ordered.normalizedToOwnRange,decreasing=T ), , drop =
FALSE]

return(data.rankedlist.abs.ordered.normalizedToOwnRange.ordered)
}

diseaseRL.normalized <- apply(diseaseRL,2,NormalizeRLData)
drugRL.normalized <- apply(drugRL,2,NormalizeRLData)

There are multiple doubts/problems i have in order to proceed. I am unsure if what i did till now can be done more effectively, in particular in regards to the following, using rank-biased overlap (RBO).

RBO is a function which is able to compare two ranked lists. I want to make use of this function for the lists of normalized data, containing data.frames of the genes (for the disease and drug ranked lists). The input of this rbo function is a named vector.

example :

> a <- c(4,2,5,5)
> b <- c(1,2,3,4)
> names(a) <- c('one','two','three','four')
> names(b) <- c('one','two','three','four')
> rbo(a,b, p = 0.95)
[1] 0.9650417

What is the most efficient way to do this, so first of all can i have a better output then what i have at the moment to provide to the rbo function ?

And second :

If not ( or similar case ), I will have a list of data.frames containing the gene information for ether a drug, and another for a disease. I want to do the rbo function for every drug against every disease.

I tried using sapply, but i could not get it to work properly, and I am unsure if it is the right way to go. I need to maintain the names of the drugs , and for the other dataset the name of the disease, but also the gene names are important. So i can later check with genes and disease and drugs are having interactions.

I really hope someone here can shed some light into this !

p.s: If any one tries to help me here, but has problem compiling the packages, I may help ! Maybe i could send an example dataset ( not sure if i can attach anything here directly ).

Best Regards,
Rick

Body:
First, your user-defined method can vastly be reduced in verbosity. No need to cast into data.frame, initially order, or use drop in [] as vectors are being passed into the method. Consider the following adjustment where last line is the returned object:

NormalizeRLData <- function(x){
  rnklist <- abs(x)
  rnklist <- rnklist[order(rnklist)]

  normRng <- rnklist / (max(rnklist) - min(rnklist))
  normRng[order(normRng, decreasing = TRUE)]
}

diseaseRL.normalized <- apply(diseaseRL,2,NormalizeRLData)
drugRL.normalized <- apply(drugRL,2,NormalizeRLData)

Secondly, your normalized matrices (not dataframes) can possibly indeed be run with sapply by passing two inputs into the method, specifically both number of columns of each matrix as arguments. When two vectors are passed in sapply a cartesian product is applied where all combinations between both sets are iterated.

Since matrices maintain named columns and rows, it should adhere to rbo requirements. The return will be a matrix M x N where dimensions are the number of columns of disease and drug matrices.

# TWO-INPUT SAPPLY
rbo_mat <- sapply(seq(ncol(diseaseRL.normalized)), function(i,j) rbo(diseaseRL.normalized[,i], drugRL.normalized[,j], p = 0.95),
                  seq(ncol(drugRL.normalized)))

# EQUIVALENT WITH VAPPLY TO [V]ERIFY TYPE AND LENGTH OF OUTPUT
rbo_mat <- vapply(seq(ncol(diseaseRL.normalized)), function(i,j) rbo(diseaseRL.normalized[,i], drugRL.normalized[,j], p = 0.95),
                  numeric(seq(ncol(drugRL.normalized))),
                  seq(ncol(drugRL.normalized)))

You might even be able to use the lesser know apply function, rapply (recursive apply):

cols_list <- list(seq(ncol(diseaseRL.normalized)), seq(ncol(drugRL.normalized)))

rbo_mat2 <- rapply(cols_list, function(i,j) rbo(drugRL.normalized[,j], diseaseRL.normalized[,i], p = 0.95),
                   how="replace")[[1]]

TEST EXAMPLE

Because I cannot reproduce OP's data and do not have necessary packages, below is working example of above methodology with random normal data and uses the correlation function, cor as substitute for rbo:

set.seed(142)

mat1 <- sapply(1:10, function(i) rnorm(20))
colnames(mat1) <-  LETTERS[1:10]
rownames(mat1) <- letters[1:20]

str(mat1)
#  num [1:20, 1:10] 1.255 1.704 0.88 -0.582 -0.169 ...
#  - attr(*, "dimnames")=List of 2
#   ..$ : chr [1:20] "a" "b" "c" "d" ...
#   ..$ : chr [1:10] "A" "B" "C" "D" ...

mat2 <- sapply(1:5, function(i) rnorm(20))
colnames(mat2) <-  LETTERS[1:5]
rownames(mat2) <- letters[1:20]

str(mat2)
#  num [1:20, 1:5] -0.156 0.449 -0.822 -1.062 0.838 ...
#  - attr(*, "dimnames")=List of 2
#   ..$ : chr [1:20] "a" "b" "c" "d" ...
#   ..$ : chr [1:5] "A" "B" "C" "D" ...

corr_mat <- sapply(seq(ncol(mat1)), function(i,j) cor(mat1[,i], mat2[,j]),
                   seq(ncol(mat2)))

corr_mat2 <- vapply(seq(ncol(mat1)), function(i,j) cor(mat1[,i], mat2[,j]),
                    numeric(ncol(mat2)),
                    seq(ncol(mat2)))

corr_mat3 <- rapply(list(seq(ncol(mat1)), ncol(mat2)), function(i,j) cor(mat2[,j], mat1[,i]),
                    how="replace")[[1]]


问:
maximum recursion depth exceeded in comparison?
Started learning python, this is maximum sum subarray i have tried. Ending up with "maximum recursion depth exceeded in comparison". My algorithm seems ok to me. Please help me if im doing anything wrong. </p>

```<code>import sys
import math
def maxtuple(lss,rss):
    if lss[2] > rss[2]:
        return lss
    else:
        return rss
def crosssubarray(A, start, mid, end):
    ls=rs=-sys.maxsize
    maxleft=0
    maxright=0
    sum = 0;
    for i in reversed(range(start, mid)):
        sum = sum + A[i]
        print(i)
        if sum > ls:
            ls = sum
            maxleft = i
    sum = 0
    for i in range(mid+1, end):
        sum = sum+ A[i]
        if sum > rs:
            rs = sum
            maxright = i
    return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))
</code>```

答:
Your problem lies in this function:

```<code>def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall
</code>```

To be precise, the first 5 lines. The reason for "working" (don't know your expected result) in python 2.x is because / is for floor division, while in python 3.x / is for float point division. And thanks to float point round-off error, start is mostly likely never going to be equal to end.

If integer floor division is what you're going for, you can replace the / to a //.

Doing so, the error will disappear and returns (8, 10, 32)

Body:
Started learning python, this is maximum sum subarray i have tried. Ending up with "maximum recursion depth exceeded in comparison". My algorithm seems ok to me. Please help me if im doing anything wrong.

import sys
import math
def maxtuple(lss,rss):
    if lss[2] > rss[2]:
        return lss
    else:
        return rss
def crosssubarray(A, start, mid, end):
    ls=rs=-sys.maxsize
    maxleft=0
    maxright=0
    sum = 0;
    for i in reversed(range(start, mid)):
        sum = sum + A[i]
        print(i)
        if sum > ls:
            ls = sum
            maxleft = i
    sum = 0
    for i in range(mid+1, end):
        sum = sum+ A[i]
        if sum > rs:
            rs = sum
            maxright = i
    return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))

Body:
Your problem lies in this function:

def maxsubarray(A,start,end):
    if start == end:
        return (start,end,A[start])
    else:
        mid = (start+end)/2
        lss = maxsubarray(A, start, mid)
        rss = maxsubarray(A, mid+1, end)
        css = crosssubarray(A, start, mid, end)
        maxsub = maxtuple(lss,rss)
        maxall = maxtuple(maxsub, css)
        return maxall

To be precise, the first 5 lines. The reason for "working" (don't know your expected result) in python 2.x is because / is for floor division, while in python 3.x / is for float point division. And thanks to float point round-off error, start is mostly likely never going to be equal to end.

If integer floor division is what you're going for, you can replace the / to a //.

Doing so, the error will disappear and returns (8, 10, 32)


问:
Data compression libraries: brotli vs zlib
Which data compression works best for compressing javascript files when downloaded from any website: brotli or zlib ?

答:
I'll assume that by "javascript files" you mean javascript source code.

brotli (content encoding "br") is better for non-dynamic content, where you expect it to be compressed once, but transmitted and decompressed many times. That would normally be the case for javascript. The average gain is about 20% for javascript code.

Not all clients accept brotli (so far Firefox, Chrome, and Edge do). If the client doesn't accept it, then the encoding negotiation will automatically fall back to content encoding gzip (what zlib produces).

ContentLicense: CC BY-SA 4.0


问:
Swift: Using Int in UILabel inside View Controller
I've set up an if statement which does things depending on an int value stored in a UILabel, however, my code can't determine the value of the int inside the label.

This is because the if statement runs within the viewdidload function. I'm basically looking for how I can pass the label value to my view. I'm struggling to make it work.

Here's the code:

```<code>   override func viewDidLoad()
   {
        // If statement
        var NumberRead = Int(Number.text!)

        if NumberRead! <= 2 {
              Picture.image = Pic1
        } else {
              Picture.image = Pic2
        }
    }

    @IBOutlet weak var Number: UILabel!
</code>```

Any suggestions for better ways to handle this would be amazing.

Thanks

答:
How about:
set the default image to pic2, then use optional binding to check the value</p>

```<code>Picture.image = Pic2
if let numTxt = Number.text {
    if let num = Int(numTxt) {
        if num <= 2 {
            Picture.image = Pic1
        }
    }
}
</code>```

Body:
I've set up an if statement which does things depending on an int value stored in a UILabel, however, my code can't determine the value of the int inside the label.

This is because the if statement runs within the viewdidload function. I'm basically looking for how I can pass the label value to my view. I'm struggling to make it work.

Here's the code:

   override func viewDidLoad()
   {
        // If statement
        var NumberRead = Int(Number.text!)

        if NumberRead! <= 2 {
              Picture.image = Pic1
        } else {
              Picture.image = Pic2
        }
    }

    @IBOutlet weak var Number: UILabel!

Any suggestions for better ways to handle this would be amazing.

Thanks

Body:
How about:
set the default image to pic2, then use optional binding to check the value

Picture.image = Pic2
if let numTxt = Number.text {
    if let num = Int(numTxt) {
        if num <= 2 {
            Picture.image = Pic1
        }
    }
}


问:
Could not fetch user details: class org.springframework.web.client.RestClientException, Could not extract response: no suitable
iam getting this error message when build simple app

Getting user info from: http://localhost:9999/uaa/user
  Could not fetch user details: class org.springframework.web.client.RestClientException, Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [text/html;charset=UTF-8]

however i sure the content type is json

this is the github repository https://github.com/ashraf-revo/oauth

this is server

```<code>@SpringBootApplication
public class AuthServerApplication {

public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
}
}

@Order(1)
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws     Exception {
      auth.inMemoryAuthentication().withUser("ashraf").password("ashraf").roles("user");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/user").authenticated().and().formLogin();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
}

@Configuration
class OAuth2ServerConfig {
private static final String RESOURCE_IDS = "revo";

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_IDS);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/user").authenticated();
    }
}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("revo")
                .resourceIds(RESOURCE_IDS)
                .authorizedGrantTypes("authorization_code", "implicit")
                .authorities("ROLE_CLIENT")
                .scopes("read", "write")
                .secret("revo");
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager);
    }
}

}
</code>```

this is the client

```<code>@SpringBootApplication
public class ClientApplication {

public static void main(String[] args) {
    SpringApplication.run(ClientApplication.class, args);
}
}

@Configuration
@EnableOAuth2Sso
class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().mvcMatchers("/home").authenticated();
}
}

 @Configuration
 class MvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index");
    registry.addViewController("/home").setViewName("home");
}
}
</code>```

答: you may consider spring-boot version and spring-cloud version,choose a not latest version,like spring-boot-1.4.4.RELEASE and spring-cloud-Camden.SR5;because i had same trouble and resolved by this way</p>

Body:
iam getting this error message when build simple app

Getting user info from: http://localhost:9999/uaa/user
  Could not fetch user details: class org.springframework.web.client.RestClientException, Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [text/html;charset=UTF-8]

however i sure the content type is json

this is the github repository https://github.com/ashraf-revo/oauth

this is server

@SpringBootApplication
public class AuthServerApplication {

public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
}
}

@Order(1)
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws     Exception {
      auth.inMemoryAuthentication().withUser("ashraf").password("ashraf").roles("user");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/user").authenticated().and().formLogin();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
}

@Configuration
class OAuth2ServerConfig {
private static final String RESOURCE_IDS = "revo";

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_IDS);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/user").authenticated();
    }
}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("revo")
                .resourceIds(RESOURCE_IDS)
                .authorizedGrantTypes("authorization_code", "implicit")
                .authorities("ROLE_CLIENT")
                .scopes("read", "write")
                .secret("revo");
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager);
    }
}

}

this is the client

@SpringBootApplication
public class ClientApplication {

public static void main(String[] args) {
    SpringApplication.run(ClientApplication.class, args);
}
}

@Configuration
@EnableOAuth2Sso
class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().mvcMatchers("/home").authenticated();
}
}

 @Configuration
 class MvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index");
    registry.addViewController("/home").setViewName("home");
}
}