问:
Speeding up an L-System renderer in C#/WPF
lsys is a blazing fast L-System renderer written in CoffeeScript.

Below is a simple renderer in C# and WPF. It is hardcoded to render this example. The result when run looks as follows:

A mouse-click in the window will adjust the angleGrowth variable. The re-calculation of the GeometryGroup as well as building the Canvas usually take much less than a tenth of a second. However, the actual screen update seems to take much longer.

Any suggestions for how to make this faster or more efficient? It's currently way slower than the CoffeeScript/JavaScript version... :-)

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Diagnostics;

namespace WpfLsysRender
{
    class DrawingVisualElement : FrameworkElement
    {
        public DrawingVisual visual;

        public DrawingVisualElement() { visual = new DrawingVisual(); }

        protected override int VisualChildrenCount { get { return 1; } }

        protected override Visual GetVisualChild(int index) { return visual; }
    }

    class State
    {
        public double size;

        public double angle;

        public double x;

        public double y;

        public double dir;

        public State Clone() { return (State) this.MemberwiseClone(); }
    }

    public partial class MainWindow : Window
    {
        static string Rewrite(Dictionary<char, string> tbl, string str)
        {
            var sb = new StringBuilder();

            foreach (var elt in str)
            {
                if (tbl.ContainsKey(elt))
                    sb.Append(tbl[elt]);
                else
                    sb.Append(elt);
            }

            return sb.ToString();
        }

        public MainWindow()
        {
            InitializeComponent();

            Width = 800;
            Height = 800;

            var states = new Stack<State>();

            var str = "L";

            {
                var tbl = new Dictionary<char, string>();

                tbl.Add('L', "|-S!L!Y");
                tbl.Add('S', "[F[FF-YS]F)G]+");
                tbl.Add('Y', "--[F-)<F-FG]-");
                tbl.Add('G', "FGF[Y+>F]+Y");

                for (var i = 0; i < 12; i++) str = Rewrite(tbl, str);
            }

            var canvas = new Canvas();

            Content = canvas;

            var sizeGrowth = -1.359672;
            var angleGrowth = -0.138235;

            State state;

            var pen = new Pen(new SolidColorBrush(Colors.Black), 0.25);

            var geometryGroup = new GeometryGroup();

            Action buildGeometry = () =>
            {
                state = new State()
                {
                    x = 0,
                    y = 0,
                    dir = 0,
                    size = 14.11,
                    angle = -3963.7485
                };

                geometryGroup = new GeometryGroup();

                foreach (var elt in str)
                {
                    if (elt == 'F')
                    {
                        var new_x = state.x + state.size * Math.Cos(state.dir * Math.PI / 180.0);
                        var new_y = state.y + state.size * Math.Sin(state.dir * Math.PI / 180.0);

                        geometryGroup.Children.Add(
                            new LineGeometry(
                                new Point(state.x, state.y),
                                new Point(new_x, new_y)));

                        state.x = new_x;
                        state.y = new_y;
                    }
                    else if (elt == '+') state.dir += state.angle;

                    else if (elt == '-') state.dir -= state.angle;

                    else if (elt == '>') state.size *= (1.0 - sizeGrowth);

                    else if (elt == '<') state.size *= (1.0 + sizeGrowth);

                    else if (elt == ')') state.angle *= (1 + angleGrowth);

                    else if (elt == '(') state.angle *= (1 - angleGrowth);

                    else if (elt == '[') states.Push(state.Clone());

                    else if (elt == ']') state = states.Pop();

                    else if (elt == '!') state.angle *= -1.0;

                    else if (elt == '|') state.dir += 180.0;
                }
            };

            Action populateCanvas = () =>
            {
                var drawingVisualElement = new DrawingVisualElement();

                Console.WriteLine(".");

                canvas.Children.Clear();

                canvas.RenderTransform = new TranslateTransform(400.0, 400.0);

                using (var dc = drawingVisualElement.visual.RenderOpen())
                    dc.DrawGeometry(null, pen, geometryGroup);

                canvas.Children.Add(drawingVisualElement);
            };

            MouseDown += (s, e) =>
                {
                    angleGrowth += 0.001;
                    Console.WriteLine("angleGrowth: {0}", angleGrowth);

                    var sw = Stopwatch.StartNew();

                    buildGeometry();
                    populateCanvas();

                    sw.Stop();

                    Console.WriteLine(sw.Elapsed);
                };

            buildGeometry();

            populateCanvas();
        }
    }
}
</code>```

答:
I have not tested the WriteableBitmapEx version, so I don't know how this compares, but I was able to substantially speed up the WPF native version by using StreamGeometry and Freeze(), which is a way to optimize when there is no animation.  (Though it still doesn't feel as fast as the javascript version)

The posted version timing is ~0.15s

The StreamGeometry version timing is ~0.029s

I don't think the timer includes the actual rendering time, just the time to populate the rendering commands. However, it also feels much more speedy. This WPF performance test demonstrates a way to get actual rendering times.

I also removed the Canvas and FrameworkElement, but it was switching to StreamGeometry that did the speedup.

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Diagnostics;

using System.Windows.Media.Imaging;

// https://stackoverflow.com/q/22599806/519568

namespace WpfLsysRender
{

    class UpdatableUIElement : UIElement {
        DrawingGroup backingStore = new DrawingGroup();
        public UpdatableUIElement() {

        }

        protected override void OnRender(DrawingContext drawingContext) {
            base.OnRender(drawingContext);
            drawingContext.DrawDrawing(backingStore);
        }
        public void Redraw(Action<DrawingContext> fn) {
            var vis = backingStore.Open();
            fn(vis);
            vis.Close();
        }
    }

    class State
    {
        public double size;

        public double angle;

        public double x;

        public double y;

        public double dir;

        public State Clone() { return (State)this.MemberwiseClone(); }
    }

    public partial class MainWindow : Window
    {
        static string Rewrite(Dictionary<char, string> tbl, string str) {
            var sb = new StringBuilder();

            foreach (var elt in str) {
                if (tbl.ContainsKey(elt))
                    sb.Append(tbl[elt]);
                else
                    sb.Append(elt);
            }

            return sb.ToString();
        }

        public MainWindow() {
            // InitializeComponent();

            Width = 800;
            Height = 800;

            var states = new Stack<State>();

            var str = "L";

            {
                var tbl = new Dictionary<char, string>();

                tbl.Add('L', "|-S!L!Y");
                tbl.Add('S', "[F[FF-YS]F)G]+");
                tbl.Add('Y', "--[F-)<F-FG]-");
                tbl.Add('G', "FGF[Y+>F]+Y");

                for (var i = 0; i < 12; i++) str = Rewrite(tbl, str);
            }

            var lsystem_view = new UpdatableUIElement();
            Content = lsystem_view;

            var sizeGrowth = -1.359672;
            var angleGrowth = -0.138235;

            State state;

            var pen = new Pen(new SolidColorBrush(Colors.Black), 0.25);

            var geometry = new StreamGeometry();

            Action buildGeometry = () => {
                state = new State() {
                    x = 0,
                    y = 0,
                    dir = 0,
                    size = 14.11,
                    angle = -3963.7485
                };

                geometry = new StreamGeometry();
                var gc = geometry.Open();

                foreach (var elt in str) {
                    if (elt == 'F') {
                        var new_x = state.x + state.size * Math.Cos(state.dir * Math.PI / 180.0);
                        var new_y = state.y + state.size * Math.Sin(state.dir * Math.PI / 180.0);
                        var p1 = new Point(state.x, state.y);
                        var p2 = new Point(new_x, new_y);
                        gc.BeginFigure(p1,false,false);
                        gc.LineTo(p2,true,true);

                        state.x = new_x;
                        state.y = new_y;
                    }
                    else if (elt == '+') state.dir += state.angle;

                    else if (elt == '-') state.dir -= state.angle;

                    else if (elt == '>') state.size *= (1.0 - sizeGrowth);

                    else if (elt == '<') state.size *= (1.0 + sizeGrowth);

                    else if (elt == ')') state.angle *= (1 + angleGrowth);

                    else if (elt == '(') state.angle *= (1 - angleGrowth);

                    else if (elt == '[') states.Push(state.Clone());

                    else if (elt == ']') state = states.Pop();

                    else if (elt == '!') state.angle *= -1.0;

                    else if (elt == '|') state.dir += 180.0;
                }
                gc.Close();
                geometry.Freeze();
            };

            Action populateCanvas = () => {
                Console.WriteLine(".");

                lsystem_view.RenderTransform = new TranslateTransform(400,400);

                lsystem_view.Redraw((dc) => {
                    dc.DrawGeometry(null, pen, geometry);
                });
            };

            MouseDown += (s, e) => {
                angleGrowth += 0.001;
                Console.WriteLine("angleGrowth: {0}", angleGrowth);

                var sw = Stopwatch.StartNew();

                buildGeometry();
                populateCanvas();

                sw.Stop();

                Console.WriteLine(sw.Elapsed);
            };

            buildGeometry();

            populateCanvas();
        }
    }
}
</code>```

Body:
lsys is a blazing fast L-System renderer written in CoffeeScript.

Below is a simple renderer in C# and WPF. It is hardcoded to render this example. The result when run looks as follows:

A mouse-click in the window will adjust the angleGrowth variable. The re-calculation of the GeometryGroup as well as building the Canvas usually take much less than a tenth of a second. However, the actual screen update seems to take much longer.

Any suggestions for how to make this faster or more efficient? It's currently way slower than the CoffeeScript/JavaScript version... :-)

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Diagnostics;

namespace WpfLsysRender
{
    class DrawingVisualElement : FrameworkElement
    {
        public DrawingVisual visual;

        public DrawingVisualElement() { visual = new DrawingVisual(); }

        protected override int VisualChildrenCount { get { return 1; } }

        protected override Visual GetVisualChild(int index) { return visual; }
    }

    class State
    {
        public double size;

        public double angle;

        public double x;

        public double y;

        public double dir;

        public State Clone() { return (State) this.MemberwiseClone(); }
    }

    public partial class MainWindow : Window
    {
        static string Rewrite(Dictionary<char, string> tbl, string str)
        {
            var sb = new StringBuilder();

            foreach (var elt in str)
            {
                if (tbl.ContainsKey(elt))
                    sb.Append(tbl[elt]);
                else
                    sb.Append(elt);
            }

            return sb.ToString();
        }

        public MainWindow()
        {
            InitializeComponent();

            Width = 800;
            Height = 800;

            var states = new Stack<State>();

            var str = "L";

            {
                var tbl = new Dictionary<char, string>();

                tbl.Add('L', "|-S!L!Y");
                tbl.Add('S', "[F[FF-YS]F)G]+");
                tbl.Add('Y', "--[F-)<F-FG]-");
                tbl.Add('G', "FGF[Y+>F]+Y");

                for (var i = 0; i < 12; i++) str = Rewrite(tbl, str);
            }

            var canvas = new Canvas();

            Content = canvas;

            var sizeGrowth = -1.359672;
            var angleGrowth = -0.138235;

            State state;

            var pen = new Pen(new SolidColorBrush(Colors.Black), 0.25);

            var geometryGroup = new GeometryGroup();

            Action buildGeometry = () =>
            {
                state = new State()
                {
                    x = 0,
                    y = 0,
                    dir = 0,
                    size = 14.11,
                    angle = -3963.7485
                };

                geometryGroup = new GeometryGroup();

                foreach (var elt in str)
                {
                    if (elt == 'F')
                    {
                        var new_x = state.x + state.size * Math.Cos(state.dir * Math.PI / 180.0);
                        var new_y = state.y + state.size * Math.Sin(state.dir * Math.PI / 180.0);

                        geometryGroup.Children.Add(
                            new LineGeometry(
                                new Point(state.x, state.y),
                                new Point(new_x, new_y)));

                        state.x = new_x;
                        state.y = new_y;
                    }
                    else if (elt == '+') state.dir += state.angle;

                    else if (elt == '-') state.dir -= state.angle;

                    else if (elt == '>') state.size *= (1.0 - sizeGrowth);

                    else if (elt == '<') state.size *= (1.0 + sizeGrowth);

                    else if (elt == ')') state.angle *= (1 + angleGrowth);

                    else if (elt == '(') state.angle *= (1 - angleGrowth);

                    else if (elt == '[') states.Push(state.Clone());

                    else if (elt == ']') state = states.Pop();

                    else if (elt == '!') state.angle *= -1.0;

                    else if (elt == '|') state.dir += 180.0;
                }
            };

            Action populateCanvas = () =>
            {
                var drawingVisualElement = new DrawingVisualElement();

                Console.WriteLine(".");

                canvas.Children.Clear();

                canvas.RenderTransform = new TranslateTransform(400.0, 400.0);

                using (var dc = drawingVisualElement.visual.RenderOpen())
                    dc.DrawGeometry(null, pen, geometryGroup);

                canvas.Children.Add(drawingVisualElement);
            };

            MouseDown += (s, e) =>
                {
                    angleGrowth += 0.001;
                    Console.WriteLine("angleGrowth: {0}", angleGrowth);

                    var sw = Stopwatch.StartNew();

                    buildGeometry();
                    populateCanvas();

                    sw.Stop();

                    Console.WriteLine(sw.Elapsed);
                };

            buildGeometry();

            populateCanvas();
        }
    }
}

Body:
I have not tested the WriteableBitmapEx version, so I don't know how this compares, but I was able to substantially speed up the WPF native version by using StreamGeometry and Freeze(), which is a way to optimize when there is no animation.  (Though it still doesn't feel as fast as the javascript version)

The posted version timing is ~0.15s

The StreamGeometry version timing is ~0.029s

I don't think the timer includes the actual rendering time, just the time to populate the rendering commands. However, it also feels much more speedy. This WPF performance test demonstrates a way to get actual rendering times.

I also removed the Canvas and FrameworkElement, but it was switching to StreamGeometry that did the speedup.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Diagnostics;

using System.Windows.Media.Imaging;

// https://stackoverflow.com/q/22599806/519568

namespace WpfLsysRender
{

    class UpdatableUIElement : UIElement {
        DrawingGroup backingStore = new DrawingGroup();
        public UpdatableUIElement() {

        }

        protected override void OnRender(DrawingContext drawingContext) {
            base.OnRender(drawingContext);
            drawingContext.DrawDrawing(backingStore);
        }
        public void Redraw(Action<DrawingContext> fn) {
            var vis = backingStore.Open();
            fn(vis);
            vis.Close();
        }
    }

    class State
    {
        public double size;

        public double angle;

        public double x;

        public double y;

        public double dir;

        public State Clone() { return (State)this.MemberwiseClone(); }
    }

    public partial class MainWindow : Window
    {
        static string Rewrite(Dictionary<char, string> tbl, string str) {
            var sb = new StringBuilder();

            foreach (var elt in str) {
                if (tbl.ContainsKey(elt))
                    sb.Append(tbl[elt]);
                else
                    sb.Append(elt);
            }

            return sb.ToString();
        }

        public MainWindow() {
            // InitializeComponent();

            Width = 800;
            Height = 800;

            var states = new Stack<State>();

            var str = "L";

            {
                var tbl = new Dictionary<char, string>();

                tbl.Add('L', "|-S!L!Y");
                tbl.Add('S', "[F[FF-YS]F)G]+");
                tbl.Add('Y', "--[F-)<F-FG]-");
                tbl.Add('G', "FGF[Y+>F]+Y");

                for (var i = 0; i < 12; i++) str = Rewrite(tbl, str);
            }

            var lsystem_view = new UpdatableUIElement();
            Content = lsystem_view;

            var sizeGrowth = -1.359672;
            var angleGrowth = -0.138235;

            State state;

            var pen = new Pen(new SolidColorBrush(Colors.Black), 0.25);

            var geometry = new StreamGeometry();

            Action buildGeometry = () => {
                state = new State() {
                    x = 0,
                    y = 0,
                    dir = 0,
                    size = 14.11,
                    angle = -3963.7485
                };

                geometry = new StreamGeometry();
                var gc = geometry.Open();

                foreach (var elt in str) {
                    if (elt == 'F') {
                        var new_x = state.x + state.size * Math.Cos(state.dir * Math.PI / 180.0);
                        var new_y = state.y + state.size * Math.Sin(state.dir * Math.PI / 180.0);
                        var p1 = new Point(state.x, state.y);
                        var p2 = new Point(new_x, new_y);
                        gc.BeginFigure(p1,false,false);
                        gc.LineTo(p2,true,true);

                        state.x = new_x;
                        state.y = new_y;
                    }
                    else if (elt == '+') state.dir += state.angle;

                    else if (elt == '-') state.dir -= state.angle;

                    else if (elt == '>') state.size *= (1.0 - sizeGrowth);

                    else if (elt == '<') state.size *= (1.0 + sizeGrowth);

                    else if (elt == ')') state.angle *= (1 + angleGrowth);

                    else if (elt == '(') state.angle *= (1 - angleGrowth);

                    else if (elt == '[') states.Push(state.Clone());

                    else if (elt == ']') state = states.Pop();

                    else if (elt == '!') state.angle *= -1.0;

                    else if (elt == '|') state.dir += 180.0;
                }
                gc.Close();
                geometry.Freeze();
            };

            Action populateCanvas = () => {
                Console.WriteLine(".");

                lsystem_view.RenderTransform = new TranslateTransform(400,400);

                lsystem_view.Redraw((dc) => {
                    dc.DrawGeometry(null, pen, geometry);
                });
            };

            MouseDown += (s, e) => {
                angleGrowth += 0.001;
                Console.WriteLine("angleGrowth: {0}", angleGrowth);

                var sw = Stopwatch.StartNew();

                buildGeometry();
                populateCanvas();

                sw.Stop();

                Console.WriteLine(sw.Elapsed);
            };

            buildGeometry();

            populateCanvas();
        }
    }
}


来源: stackexchange

问:
Aligning div and navbar to the right using bootstrap
I have a html code right:

https://jsfiddle.net/zdwkvp3c/3/

I want to align the heading on left and dropdown and the ul ( Bar and Trend) on right, when on big screens\medium screens.

I want to align the heading on left and dropdown and ul ( Bar and Trend) on right, but this time, dropdown will be on top and ul ( Bar and Trend) below the dropdown, but both of these should be towards the right.

I have used nested rows and unable to get pull-right work. Kindly let me know if I am missing something in the code.

答:
i do not exactly understand what you want to achieve ( your instructions are not clear ) but take a look at the snippet below. is this what you want ?

or jsFiddle

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 By Companies

            <select style="width:100%;">
                    <option>DropdownVal1</option>

                </select>

                    Bar Chart

                    Line Chart

```

ContentLicense: CC BY-SA 3.0

Body:
i do not exactly understand what you want to achieve ( your instructions are not clear ) but take a look at the snippet below. is this what you want ?

or jsFiddle

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
    <div class="col-md-4 col-sm-12 header pull-left" style="background: green">
 By Companies
    </div>
    <div class="col-md-8 col-sm-6 col-xs-12 pull-right"  style="background: blue">
    <div class="row inner_row">
       <div class="col-md-6 col-sm-6 col-xs-12 margin">
            <select style="width:100%;">
                    <option>DropdownVal1</option>

                </select>
        </div>

    <div class="col-md-6 col-sm-6 col-xs-12 margin" style="background: orange">
            <ul class="nav nav-pills navbar-right" style="float:right;">
                <li>
                    <a>Bar Chart</a>
                </li>
  <li>
                    <a>Line Chart</a>
                </li>
            </ul>
        </div>

  </div>
    </div>

</div>


问:
How to implement two dimensional arrays in tcl
Need assistance in creating two dimensional arrays.

I need to create the below scenario

```<code>nblist_0 = {1,2,3,4}
nblist_1 = {3,7,5,9,1}
nblist_2 = {7,4,9,2,5}
nblist_3 = {1,2,4,6}
nblist_4 = {1,5,4}
...
</code>```

Since my logic hereafter follows the above two dimensional array, I also need the logic to access the individual data (just like an array). Kindly help!!

答:
There are two recommended ways. One is to construct a list of lists and to use the multi-index versions of lindex and lset, and the other is to construct composite keys to use with associative arrays.

Nested Lists

```<code># Setup...
set nblist {
    {1 2 3 4}
    {3 7 5 9 1}
    {7 4 9 2 5}
    {1 2 4 6}
    {1 5 4}
}

# Reading...
set row 1
set column 3
set value [lindex $nblist $row $column]

# Writing...
lset nblist $row $column [expr {$value + 17}]
</code>```

You can add new rows to the table with lappend, and (in Tcl 8.6) extend a row by an element with lset nblist $rowidx end+1 $initval

Iteration of the rows or the columns of one row with foreach is trivial.

Composite Keys

```<code># Setup...
array set nblist {
    0,0 1 0,1 2 0,2 3 0,3 4
    1,0 3 1,1 7 1,2 5 1,3 9 1,4 1
    2,0 7 2,1 4 2,2 9 2,3 2 2,4 5
    3,0 1 3,1 2 3,2 4 3,3 6
    4,0 1 4,1 5 4,2 4
}

# Reading...
set row 1
set column 3
set value $nblist($row,$column)

# Writing...
set nblist($row,$column) [expr {$value + 17}]
</code>```

With this approach, the elements are fundamentally entirely unordered and your keys are fundamentally strings, but you can access individual elements fairly simply. However, there's no concept of a row or a column; iteration over the contents of the array will be annoying.

Body:
Need assistance in creating two dimensional arrays.

I need to create the below scenario

nblist_0 = {1,2,3,4}
nblist_1 = {3,7,5,9,1}
nblist_2 = {7,4,9,2,5}
nblist_3 = {1,2,4,6}
nblist_4 = {1,5,4}
...

Since my logic hereafter follows the above two dimensional array, I also need the logic to access the individual data (just like an array). Kindly help!!

Body:
There are two recommended ways. One is to construct a list of lists and to use the multi-index versions of lindex and lset, and the other is to construct composite keys to use with associative arrays.

Nested Lists

# Setup...
set nblist {
    {1 2 3 4}
    {3 7 5 9 1}
    {7 4 9 2 5}
    {1 2 4 6}
    {1 5 4}
}

# Reading...
set row 1
set column 3
set value [lindex $nblist $row $column]

# Writing...
lset nblist $row $column [expr {$value + 17}]

You can add new rows to the table with lappend, and (in Tcl 8.6) extend a row by an element with lset nblist $rowidx end+1 $initval

Iteration of the rows or the columns of one row with foreach is trivial.

Composite Keys

# Setup...
array set nblist {
    0,0 1 0,1 2 0,2 3 0,3 4
    1,0 3 1,1 7 1,2 5 1,3 9 1,4 1
    2,0 7 2,1 4 2,2 9 2,3 2 2,4 5
    3,0 1 3,1 2 3,2 4 3,3 6
    4,0 1 4,1 5 4,2 4
}

# Reading...
set row 1
set column 3
set value $nblist($row,$column)

# Writing...
set nblist($row,$column) [expr {$value + 17}]

With this approach, the elements are fundamentally entirely unordered and your keys are fundamentally strings, but you can access individual elements fairly simply. However, there's no concept of a row or a column; iteration over the contents of the array will be annoying.


问:
How to achieve this effect while listview is loading with items in android?
Lately, this kind of effect is gaining lot of popularity.
While items are being populated, listview shows this kind of affect.
What exactly is this and how can one implement it.
Thanks!

答:
Check out the LoaderViewLibrary on Github.

The description matches your requirements -

Library that enables TextView of ImageView to show loading animation
  while waiting for the text and image get loaded


问:
query search LIKE use keywords where and left join LARAVEL 5
I want to find a data from two tables based on the name contained in the users, but I am having problems.
This is the users table containing the id, and name.
This is the student table that contains the id, and user_id.
Where user_id student = id users.

```<code>public function search(Request $request)
{
  $keywords   = trim($request->input('keywords'));

  if (!empty($keywords)) {
      $id_class       = $request->input('id_class');

    //Query
    $query = User()
    ->leftjoin('student', 'users.id', '=', 'student.user_id')
    ->where('users.name', 'LIKE', '%' . $keywords . '%');

    (!empty($id_class)) ? $query->Kelas($id_class) : '';
    $data_student = $query->paginate(10);

    //URL link pagination
    $pagination = (!empty($id_class)) ? $pagination = $data_student->appends(['id_class' => $id_class]) : '';
    $pagination = $data_student->appends(['keywords' => $keywords]);

    $amount_data = $=data_student->total();
    return view('student.index', compact('data_student', 'keywords', 'pagination', 'amount_data', 'id_class'));
   }
   return redirect('student');
}
</code>```

Call to undefined function App\Http\Controllers\User()

答:
As mentioned previously you need to correctly refer to the User class with namespace, you also need to change thew following:

```<code> $query = User()
    ->leftjoin('student', 'users.id', '=', 'student.user_id')
    ->where('users.name', 'LIKE', '%' . $keywords . '%');
</code>```

to:

```<code>$query = User::leftjoin('student', 'users.id', '=', 'student.user_id')
    ->where('users.name', 'LIKE', '%' . $keywords . '%');
</code>```

You must call the first method on the class as static with ::.

Also another potential typo you join the table student should it be plural; students?

Body:
I want to find a data from two tables based on the name contained in the users, but I am having problems.
This is the users table containing the id, and name.
This is the student table that contains the id, and user_id.
Where user_id student = id users.

public function search(Request $request)
{
  $keywords   = trim($request->input('keywords'));

  if (!empty($keywords)) {
      $id_class       = $request->input('id_class');

    //Query
    $query = User()
    ->leftjoin('student', 'users.id', '=', 'student.user_id')
    ->where('users.name', 'LIKE', '%' . $keywords . '%');

    (!empty($id_class)) ? $query->Kelas($id_class) : '';
    $data_student = $query->paginate(10);

    //URL link pagination
    $pagination = (!empty($id_class)) ? $pagination = $data_student->appends(['id_class' => $id_class]) : '';
    $pagination = $data_student->appends(['keywords' => $keywords]);

    $amount_data = $=data_student->total();
    return view('student.index', compact('data_student', 'keywords', 'pagination', 'amount_data', 'id_class'));
   }
   return redirect('student');
}

Call to undefined function App\Http\Controllers\User()

Body:
As mentioned previously you need to correctly refer to the User class with namespace, you also need to change thew following:

 $query = User()
    ->leftjoin('student', 'users.id', '=', 'student.user_id')
    ->where('users.name', 'LIKE', '%' . $keywords . '%');

to:

$query = User::leftjoin('student', 'users.id', '=', 'student.user_id')
    ->where('users.name', 'LIKE', '%' . $keywords . '%');

You must call the first method on the class as static with ::.

Also another potential typo you join the table student should it be plural; students?


问:
Angular2 ng-bootstrap: Reuse modal template with different data
I am building a dashboard-like interface with a set of entities containing comparable data. Each of these entities have an edit-button which I would like to use to open a modal with the respective data displayed.

I would like to reuse the same modal template, and display the data from the entity who's edit-button was clicked. I am using Angular2 with ng-bootstrap, which relies on Bootstrap 4.

From the ng-bootstrap modal docs, and it's accompanying plunkr, I was able to create my own working modal component like so (simplified for layout):

```<code>//editmodal.html

<template #content let-c="close" let-d="dismiss">
  //Modal html content
</template>

<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Edit</button>
</code>```

```<code>//dashboard.html

<template ngbModalContainer></template>
<edit-modal></edit-modal>
</code>```

```<code>//editmodal.component.ts

@Component({
  selector: 'edit-modal',
  templateUrl: 'entity/assets/templates/editmodal.html'
})

export class EditModal {
  //exported class logic
}
</code>```

The main thing which struck me as odd, coming from the previous bootstrap version, is that the button to open the modal is now displayed within the template itself, encapsulating it. This makes it hard to attach a reference to it so I could figure out what to show from the class logic. How can I achieve this behaviour with Angular2 and ng-bootstrap?

答:
Similar to what Lev wrote in his answer, you can use the NgbModal.open() method and pass it a component to populate the content of a modal.

Now, you don't just want a component. You also want the component to fetch the data from an API. You can do this by combining the NgbModalRef.componentInstance parameter, with the OnInit interface.

So the solution would be something like this:

```<code>constructor(
  private modalService: NgbModal
) { }

openModal() {
  const modalRef = this.modalService.open(MyComponent)
  modalRef.componentInstance.mycomponent_id = 1;
}
</code>```

Your component look like this:

```<code>export class PlayerComponent implements OnInit {
  @Input() mycomponent_id;
  myObject: MyObject;

  ngOnInit() {
    this.myService.getObject(mycomponent_id)
      .subscribe(value => this.myObject = value);
  }
  ...
}
</code>```

So basically to summarize it. You open the modal by passing it the component you want as content. Then you set the mycomponent_id value from outside your component. After this your component will run the ngOnInit() method which allow you to use the mycomponent_id value to fetch the correct data from your API using your service.

Body:
I am building a dashboard-like interface with a set of entities containing comparable data. Each of these entities have an edit-button which I would like to use to open a modal with the respective data displayed.

I would like to reuse the same modal template, and display the data from the entity who's edit-button was clicked. I am using Angular2 with ng-bootstrap, which relies on Bootstrap 4.

From the ng-bootstrap modal docs, and it's accompanying plunkr, I was able to create my own working modal component like so (simplified for layout):

//editmodal.html

<template #content let-c="close" let-d="dismiss">
  //Modal html content
</template>

<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Edit</button>

//dashboard.html

<template ngbModalContainer></template>
<edit-modal></edit-modal>

//editmodal.component.ts

@Component({
  selector: 'edit-modal',
  templateUrl: 'entity/assets/templates/editmodal.html'
})

export class EditModal {
  //exported class logic
}

The main thing which struck me as odd, coming from the previous bootstrap version, is that the button to open the modal is now displayed within the template itself, encapsulating it. This makes it hard to attach a reference to it so I could figure out what to show from the class logic. How can I achieve this behaviour with Angular2 and ng-bootstrap?

Body:
Similar to what Lev wrote in his answer, you can use the NgbModal.open() method and pass it a component to populate the content of a modal.

Now, you don't just want a component. You also want the component to fetch the data from an API. You can do this by combining the NgbModalRef.componentInstance parameter, with the OnInit interface.

So the solution would be something like this:

constructor(
  private modalService: NgbModal
) { }

openModal() {
  const modalRef = this.modalService.open(MyComponent)
  modalRef.componentInstance.mycomponent_id = 1;
}

Your component look like this:

export class PlayerComponent implements OnInit {
  @Input() mycomponent_id;
  myObject: MyObject;

  ngOnInit() {
    this.myService.getObject(mycomponent_id)
      .subscribe(value => this.myObject = value);
  }
  ...
}

So basically to summarize it. You open the modal by passing it the component you want as content. Then you set the mycomponent_id value from outside your component. After this your component will run the ngOnInit() method which allow you to use the mycomponent_id value to fetch the correct data from your API using your service.


问:
Swift swap array objects
I'm unable to swap an array of strings on cell reorder:

```<code>var scatola : [String] = []

override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    swap(&scatola[fromIndexPath.row], &scatola[toIndexPath.row])
}
</code>```

this code throws:

inout writeback to computed property 'scatola' occurs in multiple arguments to call, introducing invalid aliasing

What is the right way to do it?

答:
Starting Xcode 9, you can write:</p>

```<code>@objc override func tableView(_ tableView: UITableView,
                moveRowAt sourceIndexPath: IndexPath,
                  to destinationIndexPath: IndexPath) {
    scatola.swapAt(sourceIndexPath.row, destinationIndexPath.row)
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Swift swap array objects

Body:
I'm unable to swap an array of strings on cell reorder:

var scatola : [String] = []

override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    swap(&scatola[fromIndexPath.row], &scatola[toIndexPath.row])
}

this code throws:

inout writeback to computed property 'scatola' occurs in multiple arguments to call, introducing invalid aliasing

What is the right way to do it?

Body:
Starting Xcode 9, you can write:

@objc override func tableView(_ tableView: UITableView,
                moveRowAt sourceIndexPath: IndexPath,
                  to destinationIndexPath: IndexPath) {
    scatola.swapAt(sourceIndexPath.row, destinationIndexPath.row)
}


问:
Angular 2 throws 'cssText.replace is not a function' when using ExtractTextPlugin
I have two projects: Project A and Project B.

Project A

Webpack@2.2.1

Extract-text-webpack-plugin@2.0.0-rc.3

Angular 2.4.3

Project B

Angular 2.4.3

Project B provides a series of modules/components to Project A.

The code is compiled (not bundled) by Project B into a dist folder which then is being used by Project A via npm link.

Right now, with the webpack.common.js settings using the ExtractTextPlugin the browsers throws an Exception:

This exception is being thrown by Angular 2, but only when this plugin is used.
I am saying this, because if I load .css extensions using raw-loader everything works fine, but when using ExtractTextPlugin, it just breaks.

VALID

webpack.config.js

```<code>module: {
   rules: [
      {
         test: /\.css$/,
         use: [ "raw-loader" ],
      }
   ]
}
</code>```

Output:

INVALID (using ExtractTextPlugin)

webpack.config.js

```<code>module: {
   rules: [
      {
         test: /\.css$/,
         use: ExtractTextPlugin.extract( {
                  fallback: "raw-loader",
                  use: [ "raw-loader" ]
         } )
      }
   }
},
plugins: [
   new ExtractTextPlugin( "[name].css" ),
]
</code>```

Output:

Exception thrown:

```<code>Uncaught TypeError: cssText.replace is not a function
    at extractStyleUrls (http://localhost:8080/vendor.js:75001:52)
</code>```

Node: 6.2.0
OS: macOS Sierra (10.12.2)

答:
Check answer in this Webpack SASS build issue, everything compiles fine, then I get a JS error

In addition to the answer you can either use require or you can simply import those .css files on top of your component.ts file.

Like import '../assets/app.css';

Body:
I have two projects: Project A and Project B.

Project A

Webpack@2.2.1

Extract-text-webpack-plugin@2.0.0-rc.3

Angular 2.4.3

Project B

Angular 2.4.3

Project B provides a series of modules/components to Project A.

The code is compiled (not bundled) by Project B into a dist folder which then is being used by Project A via npm link.

Right now, with the webpack.common.js settings using the ExtractTextPlugin the browsers throws an Exception:

This exception is being thrown by Angular 2, but only when this plugin is used.
I am saying this, because if I load .css extensions using raw-loader everything works fine, but when using ExtractTextPlugin, it just breaks.

VALID

webpack.config.js

module: {
   rules: [
      {
         test: /\.css$/,
         use: [ "raw-loader" ],
      }
   ]
}

Output:

INVALID (using ExtractTextPlugin)

webpack.config.js

module: {
   rules: [
      {
         test: /\.css$/,
         use: ExtractTextPlugin.extract( {
                  fallback: "raw-loader",
                  use: [ "raw-loader" ]
         } )
      }
   }
},
plugins: [
   new ExtractTextPlugin( "[name].css" ),
]

Output:

Exception thrown:

Uncaught TypeError: cssText.replace is not a function
    at extractStyleUrls (http://localhost:8080/vendor.js:75001:52)

Node: 6.2.0
OS: macOS Sierra (10.12.2)


问:
Kernel panic inside mod_timer()
I am writing a program which uses multiple timers. For every 5 seconds, they will use one same netlink to communicate with userspace.

To be more specifically, every 5 seconds each timer will call a func(), the func() will do lock, sending something, unlock, and:

```<code>delay_us(200);
if(!timer_pending(&timer1)){
    mod_timer(&timer1, jiffies+RTL_SECONDS_TO_JIFFIES(5));
}
</code>```

The strange thing is in very few occasion, the system will crash inside mod_timer(), I disassembly and find it crash at tne  zero,v0,0xc

The piece of code (MIPS instructions) is below:

```<code>    /*
     * This is a common optimization triggered by the
     * networking code - if the timer is re-modified
     * to be the same thing then just return:
     */
    if (timer_pending(timer) && timer->expires == expires)
800216bc:   8e020000    lw  v0,0(s0)
800216c0:   50400005    beqzl   v0,800216d8 <mod_timer+0x98>
800216c4:   8e020010    lw  v0,16(s0)
800216c8:   8e020008    lw  v0,8(s0)
800216cc:   10510042    beq v0,s1,800217d8 <mod_timer+0x198>
800216d0:   24130001    li  s3,1
800216d4:   8e020010    lw  v0,16(s0)
800216d8:   2c420001    sltiu   v0,v0,1
800216dc:   00020336    tne zero,v0,0xc
</code>```

I am in great pain to debug. I doubt timer race but technically if so, crash should not inside mod_timer() right? It looks very likely some kind of racing happen but it's beyond my knowledge. Any debug suggestions are appreciated.

EDIT :I just add some important dump message below：

```<code>Call Trace:
[<800243a4>] mod_timer+0x9c/0x1b8
[<8002399c>] call_timer_fn+0x20/0x88
[<80023bd0>] run_timer_softirq+0x1cc/0x244
[<8001de80>] __do_softirq+0x118/0x218
[<8001e05c>] do_softirq+0x58/0x78
[<8001e0e0>] irq_exit+0x64/0x80
[<8000044c>] ret_from_irq+0x0/0x4
[<800036cc>] __copy_user_common+0x44/0x2b8
[<8006701c>] file_read_actor+0x9c/0x114
[<8006a47c>] generic_file_aio_read+0x4f4/0x7f4
[<80092f00>] do_sync_read+0x90/0xd4
[<80093fc8>] vfs_read+0xb0/0x158
[<80094170>] SyS_read+0x60/0x9c
[<800017b0>] stack_done+0x20/0x40

Code: 24130001  8e020010  2c420001 <00020336> 02002021  0c008f12  27a50010  8e030000  10600015
</code>```

EDIT:The callback function is like:

```<code>void send_info(unsigned long task_priv)
{
    unsigned long flags;

    struct target_priv *priv = (struct target_priv *)task_priv;

    SMP_LOCK(flags);

    construct_netlink_send(priv);

    SMP_UNLOCK(flags);

    delay_us(200);

    if ((!strcmp(priv->name, "timer0")) && (!timer_pending(&priv->timer0))){
                mod_timer(&priv->timer0, jiffies+SECONDS_TO_JIFFIES(5));
                    return;
            }
    ...//do same for the rest 9 timers
}
</code>```

答:
this code may cause problem:

```<code>if ((!strcmp(priv->name, "timer0")) && (!timer_pending(&priv->timer0))){
            mod_timer(&priv->timer0, jiffies+SECONDS_TO_JIFFIES(5));
                return;
        }
</code>```

You cannot modify the other timer in the callback. It's may destruct the timer's link.

Title: Kernel panic inside mod_timer()

Body:
I am writing a program which uses multiple timers. For every 5 seconds, they will use one same netlink to communicate with userspace.

To be more specifically, every 5 seconds each timer will call a func(), the func() will do lock, sending something, unlock, and:

delay_us(200);
if(!timer_pending(&timer1)){
    mod_timer(&timer1, jiffies+RTL_SECONDS_TO_JIFFIES(5));
}

The strange thing is in very few occasion, the system will crash inside mod_timer(), I disassembly and find it crash at tne  zero,v0,0xc

The piece of code (MIPS instructions) is below:

    /*
     * This is a common optimization triggered by the
     * networking code - if the timer is re-modified
     * to be the same thing then just return:
     */
    if (timer_pending(timer) && timer->expires == expires)
800216bc:   8e020000    lw  v0,0(s0)
800216c0:   50400005    beqzl   v0,800216d8 <mod_timer+0x98>
800216c4:   8e020010    lw  v0,16(s0)
800216c8:   8e020008    lw  v0,8(s0)
800216cc:   10510042    beq v0,s1,800217d8 <mod_timer+0x198>
800216d0:   24130001    li  s3,1
800216d4:   8e020010    lw  v0,16(s0)
800216d8:   2c420001    sltiu   v0,v0,1
800216dc:   00020336    tne zero,v0,0xc

I am in great pain to debug. I doubt timer race but technically if so, crash should not inside mod_timer() right? It looks very likely some kind of racing happen but it's beyond my knowledge. Any debug suggestions are appreciated.

EDIT :I just add some important dump message below：

Call Trace:
[<800243a4>] mod_timer+0x9c/0x1b8
[<8002399c>] call_timer_fn+0x20/0x88
[<80023bd0>] run_timer_softirq+0x1cc/0x244
[<8001de80>] __do_softirq+0x118/0x218
[<8001e05c>] do_softirq+0x58/0x78
[<8001e0e0>] irq_exit+0x64/0x80
[<8000044c>] ret_from_irq+0x0/0x4
[<800036cc>] __copy_user_common+0x44/0x2b8
[<8006701c>] file_read_actor+0x9c/0x114
[<8006a47c>] generic_file_aio_read+0x4f4/0x7f4
[<80092f00>] do_sync_read+0x90/0xd4
[<80093fc8>] vfs_read+0xb0/0x158
[<80094170>] SyS_read+0x60/0x9c
[<800017b0>] stack_done+0x20/0x40

Code: 24130001  8e020010  2c420001 <00020336> 02002021  0c008f12  27a50010  8e030000  10600015

EDIT:The callback function is like:

void send_info(unsigned long task_priv)
{
    unsigned long flags;

    struct target_priv *priv = (struct target_priv *)task_priv;

    SMP_LOCK(flags);

    construct_netlink_send(priv);

    SMP_UNLOCK(flags);

    delay_us(200);

    if ((!strcmp(priv->name, "timer0")) && (!timer_pending(&priv->timer0))){
                mod_timer(&priv->timer0, jiffies+SECONDS_TO_JIFFIES(5));
                    return;
            }
    ...//do same for the rest 9 timers
}

Body:
this code may cause problem:

if ((!strcmp(priv->name, "timer0")) && (!timer_pending(&priv->timer0))){
            mod_timer(&priv->timer0, jiffies+SECONDS_TO_JIFFIES(5));
                return;
        }

You cannot modify the other timer in the callback. It's may destruct the timer's link.


问:
Changing text and color randomly
I try to write a code that puts on the screen random texts and change the color sometimes( in loop 2).

I don't understand why my code loops just once. It seems that the show() function works by itself but the test() loop doesn't run well.

```<code><script type="text/javascript">//<![CDATA[
    window.onload=function(){
        button.addEventListener('mousedown', function (e) {
            test();
        });
}//]]>

function show() {
    b=makeid();
    document.getElementById("text").innerHTML = b;
}

function test() {
    var div = document.getElementById('text');
    for (i=0;i<5;i++) {b=makeid();
        document.getElementById("text").innerHTML = b;
        if (i==2) {div.style.color = '#000000';}
        setTimeout(function(){ show();},500);
        if (i==2) {div.style.color = '#CC0000';}
    }
}

function makeid() {
    var text = "";
    var possible =     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for( var i=0; i < 2; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

</script>
</head>
<body>
    <button id="button">click</button>
    <div>
        <span id="text"></span>
    </div>
</body>
</code>```

答: you can add 'console' in front of 'show', you can see the loop run 5 times;then you can see how 'setTimeout' work ,you will know why</p>

Title: Changing text and color randomly

Body:
I try to write a code that puts on the screen random texts and change the color sometimes( in loop 2).

I don't understand why my code loops just once. It seems that the show() function works by itself but the test() loop doesn't run well.

    <button id="button">click</button>


问:
Decreasing Performance of Jena function "ResultSetFactory.copyResults()"
I am querying my ontology using SPARQL, but I observe a decreasing performance the more queries I request, the worse it gets. At the beginning the PC needs about 150ms to process the query, the 30. query needs 670ms and the 100. query needs over 7 seconds!
It is depending on the query and/or ontology, but until now, I could find it in every ontology.

The line "ResultSetRewindable r = ResultSetFactory.copyResults(results);" is responsible for the time leak, but also work arounds by avoiding the line lead to similar behaviour.

I used the pizza ontology (https://ontohub.org/pizza/pizza.owl) and the following code. Additionally, I used the Jena version 2.13.

Has anybody an idea how to fix it?

```<code>public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException{
    OntModel model = ModelFactory.createOntologyModel();
    String OWLPath = "pizza.owl";
    String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX pz: <http://www.co-ode.org/ontologies/pizza/pizza.owl#> SELECT DISTINCT ?x WHERE {     ?b owl:someValuesFrom pz:MozzarellaTopping. ?x rdfs:subClassOf ?b.      ?x rdfs:subClassOf* pz:Pizza.}";
    for(int j=0; j<100;j++){
    double starttime = System.currentTimeMillis();
                InputStream in = FileManager.get().open(OWLPath);
        if (in == null) {
            throw new IllegalArgumentException("File: " + OWLPath + " not found");
        }
        model.read(in, "");

        Query query = QueryFactory.create(queryString);
        QueryExecution qe = QueryExecutionFactory.create(query, model);
        ResultSet results = qe.execSelect();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);

        double time1 = System.currentTimeMillis();
        ResultSetRewindable r = ResultSetFactory.copyResults(results);
        double time2 = System.currentTimeMillis();

        ResultSetFormatter.out(ps, r, query);
        String queryOutput = new String(baos.toByteArray(), "UTF-8");
        String[] resultText = queryOutput.split("\n");
        for(int i=0; i<resultText.length;i++){
            System.out.println(resultText[i]);
        }
    double endtime = System.currentTimeMillis();
    System.out.println("Time: "+ (endtime-starttime) +"     Time for ResultSetFactory.copyResults(results): "+ (time2-time1));
    }
 }
</code>```

答:
It is a simple error. The problem is that the model is not cleaned up, every time the ontology is read, the model size increases.
The model can cleaned up with:

```<code>model.removeAll();
</code>```

or the line

```<code>model.read(in, "");
</code>```

can be replaces by

```<code>Model model = ModelFactory.createDefaultModel().read(in, "");
</code>```

It will work without any problem in version 2.13 and 3.3.0. Additionally, the required time decreased by the factor 5, so the performance is better and it runs stable. The second version is only slightly better than the first one.

Body:
I am querying my ontology using SPARQL, but I observe a decreasing performance the more queries I request, the worse it gets. At the beginning the PC needs about 150ms to process the query, the 30. query needs 670ms and the 100. query needs over 7 seconds!
It is depending on the query and/or ontology, but until now, I could find it in every ontology.

The line "ResultSetRewindable r = ResultSetFactory.copyResults(results);" is responsible for the time leak, but also work arounds by avoiding the line lead to similar behaviour.

I used the pizza ontology (https://ontohub.org/pizza/pizza.owl) and the following code. Additionally, I used the Jena version 2.13.

Has anybody an idea how to fix it?

public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException{
    OntModel model = ModelFactory.createOntologyModel();
    String OWLPath = "pizza.owl";
    String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX pz: <http://www.co-ode.org/ontologies/pizza/pizza.owl#> SELECT DISTINCT ?x WHERE {     ?b owl:someValuesFrom pz:MozzarellaTopping. ?x rdfs:subClassOf ?b.      ?x rdfs:subClassOf* pz:Pizza.}";
    for(int j=0; j<100;j++){
    double starttime = System.currentTimeMillis();
                InputStream in = FileManager.get().open(OWLPath);
        if (in == null) {
            throw new IllegalArgumentException("File: " + OWLPath + " not found");
        }
        model.read(in, "");

        Query query = QueryFactory.create(queryString);
        QueryExecution qe = QueryExecutionFactory.create(query, model);
        ResultSet results = qe.execSelect();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);

        double time1 = System.currentTimeMillis();
        ResultSetRewindable r = ResultSetFactory.copyResults(results);
        double time2 = System.currentTimeMillis();

        ResultSetFormatter.out(ps, r, query);
        String queryOutput = new String(baos.toByteArray(), "UTF-8");
        String[] resultText = queryOutput.split("\n");
        for(int i=0; i<resultText.length;i++){
            System.out.println(resultText[i]);
        }
    double endtime = System.currentTimeMillis();
    System.out.println("Time: "+ (endtime-starttime) +"     Time for ResultSetFactory.copyResults(results): "+ (time2-time1));
    }
 }

Body:
It is a simple error. The problem is that the model is not cleaned up, every time the ontology is read, the model size increases.
The model can cleaned up with:

model.removeAll();

or the line

model.read(in, "");

can be replaces by

Model model = ModelFactory.createDefaultModel().read(in, "");

It will work without any problem in version 2.13 and 3.3.0. Additionally, the required time decreased by the factor 5, so the performance is better and it runs stable. The second version is only slightly better than the first one.


问:
convert System.Byte[] to string or image format
We have C# MVC model web app
blob data receiving from oracle and in integration following code is there </p>

```<code>    foreach (DataRow oRow in oDataTable.Rows)
    {
    Rel oUnitData = new Rel();

    if (!string.IsNullOrEmpty(oRow["LOG_SNAP"].ToString()))
    oUnitData.imgdisp = oRow["LOG_SNAP"].ToString();

     lUnitData.Add(oUnitData);
    }

    and for display using javascript file in that datatables
    following part of code

    { data: 'imgdisp', "render": function (data) {

    var str = data
    var base64string = Convert.ToBase64String(str);
    return '<img src="data:image/jpeg;base64,+ base64_decode(str)+">';
    }

    Java Script Code
------------------------------------------------

function LoadImageDispData() {

       var jsontext = JSON.stringify({
       });

       $.ajax({
           url: '/Rel_ProjectStatusUpdate.aspx/LoadImageDisp',
           data: jsontext,
           type: 'POST',
           async: true,
           contentType: 'application/json; charset=utf-8',
           dataType: 'json',
           success: function (result) {

               if (result.d != null) {

                   oTableData = $("#tbl_imagedisp").dataTable().fnDestroy();

                   oTableData = $("#tbl_imagedisp").DataTable({
                       data: result.d,
                       responsive: true,
                       "bAutoWidth": true,
                       "bPaginate": true,
                       "bInfo": true,
                       "bFilter": true,

                       "aoColumns": [

                     { data: 'imgdisp', "render": function (data) {

                         var str = data

                         var base64string = Convert.ToBase64String(str);

                         alert(base64string);

                         return '<img src="data:image/jpeg;base64,+ base64_encode($str)+">';

                     }
                     }

                 ],

                       "columnDefs": [
                    { "visible": false, "targets": [] },
                { className: "dt-left", "targets": [] },
                { className: "dt-center", "targets": [] },
              { className: "dt-right", "targets": [] }
        ],

                       //"order": [[1, 'asc']],

                       dom: 'Bfrtip',
                       buttons: ['copy', 'excel'],

                       "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
                       "iDisplayLength": 25,
                       "bAutoWidth": true,
                       "language": {
                           //
                           //                    "zeroRecords": "Nothing found - sorry",
                           //                    "infoEmpty": "No records available"
                           "emptyTable": "No data available in table"

                       }

                   });

               }

               else {

               }

           }
       });

   }

Data Base Layer Code
----------------------------------------
public DataTable GetImageDisp()
        {
            DataTable oDataTable = new DataTable();
            try
            {
                LoggingManager.LogDetails("WebSiteModel-Begin GetImageDisp");
                List<OracleParameter> lParameterList = new List<OracleParameter>();
                lParameterList.Add(new OracleParameter("O_IMGDATA", OracleDbType.RefCursor, ParameterDirection.Output));
                oDataTable = this.GetDataTableREL("REL_GET_IMAGEDISP", lParameterList);

                if (oDataTable != null)
                    LoggingManager.LogDetails("WebSiteModel-End GetImageDisp", string.Format("GetImageDisp Data Count:{0}", oDataTable.Rows.Count));
                else
                    LoggingManager.LogDetails("WebSiteModel-End GetImageDisp", string.Format("GetImageDisp Data Count:null"));
            }
            catch (Exception oException)
            {
                LoggingManager.LogDetails("WebSiteModel-Exception GetImageDisp", oException);
                ExceptionManager.LogSiteException(oException, "DrishtiCane.Model.WebSite.Implementation.WebSiteModel::GetImageDisp");
            }

            return oDataTable;
        }

Business Layer
--------------------------------

public List<Rel> GetImageDisp()
        {
            DataTable oDataTable = null;
            List<Rel> lUnitData = new List<Rel>();
            try
            {
                LoggingManager.LogDetails("WebSiteIntegration-Begin GetImageDisp");
                oIWebSiteModel = this.ModelFactory.CreateObject<IWebSiteModel>();
                oDataTable = oIWebSiteModel.GetImageDisp();
                if (oDataTable != null)
                {
                    if (oDataTable.Rows != null && oDataTable.Rows.Count > 0)
                    {
                        foreach (DataRow oRow in oDataTable.Rows)
                        {
                            Rel oUnitData = new Rel();

                            if (!string.IsNullOrEmpty(oRow["LOG_SNAP"].ToString()))
                                oUnitData.imgdisp = oRow["LOG_SNAP"].ToString();

                            lUnitData.Add(oUnitData);
                        }
                    }
                    else
                        lUnitData = null;
                }
                else
                    lUnitData = null;

                if (lUnitData != null)
                    LoggingManager.LogDetails("WebSiteIntegration-End GetImageDisp", string.Format("GetImageDisp Data Count:{0}", lUnitData.Count));
                else
                    LoggingManager.LogDetails("WebSiteIntegration-End GetImageDisp", string.Format("GetImageDisp Data Count:null"));

                // LoggingManager.LogDetails("End GetSubCMasterData", string.Format("Legend List Count:{0}", lVillageMasterList.Count));
            }
            catch (Exception oException)
            {
                LoggingManager.LogDetails("WebSiteIntegration-Exception GetImageDisp", oException);
                ExceptionManager.LogSiteException(oException, "DrishtiCane.Integration.WebSite.Implementation.WebSiteIntegration::GetImageDisp");
            }

            return lUnitData;
        }

Code Behind .aspx file
-----------------------------------------
[WebMethod(EnableSession = true)]
        public static List<Rel> LoadImageDisp()
        {
            List<Rel> lDatalist = new List<Rel>();
            try
            {
                IControlViewController oIControlViewController = oContollerFactory.CreateObject<IControlViewController>();
                lDatalist = oIControlViewController.GetImageDisp();
            }

            catch (Exception oException)
            {
                ExceptionManager.LogSiteException(oException, "DrishtiCane.SiteView.Report:LoadImageDisp");
            }

            return lDatalist;

        }
</code>```

<p>We have C# MVC model web app blob data receiving from oracle and in integration following code is there </p>

答:
To be fair, I can't understand your code. And I'm not sure why you want to generate an img tag, rather than create an endpoint that can return the actual image.
However, one issue you have with your img tag is that it expects a string encoded in base 64 format, and I'm not sure what data type your "str" is.

Essentially, to create a base64 string in C#, the following can be used:

```<code>var byteArray = Encoding.UTF8.GetBytes(data);
var base64String = Convert.ToBase64String(byteArray);
</code>```

You may need to include more information in your question for a better response.

Body:
We have C# MVC model web app
blob data receiving from oracle and in integration following code is there

    foreach (DataRow oRow in oDataTable.Rows)
    {
    Rel oUnitData = new Rel();

    if (!string.IsNullOrEmpty(oRow["LOG_SNAP"].ToString()))
    oUnitData.imgdisp = oRow["LOG_SNAP"].ToString();

     lUnitData.Add(oUnitData);
    }

    and for display using javascript file in that datatables
    following part of code

    { data: 'imgdisp', "render": function (data) {

    var str = data
    var base64string = Convert.ToBase64String(str);
    return '';
    }

    Java Script Code
------------------------------------------------

function LoadImageDispData() {

       var jsontext = JSON.stringify({
       });

       $.ajax({
           url: '/Rel_ProjectStatusUpdate.aspx/LoadImageDisp',
           data: jsontext,
           type: 'POST',
           async: true,
           contentType: 'application/json; charset=utf-8',
           dataType: 'json',
           success: function (result) {

               if (result.d != null) {

                   oTableData = $("#tbl_imagedisp").dataTable().fnDestroy();

                   oTableData = $("#tbl_imagedisp").DataTable({
                       data: result.d,
                       responsive: true,
                       "bAutoWidth": true,
                       "bPaginate": true,
                       "bInfo": true,
                       "bFilter": true,

                       "aoColumns": [

                     { data: 'imgdisp', "render": function (data) {

                         var str = data

                         var base64string = Convert.ToBase64String(str);

                         alert(base64string);

                         return '';

                     }
                     }

                 ],

                       "columnDefs": [
                    { "visible": false, "targets": [] },
                { className: "dt-left", "targets": [] },
                { className: "dt-center", "targets": [] },
              { className: "dt-right", "targets": [] }
        ],

                       //"order": [[1, 'asc']],

                       dom: 'Bfrtip',
                       buttons: ['copy', 'excel'],

                       "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
                       "iDisplayLength": 25,
                       "bAutoWidth": true,
                       "language": {
                           //
                           //                    "zeroRecords": "Nothing found - sorry",
                           //                    "infoEmpty": "No records available"
                           "emptyTable": "No data available in table"

                       }

                   });

               }

               else {

               }

           }
       });

   }

Data Base Layer Code
----------------------------------------
public DataTable GetImageDisp()
        {
            DataTable oDataTable = new DataTable();
            try
            {
                LoggingManager.LogDetails("WebSiteModel-Begin GetImageDisp");
                List<OracleParameter> lParameterList = new List<OracleParameter>();
                lParameterList.Add(new OracleParameter("O_IMGDATA", OracleDbType.RefCursor, ParameterDirection.Output));
                oDataTable = this.GetDataTableREL("REL_GET_IMAGEDISP", lParameterList);

                if (oDataTable != null)
                    LoggingManager.LogDetails("WebSiteModel-End GetImageDisp", string.Format("GetImageDisp Data Count:{0}", oDataTable.Rows.Count));
                else
                    LoggingManager.LogDetails("WebSiteModel-End GetImageDisp", string.Format("GetImageDisp Data Count:null"));
            }
            catch (Exception oException)
            {
                LoggingManager.LogDetails("WebSiteModel-Exception GetImageDisp", oException);
                ExceptionManager.LogSiteException(oException, "DrishtiCane.Model.WebSite.Implementation.WebSiteModel::GetImageDisp");
            }

            return oDataTable;
        }

Business Layer
--------------------------------

public List<Rel> GetImageDisp()
        {
            DataTable oDataTable = null;
            List<Rel> lUnitData = new List<Rel>();
            try
            {
                LoggingManager.LogDetails("WebSiteIntegration-Begin GetImageDisp");
                oIWebSiteModel = this.ModelFactory.CreateObject<IWebSiteModel>();
                oDataTable = oIWebSiteModel.GetImageDisp();
                if (oDataTable != null)
                {
                    if (oDataTable.Rows != null && oDataTable.Rows.Count > 0)
                    {
                        foreach (DataRow oRow in oDataTable.Rows)
                        {
                            Rel oUnitData = new Rel();

                            if (!string.IsNullOrEmpty(oRow["LOG_SNAP"].ToString()))
                                oUnitData.imgdisp = oRow["LOG_SNAP"].ToString();

                            lUnitData.Add(oUnitData);
                        }
                    }
                    else
                        lUnitData = null;
                }
                else
                    lUnitData = null;

                if (lUnitData != null)
                    LoggingManager.LogDetails("WebSiteIntegration-End GetImageDisp", string.Format("GetImageDisp Data Count:{0}", lUnitData.Count));
                else
                    LoggingManager.LogDetails("WebSiteIntegration-End GetImageDisp", string.Format("GetImageDisp Data Count:null"));

                // LoggingManager.LogDetails("End GetSubCMasterData", string.Format("Legend List Count:{0}", lVillageMasterList.Count));
            }
            catch (Exception oException)
            {
                LoggingManager.LogDetails("WebSiteIntegration-Exception GetImageDisp", oException);
                ExceptionManager.LogSiteException(oException, "DrishtiCane.Integration.WebSite.Implementation.WebSiteIntegration::GetImageDisp");
            }

            return lUnitData;
        }

Code Behind .aspx file
-----------------------------------------
[WebMethod(EnableSession = true)]
        public static List<Rel> LoadImageDisp()
        {
            List<Rel> lDatalist = new List<Rel>();
            try
            {
                IControlViewController oIControlViewController = oContollerFactory.CreateObject<IControlViewController>();
                lDatalist = oIControlViewController.GetImageDisp();
            }

            catch (Exception oException)
            {
                ExceptionManager.LogSiteException(oException, "DrishtiCane.SiteView.Report:LoadImageDisp");
            }

            return lDatalist;

        }

We have C# MVC model web app blob data receiving from oracle and in integration following code is there

Body:
To be fair, I can't understand your code. And I'm not sure why you want to generate an img tag, rather than create an endpoint that can return the actual image.
However, one issue you have with your img tag is that it expects a string encoded in base 64 format, and I'm not sure what data type your "str" is.

Essentially, to create a base64 string in C#, the following can be used:

var byteArray = Encoding.UTF8.GetBytes(data);
var base64String = Convert.ToBase64String(byteArray);

You may need to include more information in your question for a better response.


问:
why isn't the data from my bundle being sent to the new activity?
For reasons I cannot determine, the name string I am passing to the display activity will not be updated when I change it in the menu setting. I have omitted some excess code but hopefully the concepts are there. In particular, when DisplayName is started, I checked with the debugger and the extras put into the intent do not change from their default values (ie: "John Doe"). I note that when I use the options menu activity to change the name, this change is reflected every time I go back to the options menu. However, when I go to the display screen, the name continues to stay the same.

I am aware that these values are simple enough that they can be kept in static member variables and I wouldn't normally have to deal with the passing of bundles, however I still am curious as to why my code fails to function correctly.

I notice that if I use the menu option to set the name first, then click the display button, the change is reflected. However, after returning to the main screen and changing the name, the display screen continues to keep the same name. This leads me to think that since I press "Back" to return to the main screen from the display activity, then the activity is never killed so it would never change the displayed name. Is this guess correct?

```<code>public class MainScreen extends activity {
  private String mName;
  public static final String EXTRA_NAME = "android.intent.extra.NAME";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mName = "John Doe"

        Button button = (Button) findViewById(R.id.display_button);
        button.setOnClickListener(mDisplayButtonListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, SET_CONTACT_ID, 0, R.string.menu_setName);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case SET_CONTACT_ID:
                Intent intent = new Intent(MainScreen.this, ContactEdit.class);
                intent.putExtra(EXTRA_NAME, mName)
                startActivityForResult(intent, 1);
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            mName = data.getExtras().getString(EXTRA_NAME);
        }
    }

    private OnClickListener mDisplayButtonListener = new OnClickListener() {
      public void onClick(View v) {
        Intent intent = new Intent(MainScreen.this, DisplayName.class);
        intent.putExtra(EXTRA_NAME, mName);
        startActivity(intent);
      }
    };
}

public class ContactEdit extends Activity {
  private EditText mEditName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mEditName = (EditText) findViewById(R.id.editName);
    mEditName.setText(this.getIntent().getExtras().getString(MainScreen.EXTRA_NAME));

    Button button = (Button) findViewById(R.id.submit_select);
    button.setOnClickListener(mSubmitName);
  }

  private OnClickListener mSubmitName = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Intent intent = new Intent();
      mName = mEditName.getText().toString();
      intent.putExtra(MainScreen.EXTRA_NAME, mName);
      setResult(RESULT_OK, intent);
      finish();
    }
  }
}

public class DisplayName extends Activity {
  private String mName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mName = getIntent.getExtras().getString(MainScreen.EXTRA_NAME)
    TextView view = (TextView) findViewById(R.id.name);
    view.setText(mName);
  }
}
</code>```

答:
Some times you use "Name" as the key to get the value from the intent and other times you use "NAME". Always use the same and try again.

Thats why you should have a static const string field instead of hardcoding that value everywhere

ContentLicense: CC BY-SA 2.5

Body:
For reasons I cannot determine, the name string I am passing to the display activity will not be updated when I change it in the menu setting. I have omitted some excess code but hopefully the concepts are there. In particular, when DisplayName is started, I checked with the debugger and the extras put into the intent do not change from their default values (ie: "John Doe"). I note that when I use the options menu activity to change the name, this change is reflected every time I go back to the options menu. However, when I go to the display screen, the name continues to stay the same.

I am aware that these values are simple enough that they can be kept in static member variables and I wouldn't normally have to deal with the passing of bundles, however I still am curious as to why my code fails to function correctly.

I notice that if I use the menu option to set the name first, then click the display button, the change is reflected. However, after returning to the main screen and changing the name, the display screen continues to keep the same name. This leads me to think that since I press "Back" to return to the main screen from the display activity, then the activity is never killed so it would never change the displayed name. Is this guess correct?

public class MainScreen extends activity {
  private String mName;
  public static final String EXTRA_NAME = "android.intent.extra.NAME";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mName = "John Doe"

        Button button = (Button) findViewById(R.id.display_button);
        button.setOnClickListener(mDisplayButtonListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, SET_CONTACT_ID, 0, R.string.menu_setName);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case SET_CONTACT_ID:
                Intent intent = new Intent(MainScreen.this, ContactEdit.class);
                intent.putExtra(EXTRA_NAME, mName)
                startActivityForResult(intent, 1);
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            mName = data.getExtras().getString(EXTRA_NAME);
        }
    }

    private OnClickListener mDisplayButtonListener = new OnClickListener() {
      public void onClick(View v) {
        Intent intent = new Intent(MainScreen.this, DisplayName.class);
        intent.putExtra(EXTRA_NAME, mName);
        startActivity(intent);
      }
    };
}

public class ContactEdit extends Activity {
  private EditText mEditName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mEditName = (EditText) findViewById(R.id.editName);
    mEditName.setText(this.getIntent().getExtras().getString(MainScreen.EXTRA_NAME));

    Button button = (Button) findViewById(R.id.submit_select);
    button.setOnClickListener(mSubmitName);
  }

  private OnClickListener mSubmitName = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Intent intent = new Intent();
      mName = mEditName.getText().toString();
      intent.putExtra(MainScreen.EXTRA_NAME, mName);
      setResult(RESULT_OK, intent);
      finish();
    }
  }
}

public class DisplayName extends Activity {
  private String mName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mName = getIntent.getExtras().getString(MainScreen.EXTRA_NAME)
    TextView view = (TextView) findViewById(R.id.name);
    view.setText(mName);
  }
}


问:
How to return images via Web API
I get the '414 (Request-URI Too Long)' error when returning my image as a Base64 encoded string via the web api.

I currently have the following Action in my Web API Controller:

```<code>[System.Web.Http.Route("GetAllEvents")]
public async Task<IEnumerable<Event>> Get()
{
    var vm = EventsViewModel.NewInstance;
    return await vm.GetAllEvents();
}
</code>```

And the vm.GetAllEvents() code:

```<code>public async Task<List<Event>> GetAllEvents()
    {
        var result = await DataStore.SelectAll();

        result.ForEach(x =>
        {
            var byteArray = File.ReadAllBytes(x.ThumbnailPath);
            x.ThumbnailEncoded = Convert.ToBase64String(byteArray);
        });

        return result;
    }
</code>```

I consume the WebAPI action as follow:

```<code>this.ajaxRetrieve = function(url, data, onSuccessCallback, onErrorCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        async: false,
        dataType: 'JSON',
        success: function(result) {
            onSuccessCallback(result);
        },
        error: function(xhr, status, error) {
            onErrorCallback(xhr, status, error);
        }
    });
}
</code>```

What would be the better approach to take, to avoid this from happening?

答:
i strongly suggest to you use stream instead of Base64String. its efficient and fast. here you can find the good example:
Returning binary file from controller in ASP.NET Web API

UPDATE
but you cant return array of streams with web api. so alternative option is byte array. something like this:

```<code>[HttpGet]
public async Task<List<byte[]>> Get()
{
    var files= await GetAllEvents();

    return files;
}
</code>```

And the GetAllEvents() code:

```<code>public async Task<List<byte[]>> GetAllEvents()
{
    var list = new List<byte[]>();
    for (int i = 0; i < 5; i++)
    {
        var byteArray = await Task.Run(() => System.IO.File.ReadAllBytes(@"filePath"));
        list.Add(byteArray);
    }
    return list;
}
</code>```

hope this could solve your problem.

Title: How to return images via Web API

Body:
I get the '414 (Request-URI Too Long)' error when returning my image as a Base64 encoded string via the web api.

I currently have the following Action in my Web API Controller:

[System.Web.Http.Route("GetAllEvents")]
public async Task<IEnumerable<Event>> Get()
{
    var vm = EventsViewModel.NewInstance;
    return await vm.GetAllEvents();
}

And the vm.GetAllEvents() code:

public async Task<List<Event>> GetAllEvents()
    {
        var result = await DataStore.SelectAll();

        result.ForEach(x =>
        {
            var byteArray = File.ReadAllBytes(x.ThumbnailPath);
            x.ThumbnailEncoded = Convert.ToBase64String(byteArray);
        });

        return result;
    }

I consume the WebAPI action as follow:

this.ajaxRetrieve = function(url, data, onSuccessCallback, onErrorCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        async: false,
        dataType: 'JSON',
        success: function(result) {
            onSuccessCallback(result);
        },
        error: function(xhr, status, error) {
            onErrorCallback(xhr, status, error);
        }
    });
}

What would be the better approach to take, to avoid this from happening?

Body:
i strongly suggest to you use stream instead of Base64String. its efficient and fast. here you can find the good example:
Returning binary file from controller in ASP.NET Web API

UPDATE
but you cant return array of streams with web api. so alternative option is byte array. something like this:

[HttpGet]
public async Task<List<byte[]>> Get()
{
    var files= await GetAllEvents();

    return files;
}

And the GetAllEvents() code:

public async Task<List<byte[]>> GetAllEvents()
{
    var list = new List<byte[]>();
    for (int i = 0; i < 5; i++)
    {
        var byteArray = await Task.Run(() => System.IO.File.ReadAllBytes(@"filePath"));
        list.Add(byteArray);
    }
    return list;
}

hope this could solve your problem.


问:
Unable to add reference in Visual Studio
I have a project in VS 2017 all was working well until I update Mysql connector and hence mysql.data reference.

As you can see in the picture, when I open the reference dialog box, only come up the new version of the referenceand when i try to select it and save, an error arises:

The error says: "Already exists a reference to 'MySql.Data' in the project"

The question is: How can I remove the older reference? It's not shown in the dialogbox and do not know where to find it.

Any help;

答:
You could take a look at the Solution Explorer of your project:

And remove the reference by pressing delete or right click and Remove.
You can open the Solution Explorer by View -> Solution Explorer:

Or pressing Ctrl + W, S


问:
Unable to POST data to WCF rest service when using transport security and client certificates
I have a self-hosted WCF REST service based on the WebHttpBinding.  One of the methods on the service looks something like this:

```<code>    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "myMethod")]
    Stream MyMethod(Stream contents);
</code>```

I wrote a simple test program that creates a HttpWebRequest to try and POST data to this method.  This works fine in the following scenarios:

Service is not using any security.

Service is using transport security without client certificate.

Service is using transport security with client certificate and I POST 0 bytes.

If I try to use transport security with a client certificate a POST more than 0 bytes, the service returns HTTP 403 (forbidden), and it never hits any of my code.

This is driving me nuts.

Any ideas?

UPDATE

After enabling tracing for http.sys, I observed the following message in the trace:

Attempt by server application to receive client certificate failed with status: 0xC0000225.

Does anyone know what this means?  I'm certain that I'm sending the client certificate and certain that it's trusted by the host machine.

答:
You probably need to set a SSL certificate for your local host.

1) Run --> "mmc"

2) File --> Add/Remove Snap-In...

3) Under "Available snap-ins" select "Certificates" and "Add > "

4) Select "Computer account"

5) Click "Next"

6) Click "Finish"

7) Click "Ok"

8) Look in Personal --> Certificates I think you should have a 127.0.0.1

9) Click and drag that certificate to "Trusted Root Certificate Authorities"

Then whatever address you use, you need to change that URL to 127.0.0.1 (not localhost) as that won't work. The certificate should then be valid and I think you will be able to get past authorization.

If you are having other problems then it's probably not your certificate, so ensure your services, behaviors and bindings are accurate.

A way to help you use WCF tracing to see what exactly the problem might after that, I will shamelessly point you to my blog post. :)

http://jtstroup.net/post/Wcf-Tracing.aspx

Good luck.

Body:
I have a self-hosted WCF REST service based on the WebHttpBinding.  One of the methods on the service looks something like this:

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "myMethod")]
    Stream MyMethod(Stream contents);

I wrote a simple test program that creates a HttpWebRequest to try and POST data to this method.  This works fine in the following scenarios:

Service is not using any security.

Service is using transport security without client certificate.

Service is using transport security with client certificate and I POST 0 bytes.

If I try to use transport security with a client certificate a POST more than 0 bytes, the service returns HTTP 403 (forbidden), and it never hits any of my code.

This is driving me nuts.

Any ideas?

UPDATE

After enabling tracing for http.sys, I observed the following message in the trace:

Attempt by server application to receive client certificate failed with status: 0xC0000225.

Does anyone know what this means?  I'm certain that I'm sending the client certificate and certain that it's trusted by the host machine.


问:
Set input date and add it to list
Basically, i want to set dates and save it to a list. From my code below:

```<code>public List<RecordList> createRecord(BigDecimal yr){

    for (int index = 0; index <= 14; index++) {
        RecordList value = new RecordList();
        if(index == 0){
            value.setStartDt(toDate(("01-04-" + yr)));
            value.setEndDt(toDate(("30-04-" + yr)));
        }
        if(index == 1){
            value.setStartDt(toDate(("01-05-" + yr.add(new BigDecimal(1)))));
            value.setEndDt(toDate(("31-05-" + yr.add(new BigDecimal(1)))));
        }
        createRecord.add(newRecordValue);
    return createRecord;
}

private Date toDate(String date) {
    Date newDate = null;
    try {
        newDate = new SimpleDateFormat("dd-MM-YYYY").parse(date);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }
    return newDate;
}
</code>```

what happens is, when I set the year to 2017, the output doesnt match with what I set:

```<code>"StartDate": "30-12-2017",
 "EndDate": "30-12-2017"
</code>```

and it doesnt increment to next year, instead it decrement to:

```<code>"StartDate": "30-12-2016",
 "EndDate": "30-12-2016"
</code>```

答:
upper case Y is week year. You have to use lower case y for the calendar year:

```<code>newDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);
</code>```

For more Information read the Javadoc of SimpleDateFormat

Title: Set input date and add it to list

Body:
Basically, i want to set dates and save it to a list. From my code below:

public List<RecordList> createRecord(BigDecimal yr){

    for (int index = 0; index <= 14; index++) {
        RecordList value = new RecordList();
        if(index == 0){
            value.setStartDt(toDate(("01-04-" + yr)));
            value.setEndDt(toDate(("30-04-" + yr)));
        }
        if(index == 1){
            value.setStartDt(toDate(("01-05-" + yr.add(new BigDecimal(1)))));
            value.setEndDt(toDate(("31-05-" + yr.add(new BigDecimal(1)))));
        }
        createRecord.add(newRecordValue);
    return createRecord;
}

private Date toDate(String date) {
    Date newDate = null;
    try {
        newDate = new SimpleDateFormat("dd-MM-YYYY").parse(date);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }
    return newDate;
}

what happens is, when I set the year to 2017, the output doesnt match with what I set:

"StartDate": "30-12-2017",
 "EndDate": "30-12-2017"

and it doesnt increment to next year, instead it decrement to:

"StartDate": "30-12-2016",
 "EndDate": "30-12-2016"

Body:
upper case Y is week year. You have to use lower case y for the calendar year:

newDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);

For more Information read the Javadoc of SimpleDateFormat


问:
How to best implement model delta (PUT/PATCH) in vue.js?
I have a POJO that I pass to a vue component - obviously, this object's values can be updated by vue's two-way data binding.

Having used backbone.js for a few years and having grown accustomed to models being instances of Backbone.Model that kept track of their changed properties, I have a hard time wrapping my head around how one would best implement a toJSONDelta()-like functionality (returning a copy of all changed properties of my vue component's data) "the vue way".

答:
Maybe you can use something like:

```<code>var app = new Vue({
        el: "#root",
        data: {
            a: 10,
            b: 20,
            c: {
                loveJS: true,
                vue: "isAwesome"
            }
        },
        methods: {
            track: (function(history){
                return function(n){
                    history.push(n)
                    console.log(history)
                }
            })([ /* history store */ ])
        },
        mounted: function(){
            this.$watch("$data", function(n){
                this.track( JSON.parse(JSON.stringify(n)) ) // to remove watchers
            }, { deep: true, immediate: true});
        }
    })
</code>```

Then, you can use something like recursive-diff to compare and generate diff between any two points in history or push the new object into something like object-history which will then manage the history for you.

Body:
Maybe you can use something like:

var app = new Vue({
        el: "#root",
        data: {
            a: 10,
            b: 20,
            c: {
                loveJS: true,
                vue: "isAwesome"
            }
        },
        methods: {
            track: (function(history){
                return function(n){
                    history.push(n)
                    console.log(history)
                }
            })([ /* history store */ ])
        },
        mounted: function(){
            this.$watch("$data", function(n){
                this.track( JSON.parse(JSON.stringify(n)) ) // to remove watchers
            }, { deep: true, immediate: true});
        }
    })

Then, you can use something like recursive-diff to compare and generate diff between any two points in history or push the new object into something like object-history which will then manage the history for you.


问:
What error is there in the jQuery
Below in the code the vanilla javascript version works fine but the jQuery one I tried to code does not produce the update to the input's text. What error is there in the jQuery one as I cannot seem to spot it.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title> Total Tutor </title>
  <link type="text/css" rel="stylesheet" href="query.css">

    <button class="fileUpload">
<input id="uploadBtn" type="file" class="upload">
</button>
    <input id="uploadFile" placeholder="0 files selected" disabled="disabled">

```

答:
Please try this : </p>

```<code>$(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       alert(fileName);
       // do whatever you want to do with file name
     });
 });
</code>```

Title: What error is there in the jQuery

Body:
Please try this :

$(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       alert(fileName);
       // do whatever you want to do with file name
     });
 });


问:
How can I pull in files by extension from latest state of remote repo on top of old local repo?
I have reset my repo to old commit, now how can I pull in latest .properties files on top of it, from a remote repo, not my origin.</p>

答:
This answer assumes that are using the master branch, which locally you have reset to some earlier commit.  You can achieve what you want by first fetching the latest master from the repo.  Then checkout your single properties file from that latest remote master branch.

```<code># update your origin/master with the latest from the remote
git fetch origin

# switch to the master branch (or another branch)
git checkout master

# checkout the properties file from the latest remote master
git checkout origin/master -- path/to/file.properties
</code>```

Body:
This answer assumes that are using the master branch, which locally you have reset to some earlier commit.  You can achieve what you want by first fetching the latest master from the repo.  Then checkout your single properties file from that latest remote master branch.

# update your origin/master with the latest from the remote
git fetch origin

# switch to the master branch (or another branch)
git checkout master

# checkout the properties file from the latest remote master
git checkout origin/master -- path/to/file.properties


问:
How can I see what SQL Is doing?
Imagine that I have a database with Name and age and i want to insert a person to that database so I'll do:

```<code>SQL="INSERT INTO Person(Name,Age) VALUES ('" & Name & "'," & Age &")"
</code>```

And in my interface I Insert the Name: Nick and age:25.

How can I see in my interface what SQL is doing for example:

```<code>INSERT INTO Person(Nick,25)
</code>```

PS: Programming this in classic asp. I've seen it done through a simple Response.Write, but I don't remember how it was done.

Hope it was clear to understand, and thank you for all the help

答:
More to compliment @kblok's answer than to undermine it:

I strongly advise that you download Microsoft SQL Server Management Studio Express, if you haven't done so already, and test your statements there, or, even better, use it to write parameterised stored procedures.

When using stored procedures you can simply call it by using the appropriate settings in your Connection object...

```<code>Set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = myConn
Set comm = Server.CreateObject("ADODB.Command")
comm.ActiveConnection  = conn
comm.CommandText = "prc_get_data"
comm.CommandType = 4 'Stored procedure
</code>```

Though the documentation is a little flaky now, I would recommend you take a look at the Microsoft Documentation for this.

Title: How can I see what SQL Is doing?

Body:
Imagine that I have a database with Name and age and i want to insert a person to that database so I'll do:

SQL="INSERT INTO Person(Name,Age) VALUES ('" & Name & "'," & Age &")"

And in my interface I Insert the Name: Nick and age:25.

How can I see in my interface what SQL is doing for example:

INSERT INTO Person(Nick,25)

PS: Programming this in classic asp. I've seen it done through a simple Response.Write, but I don't remember how it was done.

Hope it was clear to understand, and thank you for all the help

Body:
More to compliment @kblok's answer than to undermine it:

I strongly advise that you download Microsoft SQL Server Management Studio Express, if you haven't done so already, and test your statements there, or, even better, use it to write parameterised stored procedures.

When using stored procedures you can simply call it by using the appropriate settings in your Connection object...

Set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = myConn
Set comm = Server.CreateObject("ADODB.Command")
comm.ActiveConnection  = conn
comm.CommandText = "prc_get_data"
comm.CommandType = 4 'Stored procedure

Though the documentation is a little flaky now, I would recommend you take a look at the Microsoft Documentation for this.


问:
How to reset AUTO_INCREMENT in MySQL for all tables within a DB?
Is there a way to run this or similiar AUTO_INCREMENT command for all tables in a database?</p>

```<code>ALTER TABLE tablename AUTO_INCREMENT = 1
</code>```

答:
You can use xargs (replace DB_NAME):

```<code>mysql -Nsr -e "SELECT t.table_name FROM INFORMATION_SCHEMA.TABLES t WHERE t.table_schema = 'DB_NAME' AND table_type = 'BASE TABLE'" | xargs -I {} mysql DB_NAME -e "ALTER TABLE {} AUTO_INCREMENT = 1;"
</code>```

Body:
Is there a way to run this or similiar AUTO_INCREMENT command for all tables in a database?

ALTER TABLE tablename AUTO_INCREMENT = 1

Body:
You can use xargs (replace DB_NAME):

mysql -Nsr -e "SELECT t.table_name FROM INFORMATION_SCHEMA.TABLES t WHERE t.table_schema = 'DB_NAME' AND table_type = 'BASE TABLE'" | xargs -I {} mysql DB_NAME -e "ALTER TABLE {} AUTO_INCREMENT = 1;"