问:
Consuming BlockingCollection with multiple consumers
I have a program as follows

```<code> class Program
    {
        public static int TaskCount { get; set; }
        public static BlockingCollection<string> queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
        static void Main(string[] args)
        {
            TaskCount = 3;
            Task.Factory.StartNew(() => Producer());

            for (int i = 0; i < TaskCount; i++)
                Task.Factory.StartNew(() => Consumer());
            Console.ReadKey();
        }

        private static void Producer()
        {
            using (StreamWriter sw = File.AppendText(@"C:\pcadder.txt"))
            {
                for (int i = 0; i < 15; i++)
                {
                    queue.Add("Item: " + (i+1).ToString());
                    var message = string.Format("{2}.Item added: Item {0} at {1}", (i+1).ToString(), DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),i+1);
                    Console.WriteLine(message);
                    sw.WriteLine(message);

                }
                queue.CompleteAdding();
            }
        }
        private static void Consumer()
        {
            int count = 1;
            foreach (var item in queue.GetConsumingEnumerable())
            {
                var message = string.Format("{3}.Item taken: {0} at {1} by thread {2}.", item, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),
                        Thread.CurrentThread.ManagedThreadId,count);
                Console.WriteLine(message);

                using (StreamWriter sw = File.AppendText(@"C:\pctaker.txt"))
                    sw.WriteLine(message);
                count += 1;
            }
        }
    }
</code>```

The Output

```<code>1.Item added: Item 1 at 2017.07.06 09:58:49.784734
2.Item added: Item 2 at 2017.07.06 09:58:49.784734
3.Item added: Item 3 at 2017.07.06 09:58:49.784734
4.Item added: Item 4 at 2017.07.06 09:58:49.784734
5.Item added: Item 5 at 2017.07.06 09:58:49.784734
6.Item added: Item 6 at 2017.07.06 09:58:49.784734
7.Item added: Item 7 at 2017.07.06 09:58:49.784734
8.Item added: Item 8 at 2017.07.06 09:58:49.784734
9.Item added: Item 9 at 2017.07.06 09:58:49.784734
10.Item added: Item 10 at 2017.07.06 09:58:49.784734
11.Item added: Item 11 at 2017.07.06 09:58:49.784734
12.Item added: Item 12 at 2017.07.06 09:58:49.784734
13.Item added: Item 13 at 2017.07.06 09:58:49.784734
14.Item added: Item 14 at 2017.07.06 09:58:49.784734
15.Item added: Item 15 at 2017.07.06 09:58:49.784734

1.Item taken: Item: 3 at 2017.07.06 09:58:49.784734 by thread 7.
1.Item taken: Item: 2 at 2017.07.06 09:58:49.784734 by thread 4.
1.Item taken: Item: 1 at 2017.07.06 09:58:49.784734 by thread 5.
2.Item taken: Item: 5 at 2017.07.06 09:58:49.784734 by thread 4.
2.Item taken: Item: 4 at 2017.07.06 09:58:49.784734 by thread 7.
2.Item taken: Item: 6 at 2017.07.06 09:58:49.784734 by thread 5.
3.Item taken: Item: 7 at 2017.07.06 09:58:49.784734 by thread 4.
3.Item taken: Item: 8 at 2017.07.06 09:58:49.784734 by thread 7.
3.Item taken: Item: 9 at 2017.07.06 09:58:49.784734 by thread 5.
4.Item taken: Item: 11 at 2017.07.06 09:58:49.784734 by thread 7.
4.Item taken: Item: 12 at 2017.07.06 09:58:49.784734 by thread 5.
5.Item taken: Item: 13 at 2017.07.06 09:58:49.784734 by thread 7.
5.Item taken: Item: 14 at 2017.07.06 09:58:49.784734 by thread 5.
6.Item taken: Item: 15 at 2017.07.06 09:58:49.784734 by thread 7.
</code>```

After almost every running the program, I have one item missing in consumer logs.(Here, Item 10 is missing). I could't catch why this is happening.

How does not this item processed?

While using multiple tasks as consumer, is processing items in order (FIFO) being spoiled? If I want to keep/force processing in FIFO order inside the consumer method, should I avoid using multiple tasks? (Processing may include I/O,Networking operations)

答:
If you want to ensure that the output from a parallel processing block is in the same order as its input, you will have to mess around with something like a Priority Queue if you want to use BlockingCollection.

However, there is a much easier way if you're prepared to use the more modern DataFlow library (part of the Task Parallel Library).

Here's a sample program. Note that this uses await but that's not necessary to use DataFlow. The item type in the queue is int, but you can specify any type - int just happens to be a simple way to demonstrate.

The important thing to note about this sample program is that the input items are processed in parallel by multiple threads, but the final output is still in the same order as it was input.

If you look out the ouput "Returning X from thread Y" you'll see that X is not always in the same order that it was queued. The worker threads can return the data in non-input order.

But if you look at the output "Outputting X" you'll see that X is in the same order that it was queued (monotonically increasing).

The output queue has ensured that the output is in the correct order.

```<code>using System;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

namespace ConsoleApp1
{
    public class Program
    {
        static void Main()
        {
            var inQueue  = new TransformBlock<int, int>(item => process(item), processBlockOptions());
            var outQueue = new ActionBlock<int>(item => output(item), outputBlockOptions());

            inQueue.LinkTo(outQueue, new DataflowLinkOptions {PropagateCompletion = true});

            var task = queueData(inQueue);

            Console.WriteLine("Waiting for task to complete in thread " + Thread.CurrentThread.ManagedThreadId);
            task.Wait();
            Console.WriteLine("Completed.");
        }

        static async Task queueData(TransformBlock<int, int> executor)
        {
            await enqueue(executor);

            Console.WriteLine("Indicating that no more data will be queued.");
            executor.Complete(); // Indicate that no more items will be queued.

            Console.WriteLine("Waiting for queue to empty.");
            await executor.Completion; // Wait for executor queue to empty.
        }

        static async Task enqueue(TransformBlock<int, int> executor)
        {
            for (int i = 0; i < 100; ++i)
            {
                Console.WriteLine("Queuing data " + i);
                int v = i;
                await executor.SendAsync(v); // Queues a method that returns v.
            }
        }

        static int process(int value)  // Procss value by adding 1000 to it.
        {
            Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is processing item {value}");
            value += 1000;
            Thread.Sleep(150+nextRand());  // Simulate work.
            Console.WriteLine($"Returning {value} from thread {Thread.CurrentThread.ManagedThreadId}");

            return value;
        }

        static void output(int value)
        {
            Console.WriteLine($"Outputting {value}");
        }

        static ExecutionDataflowBlockOptions processBlockOptions()
        {
            return new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = 4,
                BoundedCapacity = 8
            };
        }

        static ExecutionDataflowBlockOptions outputBlockOptions()
        {
            return new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = 1,
                BoundedCapacity = 1
            };
        }

        static int nextRand()
        {
            lock (rngLock)
            {
                return rng.Next(250);
            }
        }

        static Random rng = new Random();
        static object rngLock = new object();
    }
}
</code>```

It's interesting to play around with the values of MaxDegreeOfParallelism and BoundedCapacity returned from processBlockOptions().

For example, try it with MaxDegreeOfParallelism  8 and BoundedCapacity = 16.

[EDIT] To answer your question about "How does not this item processed?" - I suspect it's because your output logging is not threadsafe (as per the good answer from Evk)

Body:
I have a program as follows

 class Program
    {
        public static int TaskCount { get; set; }
        public static BlockingCollection<string> queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
        static void Main(string[] args)
        {
            TaskCount = 3;
            Task.Factory.StartNew(() => Producer());

            for (int i = 0; i < TaskCount; i++)
                Task.Factory.StartNew(() => Consumer());
            Console.ReadKey();
        }

        private static void Producer()
        {
            using (StreamWriter sw = File.AppendText(@"C:\pcadder.txt"))
            {
                for (int i = 0; i < 15; i++)
                {
                    queue.Add("Item: " + (i+1).ToString());
                    var message = string.Format("{2}.Item added: Item {0} at {1}", (i+1).ToString(), DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),i+1);
                    Console.WriteLine(message);
                    sw.WriteLine(message);

                }
                queue.CompleteAdding();
            }
        }
        private static void Consumer()
        {
            int count = 1;
            foreach (var item in queue.GetConsumingEnumerable())
            {
                var message = string.Format("{3}.Item taken: {0} at {1} by thread {2}.", item, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),
                        Thread.CurrentThread.ManagedThreadId,count);
                Console.WriteLine(message);

                using (StreamWriter sw = File.AppendText(@"C:\pctaker.txt"))
                    sw.WriteLine(message);
                count += 1;
            }
        }
    }

The Output

1.Item added: Item 1 at 2017.07.06 09:58:49.784734
2.Item added: Item 2 at 2017.07.06 09:58:49.784734
3.Item added: Item 3 at 2017.07.06 09:58:49.784734
4.Item added: Item 4 at 2017.07.06 09:58:49.784734
5.Item added: Item 5 at 2017.07.06 09:58:49.784734
6.Item added: Item 6 at 2017.07.06 09:58:49.784734
7.Item added: Item 7 at 2017.07.06 09:58:49.784734
8.Item added: Item 8 at 2017.07.06 09:58:49.784734
9.Item added: Item 9 at 2017.07.06 09:58:49.784734
10.Item added: Item 10 at 2017.07.06 09:58:49.784734
11.Item added: Item 11 at 2017.07.06 09:58:49.784734
12.Item added: Item 12 at 2017.07.06 09:58:49.784734
13.Item added: Item 13 at 2017.07.06 09:58:49.784734
14.Item added: Item 14 at 2017.07.06 09:58:49.784734
15.Item added: Item 15 at 2017.07.06 09:58:49.784734

1.Item taken: Item: 3 at 2017.07.06 09:58:49.784734 by thread 7.
1.Item taken: Item: 2 at 2017.07.06 09:58:49.784734 by thread 4.
1.Item taken: Item: 1 at 2017.07.06 09:58:49.784734 by thread 5.
2.Item taken: Item: 5 at 2017.07.06 09:58:49.784734 by thread 4.
2.Item taken: Item: 4 at 2017.07.06 09:58:49.784734 by thread 7.
2.Item taken: Item: 6 at 2017.07.06 09:58:49.784734 by thread 5.
3.Item taken: Item: 7 at 2017.07.06 09:58:49.784734 by thread 4.
3.Item taken: Item: 8 at 2017.07.06 09:58:49.784734 by thread 7.
3.Item taken: Item: 9 at 2017.07.06 09:58:49.784734 by thread 5.
4.Item taken: Item: 11 at 2017.07.06 09:58:49.784734 by thread 7.
4.Item taken: Item: 12 at 2017.07.06 09:58:49.784734 by thread 5.
5.Item taken: Item: 13 at 2017.07.06 09:58:49.784734 by thread 7.
5.Item taken: Item: 14 at 2017.07.06 09:58:49.784734 by thread 5.
6.Item taken: Item: 15 at 2017.07.06 09:58:49.784734 by thread 7.

After almost every running the program, I have one item missing in consumer logs.(Here, Item 10 is missing). I could't catch why this is happening.

How does not this item processed?

While using multiple tasks as consumer, is processing items in order (FIFO) being spoiled? If I want to keep/force processing in FIFO order inside the consumer method, should I avoid using multiple tasks? (Processing may include I/O,Networking operations)

Body:
If you want to ensure that the output from a parallel processing block is in the same order as its input, you will have to mess around with something like a Priority Queue if you want to use BlockingCollection.

However, there is a much easier way if you're prepared to use the more modern DataFlow library (part of the Task Parallel Library).

Here's a sample program. Note that this uses await but that's not necessary to use DataFlow. The item type in the queue is int, but you can specify any type - int just happens to be a simple way to demonstrate.

The important thing to note about this sample program is that the input items are processed in parallel by multiple threads, but the final output is still in the same order as it was input.

If you look out the ouput "Returning X from thread Y" you'll see that X is not always in the same order that it was queued. The worker threads can return the data in non-input order.

But if you look at the output "Outputting X" you'll see that X is in the same order that it was queued (monotonically increasing).

The output queue has ensured that the output is in the correct order.

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

namespace ConsoleApp1
{
    public class Program
    {
        static void Main()
        {
            var inQueue  = new TransformBlock<int, int>(item => process(item), processBlockOptions());
            var outQueue = new ActionBlock<int>(item => output(item), outputBlockOptions());

            inQueue.LinkTo(outQueue, new DataflowLinkOptions {PropagateCompletion = true});

            var task = queueData(inQueue);

            Console.WriteLine("Waiting for task to complete in thread " + Thread.CurrentThread.ManagedThreadId);
            task.Wait();
            Console.WriteLine("Completed.");
        }

        static async Task queueData(TransformBlock<int, int> executor)
        {
            await enqueue(executor);

            Console.WriteLine("Indicating that no more data will be queued.");
            executor.Complete(); // Indicate that no more items will be queued.

            Console.WriteLine("Waiting for queue to empty.");
            await executor.Completion; // Wait for executor queue to empty.
        }

        static async Task enqueue(TransformBlock<int, int> executor)
        {
            for (int i = 0; i < 100; ++i)
            {
                Console.WriteLine("Queuing data " + i);
                int v = i;
                await executor.SendAsync(v); // Queues a method that returns v.
            }
        }

        static int process(int value)  // Procss value by adding 1000 to it.
        {
            Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is processing item {value}");
            value += 1000;
            Thread.Sleep(150+nextRand());  // Simulate work.
            Console.WriteLine($"Returning {value} from thread {Thread.CurrentThread.ManagedThreadId}");

            return value;
        }

        static void output(int value)
        {
            Console.WriteLine($"Outputting {value}");
        }

        static ExecutionDataflowBlockOptions processBlockOptions()
        {
            return new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = 4,
                BoundedCapacity = 8
            };
        }

        static ExecutionDataflowBlockOptions outputBlockOptions()
        {
            return new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = 1,
                BoundedCapacity = 1
            };
        }

        static int nextRand()
        {
            lock (rngLock)
            {
                return rng.Next(250);
            }
        }

        static Random rng = new Random();
        static object rngLock = new object();
    }
}

It's interesting to play around with the values of MaxDegreeOfParallelism and BoundedCapacity returned from processBlockOptions().

For example, try it with MaxDegreeOfParallelism  8 and BoundedCapacity = 16.

[EDIT] To answer your question about "How does not this item processed?" - I suspect it's because your output logging is not threadsafe (as per the good answer from Evk)


来源: stackexchange

问:
sprintf rounding
Why does the following produce different results?

```<code>echo 2.55 * 100;
echo sprintf(' %d', 2.55 * 100);
</code>```

output:

```<code>255 254
</code>```

答:
Because 2.55 * 100 in base 2 fixed size representation is not an integer and %d does not round:

```<code>var_dump(sprintf('%d', 1.99));
</code>```

string(1) "1"
```

```ini_set('precision', 20);
var_dump(2.55 * 100);
```

<pre class="lang-none prettyprint-override"><code>float(254.99999999999997158)
</code>```

Unlike printf(), echo $numeric_variable does not have a dedicated mechanism to convert from string to number. It merely casts to string using the default rules, so it's identical to (string)$numeric_variable or strval($numeric_variable). In this case:

Since variable type is float it attempts to represent a float (that implies converting from binary IEEE 754 to decimal).

It reads the precision directive to fine-tune the representation:

The number of significant digits displayed in floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.

To reduce the error in IEEE 754 to decimal conversion, string casting rounds as necessary. In my computer default precision is 14, which is pretty close to the number of nines.

ContentLicense: CC BY-SA 3.0

Title: sprintf rounding

Body:
Why does the following produce different results?

echo 2.55 * 100;
echo sprintf(' %d', 2.55 * 100);

output:

255 254

Body:
Because 2.55 * 100 in base 2 fixed size representation is not an integer and %d does not round:

var_dump(sprintf('%d', 1.99));

string(1) "1"

ini_set('precision', 20);
var_dump(2.55 * 100);

float(254.99999999999997158)

Unlike printf(), echo $numeric_variable does not have a dedicated mechanism to convert from string to number. It merely casts to string using the default rules, so it's identical to (string)$numeric_variable or strval($numeric_variable). In this case:

Since variable type is float it attempts to represent a float (that implies converting from binary IEEE 754 to decimal).

It reads the precision directive to fine-tune the representation:

The number of significant digits displayed in floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.

To reduce the error in IEEE 754 to decimal conversion, string casting rounds as necessary. In my computer default precision is 14, which is pretty close to the number of nines.


问:
Parallax Collapse Toolbar wrong scroll and layout
I have the following layout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="br.com.myproject.view.fragment.ProductActivityFragment"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_scrollFlags="scroll|exitUntilCollapsed"
            tools:contentScrim="?attr/colorPrimary"
            tools:expandedTitleMarginStart="48dp"
            tools:expandedTitleMarginEnd="64dp"
            android:fitsSystemWindows="true">

            <ImageView
                android:id="@+id/ivImgProduct"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                tools:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                tools:layout_scrollFlags="scroll|enterAlways"
                tools:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                tools:layout_collapseMode="pin">
            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/rvProductActions"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">

        </android.support.v7.widget.RecyclerView>

</android.support.design.widget.CoordinatorLayout>
</code>```

The RecyclerView is getting on the Toolbar are staying with an appearance "overlapped". The scroll both RecyclerView as the CollapsingToolbarLayout not working.
I'm trying to leave my layout with the behavior as this example link, but using RecyclerView.

答: You have to add app:layout_behavior="@string/appbar_scrolling_view_behavior" to your recyclerview</p>

Body:
I have the following layout:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="br.com.myproject.view.fragment.ProductActivityFragment"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_scrollFlags="scroll|exitUntilCollapsed"
            tools:contentScrim="?attr/colorPrimary"
            tools:expandedTitleMarginStart="48dp"
            tools:expandedTitleMarginEnd="64dp"
            android:fitsSystemWindows="true">

            <ImageView
                android:id="@+id/ivImgProduct"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                tools:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                tools:layout_scrollFlags="scroll|enterAlways"
                tools:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                tools:layout_collapseMode="pin">
            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/rvProductActions"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">

        </android.support.v7.widget.RecyclerView>

</android.support.design.widget.CoordinatorLayout>

The RecyclerView is getting on the Toolbar are staying with an appearance "overlapped". The scroll both RecyclerView as the CollapsingToolbarLayout not working.
I'm trying to leave my layout with the behavior as this example link, but using RecyclerView.


问:
CQRS - Read Model DTO Confusion
I have been reading up on CQRS and find many of the principles to be valuable. However, I have one major point of contention. Many people talk about having the read model queries map directly to view model dtos. So far, so good. However, where does the "one table or one select per view" come from that I constantly hear? Sure, some screens map 1-1 very easily. But I routinely work with some complex screens that would involve multiple selects for things like reference data in drop down lists, widgets, etc...

I could easily see my views needing multiple selects, maybe some with join or two.

How can you possibly avoid this, aside from working with perfect world scenarios where your views are simple and flat?

答:
The answer is a question: "Have I denormalized my views enough? Could I have precalculated more? Could I represent this information better so lesser queries are required?"

Strive for " 1 view == 1 query ". And as stated by qstarin, view != screen.

ContentLicense: CC BY-SA 2.5

Title: CQRS - Read Model DTO Confusion


问:
How to post url encoded json data and get response data back?
I have been trying to post URL-encoded data using below code snippet

```<code>$.post( "url",{param:"value"},function(data){
   alert("data==="+data);
});
</code>```

Here URL is a restful API URL

This one is not working. Then I tried with $.ajax

```<code>$.ajax({
  url:"url",
  type:"POST",
  dataType:"application/json",
  contentType:"application/x-www-form-urlencoded",
  data:$.param( $(param:'value') ),
  success:function(data){
   alert("data==="+data);
  }
});
</code>```

still not able to get data using a demo.html page

Then later tried with PostMan with the same configuration and it was working fine with the desired json result.

答:
$.ajax has a success param in the passed object.

To send json use dataType: 'json'.
No need for contentType, really.

Here's your updated code:

```<code>$.ajax({
  url:"url",
  type:"POST",
  dataType:"json",
  data:{param:'value'},

  success: function( data )
  {
   alert("data==="+data);
  }
})
</code>```

http://api.jquery.com/jquery.ajax/

Body:
I have been trying to post URL-encoded data using below code snippet

$.post( "url",{param:"value"},function(data){
   alert("data==="+data);
});

Here URL is a restful API URL

This one is not working. Then I tried with $.ajax

$.ajax({
  url:"url",
  type:"POST",
  dataType:"application/json",
  contentType:"application/x-www-form-urlencoded",
  data:$.param( $(param:'value') ),
  success:function(data){
   alert("data==="+data);
  }
});

still not able to get data using a demo.html page

Then later tried with PostMan with the same configuration and it was working fine with the desired json result.

Body:
$.ajax has a success param in the passed object.

To send json use dataType: 'json'.
No need for contentType, really.

Here's your updated code:

$.ajax({
  url:"url",
  type:"POST",
  dataType:"json",
  data:{param:'value'},

  success: function( data )
  {
   alert("data==="+data);
  }
})

http://api.jquery.com/jquery.ajax/


问:
Responsive design vertical align issue
I have created a page with two divs. The idea of the page is that div on the left should not have scroll bar, so it's position is set to fixed. Only div on the right should have scroll bar. It does work on desktop size, but in responsive design I want both divs have a width of 100%. So they should be aligned one after another. And the problem is that I don't know what property should I use to achieve this vertical align (with my code second div is climbing on top of first). Any ideas?

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
    float: left;
  }

  .secondDiv {
    width: 100%;
    height: 70%;
    float: left;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html></code>```

答:
Set margin-top to second div from height of first div ..

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
    float: left;
  }

  .secondDiv {
    margin-top: 30%;
    width: 100%;
    height: 70%;
    float: left;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html></code>```

Title: Responsive design vertical align issue

Body:
I have created a page with two divs. The idea of the page is that div on the left should not have scroll bar, so it's position is set to fixed. Only div on the right should have scroll bar. It does work on desktop size, but in responsive design I want both divs have a width of 100%. So they should be aligned one after another. And the problem is that I don't know what property should I use to achieve this vertical align (with my code second div is climbing on top of first). Any ideas?

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
    float: left;
  }

  .secondDiv {
    width: 100%;
    height: 70%;
    float: left;
  }
}

<!DOCTYPE html>

  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.

Body:
Set margin-top to second div from height of first div ..

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
    float: left;
  }

  .secondDiv {
    margin-top: 30%;
    width: 100%;
    height: 70%;
    float: left;
  }
}

<!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html>


问:
Multipeerconnectivity on iOS with Xcode
Both devices advertising and browsing.
The problem occurs when trying the establish a connection.

```<code>func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {}
</code>```

Does working when trying to connect but after few seconds, it's been calling again with MCSessionState == .notConnected .

Tried both with WiFi, BT, and every combination in between...

Just added:

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
    <false/>
</dict>
</code>```

Did not helped much... Still getting in the console (just on the iOS 10.2 device, though...):

```<code>2017-02-06 15:17:37.858063 Advertiser[1149:316236] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:39.727633 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.808822 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.948454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.179569 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.591829 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:41.297454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:42.547840 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:44.077537 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:45.601568 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:47.125030 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:48.110301 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [0].
2017-02-06 15:17:48.111331 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [1].
2017-02-06 15:17:48.111526 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.111705 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [2].
2017-02-06 15:17:48.111873 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.112042 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [3].
2017-02-06 15:17:48.113031 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121016 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [4].
2017-02-06 15:17:48.121321 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121506 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [5].
2017-02-06 15:17:48.121683 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
</code>```

(Advertiser is the name of the app)
Using iPhone 6S with 10.2 & iPhone 6 with 9.2.
Running code on Macbook Pro with macOS Sierra v10.12.2 from Xcode 8.2.1 (Swift3).

答: Did you keep a reference to the MCSession object for both advertiser and browser? Those BINDING_REQUEST failed messages do occur if an in-use MCSession object gets deallocated.

Title: Multipeerconnectivity on iOS with Xcode

Body:
Both devices advertising and browsing.
The problem occurs when trying the establish a connection.

func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {}

Does working when trying to connect but after few seconds, it's been calling again with MCSessionState == .notConnected .

Tried both with WiFi, BT, and every combination in between...

Just added:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
    <false/>
</dict>

Did not helped much... Still getting in the console (just on the iOS 10.2 device, though...):

2017-02-06 15:17:37.858063 Advertiser[1149:316236] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:39.727633 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.808822 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:39.948454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.179569 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:40.591829 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:41.297454 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:42.547840 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:44.077537 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:45.601568 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:47.125030 Advertiser[1149:316295] [ViceroyTrace] [ICE][ERROR]  Send BINDING_REQUEST failed(C01A0041).
2017-02-06 15:17:48.110301 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [0].
2017-02-06 15:17:48.111331 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [1].
2017-02-06 15:17:48.111526 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.111705 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [2].
2017-02-06 15:17:48.111873 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.112042 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [3].
2017-02-06 15:17:48.113031 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121016 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [4].
2017-02-06 15:17:48.121321 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)
2017-02-06 15:17:48.121506 Advertiser[1149:316267] [GCKSession] Not in connected state, so giving up for participant [66CDDFCC] on channel [5].
2017-02-06 15:17:48.121683 Advertiser[1149:316267] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (1724768204)

(Advertiser is the name of the app)
Using iPhone 6S with 10.2 & iPhone 6 with 9.2.
Running code on Macbook Pro with macOS Sierra v10.12.2 from Xcode 8.2.1 (Swift3).


问:
Encountered an error while running StatsExample in Netlogo 6
To use STATS extension, I read the information about where to put the folder as stated here:

https://ccl.northwestern.edu/netlogo/docs/extensions.html

I downloaded Stats-Extension-1.4.0 and put put the extension's folder containing all the jar files and stuff like that in the NetLogo / app/ extension folder. When I want to run STATSExample, it says "Netlogo encountered the following errors while trying to convert the model to the current version". The only option is "open unconverted model" that when it opens, there is an error saying that "can't find extension :stats". What is wrong with my installation?

Thanks,

答:
As per the current documentation of the extension:

Note that the latest version of this extension was compiled against NetLogo 5.0.5.

The extension simply has not yet been upgraded to work with NetLogo 6.

Doing so will most likely require changes to the code of the extension, since the NetLogo extension API has changed for version 6.

I would suggest opening an issue on the extension's GitHub repository.

If you really need to use the stats extension in the very short term, you could always revert back to NetLogo 5.x.


问:
Delete Button within Repeater does not exist within current context
===================

UPDATE: 29/06/2017

I am trying to get the delete button within my repeater control to function as intended. The aim is to get the button to "fire" the stored procedure within my MSSQL database.

I would like to thank Win for his in-depth response although I am still struggling to resolve the issue. I accept that I was perhaps unable to articulate my question correctly in the first instance. I have therefore edited my post to show the code I have now. I am confident that I am close to cracking the issue and would sincerely appreciate any assistance.

Code within my *.*aspx page:

```<code><asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM
[Comments] WHERE ([Ad_ID] = @Ad_ID) ORDER BY [CommentCreationDateTime] ASC">
</code>```

And further down the *.*aspx page:

```<code><asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource2"
Visible="True" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table id="displayCommentsTable" class="displayCommentsTable">
<tr class="displayCommentsTable"><td class="displayCommentsTable">
<asp:ImageButton ID="deleteCommentImageButtonReal" runat="server"
class="rightCross" ImageUrl="images/Red-Cross-Mark-PNG.png"
OnClientClick="return confirm('Are you sure you wish to delete this
comment?');" Height="11" Width="11" CommandName="Delete"
CommandArgument='<%# Eval("Comment_ID") %>' /><%# Eval("CommenterName") %>
commented on <%# Eval("CommentCreationDateTime", "{0:d/M/yyyy <i> hh:mm:ss
tt}") %>
</td></tr>
<tr class="displayCommentsTable"><td class="displayCommentsTable"><%#
Eval("CommentText") %><br /></td></tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</code>```

And finally, my code behind where the magic should be happening but isn't:

```<code>protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
DeleteCommentById(Convert.ToInt32(e.CommandArgument))
}
}
private void DeleteCommentById(int Comment_ID)
{
SqlConnection conn;
SqlCommand deleteCommentById;

string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

conn = new SqlConnection(connectionString);

deleteCommentById = new SqlCommand("usp_deleteCommentById", conn);

deleteCommentById.CommandType = System.Data.CommandType.StoredProcedure;

deleteCommentById.Parameters.Add("@Comment_ID", System.Data.SqlDbType.Int);
deleteCommentById.Parameters["@Comment_ID"].Value = Comment_ID;

conn.Open();

deleteCommentById.ExecuteNonQuery();

conn.Close();
}
</code>```

It is perhaps worth mentioning that if I "hard code" the line I am attempting to delete then it works. For example, if I used the following within my delete button:

```<code>CommandArgument='44'
</code>```

then the stored procedure would fire and affect line 44 as intended.

答: Everything was working fine but as I had not specified to only return results that had not been soft deleted, everything was getting returned. Noob mistake, learnt something for the future!</p>

Body:
===================

UPDATE: 29/06/2017

I am trying to get the delete button within my repeater control to function as intended. The aim is to get the button to "fire" the stored procedure within my MSSQL database.

I would like to thank Win for his in-depth response although I am still struggling to resolve the issue. I accept that I was perhaps unable to articulate my question correctly in the first instance. I have therefore edited my post to show the code I have now. I am confident that I am close to cracking the issue and would sincerely appreciate any assistance.

Code within my *.*aspx page:

<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM
[Comments] WHERE ([Ad_ID] = @Ad_ID) ORDER BY [CommentCreationDateTime] ASC">

And further down the *.*aspx page:

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource2"
Visible="True" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>

<asp:ImageButton ID="deleteCommentImageButtonReal" runat="server"
class="rightCross" ImageUrl="images/Red-Cross-Mark-PNG.png"
OnClientClick="return confirm('Are you sure you wish to delete this
comment?');" Height="11" Width="11" CommandName="Delete"
CommandArgument='<%# Eval("Comment_ID") %>' /><%# Eval("CommenterName") %>
commented on <%# Eval("CommentCreationDateTime", "{0:d/M/yyyy  hh:mm:ss
tt}") %>

<%#
Eval("CommentText") %>

</ItemTemplate>
<FooterTemplate>

</FooterTemplate>
</asp:Repeater>

And finally, my code behind where the magic should be happening but isn't:

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
DeleteCommentById(Convert.ToInt32(e.CommandArgument))
}
}
private void DeleteCommentById(int Comment_ID)
{
SqlConnection conn;
SqlCommand deleteCommentById;

string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

conn = new SqlConnection(connectionString);

deleteCommentById = new SqlCommand("usp_deleteCommentById", conn);

deleteCommentById.CommandType = System.Data.CommandType.StoredProcedure;

deleteCommentById.Parameters.Add("@Comment_ID", System.Data.SqlDbType.Int);
deleteCommentById.Parameters["@Comment_ID"].Value = Comment_ID;

conn.Open();

deleteCommentById.ExecuteNonQuery();

conn.Close();
}

It is perhaps worth mentioning that if I "hard code" the line I am attempting to delete then it works. For example, if I used the following within my delete button:

CommandArgument='44'

then the stored procedure would fire and affect line 44 as intended.


问:
How to set cookie with the request using rest assured?
I need to automate the rest API. The API is secured with Spring security.

Below is the code to authenticate :

```<code>Response response = given().auth()
                    .form(userName, password,   FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
                    .post("/home/xyz.html");

            Assert.assertTrue("Error occurs", response.statusCode() == 302);

            if (response.statusCode() == 302) {
                Cookie cookie = response.getDetailedCookie("JSESSIONID");
                result.actualFieldValue = "User Authenticated: Session ID ->" + cookie.getValue();
                System.out.println("Cookie set : "+cookie.getValue());
                apiTestSessionID = cookie.getValue();
            }
</code>```

The user logs in and return 302 status, means redirection.I found the cookie and set in some global variable.

Now, i set the cookie with the request :

```<code>RequestSpecification reqSpecification = new RequestSpecBuilder().addCookie("JSESSIONID", AbstractBaseClass.apiTestSessionID).build();

            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("cstmrID", "000N0961");
            parameters.put("pageNumber", "1");
            parameters.put("pageSize", "10");
            parameters.put("sortColumnName", "FIELD_NM");
            parameters.put("sortDir", "asc");
            parameters.put("filterColumnName1", "");
            parameters.put("filterColumnName2", "USER_UPDT_EMAIL_ID");
            parameters.put("filterValue2", "");

            reqSpecification.queryParams(parameters);

            Response response = given().spec(reqSpecification).when().get("/service/customerConfig").thenReturn();
            System.out.println(response.asString());
</code>```

But in response i get the login page HTML. I am not able to understand where i am doing wrong.

Assumptions :

Since with the post request, 302 is returned, do i need to redirect to the next url and after that perform get request with the cookie.

Is this the right way to set the cookie with the request.

Do i need to set the headers with the request. If yes, then following is the header info. Do i need to set all of them?

GET /example.com/abc.html HTTP/1.1 Host: example.com Connection:
  keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1
  User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
  (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Accept:
  text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
  Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8
  Cookie: JSESSIONID=C70A69F1C60D93DC3F8AC564BDE3F4DE.lon2mcaqaapp002;
  __utma=185291189.2055499590.1460104969.1460104969.1460618428.2

答:
I'm new to Rest Assured too, but I've just written the similar test.

I suggest that you write a private authenticate() method:

```<code>private static String authenticate() {
    given()
        .auth()
        .form(userName, password,FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
    when()
        .post("/home/xyz.html").
    thenReturn()
        .getDetailedCookie("JSESSIONID");
}
</code>```

and then use the cookie in the request:

```<code>given()
    .cookie(authenticate())
when()
    .get("/service/customerConfig").
thenReturn();
</code>```

But I'm not sure how do you check the statusCode here.

It's also a good idea to use .log().all() to see the logs.

Body:
I need to automate the rest API. The API is secured with Spring security.

Below is the code to authenticate :

Response response = given().auth()
                    .form(userName, password,   FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
                    .post("/home/xyz.html");

            Assert.assertTrue("Error occurs", response.statusCode() == 302);

            if (response.statusCode() == 302) {
                Cookie cookie = response.getDetailedCookie("JSESSIONID");
                result.actualFieldValue = "User Authenticated: Session ID ->" + cookie.getValue();
                System.out.println("Cookie set : "+cookie.getValue());
                apiTestSessionID = cookie.getValue();
            }

The user logs in and return 302 status, means redirection.I found the cookie and set in some global variable.

Now, i set the cookie with the request :

RequestSpecification reqSpecification = new RequestSpecBuilder().addCookie("JSESSIONID", AbstractBaseClass.apiTestSessionID).build();

            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("cstmrID", "000N0961");
            parameters.put("pageNumber", "1");
            parameters.put("pageSize", "10");
            parameters.put("sortColumnName", "FIELD_NM");
            parameters.put("sortDir", "asc");
            parameters.put("filterColumnName1", "");
            parameters.put("filterColumnName2", "USER_UPDT_EMAIL_ID");
            parameters.put("filterValue2", "");

            reqSpecification.queryParams(parameters);

            Response response = given().spec(reqSpecification).when().get("/service/customerConfig").thenReturn();
            System.out.println(response.asString());

But in response i get the login page HTML. I am not able to understand where i am doing wrong.

Assumptions :

Since with the post request, 302 is returned, do i need to redirect to the next url and after that perform get request with the cookie.

Is this the right way to set the cookie with the request.

Do i need to set the headers with the request. If yes, then following is the header info. Do i need to set all of them?

GET /example.com/abc.html HTTP/1.1 Host: example.com Connection:
  keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1
  User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
  (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Accept:
  text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
  Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8
  Cookie: JSESSIONID=C70A69F1C60D93DC3F8AC564BDE3F4DE.lon2mcaqaapp002;
  __utma=185291189.2055499590.1460104969.1460104969.1460618428.2

Body:
I'm new to Rest Assured too, but I've just written the similar test.

I suggest that you write a private authenticate() method:

private static String authenticate() {
    given()
        .auth()
        .form(userName, password,FormAuthConfig.springSecurity().withLoggingEnabled(new LogConfig(captor, true)))
    when()
        .post("/home/xyz.html").
    thenReturn()
        .getDetailedCookie("JSESSIONID");
}

and then use the cookie in the request:

given()
    .cookie(authenticate())
when()
    .get("/service/customerConfig").
thenReturn();

But I'm not sure how do you check the statusCode here.

It's also a good idea to use .log().all() to see the logs.


问:
How to create a layout of my college classrooms
I want to make an app exactly like movie apps which show which of the seats are taken. Instead replacing seats by classrooms, so that I can easily figure out which classes are empty and which classes are occupied.</p>

答:
Stack overflow, is not a place where you can ask for people to do the code for you.

Please read the help center on asking questions

https://stackoverflow.com/help

People are down-voting you because you need to show what you have learnt or showing that you have tried to at least to do your own research, most questions are already asked on this huge community.

If you attempt or edit your question to show some sort of existing google or fix up your question, people will help it.


问:
Media queries for ie only
Ie is being weird again.

Our team is trying to add some styles for ie only so resize some text that lays on an image. The first ms-high-contrast works however all the following media queries fail. Is there a better more eloquent way to do this?

We're at a loss. What's up with ie?

```<code>@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    .homebox .mdlogolg{
        left: -60px;
    }
    @media (max-width: 1199px) and (min-width: 992px) {
        .homebox .mdlogolg{
            left: -60px;
        }
    }
    @media (max-width: 991px) and (min-width: 768px) {
        .homebox .mdlogolg{
            left: -36px;
        }
    }
    @media (max-width: 767px) {
        .homebox .mdlogolg{
            left: -25px;
        }
    }
}
</code>```

答:
Actually, there is no media queries for IE, but you can create separate stylesheet for IE with all properties and he will apply automatically, if it IE.

```<code><head>
    <!--[if IE]>
        <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
    <![endif]-->
</head>
</code>```

This article might help you.
Also, you can watch at code example of Bootstrap, what they invent for IE supporting.

Title: Media queries for ie only

Body:
Ie is being weird again.

Our team is trying to add some styles for ie only so resize some text that lays on an image. The first ms-high-contrast works however all the following media queries fail. Is there a better more eloquent way to do this?

We're at a loss. What's up with ie?

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    .homebox .mdlogolg{
        left: -60px;
    }
    @media (max-width: 1199px) and (min-width: 992px) {
        .homebox .mdlogolg{
            left: -60px;
        }
    }
    @media (max-width: 991px) and (min-width: 768px) {
        .homebox .mdlogolg{
            left: -36px;
        }
    }
    @media (max-width: 767px) {
        .homebox .mdlogolg{
            left: -25px;
        }
    }
}

Body:
Actually, there is no media queries for IE, but you can create separate stylesheet for IE with all properties and he will apply automatically, if it IE.

<head>
    <!--[if IE]>
        <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
    <![endif]-->
</head>

This article might help you.
Also, you can watch at code example of Bootstrap, what they invent for IE supporting.


问:
Page turn empty when POST
I have 2 php files:

index.php

```<code><?php
@ini_set('default_charset', 'ISO-8859-1');
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="administrador"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Administração"></form>';
echo '<hr>';
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="vendedor"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Vendedor"></form>';
?>
</code>```

aplicacao.php

```<code><?php
if(isset($_POST['autorizado']))
{
    if($_POST['permissoes'] == 'administrador')
    {
        //something here
    }
    if($_POST['permissoes'] == 'vendedor')
    {
        //and something here
    }
}
?>
</code>```

Then, when I submit POST, aplicacao.php turns white.

I know why, but I don't know how to solve.

Some help would be appreciated.

Greetings!

答:
What do you expect to see on the aplicacao.php page?
If you want to see the same form, you need to create routing and .htaccess with something like this</p>

```<code>RewriteEngine on
RewriteRule !\.(js|gif|phg|jpg|css)$ index.php
</code>```

Title: Page turn empty when POST

Body:
I have 2 php files:

index.php

<?php
@ini_set('default_charset', 'ISO-8859-1');
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="administrador"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Administração"></form>';
echo '
';
echo '<form method=post action="aplicacao.php">';
echo '<input type="hidden" name="username" value="Joaquim"/>';
echo '<input type="hidden" name="permissoes" value="vendedor"/>';
echo '<input style="margin-left: 1150px; cursor=pointer;" type="submit" name="autorizado" value="Aplicação - Vendedor"></form>';
?>

aplicacao.php

<?php
if(isset($_POST['autorizado']))
{
    if($_POST['permissoes'] == 'administrador')
    {
        //something here
    }
    if($_POST['permissoes'] == 'vendedor')
    {
        //and something here
    }
}
?>

Then, when I submit POST, aplicacao.php turns white.

I know why, but I don't know how to solve.

Some help would be appreciated.

Greetings!

Body:
What do you expect to see on the aplicacao.php page?
If you want to see the same form, you need to create routing and .htaccess with something like this

RewriteEngine on
RewriteRule !\.(js|gif|phg|jpg|css)$ index.php


答:
Your callback is wrong,

```<code>$.ajax({
  url: "URL",
  type: "POST",
  dataType: "xml/html/script/json", // format for response
  contentType: "application/json", // send as JSON
  data: $.param( $(param:'value') ),

  complete: function(data) {
    //called when complete
    console.log(data);
  },

  success: function(data) {
    //called when successful
    console.log(data);
 },

  error: function(err) {
    //called when there is an error
    console.log(err);
  },
});
</code>```

This is a full Ajax function.

Title: How to post url encoded json data and get response data back?

Body:
Your callback is wrong,

$.ajax({
  url: "URL",
  type: "POST",
  dataType: "xml/html/script/json", // format for response
  contentType: "application/json", // send as JSON
  data: $.param( $(param:'value') ),

  complete: function(data) {
    //called when complete
    console.log(data);
  },

  success: function(data) {
    //called when successful
    console.log(data);
 },

  error: function(err) {
    //called when there is an error
    console.log(err);
  },
});

This is a full Ajax function.


问:
Things to ensure when deploy new laravel 5 project to VPS server
I have just finished my Laravel development (with some jquery / javascript) project and I am preparing to officially launch the website with vps servier. For the smooth running and security of the website, I only know how to handle some things in the .env file like blow:

Besides this configuration, are there any other things I have handle it before launching the website officially?

.env

```<code>APP_NAME=MyProject
APP_ENV=production
APP_KEY=base64:u93RlbQ5zcs.............
APP_DEBUG=false
APP_LOG_LEVEL=debug
APP_URL=http://mydomain

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydbname
DB_USERNAME=myuser
DB_PASSWORD=*******************

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=info@mydomain.com
MAIL_PASSWORD=*******************
MAIL_ENCRYPTION=SSL

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
</code>```

答: It seems OK, i have seen similar .env files running on various production servers.

Body:
I have just finished my Laravel development (with some jquery / javascript) project and I am preparing to officially launch the website with vps servier. For the smooth running and security of the website, I only know how to handle some things in the .env file like blow:

Besides this configuration, are there any other things I have handle it before launching the website officially?

.env

APP_NAME=MyProject
APP_ENV=production
APP_KEY=base64:u93RlbQ5zcs.............
APP_DEBUG=false
APP_LOG_LEVEL=debug
APP_URL=http://mydomain

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydbname
DB_USERNAME=myuser
DB_PASSWORD=*******************

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=info@mydomain.com
MAIL_PASSWORD=*******************
MAIL_ENCRYPTION=SSL

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=


问:
Converting string to tuple without splitting characters
I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner.

Fails

```<code>   a = 'Quattro TT'
   print tuple(a)
</code>```

Works

```<code>  a = ['Quattro TT']
  print tuple(a)
</code>```

Since my input is a string, I tried the code below by converting the string to a list, which again splits the string into characters ..

Fails

```<code>a = 'Quattro TT'
print tuple(list(a))
</code>```

Expected Output:

```<code>('Quattro TT')
</code>```

Generated Output:

```<code>('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
</code>```

答:
I use this function to convert string to tuple

```<code>import ast

def parse_tuple(string):
    try:
        s = ast.literal_eval(str(string))
        if type(s) == tuple:
            return s
        return
    except:
        return
</code>```

Usage

```<code>parse_tuple('("A","B","C",)')  # Result: ('A', 'B', 'C')
</code>```

In your case, you do

```<code>value = parse_tuple("('%s',)" % a)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner.

Fails

   a = 'Quattro TT'
   print tuple(a)

Works

  a = ['Quattro TT']
  print tuple(a)

Since my input is a string, I tried the code below by converting the string to a list, which again splits the string into characters ..

Fails

a = 'Quattro TT'
print tuple(list(a))

Expected Output:

('Quattro TT')

Generated Output:

('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')

Body:
I use this function to convert string to tuple

import ast

def parse_tuple(string):
    try:
        s = ast.literal_eval(str(string))
        if type(s) == tuple:
            return s
        return
    except:
        return

Usage

parse_tuple('("A","B","C",)')  # Result: ('A', 'B', 'C')

In your case, you do

value = parse_tuple("('%s',)" % a)


问:
ndepend - Unresolved .NET assembly
I get below error for some of my libraries.

```<code>Error!
Unresolved .NET Assembly

Can't find the .NET assembly {x} in specified folders.
Has it been compiled properly?
Is the NDepend project missing the containing folder of the .NET assembly?
</code>```

I checked this and this for a solution first.

I tried the following;

Adding from solution which is in debug mode. Built several times.

Adding folders of debug folder and the parent folders

Adding assemblies by folder

Trying all .net profiles

Adding dll by drag & drop

Thanks

EDIT: why the close flag? This application error wasted my whole day. Someone could benefit from this since the actually given error is really obscure.

答:
This is incredible but all the problematic libraries had the letter 'I' in their names. Changing them to 'i' makes them work.

For some reason Visualndepend and vs extension both cannot recognize dll's that have this letter.

Title: ndepend - Unresolved .NET assembly

Body:
I get below error for some of my libraries.

Error!
Unresolved .NET Assembly

Can't find the .NET assembly {x} in specified folders.
Has it been compiled properly?
Is the NDepend project missing the containing folder of the .NET assembly?

I checked this and this for a solution first.

I tried the following;

Adding from solution which is in debug mode. Built several times.

Adding folders of debug folder and the parent folders

Adding assemblies by folder

Trying all .net profiles

Adding dll by drag & drop

Thanks

EDIT: why the close flag? This application error wasted my whole day. Someone could benefit from this since the actually given error is really obscure.


问:
Uncaught ReferenceError: moment is not defined while using moment in laravel with vue js
im using laravel 5 and i installed moment js through npm install command. im trying to use it in one of my views with vue js. but no matter what i do i get error "moment is not defined" and if i use require, i get "require is not defined" below is the script section of my view.
`

```<code><script>
    var order = new Vue({
        el: '#create_order',

        data: {
            moment: moment,
            event_id: '',
            event_type: '',
            ticket_types: [],
            time_slots: [],
            current_timeslots: [],
            start_date: null,
            end_date: null
        },

        methods: {
            moment: function (date) {
                return moment(date);
            },`
</code>```

im beginner at this so please be as explanatory as possible, thanks.

答:
I use the following way. In app.js I add</p>

```<code>window.moment = require('moment');
window.moment.locale('ru');
</code>```

Body:
I use the following way. In app.js I add

window.moment = require('moment');
window.moment.locale('ru');


问:
Using and controlling Spring transactions within Struts 2 actions
I have been working for a while on a project with the following components:

Struts2.1.8.1,

Spring 3.0.3

JPA 2.0,

Hibernate 3

I am using Spring's EntityManager magic... But I'm having problems dealing with transactions inside my actions. For instance, I am setting values on my persisted object in several methods within my class, and I want to be able to rollback if the validate method finds a validation error, or commit these changes otherwise. I have already spent quite a long time reading half of the internet for a comprehensive explanation. Unfortunately, no complete examples exist (at least similar to my stack).

I have stumbled with this thread on a mailing list: @Transactional Spring Annotation in a Struts2 Action does not work. The message I'm linking at seems to have a pretty simple and straightforward solution, using a TransactionInterceptor will do the trick it seems... The problem is that I'm not finding useful information regarding this interceptor.

Anyone here has experience with this technology and can spare a tip and a link or two on how to use Spring transactions inside Struts2 actions?

Thanks!

- Edit 1 -

I have set up a test project if you are interested, just download the file and try it out (or inspect it). Thanks!

答:
Generally, controllers/actions/backing beans/etc don't handle transactions. Actions are the web-part of your back-end code - they should only be concerned with gathering request data, and sending response data. The logic itself (including database access) should be done in another layer. E.g. a service layer. So you create another bean, inject it in the action, and make it do the work - userService.register(user). Then configuring transactions on a service layer should be trivial since it is both in the spring documentation and in countless examples:

<tx:annotation-driven /> and @Transactional (btw, make sure you have the <tx:..> now, it might be causing the issue. Even if it works, this does not invalidate my suggestion about the service layer)


问:
pass vector of strings of columns and its interactions to use with by, eval, get in data.table
```<code>df <- data.table(A=c(1:5), B=rep(1,1,2,2,3), C=(2,2,1,1,1), D=c(1,2,2,3,1))

col_inters <- c("A_B", "A", "B_C")
</code>```

How can I iterate col_inters to get next equivalent:

```<code> df[, eval("Inter.A_B") := mean(D), by=list(A,B)]
 df[, eval("Inter.A") := mean(D), by=A]
 df[, eval("Inter.B_C") := min(D), by=list(B,C)]
</code>```

Need to continue possible solution:

```<code> for(i in 1:NROW(col_inters)) {
      df[, eval(paste("Inter.", col_inters[i], sep="")) := mean(D), by=???]
 }
</code>```

答:
Assuming that the data is correct, we split the 'col_inters' by _ into a list, get the corresponding functions and the new columns to be created and use Map

```<code>Map(function(cols, fn, new) df[, (new) := get(fn)(D), by = c(cols)],
           strsplit(col_inters, "_"), c("mean", "mean", "min"),
            paste0("Inter." , col_inters))

df
#   A B C D Inter.A_B Inter.A Inter.B_C
#1: 1 1 2 1         1       1         1
#2: 2 1 2 2         2       2         1
#3: 3 2 1 2         2       2         2
#4: 4 2 1 3         3       3         2
#5: 5 3 1 1         1       1         1
</code>```

Or we can use a for loop

```<code>lst <- strsplit(col_inters, "_")
fns <- c("mean", "mean", "min")
nm1 <- paste0("Inter." , col_inters)
for(i in seq_along(lst)) df[, (nm1[i]) := get(fns[i])(D), by = c(lst[[i]])][]
df
#    A B C D Inter.A_B Inter.A Inter.B_C
#1: 1 1 2 1         1       1         1
#2: 2 1 2 2         2       2         1
#3: 3 2 1 2         2       2         2
#4: 4 2 1 3         3       3         2
#5: 5 3 1 1         1       1         1
</code>```

data

```<code>df <- data.table(A=1:5, B= c(1,1,2,2,3), C=c(2,2,1,1,1), D=c(1,2,2,3,1))
</code>```

Body:
df <- data.table(A=c(1:5), B=rep(1,1,2,2,3), C=(2,2,1,1,1), D=c(1,2,2,3,1))

col_inters <- c("A_B", "A", "B_C")

How can I iterate col_inters to get next equivalent:

 df[, eval("Inter.A_B") := mean(D), by=list(A,B)]
 df[, eval("Inter.A") := mean(D), by=A]
 df[, eval("Inter.B_C") := min(D), by=list(B,C)]

Need to continue possible solution:

 for(i in 1:NROW(col_inters)) {
      df[, eval(paste("Inter.", col_inters[i], sep="")) := mean(D), by=???]
 }

Body:
Assuming that the data is correct, we split the 'col_inters' by _ into a list, get the corresponding functions and the new columns to be created and use Map

Map(function(cols, fn, new) df[, (new) := get(fn)(D), by = c(cols)],
           strsplit(col_inters, "_"), c("mean", "mean", "min"),
            paste0("Inter." , col_inters))

df
#   A B C D Inter.A_B Inter.A Inter.B_C
#1: 1 1 2 1         1       1         1
#2: 2 1 2 2         2       2         1
#3: 3 2 1 2         2       2         2
#4: 4 2 1 3         3       3         2
#5: 5 3 1 1         1       1         1

Or we can use a for loop

lst <- strsplit(col_inters, "_")
fns <- c("mean", "mean", "min")
nm1 <- paste0("Inter." , col_inters)
for(i in seq_along(lst)) df[, (nm1[i]) := get(fns[i])(D), by = c(lst[[i]])][]
df
#    A B C D Inter.A_B Inter.A Inter.B_C
#1: 1 1 2 1         1       1         1
#2: 2 1 2 2         2       2         1
#3: 3 2 1 2         2       2         2
#4: 4 2 1 3         3       3         2
#5: 5 3 1 1         1       1         1

data

df <- data.table(A=1:5, B= c(1,1,2,2,3), C=c(2,2,1,1,1), D=c(1,2,2,3,1))


问:
can I place a input field within a link, without making the input a link too?
I have the following problem: I have a Newsletter Banner with some content (Text, Icons and stuff) and the most important: input for E-Mail+submitbutton.

Now I would like to link the whole newsletter banner to a subpage with more information about the newsletter, but when I then click the textfield or submitbutton I get redirected to the link...

Is there any solution for this problem?

Here is a fiddle showing the problem:
try to click the input and you see it´ll be a link.

https://jsfiddle.net/wu6js2v7/2/

Btw: its no solution for me to only party link the banner

答:
can I place a input field within a link

No.

The specification says:

Content Model:
  Transparent, but there must be no interactive content descendant.

An input field is interactive content.

without making the input a link too?

Not then either.


问:
Can't Fix ASP.NET MVC Validation
I've been trying to fix the validation on my form for a while now, but can't get it to work properly. The validation works fine, unless I enter a valid email address. If I do, then it just skips all other validation for some reason.

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

EDIT: Correction: If I enter a valid email address, the form submits fine and ignores the other validation. If I don't have a valid email address, the validation checks everything.

Here's my model class:

```<code>public class User
{
    public int ID { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [DisplayName("Email")]
    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(
        @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
        ErrorMessage = "Invalid email")]
    public string Email { get; set; }

    [DisplayName("Password")]
    [DataType(DataType.Password)]
    [Required(ErrorMessage = "Password required")]
    [MinLength(6, ErrorMessage = "Min 6 characters")]
    public string Password { get; set; }
}
</code>```

Here is my controller:

```<code>    public ActionResult Register()
    {
        ViewBag.LoggedIn = false;

        return View();
    }

    [HttpPost]
    public ActionResult Register(User user)
    {
        ViewBag.LoggedIn = false;

        user.Password = PasswordHash.CreateHash(user.Password);

        using (var context = new FoundationContext())
        {
            // if user exists
            if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

            context.Users.Add(user);
            context.SaveChanges();
        }

        return View("~/Views/Home.Index.cshtml");
    }
</code>```

And here is my form:

```<code>    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-10 text-center">
                    <input type="submit" value="Register" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
</code>```

And of course bottom of the body includes:

```<code>@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</code>```

答:
First of all, your structure seems correct, to split the actions to have a differentiated Get and Post actions is correct and a good way to do it.

I am not able to test, but I think the issue is that you don't handle the validation correctly in your controller; you should check the the ModelState to be valid.

```<code>    [HttpPost]
    public ActionResult Register(User user)
    {
        if (ModelState.IsValid)
        {
            ViewBag.LoggedIn = false;

            user.Password = PasswordHash.CreateHash(user.Password);

            using (var context = new FoundationContext())
            {
                // if user exists
                if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

                context.Users.Add(user);
                context.SaveChanges();
            }

            return View("~/Views/Home.Index.cshtml");
        }
        return View(user);
    }
</code>```

This way if there is an error in the Model (based on the Rules you put with DataAnnotations).

Also I am not sure that your DataAnnotations Attributes are the correct one:
Some differ from those that are used in this article:

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation

Hope this helps.

Title: Can't Fix ASP.NET MVC Validation

Body:
I've been trying to fix the validation on my form for a while now, but can't get it to work properly. The validation works fine, unless I enter a valid email address. If I do, then it just skips all other validation for some reason.

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

EDIT: Correction: If I enter a valid email address, the form submits fine and ignores the other validation. If I don't have a valid email address, the validation checks everything.

Here's my model class:

public class User
{
    public int ID { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [DisplayName("Email")]
    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(
        @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
        ErrorMessage = "Invalid email")]
    public string Email { get; set; }

    [DisplayName("Password")]
    [DataType(DataType.Password)]
    [Required(ErrorMessage = "Password required")]
    [MinLength(6, ErrorMessage = "Min 6 characters")]
    public string Password { get; set; }
}

Here is my controller:

    public ActionResult Register()
    {
        ViewBag.LoggedIn = false;

        return View();
    }

    [HttpPost]
    public ActionResult Register(User user)
    {
        ViewBag.LoggedIn = false;

        user.Password = PasswordHash.CreateHash(user.Password);

        using (var context = new FoundationContext())
        {
            // if user exists
            if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

            context.Users.Add(user);
            context.SaveChanges();
        }

        return View("~/Views/Home.Index.cshtml");
    }

And here is my form:

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                    <input type="submit" value="Register" class="btn btn-primary" />

    }

And of course bottom of the body includes:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

Body:
First of all, your structure seems correct, to split the actions to have a differentiated Get and Post actions is correct and a good way to do it.

I am not able to test, but I think the issue is that you don't handle the validation correctly in your controller; you should check the the ModelState to be valid.

    [HttpPost]
    public ActionResult Register(User user)
    {
        if (ModelState.IsValid)
        {
            ViewBag.LoggedIn = false;

            user.Password = PasswordHash.CreateHash(user.Password);

            using (var context = new FoundationContext())
            {
                // if user exists
                if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

                context.Users.Add(user);
                context.SaveChanges();
            }

            return View("~/Views/Home.Index.cshtml");
        }
        return View(user);
    }

This way if there is an error in the Model (based on the Rules you put with DataAnnotations).

Also I am not sure that your DataAnnotations Attributes are the correct one:
Some differ from those that are used in this article:

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation

Hope this helps.


问:
c# doing a custom sort on a datatable
i have data in a datatable that needs to be sorted on the first column this way:

```<code>A02 BLANK0010
D02 BLANK0007
B04 BLANK0011
G05 BLANK0012
C06 BLANK0014
E08 BLANK0013
F10 BLANK0016
H12 BLANK0015
B02 G112486
C02 G125259
E02 G125257
F02 G112492
G02 G125095
H02 G112489
A03 G125090
B03 G112499
C03 G125256
D03 G002007
E03 G112494
F03 G002005
G03 G112495
H03 G002008
A04 G115717
</code>```

if i do a regular sort, it will just sort like this: A02, A03, A04. but i need A02, B02, C02... etc

how can i do this>? here my code so far:

DataView view = dt.DefaultView;
        view.Sort = "position";

答:
You'll want to do a custom sort.  See the following question for hints: DataView.Sort - more than just asc/desc (need custom sort)

You might want to break the first column into two separate columns.

Title: c# doing a custom sort on a datatable

Body:
i have data in a datatable that needs to be sorted on the first column this way:

A02 BLANK0010
D02 BLANK0007
B04 BLANK0011
G05 BLANK0012
C06 BLANK0014
E08 BLANK0013
F10 BLANK0016
H12 BLANK0015
B02 G112486
C02 G125259
E02 G125257
F02 G112492
G02 G125095
H02 G112489
A03 G125090
B03 G112499
C03 G125256
D03 G002007
E03 G112494
F03 G002005
G03 G112495
H03 G002008
A04 G115717

if i do a regular sort, it will just sort like this: A02, A03, A04. but i need A02, B02, C02... etc

how can i do this>? here my code so far:

DataView view = dt.DefaultView;
        view.Sort = "position";


问:
How can I perform click on input using xpath
I have used the below code to click the element.But it failed to locate the element and shows element not visible.

```<code>elem3=driver.find_element_by_xpath(".//*[@id='check-box']")
elem3.click()
</code>```

The html code:

```<code><span id="Some-span" class="urCWhl" title="Indicator">
<input id="check-box" class="urC" type="checkbox" hidefocus="hidefocus" ti="-1" tabindex="-1" ct="C"/>
<span id="label-lbl" class="name_class" style="width:100%;box-sizing:border-box;" unselectable="on" f="some-id" ti="0" tabindex="0" title="Indicator"></span>
</code>```

答:
You can try something like this:</p>

```<code>    element = driver.find_element_by_xpath(".//*[@id='check-box']")
    driver.execute_script("arguments[0].click();", element)
</code>```

Body:
I have used the below code to click the element.But it failed to locate the element and shows element not visible.

elem3=driver.find_element_by_xpath(".//*[@id='check-box']")
elem3.click()

The html code:

<input id="check-box" class="urC" type="checkbox" hidefocus="hidefocus" ti="-1" tabindex="-1" ct="C"/>

Body:
You can try something like this:

    element = driver.find_element_by_xpath(".//*[@id='check-box']")
    driver.execute_script("arguments[0].click();", element)


问:
Passing a list generated with Javascript to a Spring controller
My app is being built with Spring Boot using a MVC pattern, and as template viewer I use Thymeleaf.

I'm generating a dynamic list with Javascript in a form, which I need to collect as a List with the controller.

I have tried to solve it with a @RequestParam, but generating the list with Javascript, as far as I'm concerned, I can't set the Thymeleaf tags.

This is the list:

```<code><ul id="addItemList">
   <li class="list-group-item" id="group" name="group" value="Outdoors">Outdoors</li>
   <li class="list-group-item" id="group" name="group" value="Entertainment">Entertainment</li>
</ul>
</code>```

Any indication on which approach I should take, would be much appreciated.

Thanks in advance.

答: Create a Model having a List as property, and pass it as @ModelAttribute in your controller.

Body:
My app is being built with Spring Boot using a MVC pattern, and as template viewer I use Thymeleaf.

I'm generating a dynamic list with Javascript in a form, which I need to collect as a List with the controller.

I have tried to solve it with a @RequestParam, but generating the list with Javascript, as far as I'm concerned, I can't set the Thymeleaf tags.

This is the list:

Outdoors

Entertainment

Any indication on which approach I should take, would be much appreciated.

Thanks in advance.


问:
Pass file as command line argument to Spark
I am coding a Spark job in Scala and need to send some argument through command-line in JSON file format like the application name, master and some more variables.

```<code>./bin/spark-submit --name "My app" --master local[4] --conf spark.eventLog.enabled=false --conf "spark.executor.extraJavaOptions=-XX:+PrintGCDetails -XX:+PrintGCTimeStamps" myApp.jar
</code>```

I need to send app name, master and all arguments in one JSON file like:

```<code>$SPARK_HOME/bin/spark-submit --properties-file  property.conf
</code>```

Is that possible? How? Can anyone please explain with a simple example?

答:
You can use the --jars option as follows:

```<code>$SPARK_HOME/bin/spark-submit --jars property.conf --class your.Class your.jar
</code>```

The help page of spark-submit will yell you more:

```<code>$SPARK_HOME/bin/spark-submit --help

  --jars JARS Comma-separated list of local jars to include on the driver
              and executor classpaths.
</code>```

Despite the name, you can also use it to move around configuration files that you want to be in your driver and executors' classpath.

Body:
I am coding a Spark job in Scala and need to send some argument through command-line in JSON file format like the application name, master and some more variables.

./bin/spark-submit --name "My app" --master local[4] --conf spark.eventLog.enabled=false --conf "spark.executor.extraJavaOptions=-XX:+PrintGCDetails -XX:+PrintGCTimeStamps" myApp.jar

I need to send app name, master and all arguments in one JSON file like:

$SPARK_HOME/bin/spark-submit --properties-file  property.conf

Is that possible? How? Can anyone please explain with a simple example?

Body:
You can use the --jars option as follows:

$SPARK_HOME/bin/spark-submit --jars property.conf --class your.Class your.jar

The help page of spark-submit will yell you more:

$SPARK_HOME/bin/spark-submit --help

  --jars JARS Comma-separated list of local jars to include on the driver
              and executor classpaths.

Despite the name, you can also use it to move around configuration files that you want to be in your driver and executors' classpath.


问:
Xamarin iOS Native Linking Error. Could not find file
I updated to the newest XCode recently and ever since I have been getting errors while building for iOS. The errors all look like:

```<code> Error MT5209: Native linking error: clang: error: no such file or directory: 'project directory/obj/iPhone/Debug/device-builds/iphone5.3-10.3.2/mtouch-cache/GoogleMaps'
</code>```

There are 11 of them. Each one has a different final folder name:

FirebaseAuth

FirebaseAnalytics

GoogleSymbolUtilities

GoogleInterchangeUtilities

FirebaseInstanceID

FirebaseCore

GoogleMapsCore

GoogleMapsBase

GooglePlaces

GooglePlacePicker

答: Go to the project directory and remove obj and bin folders. Then try to build again.

Body:
I updated to the newest XCode recently and ever since I have been getting errors while building for iOS. The errors all look like:

 Error MT5209: Native linking error: clang: error: no such file or directory: 'project directory/obj/iPhone/Debug/device-builds/iphone5.3-10.3.2/mtouch-cache/GoogleMaps'

There are 11 of them. Each one has a different final folder name:

FirebaseAuth

FirebaseAnalytics

GoogleSymbolUtilities

GoogleInterchangeUtilities

FirebaseInstanceID

FirebaseCore

GoogleMapsCore

GoogleMapsBase

GooglePlaces

GooglePlacePicker