问:
Xamarin.Forms.CarouselView doesn't work on iOS
I have tried to implement Xamarin.Forms.CarouselView for use on both iOS and Android using Xamarin.Forms in Visual Studio. It works perfectly in Android, but it doesn't work on iOS. On iOS it shows the first slide, but it doesn't allow me to swipe right or left to change the current slide. I have installed the NuGet package in both the iOS and Android projects. The XAML looks like this:

```<code>    <cv:CarouselView ItemsSource="{Binding Slider}" x:Name="CarouselSlider">
        <cv:CarouselView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                        <!--<RowDefinition Height="Auto"/>-->
                    </Grid.RowDefinitions>
                    <Image Grid.RowSpan="1" Aspect="AspectFill" Source="{Binding ImageUrl}" />
                    <StackLayout BackgroundColor="#7F000000" Padding="12" VerticalOptions="Center" TranslationY="100">
                        <Label TextColor="White" Text="{Binding Title}" FontSize="26" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
                        <Label TextColor="White" Text="{Binding TextBody}" FontSize="16" HorizontalOptions="Center" HorizontalTextAlignment="Center" VerticalOptions="CenterAndExpand"/>
                    </StackLayout>
                </Grid>
            </DataTemplate>
        </cv:CarouselView.ItemTemplate>
    </cv:CarouselView>
</code>```

And the backend looks like this:

```<code>public partial class MainPage : ContentPage
{
    public System.Collections.ObjectModel.ObservableCollection<SliderContent> Slider { get; set; }

    public MainPage()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);

        Slider = new System.Collections.ObjectModel.ObservableCollection<SliderContent>
        {
            new SliderContent
            {
                Id = 1,
                ImageUrl = "https://thumb9.shutterstock.com/display_pic_with_logo/1975943/561919966/stock-photo-brutal-strong-athletic-men-pumping-up-muscles-workout-bodybuilding-concept-background-muscular-561919966.jpg",
                Title = "Aliquam et neque arcu",
                TextBody = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porttitor erat arcu, vitae accumsan odio iaculis et."
            },
                new SliderContent
            {
                Id = 2,
                ImageUrl = "https://ifitlife.files.wordpress.com/2014/06/20140604-155437-57277345.jpg",
                Title = "Donec lobortis sodales dui",
                TextBody = "Morbi congue scelerisque vulputate. Vestibulum sit amet hendrerit justo. Nulla facilisi."
                },
            new SliderContent
            {
                Id = 3,
                ImageUrl = "https://uproxx.files.wordpress.com/2013/05/dmx-black.jpg?quality=100&w=650",
                Title = "Vestibulum arcu elit",
                TextBody = "Aliquam in maximus ante. Suspendisse facilisis posuere nulla quis hendrerit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas."
            }
        };

        Grid dotsGrid = DotsIndicator;
        dotsGrid.HorizontalOptions = LayoutOptions.CenterAndExpand;

        dotsGrid.ColumnDefinitions = new ColumnDefinitionCollection
        {
            new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
            new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
            new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }
        };

        dotsGrid.RowDefinitions = new RowDefinitionCollection
        {
            new RowDefinition { Height = new GridLength(6, GridUnitType.Star) },
            new RowDefinition { Height = new GridLength(2, GridUnitType.Star) },
            new RowDefinition { Height = new GridLength(6, GridUnitType.Star) }
        };

        int counter = 0;

        foreach (var i in Slider)
        {
            Button label = new Button();
            if (Slider.First() == i)
            {
                label = new Button
                {
                    BackgroundColor = Color.White,
                    BindingContext = i,
                    VerticalOptions = LayoutOptions.Fill,
                    WidthRequest = 20,
                    HeightRequest = 20,
                    BorderRadius = 30
                };
            }
            else
            {
                label = new Button
                {
                    BackgroundColor = Color.Gray,
                    BindingContext = i,
                    VerticalOptions = LayoutOptions.Fill,
                    WidthRequest = 20,
                    HeightRequest = 20,
                    BorderRadius = 30
                };
            }

            dotsGrid.Children.Add(label, counter, 1);
            counter++;
        }

        DotsIndicator = dotsGrid;
        this.BindingContext = this;
        CarouselSlider.ItemSelected += CarouselSlider_ItemSelected;
    }

    private void CarouselSlider_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var item = e.SelectedItem as SliderContent;
        foreach (var i in DotsIndicator.Children)
        {
            i.BackgroundColor = Color.Gray;
            if (i.BindingContext == item)
            {
                i.BackgroundColor = Color.White;
            }
        }

        return;
    }
}
</code>```

Are there any known issues using Xamarin.Forms.CarouselView on iOS or am I missing something?

答: I solved the issue by putting a StackLayout tag around the CarouselView.</p>

Body:
I have tried to implement Xamarin.Forms.CarouselView for use on both iOS and Android using Xamarin.Forms in Visual Studio. It works perfectly in Android, but it doesn't work on iOS. On iOS it shows the first slide, but it doesn't allow me to swipe right or left to change the current slide. I have installed the NuGet package in both the iOS and Android projects. The XAML looks like this:

    <cv:CarouselView ItemsSource="{Binding Slider}" x:Name="CarouselSlider">
        <cv:CarouselView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>

                    </Grid.RowDefinitions>
                    <Image Grid.RowSpan="1" Aspect="AspectFill" Source="{Binding ImageUrl}" />
                    <StackLayout BackgroundColor="#7F000000" Padding="12" VerticalOptions="Center" TranslationY="100">

                    </StackLayout>
                </Grid>
            </DataTemplate>
        </cv:CarouselView.ItemTemplate>
    </cv:CarouselView>

And the backend looks like this:

public partial class MainPage : ContentPage
{
    public System.Collections.ObjectModel.ObservableCollection<SliderContent> Slider { get; set; }

    public MainPage()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);

        Slider = new System.Collections.ObjectModel.ObservableCollection<SliderContent>
        {
            new SliderContent
            {
                Id = 1,
                ImageUrl = "https://thumb9.shutterstock.com/display_pic_with_logo/1975943/561919966/stock-photo-brutal-strong-athletic-men-pumping-up-muscles-workout-bodybuilding-concept-background-muscular-561919966.jpg",
                Title = "Aliquam et neque arcu",
                TextBody = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porttitor erat arcu, vitae accumsan odio iaculis et."
            },
                new SliderContent
            {
                Id = 2,
                ImageUrl = "https://ifitlife.files.wordpress.com/2014/06/20140604-155437-57277345.jpg",
                Title = "Donec lobortis sodales dui",
                TextBody = "Morbi congue scelerisque vulputate. Vestibulum sit amet hendrerit justo. Nulla facilisi."
                },
            new SliderContent
            {
                Id = 3,
                ImageUrl = "https://uproxx.files.wordpress.com/2013/05/dmx-black.jpg?quality=100&w=650",
                Title = "Vestibulum arcu elit",
                TextBody = "Aliquam in maximus ante. Suspendisse facilisis posuere nulla quis hendrerit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas."
            }
        };

        Grid dotsGrid = DotsIndicator;
        dotsGrid.HorizontalOptions = LayoutOptions.CenterAndExpand;

        dotsGrid.ColumnDefinitions = new ColumnDefinitionCollection
        {
            new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
            new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
            new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }
        };

        dotsGrid.RowDefinitions = new RowDefinitionCollection
        {
            new RowDefinition { Height = new GridLength(6, GridUnitType.Star) },
            new RowDefinition { Height = new GridLength(2, GridUnitType.Star) },
            new RowDefinition { Height = new GridLength(6, GridUnitType.Star) }
        };

        int counter = 0;

        foreach (var i in Slider)
        {
            Button label = new Button();
            if (Slider.First() == i)
            {
                label = new Button
                {
                    BackgroundColor = Color.White,
                    BindingContext = i,
                    VerticalOptions = LayoutOptions.Fill,
                    WidthRequest = 20,
                    HeightRequest = 20,
                    BorderRadius = 30
                };
            }
            else
            {
                label = new Button
                {
                    BackgroundColor = Color.Gray,
                    BindingContext = i,
                    VerticalOptions = LayoutOptions.Fill,
                    WidthRequest = 20,
                    HeightRequest = 20,
                    BorderRadius = 30
                };
            }

            dotsGrid.Children.Add(label, counter, 1);
            counter++;
        }

        DotsIndicator = dotsGrid;
        this.BindingContext = this;
        CarouselSlider.ItemSelected += CarouselSlider_ItemSelected;
    }

    private void CarouselSlider_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var item = e.SelectedItem as SliderContent;
        foreach (var i in DotsIndicator.Children)
        {
            i.BackgroundColor = Color.Gray;
            if (i.BindingContext == item)
            {
                i.BackgroundColor = Color.White;
            }
        }

        return;
    }
}

Are there any known issues using Xamarin.Forms.CarouselView on iOS or am I missing something?


来源: stackexchange

问:
Real-time video analysis on Europe server
I'm trying out the real-time video analysis app as provided here:
https://learn.microsoft.com/nl-nl/azure/cognitive-services/Computer-vision/vision-api-how-to-topics/howtoanalyzevideo_vision

More specifically, right now the LiveCameraSample. I found out it can only use WestUS server API keys, not WestEU. Is there a way to change this? I've looked into the .cs files, but no luck so far.

Thanks!

答: A fix for this has been pushed to github.  Please pull the lastest, and when you run the new app you will be presented with text fields into which you can enter the endpoint locations.</p>

ContentLicense: CC BY-SA 3.0


问:
How can I assign a bitmap to a Image control in asp.net using c#?
I have an asp.net file as follows:

```<code><body>
<form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    <div>
        <asp:Image ID="Image1" runat="server" />
    </div>
</form>
</code>```

I want to set the Image1 in the c# using the following code:

```<code>    protected void Button1_Click(object sender, EventArgs e)
{
    Bitmap oBmp1 = new Bitmap(460, 60);
    Graphics oGrp1 = Graphics.FromImage(oBmp1);
    Color ocolor = new Color();
    ocolor = Color.Yellow;
    SolidBrush oBrush = new SolidBrush(ocolor);
    SolidBrush oBrushWrite = new SolidBrush(Color.White);
    oGrp1.FillRectangle(oBrush, 100, 25, 500, 75);
    Response.ContentType = "image/jpeg";
    oBmp1.Save(Response.OutputStream, ImageFormat.Jpeg);
}
</code>```

How can I directly set the image1 in c# after I generate the bitmap without saving bitmap as an image file?

答:
Your above solution won't work.

You have to create a separate handler (.ashx) to return image. You will have to pass appropriate parameters as query string and link it to your Image control

See this https://web.archive.org/web/20211020111734/https://www.4guysfromrolla.com/articles/042209-1.aspx

Body:
I have an asp.net file as follows:

<form id="form1" runat="server">

        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

        <asp:Image ID="Image1" runat="server" />

</form>

I want to set the Image1 in the c# using the following code:

    protected void Button1_Click(object sender, EventArgs e)
{
    Bitmap oBmp1 = new Bitmap(460, 60);
    Graphics oGrp1 = Graphics.FromImage(oBmp1);
    Color ocolor = new Color();
    ocolor = Color.Yellow;
    SolidBrush oBrush = new SolidBrush(ocolor);
    SolidBrush oBrushWrite = new SolidBrush(Color.White);
    oGrp1.FillRectangle(oBrush, 100, 25, 500, 75);
    Response.ContentType = "image/jpeg";
    oBmp1.Save(Response.OutputStream, ImageFormat.Jpeg);
}

How can I directly set the image1 in c# after I generate the bitmap without saving bitmap as an image file?


问:
Gson nested objects
I'm using a library with a class to map a json message and I'm using Gson to serialized the classes over json. The message contains a data field. The field is generic and it contains anything. The class provided by the library is:

```<code>public class Api {
....
@SerializedName("data")
Map<String, JsonElement> data;
....
}
</code>```

Now I'd like to extend the class but I have my own root object to map the data sub field, so to do a summary the json is something like:

```<code>{...., "data": {"myownroot":"aaaa"}}
</code>```

How can I do? I could create my own classes of course but I would prefer to extend the library if possible. If I extend the class I would have:

```<code>public class MyOwnRoot extends Api {
@SerializedName("myownroot")
public String root;
}
</code>```

but in this case when I serialize it doesn't work because myownroot must be a child of data but how can I say to Gson "put MyOwnRoot in the data map"??

答:
I can't really understand why you would need to extend the Api class.
I guess the class name is a bit of a misnomer, since API are (generally speaking) interfaces, and they get implemented.

I guess you could do this by using getters to your advantages, while letting Gson do its work on fields.

EDIT: To serialize also

```<code>public class Api {
    @SerializedName("data")
    protected Map<String, JsonElement> data;
}

public class RootEntity extends Api {
    transient StructuredRootImpl _cached;
    transient Gson _gson = new Gson();

    public class StructuredRootImpl {
        Integer v;
        String name;
    }

    public Integer getV() {
        synch();
        return _cached.v;
    }

    public void setV(Integer v) {
        _cached.v=v;
        synch();
    }

    private void synch() {
        if(_cached==null){
            if(data==null){
                data = new LinkedHashMap<>();
            }
            JsonElement jsonElement = data.get("myroot");
            _cached = _gson.fromJson(jsonElement, StructuredRootImpl.class);
        }
        JsonElement jsonTree = _gson.toJsonTree(_cached);
        data.put("myroot", jsonTree);
    }

    public String getName() {
        synch();
        return _cached.name;
    }

    public void setName(String name) {
        _cached.name = name;
        synch();
    }

    @Override
    public String toString() {
        return "RootEntity [v=" + getV() + ", n=" + getName() + "]";
    }

}
</code>```

Running the main you can both serialize and deserialize your entity.

```<code>public class TestGson {

    public static void main(String[] args) {
        String jsonText = "{data:{\"myroot\":{\"v\":123,\"name\":\"mario\"}}}";
        Gson gson = new Gson();
        RootEntity entity = gson.fromJson(jsonText, RootEntity.class);
        System.out.println(entity);
        entity.setName("Alex");
        entity.setV(150);
        String thenBack = gson.toJson(entity);
        System.out.println(thenBack);

    }
}
</code>```

This will result in :

```<code>so.alpha.TestGson$Foo@4b85612c
StructuredRoot [v=123, name=mario]
</code>```

Still I don't understand why you would extend the Api class.

Title: Gson nested objects

Body:
I'm using a library with a class to map a json message and I'm using Gson to serialized the classes over json. The message contains a data field. The field is generic and it contains anything. The class provided by the library is:

public class Api {
....
@SerializedName("data")
Map<String, JsonElement> data;
....
}

Now I'd like to extend the class but I have my own root object to map the data sub field, so to do a summary the json is something like:

{...., "data": {"myownroot":"aaaa"}}

How can I do? I could create my own classes of course but I would prefer to extend the library if possible. If I extend the class I would have:

public class MyOwnRoot extends Api {
@SerializedName("myownroot")
public String root;
}

but in this case when I serialize it doesn't work because myownroot must be a child of data but how can I say to Gson "put MyOwnRoot in the data map"??

Body:
I can't really understand why you would need to extend the Api class.
I guess the class name is a bit of a misnomer, since API are (generally speaking) interfaces, and they get implemented.

I guess you could do this by using getters to your advantages, while letting Gson do its work on fields.

EDIT: To serialize also

public class Api {
    @SerializedName("data")
    protected Map<String, JsonElement> data;
}

public class RootEntity extends Api {
    transient StructuredRootImpl _cached;
    transient Gson _gson = new Gson();

    public class StructuredRootImpl {
        Integer v;
        String name;
    }

    public Integer getV() {
        synch();
        return _cached.v;
    }

    public void setV(Integer v) {
        _cached.v=v;
        synch();
    }

    private void synch() {
        if(_cached==null){
            if(data==null){
                data = new LinkedHashMap<>();
            }
            JsonElement jsonElement = data.get("myroot");
            _cached = _gson.fromJson(jsonElement, StructuredRootImpl.class);
        }
        JsonElement jsonTree = _gson.toJsonTree(_cached);
        data.put("myroot", jsonTree);
    }

    public String getName() {
        synch();
        return _cached.name;
    }

    public void setName(String name) {
        _cached.name = name;
        synch();
    }

    @Override
    public String toString() {
        return "RootEntity [v=" + getV() + ", n=" + getName() + "]";
    }

}

Running the main you can both serialize and deserialize your entity.

public class TestGson {

    public static void main(String[] args) {
        String jsonText = "{data:{\"myroot\":{\"v\":123,\"name\":\"mario\"}}}";
        Gson gson = new Gson();
        RootEntity entity = gson.fromJson(jsonText, RootEntity.class);
        System.out.println(entity);
        entity.setName("Alex");
        entity.setV(150);
        String thenBack = gson.toJson(entity);
        System.out.println(thenBack);

    }
}

This will result in :

so.alpha.TestGson$Foo@4b85612c
StructuredRoot [v=123, name=mario]

Still I don't understand why you would extend the Api class.


问:
Count of each unique element in a list
Say I have a list of countries

```<code>l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
</code>```

and then I have a list of unique countries

```<code>ul = ['India', 'China', 'Japan', 'USA']
</code>```

I want to have a count of each unique country in the list in ascending order. So output should be as follows:

```<code>Japan 1
China 2
India 2
USA   2
</code>```

答:
If you want to sort depending on the ul list, you can use list comprehension like:

```<code>l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
ul = ['India', 'China', 'Japan', 'USA']
result = sorted([(x, l.count(x)) for x in ul], key=lambda y: y[1])
for elem in result:
    print '{} {}'.format(elem[0], elem[1])
</code>```

output:

```<code>Japan 1
India 2
China 2
USA 2
</code>```

And if you want to sort by alphabet after sorting by count, you can change result to the following:

```<code>result = sorted(sorted([(x, l.count(x)) for x in ul]), key=lambda y: y[1])
</code>```

output:

```<code>Japan 1
China 2
India 2
USA 2
</code>```

Title: Count of each unique element in a list

Body:
Say I have a list of countries

l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']

and then I have a list of unique countries

ul = ['India', 'China', 'Japan', 'USA']

I want to have a count of each unique country in the list in ascending order. So output should be as follows:

Japan 1
China 2
India 2
USA   2

Body:
If you want to sort depending on the ul list, you can use list comprehension like:

l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
ul = ['India', 'China', 'Japan', 'USA']
result = sorted([(x, l.count(x)) for x in ul], key=lambda y: y[1])
for elem in result:
    print '{} {}'.format(elem[0], elem[1])

output:

Japan 1
India 2
China 2
USA 2

And if you want to sort by alphabet after sorting by count, you can change result to the following:

result = sorted(sorted([(x, l.count(x)) for x in ul]), key=lambda y: y[1])

output:

Japan 1
China 2
India 2
USA 2


问:
Difference between how Visual studio loads assemblies and Assembly.LoadFrom?
I have an assembly (2 actually) both are from SAP directory C:\Program Files (x86)\SAP\FrontEnd\SAPgui.

Visual Studio Add Reference - Works just fine.

Assembly.LoadFrom - Throws exception below.

Could not load file or assembly 'file:///C:\Program Files (x86)\SAP\FrontEnd\SAPgui\sapfewse.ocx' or one of its dependencies. The module was expected to contain an assembly manifest.

Why is it that I can add the reference to visual studio and use the dll that way no problem, but loading it via reflection doesn't work?

Is there a way to load the assemblies types at runtime?

答:
As Lucas pointed out in the comments, Assembly.LoadFrom only works on .NET assemblies and the assemblies I was trying to load were COM dlls.

What I ended up having to do was add them to a project which produced Interop versions of the dlls which I then added to the GAC so that the program we originally wanted to use it with could access it.

Thank you to everyone who posted in the comments that lead me to this solution.


问:
Why does C# handle command line args inconsistently?
In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.

Getting those same command line args via Environment.GetCommandLineArgs includes it.

Is there some good logical reason I'm missing for this apparent inconsistency?

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("args.Length = {0}", args.Length));

        foreach(string arg in args)
        {
            Console.WriteLine(string.Format("args = {0}", arg));
        }

        Console.WriteLine("");

        string[] Eargs = Environment.GetCommandLineArgs();
        Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
        foreach (string arg in Eargs)
        {
            Console.WriteLine(string.Format("Eargs = {0}", arg));
        }

    }
}
</code>```

Output:

```<code>C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa
args.Length = 3
args = xx
args = zz
args = aa
Eargs.Length = 4
Eargs = consoleapplication1
Eargs = xx
Eargs = zz
Eargs = aa
</code>```

答:
[status-by-design]  -- http://msdn.microsoft.com/en-us/library/acy3edy3(v=VS.100).aspx

Unlike C and C++, the name of the program is not treated as the first command-line argument.

ContentLicense: CC BY-SA 2.5

Body:
In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.

Getting those same command line args via Environment.GetCommandLineArgs includes it.

Is there some good logical reason I'm missing for this apparent inconsistency?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("args.Length = {0}", args.Length));

        foreach(string arg in args)
        {
            Console.WriteLine(string.Format("args = {0}", arg));
        }

        Console.WriteLine("");

        string[] Eargs = Environment.GetCommandLineArgs();
        Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
        foreach (string arg in Eargs)
        {
            Console.WriteLine(string.Format("Eargs = {0}", arg));
        }

    }
}

Output:

C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa
args.Length = 3
args = xx
args = zz
args = aa
Eargs.Length = 4
Eargs = consoleapplication1
Eargs = xx
Eargs = zz
Eargs = aa


问:
Javascript canvas change shape dynamically
I am trying to make a drawing I made in the canvas change shape dynamically based on variables I pass in. what I have is that if want to change the shape of the monster or make it bigger, I have to change a lot of values to make it happen, how do I make all my number so that when I change it at 1 place, the change happens everywhere.

Here is the code on code pen

here is the html code

```<code><!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Monster</title>
</head>
<body>
  <canvas id="canvas" width="900" height="800" style="light-grey; border: 1px solid black">
  Your browser does not support canvas
  </canvas>
 </body>
</html>
</code>```

here is the javascript code

```<code>window.onload = function(){

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = 0;
var height = 0;
var radius = 0;

var squareLength = 450;

ctx.save();
ctx.beginPath();
ctx.fillStyle = '#33b262';
//Translate to the center of the canvas
ctx.translate(x+ 450, y+ 350);
ctx.rotate(Math.PI /4);
ctx.translate(x+ (-(squareLength / 2)), y+ (- (squareLength / 2)));
ctx.fillRect(x + 0,y+ 0,  width + squareLength, height+
squareLength);
ctx.restore();
ctx.closePath();

// eye
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 75, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

// eye black filling
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 17, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

//mouth
ctx.beginPath();
ctx.restore();
ctx.translate(x+ 250,y+ 100);
ctx.rect(x + 100,y+ 300, width + 200,height+ 70);
ctx.fillStyle = 'black';
ctx.fill();
ctx.closePath();

//left tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 135,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//right tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 237,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//bottom tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 185,y+ 340, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//left leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 303, y+ 465);
ctx.lineTo(x + 335, y+ 433);
ctx.lineTo(x + 335, y+ 615);
ctx.lineTo(x + 303, y+ 615);
ctx.fill();
ctx.closePath();

//right leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 97, y+ 465);
ctx.lineTo(x + 65, y+ 433);
ctx.lineTo(x + 65, y+ 615);
ctx.lineTo(x + 97, y+ 615);
ctx.fill();
ctx.closePath();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 319, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 79, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();
};
</code>```

答:
You can use canvas.scale method for this kind of purposes
https://www.w3schools.com/tags/canvas_scale.asp
I wrap up my drawing code into a function and add a plus line at the beginning of it:

```

    function drawShape(scalewidth,scaleheight) {
        ctx.scale(scalewidth,scaleheight);
        ...
    }

```

Then call it with some values:

```

    drawShape(0.5, 0.5);

```

Body:
I am trying to make a drawing I made in the canvas change shape dynamically based on variables I pass in. what I have is that if want to change the shape of the monster or make it bigger, I have to change a lot of values to make it happen, how do I make all my number so that when I change it at 1 place, the change happens everywhere.

Here is the code on code pen

here is the html code

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Monster</title>

  <canvas id="canvas" width="900" height="800" style="light-grey; border: 1px solid black">
  Your browser does not support canvas
  </canvas>

here is the javascript code

window.onload = function(){

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = 0;
var height = 0;
var radius = 0;

var squareLength = 450;

ctx.save();
ctx.beginPath();
ctx.fillStyle = '#33b262';
//Translate to the center of the canvas
ctx.translate(x+ 450, y+ 350);
ctx.rotate(Math.PI /4);
ctx.translate(x+ (-(squareLength / 2)), y+ (- (squareLength / 2)));
ctx.fillRect(x + 0,y+ 0,  width + squareLength, height+
squareLength);
ctx.restore();
ctx.closePath();

// eye
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 75, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

// eye black filling
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 17, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

//mouth
ctx.beginPath();
ctx.restore();
ctx.translate(x+ 250,y+ 100);
ctx.rect(x + 100,y+ 300, width + 200,height+ 70);
ctx.fillStyle = 'black';
ctx.fill();
ctx.closePath();

//left tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 135,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//right tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 237,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//bottom tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 185,y+ 340, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//left leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 303, y+ 465);
ctx.lineTo(x + 335, y+ 433);
ctx.lineTo(x + 335, y+ 615);
ctx.lineTo(x + 303, y+ 615);
ctx.fill();
ctx.closePath();

//right leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 97, y+ 465);
ctx.lineTo(x + 65, y+ 433);
ctx.lineTo(x + 65, y+ 615);
ctx.lineTo(x + 97, y+ 615);
ctx.fill();
ctx.closePath();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 319, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 79, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();
};

Body:
You can use canvas.scale method for this kind of purposes
https://www.w3schools.com/tags/canvas_scale.asp
I wrap up my drawing code into a function and add a plus line at the beginning of it:

    function drawShape(scalewidth,scaleheight) {
        ctx.scale(scalewidth,scaleheight);
        ...
    }

Then call it with some values:

    drawShape(0.5, 0.5);


问:
How can I implement a step definition method for a line in feature file which tests for multiple values in a protractor-cucumber framework?
Feature file(In gherkins) line:
Then I should see "New Order,Old Order,Contact,City,Country,Account,Tier" text appearing in attributes column

Step Definition which I implemeted which doesn't seem to work:

```<code>this.Then(/^I should see "([^"]*)" text appearing in attributes column$/, function (arg1/*,callback*/) {
    varattributeNames = arg1.split(",");
    varattributesGroup = element.all(by.css('css-selector')).each((ele,index)=>{
        browser.wait(EC.presenceOf(ele)).then(()=>{
            expect(ele.getText()).to.eventually.equal(attributeNames[index]);
        });
        //if(index+1===attributeNames.length){
        //callback();
        //}
    });
});
</code>```

I am passing all these column attribute names to step definition method. I want it to wait for expect statements to finish fully. But instead it is returning as soon as the 'each' loop gets over and not waiting for all the expect statements to fully resolve.

Note: I have used "ignoreSynchronisation = true" in protractor-conf.js as the webpage I am testing is not fully angular.

答:
You can use map method for these scenarios-

```<code>this.Then(/^I should see "([^"]*)" text appearing in attributes column$/, function (arg1/*,callback*/) {

varattributeNames = arg1.split(",");

varattributesGroup = element.all(by.css('css-selector')).map((ele,index)=>{
    browser.wait(EC.presenceOf(ele)).then(()=>{
        return ele.getText().then(function(text) {
                return text;
              });
    });

     //varattributesGroup should have your texts in an array.
     //deep equal is used to compare objects/nested arrays in chai assertions

     expect(varattributesGroup).to.eventually.deep.equal(varattributeNames);
});
});
</code>```

Also cucumber.js supports promises no need of callbacks. Please have a look at this link.

Body:
Feature file(In gherkins) line:
Then I should see "New Order,Old Order,Contact,City,Country,Account,Tier" text appearing in attributes column

Step Definition which I implemeted which doesn't seem to work:

this.Then(/^I should see "([^"]*)" text appearing in attributes column$/, function (arg1/*,callback*/) {
    varattributeNames = arg1.split(",");
    varattributesGroup = element.all(by.css('css-selector')).each((ele,index)=>{
        browser.wait(EC.presenceOf(ele)).then(()=>{
            expect(ele.getText()).to.eventually.equal(attributeNames[index]);
        });
        //if(index+1===attributeNames.length){
        //callback();
        //}
    });
});

I am passing all these column attribute names to step definition method. I want it to wait for expect statements to finish fully. But instead it is returning as soon as the 'each' loop gets over and not waiting for all the expect statements to fully resolve.

Note: I have used "ignoreSynchronisation = true" in protractor-conf.js as the webpage I am testing is not fully angular.

Body:
You can use map method for these scenarios-

this.Then(/^I should see "([^"]*)" text appearing in attributes column$/, function (arg1/*,callback*/) {

varattributeNames = arg1.split(",");

varattributesGroup = element.all(by.css('css-selector')).map((ele,index)=>{
    browser.wait(EC.presenceOf(ele)).then(()=>{
        return ele.getText().then(function(text) {
                return text;
              });
    });

     //varattributesGroup should have your texts in an array.
     //deep equal is used to compare objects/nested arrays in chai assertions

     expect(varattributesGroup).to.eventually.deep.equal(varattributeNames);
});
});

Also cucumber.js supports promises no need of callbacks. Please have a look at this link.


问:
I can't retrieve just Unread Messages using TIdIMAP4
I'm trying to retrieve all my unread email messages using IMAP, and I seem to connect and locate fine those unread message (I can see, for example, that SearchResult returns 3 items corresponding to my 3 currently unread messages), but the IMAP.Retrieve call always returns false, not retrieving any of them.

Do you see what must be lacking on my code ?.

```<code>procedure TForm1.btnUnreadMessagesClick(Sender: TObject);
var i: integer;
    SearchInfo: array of TIdIMAP4SearchRec;
    MSG: TIdMessage;
begin
  Memo1.Lines.Clear;

  IMAP.Host := 'outlook.office365.com';
  IMAP.Port := 993;
  IMAP.Username := 'xxxxx@acme.com';
  IMAP.Password := 'xxxxx';

  SSL.Host := IMAP.Host;
  SSL.Port := IMAP.Port;
  SSL.Destination := SSL.Host + ':' + IntToStr(SSL.Port);
  SSL.MaxLineLength := MaxInt;

  IMAP.IOHandler := SSL;
  IMAP.UseTLS := utUseImplicitTLS;

  IMAP.Connect;
  IMAP.SelectMailBox('INBOX');

  SetLength(SearchInfo, 1);
  SearchInfo[0].SearchKey := skUnseen;
  IMAP.UIDSearchMailBox(SearchInfo);

  for i := 0 to High(IMAP.MailBox.SearchResult) do begin
    MSG := TIdMessage.Create(nil);
    try
      if IMAP.Retrieve(IMAP.MailBox.SearchResult[i], MSG) then begin
        // Here is the problem, I never enter this section
        Memo1.Lines.Add(MSG.From.Text);
      end;
    finally
      MSG.Free;
    end;
  end;
  IMAP.Disconnect;
end;
</code>```

Thanks for your help.

答:
When using SearchMailBox(), the SearchResult array contains sequence numbers.

When using UIDSearchMailBox(), the SearchResult array contains UIDs.

Retrieve() expects a sequence number.  Since you have UIDs instead, use UIDRetrieve(), eg:

```<code>IMAP.UIDRetrieve(IntToStr(IMAP.MailBox.SearchResult[i]), MSG)
</code>```

Body:
I'm trying to retrieve all my unread email messages using IMAP, and I seem to connect and locate fine those unread message (I can see, for example, that SearchResult returns 3 items corresponding to my 3 currently unread messages), but the IMAP.Retrieve call always returns false, not retrieving any of them.

Do you see what must be lacking on my code ?.

procedure TForm1.btnUnreadMessagesClick(Sender: TObject);
var i: integer;
    SearchInfo: array of TIdIMAP4SearchRec;
    MSG: TIdMessage;
begin
  Memo1.Lines.Clear;

  IMAP.Host := 'outlook.office365.com';
  IMAP.Port := 993;
  IMAP.Username := 'xxxxx@acme.com';
  IMAP.Password := 'xxxxx';

  SSL.Host := IMAP.Host;
  SSL.Port := IMAP.Port;
  SSL.Destination := SSL.Host + ':' + IntToStr(SSL.Port);
  SSL.MaxLineLength := MaxInt;

  IMAP.IOHandler := SSL;
  IMAP.UseTLS := utUseImplicitTLS;

  IMAP.Connect;
  IMAP.SelectMailBox('INBOX');

  SetLength(SearchInfo, 1);
  SearchInfo[0].SearchKey := skUnseen;
  IMAP.UIDSearchMailBox(SearchInfo);

  for i := 0 to High(IMAP.MailBox.SearchResult) do begin
    MSG := TIdMessage.Create(nil);
    try
      if IMAP.Retrieve(IMAP.MailBox.SearchResult[i], MSG) then begin
        // Here is the problem, I never enter this section
        Memo1.Lines.Add(MSG.From.Text);
      end;
    finally
      MSG.Free;
    end;
  end;
  IMAP.Disconnect;
end;

Thanks for your help.

Body:
When using SearchMailBox(), the SearchResult array contains sequence numbers.

When using UIDSearchMailBox(), the SearchResult array contains UIDs.

Retrieve() expects a sequence number.  Since you have UIDs instead, use UIDRetrieve(), eg:

IMAP.UIDRetrieve(IntToStr(IMAP.MailBox.SearchResult[i]), MSG)


问:
How to create a new contact via Google Contacts API?
I am creating a new contact as described in Google Contacts API . Specifically, I do a POST to https://www.google.com/m8/feeds/contacts/default/full. The content that I POST is taken directly from Google Contacts API document and also copied below.

The problem is Google puts the newly created contact under "Other Contacts". That is if I open https://contacts.google.com/ in the browser, the new contact is not shown. I have to go to the sidebar in the left, click "More" and then click "Other Contacts".

How can I create a contact programmatically, so that I can see it directly in https://contacts.google.com/ without going to "Other Contacts"?

```<code><atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:gd="http://schemas.google.com/g/2005">
  <atom:category scheme="http://schemas.google.com/g/2005#kind"
    term="http://schemas.google.com/contact/2008#contact"/>
  <gd:name>
     <gd:givenName>Elizabeth</gd:givenName>
     <gd:familyName>Bennet</gd:familyName>
     <gd:fullName>Elizabeth Bennet</gd:fullName>
  </gd:name>
  <atom:content type="text">Notes</atom:content>
  <gd:email rel="http://schemas.google.com/g/2005#work"
    primary="true"
    address="liz@gmail.com" displayName="E. Bennet"/>
  <gd:email rel="http://schemas.google.com/g/2005#home"
    address="liz@example.org"/>
  <gd:phoneNumber rel="http://schemas.google.com/g/2005#work"
    primary="true">
    (206)555-1212
  </gd:phoneNumber>
  <gd:phoneNumber rel="http://schemas.google.com/g/2005#home">
    (206)555-1213
  </gd:phoneNumber>
  <gd:im address="liz@gmail.com"
    protocol="http://schemas.google.com/g/2005#GOOGLE_TALK"
    primary="true"
    rel="http://schemas.google.com/g/2005#home"/>
  <gd:structuredPostalAddress
      rel="http://schemas.google.com/g/2005#work"
      primary="true">
    <gd:city>Mountain View</gd:city>
    <gd:street>1600 Amphitheatre Pkwy</gd:street>
    <gd:region>CA</gd:region>
    <gd:postcode>94043</gd:postcode>
    <gd:country>United States</gd:country>
    <gd:formattedAddress>
      1600 Amphitheatre Pkwy Mountain View
    </gd:formattedAddress>
  </gd:structuredPostalAddress>
</atom:entry>
</code>```

答:
First, I recommend making sure that you sent an authorized request with the header GData-Version: 3.0 included.

```<code>https://www.google.com/m8/feeds/groups/default/full
</code>```

A successful request will return a list of groups, 'My Contacts' included.

Using the groupId of 'My Contacts', you can now change the Group Membership of that contact.

Check this google forum for more info.

Body:
I am creating a new contact as described in Google Contacts API . Specifically, I do a POST to https://www.google.com/m8/feeds/contacts/default/full. The content that I POST is taken directly from Google Contacts API document and also copied below.

The problem is Google puts the newly created contact under "Other Contacts". That is if I open https://contacts.google.com/ in the browser, the new contact is not shown. I have to go to the sidebar in the left, click "More" and then click "Other Contacts".

How can I create a contact programmatically, so that I can see it directly in https://contacts.google.com/ without going to "Other Contacts"?

<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:gd="http://schemas.google.com/g/2005">
  <atom:category scheme="http://schemas.google.com/g/2005#kind"
    term="http://schemas.google.com/contact/2008#contact"/>
  <gd:name>
     <gd:givenName>Elizabeth</gd:givenName>
     <gd:familyName>Bennet</gd:familyName>
     <gd:fullName>Elizabeth Bennet</gd:fullName>
  </gd:name>
  <atom:content type="text">Notes</atom:content>
  <gd:email rel="http://schemas.google.com/g/2005#work"
    primary="true"
    address="liz@gmail.com" displayName="E. Bennet"/>
  <gd:email rel="http://schemas.google.com/g/2005#home"
    address="liz@example.org"/>
  <gd:phoneNumber rel="http://schemas.google.com/g/2005#work"
    primary="true">
    (206)555-1212
  </gd:phoneNumber>
  <gd:phoneNumber rel="http://schemas.google.com/g/2005#home">
    (206)555-1213
  </gd:phoneNumber>
  <gd:im address="liz@gmail.com"
    protocol="http://schemas.google.com/g/2005#GOOGLE_TALK"
    primary="true"
    rel="http://schemas.google.com/g/2005#home"/>
  <gd:structuredPostalAddress
      rel="http://schemas.google.com/g/2005#work"
      primary="true">
    <gd:city>Mountain View</gd:city>
    <gd:street>1600 Amphitheatre Pkwy</gd:street>
    <gd:region>CA</gd:region>
    <gd:postcode>94043</gd:postcode>
    <gd:country>United States</gd:country>
    <gd:formattedAddress>
      1600 Amphitheatre Pkwy Mountain View
    </gd:formattedAddress>
  </gd:structuredPostalAddress>
</atom:entry>

Body:
First, I recommend making sure that you sent an authorized request with the header GData-Version: 3.0 included.

https://www.google.com/m8/feeds/groups/default/full

A successful request will return a list of groups, 'My Contacts' included.

Using the groupId of 'My Contacts', you can now change the Group Membership of that contact.

Check this google forum for more info.


问:
running multiple sudo'd commands concurrently
I've once again been bitten by out-of-date caches. I finally got tired of looking up all the cache rebuilding commands and decided to write myself a short zsh function to do all the ones I know about (and as I discover more they can go in here). Here's what I've got at the moment:

```<code>recache() {
    sudo true
    sudo updatedb &
    local updatedbpid=$!
    sudo ldconfig &
    local ldconfigpid=$!
    rehash
    wait $updatedbpid $ldconfigpid
}
</code>```

The first sudo true is intended to make sure sudo has a recent timestamp, so that the following background processes don't sit suspended on input waiting for me to type my password. I don't use sudo -b because I want to wait until the caches are up to date before continuing my work.

Most of the time, this works great; but about one time in three or so, I get endless copies of the following text:

```<code>[2]  + suspended (tty output)  sudo updatedb
</code>```

Why? What can I do to fix it?

答:
So I never did figure out why this was happening. My best guess is there's some resource that sudo is trying to lock, and the two invocations of sudo get in a race for it. In any case, I've been using the following modified recache function for some time without trouble. The main difference is that there is only a single backgrounded sudo, and it runs both updatedb and ldconfig in parallel, rather than one backgrounded sudo per process.

```<code>recache() {
    sudo true
    sudo zsh -c 'updatedb & ldconfig & wait' &
    local pid=$!
    rehash
    wait $pid
}
</code>```

Body:
I've once again been bitten by out-of-date caches. I finally got tired of looking up all the cache rebuilding commands and decided to write myself a short zsh function to do all the ones I know about (and as I discover more they can go in here). Here's what I've got at the moment:

recache() {
    sudo true
    sudo updatedb &
    local updatedbpid=$!
    sudo ldconfig &
    local ldconfigpid=$!
    rehash
    wait $updatedbpid $ldconfigpid
}

The first sudo true is intended to make sure sudo has a recent timestamp, so that the following background processes don't sit suspended on input waiting for me to type my password. I don't use sudo -b because I want to wait until the caches are up to date before continuing my work.

Most of the time, this works great; but about one time in three or so, I get endless copies of the following text:

[2]  + suspended (tty output)  sudo updatedb

Why? What can I do to fix it?

Body:
So I never did figure out why this was happening. My best guess is there's some resource that sudo is trying to lock, and the two invocations of sudo get in a race for it. In any case, I've been using the following modified recache function for some time without trouble. The main difference is that there is only a single backgrounded sudo, and it runs both updatedb and ldconfig in parallel, rather than one backgrounded sudo per process.

recache() {
    sudo true
    sudo zsh -c 'updatedb & ldconfig & wait' &
    local pid=$!
    rehash
    wait $pid
}


问:
Laravel 5.4 null csrf_token() when posting to route
I'm sending an ajax post request, and with Laravel it seems that is done by creating a post route for it. I've set it up so a csrf token is put in the header automaticaly for every ajax request using ajaxSetup. I'm attempting to then catch that header on the backend and verify the tokens match.

In my web routes (which automatically use the web middleware), this returns as expected:

```<code>Route::get('/test', function() {
    return csrf_token();
});
</code>```

However, when I post to a route via AJAX, like either of the below ways:

Attempt 1:

```<code>Route::post('/test', 'AjaxController@test');
</code>```

In the AjaxController construct, followed by an alert in the view:

```<code>var_dump(csrf_token().',hi'); die;
</code>```

Response: ',hi' (csrf_token was null).

Attempt 2:

```<code>Route::post('/test', ['test' => csrf_token().',hi', 'uses' => 'AjaxController@test']);

$test = $request->route()->getAction()['test'];
var_dump($test); die;
</code>```

Response: ',hi' (csrf_token was null).

What I seem to be running into is, with get requests csrf_token() is populated, on my post request, it is not.

Any ideas?

答:
Finally figured this out.

CSRF can indeed be checked on an ajax post request. I wanted to make sure someone on their own site isn't hitting my ajax endpoint with any success of doing anything, especially for another user.

However, I ran into a Laravel order of operations issue, with the way Laravel sets up the session. I was trying to call a validation method (within in the same class) in the constructor, where I validated for CSRF and verified the requesting user all in one place. I wanted to do this so that any time someone hits this class, I didn't have to call the verification in each public method in the class, I'd only have to call it once.

However, csrf_token(), and the request session in general, is not available to me yet in my construct. It is, however, available to me in the method within the controller class that is called in the route.

For example, given the following route:

```<code>Route::post('/test', 'AjaxController@test');
</code>```

If I injected Request into the construct and then tried to reference anything in the session (in the construct), or get the value of csrf_token(), it will throw an error, because Laravel hasn't set that stuff up yet. But if I reference either of those things in the test method, it'll be there and available just fine.

A bit of a weird Laravel order of operations issue.

Body:
I'm sending an ajax post request, and with Laravel it seems that is done by creating a post route for it. I've set it up so a csrf token is put in the header automaticaly for every ajax request using ajaxSetup. I'm attempting to then catch that header on the backend and verify the tokens match.

In my web routes (which automatically use the web middleware), this returns as expected:

Route::get('/test', function() {
    return csrf_token();
});

However, when I post to a route via AJAX, like either of the below ways:

Attempt 1:

Route::post('/test', 'AjaxController@test');

In the AjaxController construct, followed by an alert in the view:

var_dump(csrf_token().',hi'); die;

Response: ',hi' (csrf_token was null).

Attempt 2:

Route::post('/test', ['test' => csrf_token().',hi', 'uses' => 'AjaxController@test']);

$test = $request->route()->getAction()['test'];
var_dump($test); die;

Response: ',hi' (csrf_token was null).

What I seem to be running into is, with get requests csrf_token() is populated, on my post request, it is not.

Any ideas?

Body:
Finally figured this out.

CSRF can indeed be checked on an ajax post request. I wanted to make sure someone on their own site isn't hitting my ajax endpoint with any success of doing anything, especially for another user.

However, I ran into a Laravel order of operations issue, with the way Laravel sets up the session. I was trying to call a validation method (within in the same class) in the constructor, where I validated for CSRF and verified the requesting user all in one place. I wanted to do this so that any time someone hits this class, I didn't have to call the verification in each public method in the class, I'd only have to call it once.

However, csrf_token(), and the request session in general, is not available to me yet in my construct. It is, however, available to me in the method within the controller class that is called in the route.

For example, given the following route:

Route::post('/test', 'AjaxController@test');

If I injected Request into the construct and then tried to reference anything in the session (in the construct), or get the value of csrf_token(), it will throw an error, because Laravel hasn't set that stuff up yet. But if I reference either of those things in the test method, it'll be there and available just fine.

A bit of a weird Laravel order of operations issue.


问:
Android SDK installation doesn't find JDK
I'm trying to install the Android SDK on my Windows 7 x64 System.

jdk-6u23-windows-x64.exe is installed, but the Android SDK setup refuses to proceed because it doesn't find the JDK installation.

Is this a known issue? And is there a solution?

答: I downloaded the .zip archive instead and ran SDK Manager.exe, and it worked like a charm. You had the same issue with the .exe otherwise.

ContentLicense: CC BY-SA 4.0


问:
""Java"" is not recognized as an internal or external command, program or batch file. in Kotlin
I'm starting with kotlin on windows, I'm following the steps of
Working with the Command Line Compiler

And I get the following error after trying to compile(and add the bin directory in the path of my system):

Comand compile:

```<code>$ kotlinc hello.kt -include-runtime -d hello.jar
</code>```

Error:

```<code>""Java"" is not recognized as an internal or external command, program or batch file
</code>```

in my windows CMD.

I need to have java installed on my pc. To start with kotlin?

答: Install Java 8 JDK (not JRE) on your development machine as it is a prerequisite for running the Kotlin compiler, and also for any Java or Kotlin application.  You can use either the Oracle JDK for most platforms or OpenJDK for Linux platforms.</p>

Body:
I'm starting with kotlin on windows, I'm following the steps of
Working with the Command Line Compiler

And I get the following error after trying to compile(and add the bin directory in the path of my system):

Comand compile:

$ kotlinc hello.kt -include-runtime -d hello.jar

Error:

""Java"" is not recognized as an internal or external command, program or batch file

in my windows CMD.

I need to have java installed on my pc. To start with kotlin?


问:
Ruby assign do-block to array
I'm a newbie Rails learner. I want to try out some ruby language features, e.g. shorten the following method:

```<code>def update(params)
  attrs = []
  params[:attributes].each do |attr_hash|
    attr = Attribute.new attr_hash
    attrs.push attr
  end
  ...
end
</code>```

like:

```<code>def update(params)
   attrs = fill_attrs_from_params params
   ...
end

def fill_attrs_from_params(params)
  attrs = params[:attributes].each do |attr_hash|
    Attribute.new(attr_hash)
  end
end
</code>```

The second doesn't work as the first one however. What do I miss here?

Edit: I couldn't really decide how the second one worked, the application went buggy, and I'm a beginner with rails debugging as well.

答:
That's what .map is for

```<code>  attrs = params[:attributes].map do |attr_hash|
    Attribute.new(attr_hash)
  end
</code>```

.each is very versatile. With a bit of helper code, you can make it do anything. And that is its weakness. When you think to use .each, there's almost always a method on Enumerable that does the job better with less code (of course, except the obvious use case: performing an action on each element of a collection. Here you use .each.)

Title: Ruby assign do-block to array

Body:
I'm a newbie Rails learner. I want to try out some ruby language features, e.g. shorten the following method:

def update(params)
  attrs = []
  params[:attributes].each do |attr_hash|
    attr = Attribute.new attr_hash
    attrs.push attr
  end
  ...
end

like:

def update(params)
   attrs = fill_attrs_from_params params
   ...
end

def fill_attrs_from_params(params)
  attrs = params[:attributes].each do |attr_hash|
    Attribute.new(attr_hash)
  end
end

The second doesn't work as the first one however. What do I miss here?

Edit: I couldn't really decide how the second one worked, the application went buggy, and I'm a beginner with rails debugging as well.

Body:
That's what .map is for

  attrs = params[:attributes].map do |attr_hash|
    Attribute.new(attr_hash)
  end

.each is very versatile. With a bit of helper code, you can make it do anything. And that is its weakness. When you think to use .each, there's almost always a method on Enumerable that does the job better with less code (of course, except the obvious use case: performing an action on each element of a collection. Here you use .each.)


问:
Checkmark pushes cell content in UITableVIewCell
I'm building a filter view controller.
The top section is a selectable list that the selection is being marked with checkmark.

My problem is that the checkmark pushes my textlabel to the left.
The UITextLabel is aligned right to left.

How do i disable the checkmark from pushing the textlabel so it would work like the ringtone selection viewController in iphone (for example)

答:
You have to handle manually the checkmark adding an UIImage at the left of the UITableViewCell and not using accessoryType because it appears only at the right: https://developer.apple.com/documentation/uikit/uitableviewcell/1623228-accessorytype

But if you want to still use accessoryType you can give more space at the right of the UILabel.


问:
Does JavaScript have a built in stringbuilder class?
I see a few code project solutions.

But is there a regular implementation in JavaScript?

答:
In C# you can do something like

```<code> String.Format("hello {0}, your age is {1}.",  "John",  29)
</code>```

In JavaScript you could do something like

```<code> var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);
</code>```

Body:
In C# you can do something like

 String.Format("hello {0}, your age is {1}.",  "John",  29)

In JavaScript you could do something like

 var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);


问:
Kubernetes set-up on ubuntu on Google compute
Can any one help me understanding this error I am getting while trying to set-up kubernetes. I am trying to follow this url and run the command

```<code>$ curl -sS https://get.k8s.io | bash
ERROR: (gcloud.components.update) The component manager is disabled for this installation
</code>```

I am running the command on google compute Ubuntu machine. Appreciate any help

Adding the complete error ( Ubunut 15.4), after full blown google sdk installation
.............
Unpacking kubernetes release v1.0.3
Creating a kubernetes on gce...
Starting cluster using provider: gce
... calling verify-prereqs
You cannot perform this action because the component manager has been
disabled for this installation.  If you would like get the latest
version of the Google Cloud SDK, please see our main download page at:

https://developers.google.com/cloud/sdk/

ERROR: (gcloud.components.update) The component manager is disabled for this installation
You cannot perform this action because the component manager has been
disabled for this installation.  If you would like get the latest
version of the Google Cloud SDK, please see our main download page at:

https://developers.google.com/cloud/sdk/

ERROR: (gcloud.components.update) The component manager is disabled for this installation
You cannot perform this action because the component manager has been
disabled for this installation.  If you would like get the latest
version of the Google Cloud SDK, please see our main download page at:

https://developers.google.com/cloud/sdk/

ERROR: (gcloud.components.update) The component manager is disabled for this installation
... calling kube-up

答:
The latest Google SDK package manager installs:

https://cloud.google.com/sdk/downloads#apt-get

https://cloud.google.com/sdk/downloads#yum

now support installing kubectl "directly" from the repo:

sudo apt install kubectl
sudo yum install kubectl

Body:
Can any one help me understanding this error I am getting while trying to set-up kubernetes. I am trying to follow this url and run the command

$ curl -sS https://get.k8s.io | bash
ERROR: (gcloud.components.update) The component manager is disabled for this installation

I am running the command on google compute Ubuntu machine. Appreciate any help

Adding the complete error ( Ubunut 15.4), after full blown google sdk installation
.............
Unpacking kubernetes release v1.0.3
Creating a kubernetes on gce...
Starting cluster using provider: gce
... calling verify-prereqs
You cannot perform this action because the component manager has been
disabled for this installation.  If you would like get the latest
version of the Google Cloud SDK, please see our main download page at:

https://developers.google.com/cloud/sdk/

ERROR: (gcloud.components.update) The component manager is disabled for this installation
You cannot perform this action because the component manager has been
disabled for this installation.  If you would like get the latest
version of the Google Cloud SDK, please see our main download page at:

https://developers.google.com/cloud/sdk/

ERROR: (gcloud.components.update) The component manager is disabled for this installation
You cannot perform this action because the component manager has been
disabled for this installation.  If you would like get the latest
version of the Google Cloud SDK, please see our main download page at:

https://developers.google.com/cloud/sdk/

ERROR: (gcloud.components.update) The component manager is disabled for this installation
... calling kube-up


问:
PyGame: Load tile image information just before blitting?
My project is a large map that can be panned around containing "info spots" that can be clicked. For now I use four large images, each spans 5000x5000 pixels (so total map size is 20'000x20'000 pixel). On my AMD Phenom 9950 Quad-Core with 8GB RAM and an NVIDIA GeForce 610 this takes a certain while to load while it's quite fast afterwards when panning the image. I tried tiling it up but there's no visible enhancement in loading speed as the image still has to be loaded completely before it's separated into tiles.

The only way to have some real improvement on speed and memory usage would be, to only load those parts of the map image that are actually shown.
Does PyGame offer any way of doing so? I'm thinking of a "theoretical" tile map which contains the needed x and y values of each tile (I group them a little, less to compute each frame) and a theoretical image information (like: which image and which position therein). Only when a tile comes near the visible part of the screen, its image information is loaded, otherwise it remains a number and string value.

Would this make any sense? Is there any way to achieve this?

答:
After reading @lukevp 's reply, I was interested and tried this:

http://imgur.com/Q1N2UtU

Go get this image and create a folder named 'test_data'. Now place this image, code outside of test_data folder and run. The output would be cropped figures named as per their order (It's a bit off on the edges as the image is 1920 * 1080). You can try it with your custom size tho. Also note that I am on ubuntu so take care to appropriate paths.

OUTPUT: http://imgur.com/2v4ucGI Final link: http://imgur.com/a/GHc9l

```<code>import pygame, os
pygame.init()

original_image = pygame.image.load('test_pic.jpg')

x_max = 1920
y_max = 1080

current_x = 0
current_y = 0

count = 1

begin_surf = pygame.Surface((x_max,y_max), flags = pygame.SRCALPHA)
begin_surf.blit(original_image,(0,0))

cropped_surf =  pygame.Surface((100,100),flags=pygame.SRCALPHA)

while current_y + 100 < y_max:

    while current_x + 100 < x_max:
    cropped_surf.blit(begin_surf, (0,0), (current_x, current_y,100,100))
    pygame.image.save(cropped_surf, os.path.join("test_data", str(count) + '.jpg'))

    current_x += 100

    count += 1

    current_x = 0

    current_y += 100
</code>```

Would now actually be working to load those images and span them as he said.

Body:
After reading @lukevp 's reply, I was interested and tried this:

http://imgur.com/Q1N2UtU

Go get this image and create a folder named 'test_data'. Now place this image, code outside of test_data folder and run. The output would be cropped figures named as per their order (It's a bit off on the edges as the image is 1920 * 1080). You can try it with your custom size tho. Also note that I am on ubuntu so take care to appropriate paths.

OUTPUT: http://imgur.com/2v4ucGI Final link: http://imgur.com/a/GHc9l

import pygame, os
pygame.init()

original_image = pygame.image.load('test_pic.jpg')

x_max = 1920
y_max = 1080

current_x = 0
current_y = 0

count = 1

begin_surf = pygame.Surface((x_max,y_max), flags = pygame.SRCALPHA)
begin_surf.blit(original_image,(0,0))

cropped_surf =  pygame.Surface((100,100),flags=pygame.SRCALPHA)

while current_y + 100 < y_max:

    while current_x + 100 < x_max:
    cropped_surf.blit(begin_surf, (0,0), (current_x, current_y,100,100))
    pygame.image.save(cropped_surf, os.path.join("test_data", str(count) + '.jpg'))

    current_x += 100

    count += 1

    current_x = 0

    current_y += 100

Would now actually be working to load those images and span them as he said.


问:
Regex that gets me string, given beginning and end
I want to build a function with 3 parameters:

```<code>var function = searchMyRegex(begin_marker, end_marker, text) { ... }
</code>```

I need a RegExp that will give me certain string, given the beginning and end, but it will me the shortest version, meaning that neither the beginning nor the end will be in between the 2 markers

For instance

```<code>var text = "Lorem ipsum ipsum sit amet amet adipisicing elit"
</code>```

If BEGIN is ipsum and END is amet, I want to get in return ipsum sit amet, not ipsum ipsum sit amet amet

The way I tried it to solve myself was like this:

```<code>new RegExp(begin_marker + "[^" + end_marker + "]*\ " + end_marker);
</code>```

But this does not seem to work, and Im not sure why.

答:
You can use this kind of construct:

```<code>ipsum(?:(?!ipsum).)*?amet
</code>```

(?:(?!ipsum).)*? checks if each position after ipsum and before amet isn't the start of an other ipsum.

With the non-greedy quantifier *?, the match stop at the first amet occurrence.

Note that the previous technique needs to perform a test with a lookahead for each position. If you deal with a long string, you can also play with character classes to be more efficient:

```<code>ipsum[^ia]*(?:i(?!psum)[^ia]*|a(?!met)[^ia]*)*amet
</code>```

However it's less easy to build this pattern dynamically.

When the markers are words (i.e. that start and end with word characters), you can limit the number of positions tested with the lookahead like this:

```<code>\bipsum\W+(?:(?!ipsum\b)\w+\W+)*?amet\b
</code>```

The lookahead is only tested at the start of words. This one can be easily build dynamically.

Body:
I want to build a function with 3 parameters:

var function = searchMyRegex(begin_marker, end_marker, text) { ... }

I need a RegExp that will give me certain string, given the beginning and end, but it will me the shortest version, meaning that neither the beginning nor the end will be in between the 2 markers

For instance

var text = "Lorem ipsum ipsum sit amet amet adipisicing elit"

If BEGIN is ipsum and END is amet, I want to get in return ipsum sit amet, not ipsum ipsum sit amet amet

The way I tried it to solve myself was like this:

new RegExp(begin_marker + "[^" + end_marker + "]*\ " + end_marker);

But this does not seem to work, and Im not sure why.

Body:
You can use this kind of construct:

ipsum(?:(?!ipsum).)*?amet

(?:(?!ipsum).)*? checks if each position after ipsum and before amet isn't the start of an other ipsum.

With the non-greedy quantifier *?, the match stop at the first amet occurrence.

Note that the previous technique needs to perform a test with a lookahead for each position. If you deal with a long string, you can also play with character classes to be more efficient:

ipsum[^ia]*(?:i(?!psum)[^ia]*|a(?!met)[^ia]*)*amet

However it's less easy to build this pattern dynamically.

When the markers are words (i.e. that start and end with word characters), you can limit the number of positions tested with the lookahead like this:

\bipsum\W+(?:(?!ipsum\b)\w+\W+)*?amet\b

The lookahead is only tested at the start of words. This one can be easily build dynamically.


问:
Cannot read property 'sync' of undefined
I am following a tutorial on how to set up a basic mvc in Nodejs using the hapi server and a few other packages.

Tutorial: https://www.sitepoint.com/node-js-mvc-application/

Git for my project: https://github.com/christoph88/node-js-mvc-tut/

I have an error when I try to launch the server:

```<code>~/Projects/node-js-mvc-tut$ node server.js
/home/christoph/Projects/node-js-mvc-tut/server.js:33
Models.sequelize.sync().then(() => {
^
TypeError: Cannot read property 'sync' of undefined
at Object.<anonymous> (/home/christoph/Projects/node-js-mvc-tut/server.js:33:17)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
</code>```

Model is defined within the requirements. I do not understand why sync is undefined. Sequelise is required within the lib/index.js file.

```<code>'use strict';

const Hapi = require('hapi');
const Hoek = require('hoek');
const Path = require('path');
const Settings = require('./settings');
const Routes = require('./lib/routes');
const Models = require('./lib/models/');

const server = new Hapi.Server();

server.connection({ port: Settings.port });

server.register([
    require('vision'),
    require('inert')
], (err) => {
  Hoek.assert(!err, err);

  server.views({
    engines: { pug: require('pug') },
    path: Path.join(__dirname, 'lib/views'),
    compileOptions: {
      pretty: false
    },
    isCached: Settings.env === 'production'
  });

  // Add routes
  server.route(Routes);
});

Models.sequelize.sync().then(() => {
  server.start((err) => {
    Hoek.assert(!err, err);
    console.log(`Server running at: ${server.info.uri}`);
  });
});
</code>```

Can somebody help me with this? Would be great to get this running so I can try to adapt it to my needs.

答:
I have got it working by moving my index.js file to the models folder.

This file has the necessairy scripts that dispatches sequelise in the model thus fixing the problem.

Body:
I am following a tutorial on how to set up a basic mvc in Nodejs using the hapi server and a few other packages.

Tutorial: https://www.sitepoint.com/node-js-mvc-application/

Git for my project: https://github.com/christoph88/node-js-mvc-tut/

I have an error when I try to launch the server:

~/Projects/node-js-mvc-tut$ node server.js
/home/christoph/Projects/node-js-mvc-tut/server.js:33
Models.sequelize.sync().then(() => {
^
TypeError: Cannot read property 'sync' of undefined
at Object.<anonymous> (/home/christoph/Projects/node-js-mvc-tut/server.js:33:17)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3

Model is defined within the requirements. I do not understand why sync is undefined. Sequelise is required within the lib/index.js file.

'use strict';

const Hapi = require('hapi');
const Hoek = require('hoek');
const Path = require('path');
const Settings = require('./settings');
const Routes = require('./lib/routes');
const Models = require('./lib/models/');

const server = new Hapi.Server();

server.connection({ port: Settings.port });

server.register([
    require('vision'),
    require('inert')
], (err) => {
  Hoek.assert(!err, err);

  server.views({
    engines: { pug: require('pug') },
    path: Path.join(__dirname, 'lib/views'),
    compileOptions: {
      pretty: false
    },
    isCached: Settings.env === 'production'
  });

  // Add routes
  server.route(Routes);
});

Models.sequelize.sync().then(() => {
  server.start((err) => {
    Hoek.assert(!err, err);
    console.log(`Server running at: ${server.info.uri}`);
  });
});

Can somebody help me with this? Would be great to get this running so I can try to adapt it to my needs.


问:
Java Regex to extract any characters between two tokens
I am trying to parse the following text

```<code>### __Description of the report__
Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh,
consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,
sed eleifend
* amet, sollicitudin sit egestas
* quis eros nulla. Sed donec

### __Notable filters__
* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel
* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices
</code>```

I want to capture all text between the ### __Description of the report__ and ### __Notable filters__ which could be numbers letters, or any combination of special characters.

I thought using ### __Description of the report__(.*?)### __Notable filters__ would work, but it doesn't return any results. How can i extract the text between the two headings?

答:
Trying out your regex seems to return nothing because of your choice of expression:

...report__(.*?)### __N...

The . character matches non-newline characters, so either you need to take out newlines in your string before parsing, or change your expression to fit newlines in your input

@CoffeehouseCoder's answer suggests using Pattern.DOTALL, which will fix this issue by allowing . to match newlines

Alternatively, you can update your regex to match either a character or a newline like so:

...report__((.|\n)*?)###...

Body:
I am trying to parse the following text

### __Description of the report__
Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh,
consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,
sed eleifend
* amet, sollicitudin sit egestas
* quis eros nulla. Sed donec

### __Notable filters__
* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel
* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices

I want to capture all text between the ### __Description of the report__ and ### __Notable filters__ which could be numbers letters, or any combination of special characters.

I thought using ### __Description of the report__(.*?)### __Notable filters__ would work, but it doesn't return any results. How can i extract the text between the two headings?


问:
Pushing old items from storage into array with new items and than saving all items to storage
I have an app that is like a shopping cart. Users search for a product and can add it to their cart. After adding it they can checkout or go back and add more items.

The problem is that when a new item is added, the old items are taken and put into an array of objects. However the old items also remain as objects An example

```<code>Object1
Object2
Array[Object1, Object2]
Object3

[Object, Object, Array(2), Object]
</code>```

If I add another item it will become

```<code>[Object1, Object,2 Array(2), Object3, Array(4), Object4]
</code>```

What am I doing wrong?

dataStorage.ts

```<code>temp = [];
temp2 = [];

// How data is saved
save(data): Promise<any> {
  return this.getData().then((products: any[]) => {
    if (products) {
      //this.temp = products;
      this.temp.push(products, data);
      console.log(this.temp);
      return this.storage.set('products', this.temp);
    }
    return this.storage.set('products', data);
  });
}
</code>```

// How data is returned

```<code>getData() {
  return this.storage.get('products');
}
</code>```

component.ts

```<code>// they click on an add button that calls this
saveItem() {

let newItem = {
  prodName: this.prodName,
  prodDesc: this.prodDesc
};

this.dataService.save(newItem).then(()=>{
  this.navCtrl.pop(SearchProducts);
});
}
</code>```

答:
Variable products is array in case storage had it, so push array to temp array will be array in array , not concat.

```<code>temp = [];
temp2 = [];

// How data is saved
save(data): Promise<any> {
  return this.getData().then((products: any[]) => {
    if (products) {
      products.push(data);
      return this.storage.set('products', products);
    }
    return this.storage.set('products', [data]);
  });
}
</code>```

Body:
I have an app that is like a shopping cart. Users search for a product and can add it to their cart. After adding it they can checkout or go back and add more items.

The problem is that when a new item is added, the old items are taken and put into an array of objects. However the old items also remain as objects An example

Object1
Object2
Array[Object1, Object2]
Object3

[Object, Object, Array(2), Object]

If I add another item it will become

[Object1, Object,2 Array(2), Object3, Array(4), Object4]

What am I doing wrong?

dataStorage.ts

temp = [];
temp2 = [];

// How data is saved
save(data): Promise<any> {
  return this.getData().then((products: any[]) => {
    if (products) {
      //this.temp = products;
      this.temp.push(products, data);
      console.log(this.temp);
      return this.storage.set('products', this.temp);
    }
    return this.storage.set('products', data);
  });
}

// How data is returned

getData() {
  return this.storage.get('products');
}

component.ts

// they click on an add button that calls this
saveItem() {

let newItem = {
  prodName: this.prodName,
  prodDesc: this.prodDesc
};

this.dataService.save(newItem).then(()=>{
  this.navCtrl.pop(SearchProducts);
});
}

Body:
Variable products is array in case storage had it, so push array to temp array will be array in array , not concat.

temp = [];
temp2 = [];

// How data is saved
save(data): Promise<any> {
  return this.getData().then((products: any[]) => {
    if (products) {
      products.push(data);
      return this.storage.set('products', products);
    }
    return this.storage.set('products', [data]);
  });
}


问:
Update SQL Server database' s values quickly C#
I need to update a lot of rows in a database.

Currently I'm using the following code:

```<code>string cmd = "";
cmd = "UPDATE [" + symb + "] SET V1='" + v1.ToString() + "',V2 ='" + v2.ToString() + "',V3='" + v3.ToString() + "' Where V4='" + v4.ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5.ToString() + "'";

l_Cmd = new SqlCommand(cmd, access_connection);
l_Cmd.ExecuteNonQuery();
</code>```

Since I have to update 500/700k rows, it takes a lot of time.

Have you got any advice?

Sorry for previous post, but all values are different:

```<code>for (int a = 0; a < tot_rows; a++)
{
    string cmd = "";
    cmd = "UPDATE [" + symb + "] SET V1='" + v1[a].ToString() + "',V2 ='" + v2[a].ToString() + "',V3='" + v3[a].ToString() + "' Where V4='" + v4[a].ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5[a].ToString() + "'";

    l_Cmd = new SqlCommand(cmd, access_connection);
    l_Cmd.ExecuteNonQuery();
}
</code>```

答: You can try to implement a second (inner) loop that "collects" e. g. 100 UPDATE strings and concatenates them by ";" and then execute the 100 UPDATEs within one SqlCommand. As far as I remember that gave us a remarkable boost in a recent project.</p>

Body:
I need to update a lot of rows in a database.

Currently I'm using the following code:

string cmd = "";
cmd = "UPDATE [" + symb + "] SET V1='" + v1.ToString() + "',V2 ='" + v2.ToString() + "',V3='" + v3.ToString() + "' Where V4='" + v4.ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5.ToString() + "'";

l_Cmd = new SqlCommand(cmd, access_connection);
l_Cmd.ExecuteNonQuery();

Since I have to update 500/700k rows, it takes a lot of time.

Have you got any advice?

Sorry for previous post, but all values are different:

for (int a = 0; a < tot_rows; a++)
{
    string cmd = "";
    cmd = "UPDATE [" + symb + "] SET V1='" + v1[a].ToString() + "',V2 ='" + v2[a].ToString() + "',V3='" + v3[a].ToString() + "' Where V4='" + v4[a].ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5[a].ToString() + "'";

    l_Cmd = new SqlCommand(cmd, access_connection);
    l_Cmd.ExecuteNonQuery();
}


问:
Add star to google maps account programatically
I have a load of maps stars I want to transfer from one google account to another. I can export them as HTML and get a link to each one which looks something like this:

http://maps.google.com/?cid=1863378062783191712

I was then hoping to programmatically call a maps API to add these stars to another account. I can't seem to find anything in the Google Maps API that would allow this, however. It seems straightforward?

答: This looks to have been possible using signed-in maps, which is now deprecated. There is no support for this in the latest maps api.</p>


问:
$cordovaFileTransfer.download Permission Error
I created a mobile app (using ionic/cordova) that is downloading an mp4 file.  I made it work in android, but no luck doing in iOS.  Weird thing is that, sometimes it works, sometimes it doesn't (only in iOS).  I used the plugin cordova-plugin-file-transfer when it works, it works perfectly.  But when I alert the error, I get the  following:

Could not create path to save downloaded file: You don't hvae permission to save the file

  Error code: 1

Here's my following code:

```<code>$scope.download = function(){

        var downloadProgress ='';
        var url = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_5mb.mp4";
        var MyFiles = cordova.file.dataDirectory + 'test1.mp4';
        $cordovaFileTransfer.download(url,MyFiles,{}, true).then(
            function(result){//success download

                $ionicLoading.hide();
                var alertPopup = $ionicPopup.alert({
                    title: 'Download Successful!',
                });

            }, function(error){
                    var alertPopup = $ionicPopup.alert({
                                        title: 'Error',
                                        template: JSON.stringify(error)
                                    });
            }, function(progress){
                            $timeout(function () {
                                downloadProgress = (progress.loaded / progress.total) * 100;
                            });

                            $ionicLoading.show({
                                template: 'Download in progress please wait<br/><progress id="progressbar" max="100" value="'+ downloadProgress +'"> </progress>' +
                                '<div id="progressbarlabel">' + Math.ceil(downloadProgress) + '%</div>'
                                    });
                });

    }
</code>```

答:
I tried with cordova.file.documentsDirectory in iOS this:

```<code>if (ionic.Platform.isIPad() || ionic.Platform.isIOS()) {
            console.log("Is iPad or iOS");
            $rootScope.TARGETPATH = cordova.file.documentsDirectory;;
        }
</code>```

And the result in the Emulator was very well, but when I tried in a real device I get:

You don’t have permission to save the file “Documents” in the folder “MY-APP-ID-XXXXXX”.

so, I tried with cordova.file.dataDirectory:

```<code>if (ionic.Platform.isIPad() || ionic.Platform.isIOS()) {
            console.log("Is iPad or iOS");
            $rootScope.TARGETPATH = cordova.file.dataDirectory;;
        }
</code>```

Body:
I created a mobile app (using ionic/cordova) that is downloading an mp4 file.  I made it work in android, but no luck doing in iOS.  Weird thing is that, sometimes it works, sometimes it doesn't (only in iOS).  I used the plugin cordova-plugin-file-transfer when it works, it works perfectly.  But when I alert the error, I get the  following:

Could not create path to save downloaded file: You don't hvae permission to save the file

  Error code: 1

Here's my following code:

$scope.download = function(){

        var downloadProgress ='';
        var url = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_5mb.mp4";
        var MyFiles = cordova.file.dataDirectory + 'test1.mp4';
        $cordovaFileTransfer.download(url,MyFiles,{}, true).then(
            function(result){//success download

                $ionicLoading.hide();
                var alertPopup = $ionicPopup.alert({
                    title: 'Download Successful!',
                });

            }, function(error){
                    var alertPopup = $ionicPopup.alert({
                                        title: 'Error',
                                        template: JSON.stringify(error)
                                    });
            }, function(progress){
                            $timeout(function () {
                                downloadProgress = (progress.loaded / progress.total) * 100;
                            });

                            $ionicLoading.show({
                                template: 'Download in progress please wait
<progress id="progressbar" max="100" value="'+ downloadProgress +'"> </progress>' +
                                '
' + Math.ceil(downloadProgress) + '%
'
                                    });
                });

    }

Body:
I tried with cordova.file.documentsDirectory in iOS this:

if (ionic.Platform.isIPad() || ionic.Platform.isIOS()) {
            console.log("Is iPad or iOS");
            $rootScope.TARGETPATH = cordova.file.documentsDirectory;;
        }

And the result in the Emulator was very well, but when I tried in a real device I get:

You don’t have permission to save the file “Documents” in the folder “MY-APP-ID-XXXXXX”.

so, I tried with cordova.file.dataDirectory:

if (ionic.Platform.isIPad() || ionic.Platform.isIOS()) {
            console.log("Is iPad or iOS");
            $rootScope.TARGETPATH = cordova.file.dataDirectory;;
        }


问:
Regex for n-directory file path
I'm trying to use regex to evaluate if a given path is valid or not:

List of acceptable values:

```<code> 1. /a_B_1/b_Sc2/c_d3/23_DS_xy/some_file_name.txt
 2. /x_y_q/ffs/www/A/a_ol/some_file_name.txt
 3. /tsf/ggg/wWw/abc/a_o@l/some=file name.csv
 4. /a/b/c/d/some file.txt
</code>```

As you can see for all groups, accepted range is [a-zA-Z0-9_]. Only the last group can have spaces, @, =.

Group ordering: /<group1>/<group2>/<group3>/<group4>/<group5>.

Group 5 can have sub-directories and hence the '*'.

I've tried:

```<code>"""/?[^/\\n]+/([^/\\n]+)/([^/\\n]+)/([^/\\n]+)/([^/\\n]+)/.*""".r

"""/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_\\s]*)""".r

"""/([\\w,\\s-_]+)/([\\w,\\s-_]+)/([\\w,\\s-_]+)/([\\w,\\s-_]+)/([\\w,\\s]*)""".r
</code>```

Can someone please guide?

Sample code

```<code>val regex = """ ... """.r
val testString = "/a/b/c/d/some file.txt"
regex.findFirstMatchIn(testString) match {
    case Some(r) => println(r)
    case _ => println("Regex did not match")
}
</code>```

答:
Not sure what your question is, but note that you don't need to escape backslahes inside triple-quoted strings.

Something like this """(/\w+){4}/([\w\s@=/]+)""".r seems like it should do what you are describing.

Title: Regex for n-directory file path

Body:
I'm trying to use regex to evaluate if a given path is valid or not:

List of acceptable values:

 1. /a_B_1/b_Sc2/c_d3/23_DS_xy/some_file_name.txt
 2. /x_y_q/ffs/www/A/a_ol/some_file_name.txt
 3. /tsf/ggg/wWw/abc/a_o@l/some=file name.csv
 4. /a/b/c/d/some file.txt

As you can see for all groups, accepted range is [a-zA-Z0-9_]. Only the last group can have spaces, @, =.

Group ordering: /<group1>/<group2>/<group3>/<group4>/<group5>.

Group 5 can have sub-directories and hence the '*'.

I've tried:

"""/?[^/\\n]+/([^/\\n]+)/([^/\\n]+)/([^/\\n]+)/([^/\\n]+)/.*""".r

"""/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_]+)/(^[a-zA-Z0-9-_\\s]*)""".r

"""/([\\w,\\s-_]+)/([\\w,\\s-_]+)/([\\w,\\s-_]+)/([\\w,\\s-_]+)/([\\w,\\s]*)""".r

Can someone please guide?

Sample code

val regex = """ ... """.r
val testString = "/a/b/c/d/some file.txt"
regex.findFirstMatchIn(testString) match {
    case Some(r) => println(r)
    case _ => println("Regex did not match")
}


问:
anchor tag text over flow from div box
```<code><div>
    <ul>
        <li><a href="#">Test_link_is_soooo_long</a></li>
    </ul>
</div>

<style>
div {
    border: 2px solid rgba(0,0,0,0.1);
    width: 150px;
}
a {
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>
</code>```

link text goes outside border and i want to fix it. But not get any solution.

result of above code

how I fix this problem.

答:
Use text ellipsis.if you dont want to increase the width of the div and display the link in a single line.The part going out of the with will be displayed as three dots

div {
    border: 2px solid rgba(0,0,0,0.1);
    width: 150px;
}
a {
      width: 100px;
      display:inline-block;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <ul>
        <li>Test_link_is_soooo_long</li>
    </ul>
</div></code>```

Title: anchor tag text over flow from div box

Body:
Test_link_is_soooo_long

link text goes outside border and i want to fix it. But not get any solution.

result of above code

how I fix this problem.

Body:
Use text ellipsis.if you dont want to increase the width of the div and display the link in a single line.The part going out of the with will be displayed as three dots

div {
    border: 2px solid rgba(0,0,0,0.1);
    width: 150px;
}
a {
      width: 100px;
      display:inline-block;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
}

<div>
    <ul>
        <li><a href="#">Test_link_is_soooo_long</a></li>
    </ul>
</div>


问:
Conditional actions between rows based on a given condition in jQgrid?
I need to swap between actions based on a given condition in a jqGrid  4.4.1 grid. Take a look to the following image:

How it should works is:

if Type is api_response then the actions should be only the magnifier icon.

if Type is api_request then the actions should be the second icon but magnifier shouldn't be there.

This is how I am creating the buttons:

```<code>$.fn.fmatter.btnFormatter = function (cellValue, options, rowData, addOrEdit) {
    return '<a href="#">' +
        '<img class="api_button" data-id="' + options.rowId + '" src="/images/icons/16x16/document_view.png" alt="Show API Response Data" title="Show API Response Data" />' +
        '</a>' +
        '<a href="/sf/api-logs/error/' + options.rowId + '">' +
        '<img class="error_button" data-id="' + options.rowId + '" src="/images/icons/16x16/document_warning.png" alt="Show Errors" title="Show Errors" />' +
        '</a>';
};

$(function () {
    $("#grid").jqGrid({
        url: '/api-logs',
        datatype: "json",
        colNames: $('#colnames').data('values'),
        colModel: $('#colmodel').data('values'),
        width: 980,
        height: 300,
        pager: "#gridpager",
        toppager: true,
        hoverrows: true,
        shrinkToFit: true,
        autowidth: true,
        rownumbers: true,
        viewrecords: true,
        rowList: [10, 20, 50, 100],
        data: [],
        rownumWidth: 50,
        gridview: true,
        sortable: true,
        rowattr: function (item) {
            if (item.type === "api_response") {
                return {"class": "api_response"};
            } else if (item.type === 'api_request') {
                return {"class": "api_request"};
            }
        },
        jsonReader: {
            root: 'rows',
            page: 'page',
            total: 'total',
            records: 'records',
            cell: '',
            repeatitems: false
        }
    });
});
</code>```

Of course the first column has the btnFormatter applied.

How I can do this?

答:
You can modify the code of $.fn.fmatter.btnFormatter, which you use to test rowData.type in the same way like you do it inside of rowattr callback.

In any way I would strictly recommend you to test, whether your existing code works with the current version of free jqGrid (the version 4.14.1). You can modify 3 lines of your HTML code and load CSS and JS files from CDN (see the wiki article). The version 4.4.1 of jqGrid is dead. It's really dangerous to use such old and unsupported version.

Body:
I need to swap between actions based on a given condition in a jqGrid  4.4.1 grid. Take a look to the following image:

How it should works is:

if Type is api_response then the actions should be only the magnifier icon.

if Type is api_request then the actions should be the second icon but magnifier shouldn't be there.

This is how I am creating the buttons:

$.fn.fmatter.btnFormatter = function (cellValue, options, rowData, addOrEdit) {
    return '' +
        '' +
        '' +
        '' +
        '' +
        '';
};

$(function () {
    $("#grid").jqGrid({
        url: '/api-logs',
        datatype: "json",
        colNames: $('#colnames').data('values'),
        colModel: $('#colmodel').data('values'),
        width: 980,
        height: 300,
        pager: "#gridpager",
        toppager: true,
        hoverrows: true,
        shrinkToFit: true,
        autowidth: true,
        rownumbers: true,
        viewrecords: true,
        rowList: [10, 20, 50, 100],
        data: [],
        rownumWidth: 50,
        gridview: true,
        sortable: true,
        rowattr: function (item) {
            if (item.type === "api_response") {
                return {"class": "api_response"};
            } else if (item.type === 'api_request') {
                return {"class": "api_request"};
            }
        },
        jsonReader: {
            root: 'rows',
            page: 'page',
            total: 'total',
            records: 'records',
            cell: '',
            repeatitems: false
        }
    });
});

Of course the first column has the btnFormatter applied.

How I can do this?


问:
Windows command for cutting columns from a text
The following content is stored in a file:

```<code>chrome.exe                   512 Console                 0     73,780 K
chrome.exe                   800 Console                 0     11,052 K
chrome.exe                  1488 Console                 0     92,720 K
chrome.exe                  1600 Console                 0     32,344 K
chrome.exe                  2240 Console                 0     35,132 K
chrome.exe                  2360 Console                 0     21,276 K
chrome.exe                  3524 Console                 0     66,732 K
chrome.exe                  3924 Console                 0     23,524 K
</code>```

Is there a way to extract the 5th column with the Windows command line?

Something like the UNIX cut command.

答:
If you had perl installed:</p>

```<code>perl.exe -na  -e "print qq{$F[4]\n}" < myfile.txt
</code>```

Body:
The following content is stored in a file:

chrome.exe                   512 Console                 0     73,780 K
chrome.exe                   800 Console                 0     11,052 K
chrome.exe                  1488 Console                 0     92,720 K
chrome.exe                  1600 Console                 0     32,344 K
chrome.exe                  2240 Console                 0     35,132 K
chrome.exe                  2360 Console                 0     21,276 K
chrome.exe                  3524 Console                 0     66,732 K
chrome.exe                  3924 Console                 0     23,524 K

Is there a way to extract the 5th column with the Windows command line?

Something like the UNIX cut command.

Body:
If you had perl installed:

perl.exe -na  -e "print qq{$F[4]\n}" < myfile.txt