问:
Download generated PDF use FileSaver on client side and Snappy on server side
I try to use FileSaver to download generated PDF from server. However, it's not work.

In Laravel framework, I use Snappy to create PDF file from HTML.

```<code>$pdf = \PDF::loadView('pub.view', $data);
//$pdf->save('myfile.pdf');    //It's saved successfully.
return $pdf->download('printing.pdf');
</code>```

From client, I apply $resource service of AngularJS for getting PDF file.

```<code>printPDF: {
            method: 'GET',
            headers: {
                accept: 'application/pdf'
            },
            responseType: 'arraybuffer',
            cache: true,
            transformResponse: function (data) {
                var pdf;
                if (data) {
                    pdf = new Blob([data], {
                        type: 'application/pdf'
                    });
                }
                return {
                    response: pdf
                };
            },
            url:'/u/:id/exportTopdf',
            params:{id:'@id'}
        }
</code>```

After server response, FileSaver will save this file.

```<code>myService.printPDF({id: myId},
function successCallback(response){

   saveAs(response, 'filename.pdf');  //FileSaver function

}, function errorCallback(response){

});
</code>```

When running, the issue is happen in browser console:

```<code>`TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided`.
</code>```

I think FileSaver makes the problem but I don't know how to fix it.

答:
```<code>param = {
  action: "downloadReport",
};
$http({
  method: 'POST',
  url: 'http://localhost:8080/ivftcwcm2/services/fundTransferServices/downloadFile',
  //url:'http://localhost:8080/FundTransferUI/resources/locales/Disclosure.pdf',
  data: param,
  responseType: 'arraybuffer'
}).then(function(response) {
  var file = new Blob([response.data], {
    type: 'application/pdf'
  });
  var fileURL = URL.createObjectURL(file);
  var a = document.createElement('a');
  a.href = fileURL;
  a.target = '_blank';
  a.download = 'pdfFile.pdf';
  document.body.appendChild(a);
  a.click();
}, function(response) {
  alert('call failed');
});
</code>```

Body:
I try to use FileSaver to download generated PDF from server. However, it's not work.

In Laravel framework, I use Snappy to create PDF file from HTML.

$pdf = \PDF::loadView('pub.view', $data);
//$pdf->save('myfile.pdf');    //It's saved successfully.
return $pdf->download('printing.pdf');

From client, I apply $resource service of AngularJS for getting PDF file.

printPDF: {
            method: 'GET',
            headers: {
                accept: 'application/pdf'
            },
            responseType: 'arraybuffer',
            cache: true,
            transformResponse: function (data) {
                var pdf;
                if (data) {
                    pdf = new Blob([data], {
                        type: 'application/pdf'
                    });
                }
                return {
                    response: pdf
                };
            },
            url:'/u/:id/exportTopdf',
            params:{id:'@id'}
        }

After server response, FileSaver will save this file.

myService.printPDF({id: myId},
function successCallback(response){

   saveAs(response, 'filename.pdf');  //FileSaver function

}, function errorCallback(response){

});

When running, the issue is happen in browser console:

`TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided`.

I think FileSaver makes the problem but I don't know how to fix it.


来源: stackexchange

问:
How can I check wether an array contains any item or is completely empty?
If I define an integer array:

```<code>int[] a = new int[13];
</code>```

and I do not insert any item into it, how can I know whether the array a contains any items or is completely empty?
Do I have to iterate through all the a.Length indices?
In a list

```<code>List<int> b = new List<int>();
</code>```

if I check:

```<code>if(b.Count == 0)
{
    // The list does not contain any items.
}
</code>```

Is there an equivalent way to check an array?
I found on the internet the check if an array is null or empty.
In my case I know for sure that the array is not null.
I just wish to know whether it contains any item or not.
I do not care in which position within the array and also not exactly which item.
Thank you very much in advance.

答:
Since its an integer, you can check if all values are zero:</p>

```<code>if (array.All(y=>y == 0))
  {
    //If all values are zero, this will proceed on this statement.
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I define an integer array:

int[] a = new int[13];

and I do not insert any item into it, how can I know whether the array a contains any items or is completely empty?
Do I have to iterate through all the a.Length indices?
In a list

List<int> b = new List<int>();

if I check:

if(b.Count == 0)
{
    // The list does not contain any items.
}

Is there an equivalent way to check an array?
I found on the internet the check if an array is null or empty.
In my case I know for sure that the array is not null.
I just wish to know whether it contains any item or not.
I do not care in which position within the array and also not exactly which item.
Thank you very much in advance.

Body:
Since its an integer, you can check if all values are zero:

if (array.All(y=>y == 0))
  {
    //If all values are zero, this will proceed on this statement.
  }


问:
How to make a charts using jQuery?
Iam really new in to jQuery or something.
Iam using adminlte2 template as my project dashboards, and i use codeigniter as my framework.
I want to use charts based on this.

```<code>$(function () {
  var donutData = [
  {label: "Series1", data: 30, color: "#1a5dad"},
  {label: "Series2", data: 20, color: "#2b6cbc"},
  {label: "Series3", data: 50, color: "#3c7bcb"},
  {label: "Series4", data: 50, color: "#4d8ada"}
];
$.plot("#donut-chart", donutData, {
  series: {
    pie: {
      show: true,
      radius: 1,
      innerRadius: 0.5,
      label: {
        show: true,
        radius: 2 / 3,
        formatter: labelFormatter,
        threshold: 0.1
      }

    }
  },
  legend: {
    show: false
  }
});
/*
 * END DONUT CHART
 */
</code>```

The task is just, how to change label and data in that code into variable?
I already have the variable for label: $row['productSubgroup'] and for data: $row['counts']. And i just cant input it... Hope someone will help.

答:
Considering your situation your code will be like this:

Controller :

```<code>$chart_data = array();
foreach ($result as $row) {
    $chart_data[] = array(
                                    'label' => $row['productSubgroup'],
                                    'data'  => $row['count'],
                                    'color' => dechex(rand(0x000000, 0xFFFFFF)) //Random Hex color code
                                );
}
$data['chart_data'] = json_encode($chart_data);
</code>```

Explanation : This code will get label and count from your data store. $result is having your data. We're preparing array for chart and storing it in $data['chart_data'], it is in json format. You've to pass $data to the view file.

JS :

```<code>$(function () {
    var donutData = <?php echo $chart_data; ?>;
    $.plot("#donut-chart", donutData, {
      series: {
        pie: {
          show: true,
          radius: 1,
          innerRadius: 0.5,
          label: {
            show: true,
            radius: 2 / 3,
            formatter: labelFormatter,
            threshold: 0.1
          }

        }
      },
      legend: {
        show: false
      }
    });
/*
 * END DONUT CHART
 */
});
</code>```

Explanation : $chart_data holds the chart details. We're storing this php variable data into donutData.

Try this and let me know if there is any issue.

Happy Coding!

Title: How to make a charts using jQuery?

Body:
Iam really new in to jQuery or something.
Iam using adminlte2 template as my project dashboards, and i use codeigniter as my framework.
I want to use charts based on this.

$(function () {
  var donutData = [
  {label: "Series1", data: 30, color: "#1a5dad"},
  {label: "Series2", data: 20, color: "#2b6cbc"},
  {label: "Series3", data: 50, color: "#3c7bcb"},
  {label: "Series4", data: 50, color: "#4d8ada"}
];
$.plot("#donut-chart", donutData, {
  series: {
    pie: {
      show: true,
      radius: 1,
      innerRadius: 0.5,
      label: {
        show: true,
        radius: 2 / 3,
        formatter: labelFormatter,
        threshold: 0.1
      }

    }
  },
  legend: {
    show: false
  }
});
/*
 * END DONUT CHART
 */

The task is just, how to change label and data in that code into variable?
I already have the variable for label: $row['productSubgroup'] and for data: $row['counts']. And i just cant input it... Hope someone will help.

Body:
Considering your situation your code will be like this:

Controller :

$chart_data = array();
foreach ($result as $row) {
    $chart_data[] = array(
                                    'label' => $row['productSubgroup'],
                                    'data'  => $row['count'],
                                    'color' => dechex(rand(0x000000, 0xFFFFFF)) //Random Hex color code
                                );
}
$data['chart_data'] = json_encode($chart_data);

Explanation : This code will get label and count from your data store. $result is having your data. We're preparing array for chart and storing it in $data['chart_data'], it is in json format. You've to pass $data to the view file.

JS :

$(function () {
    var donutData = <?php echo $chart_data; ?>;
    $.plot("#donut-chart", donutData, {
      series: {
        pie: {
          show: true,
          radius: 1,
          innerRadius: 0.5,
          label: {
            show: true,
            radius: 2 / 3,
            formatter: labelFormatter,
            threshold: 0.1
          }

        }
      },
      legend: {
        show: false
      }
    });
/*
 * END DONUT CHART
 */
});

Explanation : $chart_data holds the chart details. We're storing this php variable data into donutData.

Try this and let me know if there is any issue.

Happy Coding!


问:
jsx style with condition
I know I can do condition with className but how about style?

```<code><span style={{float:'right'}}>Something</span>
</code>```

Like for above jsx, I want to float right if obj.name is equal to 'active'

答:
One Way, if you want the whole style only when the object.name == 'active':

```<code><span style={obj.name == 'active' ? {float:'right'} : {}}>Something</span>
</code>```

Another, when you want to put the condition on separate style property values:

```<code><span style={{float: obj.name == 'active' ? 'right' : ''}}>Something</span>
</code>```

Title: jsx style with condition

Body:
I know I can do condition with className but how about style?

Something

Like for above jsx, I want to float right if obj.name is equal to 'active'

Body:
One Way, if you want the whole style only when the object.name == 'active':

<span style={obj.name == 'active' ? {float:'right'} : {}}>Something</span>

Another, when you want to put the condition on separate style property values:

<span style={{float: obj.name == 'active' ? 'right' : ''}}>Something</span>


问:
How to copy a link to socialshare-url using ng-model in javascript?

 <input type="url" id="linkid" style="border:1px solid black;padding:0.5%" ng-model="shareLink">

 target="_self" socialshare socialshare-provider="facebook" socialshare-text="720kb AngularJS Socialshare" socialshare-hashtags="angularjs, angular-socialshare" socialshare-url="shareLink">```

I want to copy a link to socialshare-url for sharing that link in social sites that was generated when a button is clicked.Iam trying to copy the link using ng-model but it was not working.How can I copy a link to social

答:
On ng-change of the input call a function to update the attribute of the anchor link. Then in your angular controller assign the input model to that anchor element.

In the html:

```<code><input ng-model="shareLink" ng-change="updateLink()">
</code>```

And in the controller:

```<code>$scope.updateLink = function()
        {
            document.getElementsByTagName("a")[0].setAttribute("socialshare-url", $scope.shareLink);
        }
</code>```

Here is the fiddle: https://jsfiddle.net/AKMorris/cm4jbo6p/

Body:
 <input type="url" id="linkid" style="border:1px solid black;padding:0.5%" ng-model="shareLink">

I want to copy a link to socialshare-url for sharing that link in social sites that was generated when a button is clicked.Iam trying to copy the link using ng-model but it was not working.How can I copy a link to social

Body:
On ng-change of the input call a function to update the attribute of the anchor link. Then in your angular controller assign the input model to that anchor element.

In the html:

<input ng-model="shareLink" ng-change="updateLink()">

And in the controller:

$scope.updateLink = function()
        {
            document.getElementsByTagName("a")[0].setAttribute("socialshare-url", $scope.shareLink);
        }

Here is the fiddle: https://jsfiddle.net/AKMorris/cm4jbo6p/


问:
Joining tables depends on activity and activity id
i need to do a search query whitch will look for result in 2 separated tables depending on activity.
The problem is, they are joining the same id. Right now its not working properly..

Table log

```<code>id     activity     activityid
1       news          155
2       prod          232
3       news          412
</code>```

Table news

```<code>id       title
155      Something
412      Something
</code>```

Table product

```<code>id       intro
232      Something

SELECT *
FROM log l
INNER JOIN product p ON l.activityid=p.id and l.activity='prod'
INNER JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE p.title like '%something%' or n.intro like '%something%'
</code>```

What am i missing?

答:
May be you should use left join instead of inner join:

```<code>SELECT *
FROM log l
LEFT JOIN product p ON l.activityid=p.id and l.activity='prod'
LEFT JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE p.title like '%something%'
    or n.intro like '%something%'
</code>```

Anyway, please follow Strawberry suggestion...

Body:
i need to do a search query whitch will look for result in 2 separated tables depending on activity.
The problem is, they are joining the same id. Right now its not working properly..

Table log

id     activity     activityid
1       news          155
2       prod          232
3       news          412

Table news

id       title
155      Something
412      Something

Table product

id       intro
232      Something

SELECT *
FROM log l
INNER JOIN product p ON l.activityid=p.id and l.activity='prod'
INNER JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE p.title like '%something%' or n.intro like '%something%'

What am i missing?

Body:
May be you should use left join instead of inner join:

SELECT *
FROM log l
LEFT JOIN product p ON l.activityid=p.id and l.activity='prod'
LEFT JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE p.title like '%something%'
    or n.intro like '%something%'

Anyway, please follow Strawberry suggestion...


问:
String is not recognized as valid date time
Description:

In my application user is allowed to insert date in string format EX- "01/01/2000"and I'm parsing this string value using DateTime.Parse("01/01/00"); it is working fine. But in few case it is breaking.

Case 1:

Input : "01/01/00"

Code: DateTime.Parse("01/01/00");

Output: 01/01/2000

Case 2:

Input : "01/01/000"

Code: DateTime.Parse("01/01/000");

Output: Getting error "String is not recognized as valid date time."

Case 3:

Input : "01/01/0000"

Code: DateTime.Parse("01/01/0000");

Output: Getting error "String is not recognized as valid date time."

How to parse 000 or 0000 as correct year ?

答:
You can convert it with below extension method</p>

```<code>public static DateTime GetDateTime(this string strdate)
{
    int day = Convert.ToInt32(strdate.Split('/')[0]);
    int month = Convert.ToInt32(strdate.Split('/')[1]);
    int year = Convert.ToInt32(strdate.Split('/')[2]);

    if (year == 0)
        year = 2000;

    return new DateTime(year, month, day);
}
</code>```

Body:
You can convert it with below extension method

public static DateTime GetDateTime(this string strdate)
{
    int day = Convert.ToInt32(strdate.Split('/')[0]);
    int month = Convert.ToInt32(strdate.Split('/')[1]);
    int year = Convert.ToInt32(strdate.Split('/')[2]);

    if (year == 0)
        year = 2000;

    return new DateTime(year, month, day);
}


问:
Show only text in Notification without any icon
I want to show a notification that only shows a text instead of an icon!

I just try it as:

```<code>private void showNotification(String msg) {
    try {
        Intent intent = new Intent(this, Act.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        //set the notification
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(msg)
            .setAutoCancel(true)
            .setSound(notificationSound)
            .setContentIntent(pendingIntent);

       NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       notificationManager.notify(0, builder.build());

    } catch (Exception exp) {
        Log.e("xmn", exp.toString());
}
}
</code>```

The problem is that the notification never occurs.

答:
Android requires you to have the following content in your notification:

A small icon, set by setSmallIcon()

A title, set by setContentTitle()

Detail text, set by setContentText()

So you must show an icon in your notification.

Body:
I want to show a notification that only shows a text instead of an icon!

I just try it as:

private void showNotification(String msg) {
    try {
        Intent intent = new Intent(this, Act.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        //set the notification
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(msg)
            .setAutoCancel(true)
            .setSound(notificationSound)
            .setContentIntent(pendingIntent);

       NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       notificationManager.notify(0, builder.build());

    } catch (Exception exp) {
        Log.e("xmn", exp.toString());
}
}

The problem is that the notification never occurs.


问:
Count unique elements in array without sorting
In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array

```<code>arr = ["jam", "beef", "cream", "jam"]
arr.sort();
var count = 1;
var results = "";
for (var i = 0; i < arr.length; i++)
{
    if (arr[i] == arr[i+1])
    {
      count +=1;
    }
    else
    {
        results += arr[i] + " --> " + count + " times\n" ;
        count=1;
    }
}
</code>```

Is it possible to do this without using sort() or without mutating the array in any way? I would imagine that the array would have to be re-created and then sort could be done on the newly created array, but I want to know what's the best way without sorting.
And yes, I'm an artist, not a programmer, your honour.

答:
The fast way to do this is with a new Set() object.

Sets are awesome and we should use them more often. They are fast, and supported by Chrome, Firefox, Microsoft Edge, and node.js.

  — What is faster Set or Object? by Andrei Kashcha

The items in a Set will always be unique, as it only keeps one copy of each value you put in. Here's a function that uses this property:

function countUnique(iterable) {
  return new Set(iterable).size;
}

console.log(countUnique('banana')); //=> 3
console.log(countUnique([5,6,5,6])); //=> 2
console.log(countUnique([window, document, window])); //=> 2```

This can be used to count the items in any iterable (including an Array, String, TypedArray, and arguments object).

Body:
In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array

arr = ["jam", "beef", "cream", "jam"]
arr.sort();
var count = 1;
var results = "";
for (var i = 0; i < arr.length; i++)
{
    if (arr[i] == arr[i+1])
    {
      count +=1;
    }
    else
    {
        results += arr[i] + " --> " + count + " times\n" ;
        count=1;
    }
}

Is it possible to do this without using sort() or without mutating the array in any way? I would imagine that the array would have to be re-created and then sort could be done on the newly created array, but I want to know what's the best way without sorting.
And yes, I'm an artist, not a programmer, your honour.

Body:
The fast way to do this is with a new Set() object.

Sets are awesome and we should use them more often. They are fast, and supported by Chrome, Firefox, Microsoft Edge, and node.js.

  — What is faster Set or Object? by Andrei Kashcha

The items in a Set will always be unique, as it only keeps one copy of each value you put in. Here's a function that uses this property:

function countUnique(iterable) {
  return new Set(iterable).size;
}

console.log(countUnique('banana')); //=> 3
console.log(countUnique([5,6,5,6])); //=> 2
console.log(countUnique([window, document, window])); //=> 2

This can be used to count the items in any iterable (including an Array, String, TypedArray, and arguments object).


问:
Why is Visual Studio telling me I need to reference System.Private.CoreLib?
I'm trying out EF Core for the first time and have coded a very simple MVC app to get my feet wet. I am using a method for seeding the database found in the UnicornStore project where they write some code in Startup.cs to migrate the database and then run a seed method.

Before they call the seed method, they run this DbContext extension method to check if all migrations have been applied:

```<code>using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

namespace UnicornStore.Models
{
    public static class DbContextExtensions
    {
        public static bool AllMigrationsApplied(this DbContext context)
        {
            var applied = context.GetService<IHistoryRepository>()
                .GetAppliedMigrations()
                .Select(m => m.MigrationId);

            var total = context.GetService<IMigrationsAssembly>()
                .Migrations
                .Select(m => m.Key);

            return !total.Except(applied).Any();
        }
    }
}
</code>```

I've put this same method in my application and everything works -- the code compiles and the database is migrated and seeded. However, Visual Studio (2017 Enterprise) is red underlining this line:

```<code>context.GetService<IMigrationsAssembly>()
                    .Migrations
                    .Select(m => m.Key);
</code>```

If I hover over the red line, it tells me:

Module 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=foo' should be referenced

Can anyone tell me why I am getting this message? I actually tried to add a reference to System.Private.CoreLib to see what would happen, and that caused a ton of errors (undefined System.Object, etc). I'm never comfortable leaving things like this unresolved in case they come back to bite me later, so any resolution (or a confirmation that I can leave this be and ignore the message) would be appreciated!

答:
Do you have R# installed? You might have been hitting this issue: RSRP-464676

If so, try suspending R# and see if the issues are not shown anymore.

Body:
I'm trying out EF Core for the first time and have coded a very simple MVC app to get my feet wet. I am using a method for seeding the database found in the UnicornStore project where they write some code in Startup.cs to migrate the database and then run a seed method.

Before they call the seed method, they run this DbContext extension method to check if all migrations have been applied:

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

namespace UnicornStore.Models
{
    public static class DbContextExtensions
    {
        public static bool AllMigrationsApplied(this DbContext context)
        {
            var applied = context.GetService<IHistoryRepository>()
                .GetAppliedMigrations()
                .Select(m => m.MigrationId);

            var total = context.GetService<IMigrationsAssembly>()
                .Migrations
                .Select(m => m.Key);

            return !total.Except(applied).Any();
        }
    }
}

I've put this same method in my application and everything works -- the code compiles and the database is migrated and seeded. However, Visual Studio (2017 Enterprise) is red underlining this line:

context.GetService<IMigrationsAssembly>()
                    .Migrations
                    .Select(m => m.Key);

If I hover over the red line, it tells me:

Module 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=foo' should be referenced

Can anyone tell me why I am getting this message? I actually tried to add a reference to System.Private.CoreLib to see what would happen, and that caused a ton of errors (undefined System.Object, etc). I'm never comfortable leaving things like this unresolved in case they come back to bite me later, so any resolution (or a confirmation that I can leave this be and ignore the message) would be appreciated!


问:
C# MVC Query String Encoding and Decoding
I want to encode and decode the url parameters.

calling function in javascript

```<code>var url = '/Demo/Demo?id=58';
$(location).attr('href', url)
</code>```

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

```<code>public ActionResult Demo(int id)
{
   return view();
}
</code>```

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method

答:
```<code>var id=Encrypt(YourID);
var id=Decrypt(YourID);

  using System.Security.Cryptography;

public static string Encrypt(string inputText)
    {
        string encryptionkey = "SAUW193BX628TD57";
        byte[] keybytes = Encoding.ASCII.GetBytes(encryptionkey.Length.ToString());
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        byte[] plainText = Encoding.Unicode.GetBytes(inputText);
        PasswordDeriveBytes pwdbytes = new PasswordDeriveBytes(encryptionkey, keybytes);
        using (ICryptoTransform encryptrans = rijndaelCipher.CreateEncryptor(pwdbytes.GetBytes(32), pwdbytes.GetBytes(16)))
        {
            using (MemoryStream mstrm = new MemoryStream())
            {
                using (CryptoStream cryptstm = new CryptoStream(mstrm, encryptrans, CryptoStreamMode.Write))
                {
                cryptstm.Write(plainText, 0, plainText.Length);
                cryptstm.Close();
                return Convert.ToBase64String(mstrm.ToArray());
                }
            }
        }
    }

public static string Decrypt(string encryptText)
{
    string encryptionkey = "SAUW193BX628TD57";
    byte[] keybytes = Encoding.ASCII.GetBytes(encryptionkey.Length.ToString());
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    byte[] encryptedData = Convert.FromBase64String(encryptText.Replace(" ", "+"));
    PasswordDeriveBytes pwdbytes = new PasswordDeriveBytes(encryptionkey, keybytes);
    using (ICryptoTransform decryptrans = rijndaelCipher.CreateDecryptor(pwdbytes.GetBytes(32), pwdbytes.GetBytes(16)))
    {
        using (MemoryStream mstrm = new MemoryStream(encryptedData))
        {
            using (CryptoStream cryptstm = new CryptoStream(mstrm, decryptrans, CryptoStreamMode.Read))
            {
            byte[] plainText = new byte[encryptedData.Length];
            int decryptedCount = cryptstm.Read(plainText, 0, plainText.Length);
            return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
            }
        }
    }
}
</code>```

Body:
I want to encode and decode the url parameters.

calling function in javascript

var url = '/Demo/Demo?id=58';
$(location).attr('href', url)

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

public ActionResult Demo(int id)
{
   return view();
}

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method


问:
In Python, is there an elegant way to print a list in a custom format without explicit looping?
I know you can do

```<code>print str(myList)
</code>```

to get

```<code>[1, 2, 3]
</code>```

and you can do

```<code>i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1
</code>```

to get

```<code>0: 1
1: 2
2: 3
</code>```

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

```<code>print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])
</code>```

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

答:
```<code>>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3
</code>```

Note: you just need to understand that list comprehension or iterating over a generator expression is explicit looping.

ContentLicense: CC BY-SA 2.5

Body:
I know you can do

print str(myList)

to get

[1, 2, 3]

and you can do

i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1

to get

0: 1
1: 2
2: 3

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

Body:
>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3

Note: you just need to understand that list comprehension or iterating over a generator expression is explicit looping.


问:
How to breakdown List<List<String>> rows
So I have a code where my variables var1, var2, and var3 goes to a List<String> temp. And for every click of a button, another batch of variables will go to temp and temp goes to List<List<String>> rows at the end of the function. Note that I can click the button as many times I want and the process temp.add(var1); temp.add(var2); ... rows.add(temp); will run.

Now, I want to break down rows and save all of the data of temp to my database.

here is a part of my code:

```<code>ArrayList<String> temp = new ArrayList<String>();
temp.add(itemnameCol);
temp.add(itempriceCol+"");
temp.add(dialogVar+"");
t2Rows.add(temp);
</code>```

here is the insert method

```<code>public void addItem(String itemIn, String itemProd, String itemQuan){
    cv.clear();
    cv.put(INVOICE_NUM_ITEM,itemIn);
    cv.put(PRODUCT_ID_ITEM,itemProd);
    cv.put(PRODUCT_QUANTITY_ITEM,itemQuan);
    dbw.insertOrThrow(TABLE_NAME_ITEM, null, cv);

}
</code>```

答:
Try using a for loop. Try this.</p>

```<code>String[] itemCode12345 = itemCode123.toArray(new String[itemCode123.size()]);
String[] itemQuan12345 = itemQuan123.toArray(new String[itemQuan123.size()]);

for(int a=0; a< t2Rows.size(); a++){
    db_data.addItem(abc+"",itemCode12345[a],itemQuan12345[a]);
}
</code>```

Body:
So I have a code where my variables var1, var2, and var3 goes to a List<String> temp. And for every click of a button, another batch of variables will go to temp and temp goes to List<List<String>> rows at the end of the function. Note that I can click the button as many times I want and the process temp.add(var1); temp.add(var2); ... rows.add(temp); will run.

Now, I want to break down rows and save all of the data of temp to my database.

here is a part of my code:

ArrayList<String> temp = new ArrayList<String>();
temp.add(itemnameCol);
temp.add(itempriceCol+"");
temp.add(dialogVar+"");
t2Rows.add(temp);

here is the insert method

public void addItem(String itemIn, String itemProd, String itemQuan){
    cv.clear();
    cv.put(INVOICE_NUM_ITEM,itemIn);
    cv.put(PRODUCT_ID_ITEM,itemProd);
    cv.put(PRODUCT_QUANTITY_ITEM,itemQuan);
    dbw.insertOrThrow(TABLE_NAME_ITEM, null, cv);

}

Body:
Try using a for loop. Try this.

String[] itemCode12345 = itemCode123.toArray(new String[itemCode123.size()]);
String[] itemQuan12345 = itemQuan123.toArray(new String[itemQuan123.size()]);

for(int a=0; a< t2Rows.size(); a++){
    db_data.addItem(abc+"",itemCode12345[a],itemQuan12345[a]);
}


问:
new Date() doesn't work with canvasjs & rangeBar
I tried to read some datas with AJAX json format from PHP code.

```<code>.../...
    $data[]     = array("label" => $my_label, "y" => array("new Date($yci,$mci,$dci,$hci,$ici)","new Date($yco,$mco,$dco,$hco,$ico)"));
}

return json_encode($data, JSON_NUMERIC_CHECK);
</code>```

Side JS

```<code>var chart = new CanvasJS.Chart("timeline", {
    title: {
        text: "How long an event occurred for on a given day"
    },
    axisY: {
        minimum: (new Date(2017, 5, 1, 00, 01)).getTime(),
        interval: (24 * 60 * 60 * 1000 * 7 ),
        labelFormatter: function(e){
        return CanvasJS.formatDate(e.value, "MM/DD");
        },
        gridThickness: 1
    },

    toolTip:{
        contentFormatter: function ( e ) {
        return "<strong>" + e.entries[0].dataPoint.label + "</strong></br> Start: " +  CanvasJS.formatDate(e.entries[0].dataPoint.y[0], "DD - h:mm TT") + "</br>End : " + CanvasJS.formatDate(e.entries[0].dataPoint.y[1], "DD - h:mm TT");
    }},

    data: [
    {
      type: "rangeBar",
    dataPoints: JSON.parse(json.message),
    }
    ]
});
chart.render();

}
</code>```

The issue is, unable to display the datas.
I think new date is not formated correctely.

```<code>[
{
    "label":"Room 200",
    "y":
         [
            "new Date(2017,5,06,14,20)",
            "new Date(2017,5,08,14,20)"
         ]
 },
 {
    "label":"Room 200",
    "y":
        [
            "new Date(2017,5,08,14,21)",
            "new Date(2017,5,10,14,21)"
        ]
},
{
    "label":"Room 201",
    "y":
        [
            "new Date(2017,5,11,15,59)",
            "new Date(2017,5,13,15,59)"
        ]
}
]
</code>```

Also, something is weird with new date() from canvasjs sample, at the end of each code, there's .getTime() like this : new date().getTime()

http://jsfiddle.net/canvasjs/xqgja576/

Can you help me please?

答:
The y values you have provided in array are strings ("new Date(2017,5,06,14,20)"). To evaluate this y value as date you can use eval function. Also, CanvasJS doesn't support dateTime over yAxis. As a workaround, you can call getTime() to fetch it's time-stamp and set it to y values.

```<code>for (var i = 0; i < dataPoints.length; i++) {
  for (var j = 0; j < dataPoints[i].y.length; j++) {
    y = eval(dataPoints[i].y[j]);
    //if(y.getTime)
    dataPoints[i].y[j] = y.getTime();
  }
}
</code>```

Here is a jsfiddle with your code and the changes.

Body:
I tried to read some datas with AJAX json format from PHP code.

.../...
    $data[]     = array("label" => $my_label, "y" => array("new Date($yci,$mci,$dci,$hci,$ici)","new Date($yco,$mco,$dco,$hco,$ico)"));
}

return json_encode($data, JSON_NUMERIC_CHECK);

Side JS

var chart = new CanvasJS.Chart("timeline", {
    title: {
        text: "How long an event occurred for on a given day"
    },
    axisY: {
        minimum: (new Date(2017, 5, 1, 00, 01)).getTime(),
        interval: (24 * 60 * 60 * 1000 * 7 ),
        labelFormatter: function(e){
        return CanvasJS.formatDate(e.value, "MM/DD");
        },
        gridThickness: 1
    },

    toolTip:{
        contentFormatter: function ( e ) {
        return "" + e.entries[0].dataPoint.label + "
 Start: " +  CanvasJS.formatDate(e.entries[0].dataPoint.y[0], "DD - h:mm TT") + "
End : " + CanvasJS.formatDate(e.entries[0].dataPoint.y[1], "DD - h:mm TT");
    }},

    data: [
    {
      type: "rangeBar",
    dataPoints: JSON.parse(json.message),
    }
    ]
});
chart.render();

}

The issue is, unable to display the datas.
I think new date is not formated correctely.

[
{
    "label":"Room 200",
    "y":
         [
            "new Date(2017,5,06,14,20)",
            "new Date(2017,5,08,14,20)"
         ]
 },
 {
    "label":"Room 200",
    "y":
        [
            "new Date(2017,5,08,14,21)",
            "new Date(2017,5,10,14,21)"
        ]
},
{
    "label":"Room 201",
    "y":
        [
            "new Date(2017,5,11,15,59)",
            "new Date(2017,5,13,15,59)"
        ]
}
]

Also, something is weird with new date() from canvasjs sample, at the end of each code, there's .getTime() like this : new date().getTime()

http://jsfiddle.net/canvasjs/xqgja576/

Can you help me please?

Body:
The y values you have provided in array are strings ("new Date(2017,5,06,14,20)"). To evaluate this y value as date you can use eval function. Also, CanvasJS doesn't support dateTime over yAxis. As a workaround, you can call getTime() to fetch it's time-stamp and set it to y values.

for (var i = 0; i < dataPoints.length; i++) {
  for (var j = 0; j < dataPoints[i].y.length; j++) {
    y = eval(dataPoints[i].y[j]);
    //if(y.getTime)
    dataPoints[i].y[j] = y.getTime();
  }
}

Here is a jsfiddle with your code and the changes.


问:
Remove toolbar elevation for specific fragment
How can I set Elevation to 0 or disable it for a specific Fragment of my NavigationDrawer? Programmatically or with theme maybe ?

toolbar.setElevation(0) seems not working.

This ìn my onNavigationItemSelected doesn't work, elevation won't change :

```<code>if (item.getItemId() == R.id.drawer_menu_account) {
    if (getSupportActionBar() != null) {
        getSupportActionBar().setElevation(0);
    }
} else {
    if (getSupportActionBar() != null) {
        getSupportActionBar().setElevation(8);
    }
}
</code>```

And there is my Coordinator layout with Toolbar

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".activity.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

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

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/ic_add_24dp" />

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

RESOLVED - Thanks to Amir ! Work with this in my onNavigationItemSelected

```<code>if (android.os.Build.VERSION.SDK_INT >= 21) {
    if (item.getItemId() == R.id.drawer_menu_account) {
         appBar.setElevation(0);
    } else {
         appBar.setElevation(8);
    }
}
</code>```

答:
To remove shadow in Toolbar use

app:elevation="0" in AppBarLayout xml or

use mAppBarLayout.setTargetElevation(0) in java.

It worked for me.

Body:
How can I set Elevation to 0 or disable it for a specific Fragment of my NavigationDrawer? Programmatically or with theme maybe ?

toolbar.setElevation(0) seems not working.

This ìn my onNavigationItemSelected doesn't work, elevation won't change :

if (item.getItemId() == R.id.drawer_menu_account) {
    if (getSupportActionBar() != null) {
        getSupportActionBar().setElevation(0);
    }
} else {
    if (getSupportActionBar() != null) {
        getSupportActionBar().setElevation(8);
    }
}

And there is my Coordinator layout with Toolbar

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".activity.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

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

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/ic_add_24dp" />

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

RESOLVED - Thanks to Amir ! Work with this in my onNavigationItemSelected

if (android.os.Build.VERSION.SDK_INT >= 21) {
    if (item.getItemId() == R.id.drawer_menu_account) {
         appBar.setElevation(0);
    } else {
         appBar.setElevation(8);
    }
}


问:
Fullcalendar v2 dayRender for agenda view and agendaWeek
In version 2 of Fullcalender I need the dayRender callback, I want to change color of disable day.

This callback only works for month, basicWeek, and basicDay views.. But I need this callback for agendaWeek and agenda.

Do you have any alternative or answers for dayRender ?

I try this :

```<code>        dayRender: function(date, cell){
            if (date > maxDate){
                $(cell).addClass('disabled');
                console.log("ok");
            }
        }
</code>```

and my view

```<code>       views: {
          agendaSix: {
              type: 'agenda',
              duration: { days: 6 },
              buttonText: '5 day',
          },
          agendaFive: {
              type: 'agenda',
              duration: { days: 5 },
              buttonText: '4 day'
          },
          agendaFour: {
              type: 'agenda',
              duration: { days: 4 },
              buttonText: '3 day'
          },
      },

      defaultView: 'agendaWeek'
</code>```

Thank you a lot !

答: For the agendaWeek, the dayRender call only fired if allDaySlot is set to true. If you set allDaySlot false then dayRender will not be called.</p>

Body:
In version 2 of Fullcalender I need the dayRender callback, I want to change color of disable day.

This callback only works for month, basicWeek, and basicDay views.. But I need this callback for agendaWeek and agenda.

Do you have any alternative or answers for dayRender ?

I try this :

        dayRender: function(date, cell){
            if (date > maxDate){
                $(cell).addClass('disabled');
                console.log("ok");
            }
        }

and my view

       views: {
          agendaSix: {
              type: 'agenda',
              duration: { days: 6 },
              buttonText: '5 day',
          },
          agendaFive: {
              type: 'agenda',
              duration: { days: 5 },
              buttonText: '4 day'
          },
          agendaFour: {
              type: 'agenda',
              duration: { days: 4 },
              buttonText: '3 day'
          },
      },

      defaultView: 'agendaWeek'

Thank you a lot !


问:
GROUP BY & ORDER BY - Ordering by a specific field
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

```<code>SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

```<code>SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!

答:
```<code>SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
ORDER BY items.popularity DESC
</code>```

You shouldn't need the group by as you are already selecting a specific class in the where statement. Additionally, the DESC in the order by should take care of the order without the need for the MAX.

Body:
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!

Body:
SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
ORDER BY items.popularity DESC

You shouldn't need the group by as you are already selecting a specific class in the where statement. Additionally, the DESC in the order by should take care of the order without the need for the MAX.


问:
How to clear APC cache entries?
I need to clear all APC cache entries when I deploy a new version of the site.
APC.php has a button for clearing all opcode caches, but I don't see buttons for clearing all User Entries, or all System Entries, or all Per-Directory Entries.

Is it possible to clear all cache entries via the command-line, or some other way?

答:
My work-around for Symfony build having loot of instances at the same server:

Step 1.
Create trigger or something to set a file flag (eg. Symfony command) then create marker file ..

```<code>file_put_contents('clearAPCU','yes sir i can buggy')
</code>```

Step 2.
On index file at start add clearing code and remove marker file.

```<code>if(file_exists('clearAPCU')){
    apcu_clear_cache();
    unlink('clearAPCU');
}
</code>```

Step 2.
Run app.

Title: How to clear APC cache entries?

Body:
My work-around for Symfony build having loot of instances at the same server:

Step 1.
Create trigger or something to set a file flag (eg. Symfony command) then create marker file ..

file_put_contents('clearAPCU','yes sir i can buggy')

Step 2.
On index file at start add clearing code and remove marker file.

if(file_exists('clearAPCU')){
    apcu_clear_cache();
    unlink('clearAPCU');
}

Step 2.
Run app.


问:
file record delimeter validation in xsd
Require you help in getting the below one.

Requirement :

We are getting data in file using , as a delimeter .

Example Data :

12345,aaaa,bbbb,ssc,aaa,99999999,xxx@gmail.com

So my problem is when we are using it in nxsd , can we validate the data that is coming in with some regular expression or something ( so that it takes only , delimiter records) apart from that when ever there will be another special character it should throw an error. Is it possible in nxsd.

Example1 of invalid data :

1|ddd|ggg|fff|ttt|777777777|ee@gmail.com

Example2 of invalid data :

12345,aaaa,bbbb,ssc,aaa,99999999,xxx@gmail.com
1|ddd|ggg|fff|ttt|777777777|ee@gmail.com

Please let me know how we can proceed further in this case.

Thanks & Regards,
Vivek.

答:
the regex that would only give you valid strings would be:

^(?:[a-zA-Z0-9 ]+,)*[a-zA-Z0-9 ]+$

Then you could do a fn:tokenize in your transformation which would help this?

Let me know if this is the answer you need?

Title: file record delimeter validation in xsd


问:
Testing Java Optional
I'm looking into Java Optional and testing some usecases beyond the standard ones.

ok, let's take this example:

```<code>public void increment(Integer value) {
        if (currentValue != null && endValue != null && currentValue < (endValue - value)) {
            currentValue+=value;
        }
    }
</code>```

currentValue and endValue are Integer.

Can the example above be converted in Java8 using Optional?

I was thinking something like that:

```<code>public void increment(Integer value) {
        currentValue.filter(a-> a < (endValue.get()-value)).map(???);
    }
</code>```

where currentValue and endValue are Optional<Integer>

I'm actually stuck with the .map Function.

I would appreciate any suggestion, thanks

答:
Note that I think you code is fine without optionals. If you insist that you want to use the optionals, keep reading.

You just want to add value in the map function, right? Then do this in the map call:

```<code>x -> x + value
</code>```

Since map returns an Optional<Integer>, you should assign the result back to currentValue:

```<code>currenValue = currentValue.filter(
    a -> a < endValue.get() - value).map(x -> x + value);
</code>```

However, this will crash if endValue does not have a value.

I used this little trick here to make this work:

```<code>currenValue = currentValue.filter(
    a -> a < endValue.orElse(Integer.MIN_VALUE + value) - value).map(x -> x + value).orElse(currentValue);
</code>```

The idea is that if endValue is empty, it is replaced with Integer.MIN_VALUE + value. Integer.MIN_VALUE + value - value is equal to Integer.MIN_VALUE, which no number can be smaller than. a < Integer.MIN_VALUE must fail.

Title: Testing Java Optional

Body:
I'm looking into Java Optional and testing some usecases beyond the standard ones.

ok, let's take this example:

public void increment(Integer value) {
        if (currentValue != null && endValue != null && currentValue < (endValue - value)) {
            currentValue+=value;
        }
    }

currentValue and endValue are Integer.

Can the example above be converted in Java8 using Optional?

I was thinking something like that:

public void increment(Integer value) {
        currentValue.filter(a-> a < (endValue.get()-value)).map(???);
    }

where currentValue and endValue are Optional<Integer>

I'm actually stuck with the .map Function.

I would appreciate any suggestion, thanks

Body:
Note that I think you code is fine without optionals. If you insist that you want to use the optionals, keep reading.

You just want to add value in the map function, right? Then do this in the map call:

x -> x + value

Since map returns an Optional<Integer>, you should assign the result back to currentValue:

currenValue = currentValue.filter(
    a -> a < endValue.get() - value).map(x -> x + value);

However, this will crash if endValue does not have a value.

I used this little trick here to make this work:

currenValue = currentValue.filter(
    a -> a < endValue.orElse(Integer.MIN_VALUE + value) - value).map(x -> x + value).orElse(currentValue);

The idea is that if endValue is empty, it is replaced with Integer.MIN_VALUE + value. Integer.MIN_VALUE + value - value is equal to Integer.MIN_VALUE, which no number can be smaller than. a < Integer.MIN_VALUE must fail.


问:
How can I check wether an array contains any item or is completely empty?
If I define an integer array:

```<code>int[] a = new int[13];
</code>```

and I do not insert any item into it, how can I know whether the array a contains any items or is completely empty?
Do I have to iterate through all the a.Length indices?
In a list

```<code>List<int> b = new List<int>();
</code>```

if I check:

```<code>if(b.Count == 0)
{
    // The list does not contain any items.
}
</code>```

Is there an equivalent way to check an array?
I found on the internet the check if an array is null or empty.
In my case I know for sure that the array is not null.
I just wish to know whether it contains any item or not.
I do not care in which position within the array and also not exactly which item.
Thank you very much in advance.

答:
```<code>int[] a = new int[13]; // [0,0,0,0,0,0,0,0,0,0,0,0,0]
</code>```

allocates a array with 13 items. The value of each item is 0 or default(int).

So you have to check

```<code>bool isEmpty =  a.All(x => x == default(int));
</code>```

If 0 is a valid value within your array, you should use nullable type:

```<code>int?[] a = new int?[13]; // [null,null,null,null,null,null,null,null,null,null,null,null,null]
bool isEmpty =  a.All(x => !x.HasValue);
</code>```

Body:
If I define an integer array:

int[] a = new int[13];

and I do not insert any item into it, how can I know whether the array a contains any items or is completely empty?
Do I have to iterate through all the a.Length indices?
In a list

List<int> b = new List<int>();

if I check:

if(b.Count == 0)
{
    // The list does not contain any items.
}

Is there an equivalent way to check an array?
I found on the internet the check if an array is null or empty.
In my case I know for sure that the array is not null.
I just wish to know whether it contains any item or not.
I do not care in which position within the array and also not exactly which item.
Thank you very much in advance.

Body:
int[] a = new int[13]; // [0,0,0,0,0,0,0,0,0,0,0,0,0]

allocates a array with 13 items. The value of each item is 0 or default(int).

So you have to check

bool isEmpty =  a.All(x => x == default(int));

If 0 is a valid value within your array, you should use nullable type:

int?[] a = new int?[13]; // [null,null,null,null,null,null,null,null,null,null,null,null,null]
bool isEmpty =  a.All(x => !x.HasValue);

ContentLicense: CC BY-SA 4.0


问:
SQL return the most recent record of a specific type if a condition is met
Hopefully I don't make this complicated.
I wrote the following SQL that returns the users that their most recent transactions meet a condition
(TRANS_TYPE NOT IN (4, 6, 21, 23) OR DEPOSIT_OPTION & 64 <> 64).

```<code>SELECT
TERMINAL_ID,REGISTER_ID,[USER_ID],sub.CREATE_DATE,sub.TRANS_TYPE_ID,BUS_DATE_ID
FROM (
SELECT
T.TERMINAL_ID
,US.REGISTER_ID
,U.[USER_ID]
,T.CREATE_DATE
,T.TRANS_TYPE_ID
,T.BUS_DATE_ID
,T.TRANS_CONFIG_ID
,TT.TRANS_TYPE
, row_number()
over (partition by U.[USER_ID]
order by T.CREATE_DATE desc) rn
From [RCMDYNAMIC].[dbo].[Transaction] T
INNER JOIN [RCMDYNAMIC].[dbo].[UserSession] US ON T.USER_SESSION_ID = US.USER_SESSION_ID
INNER JOIN [RCMSTATIC].[dbo].[User] U ON U.[USER_ID] = US.[USER_ID]
INNER JOIN [RCMSTATIC].[dbo].[TransactionType] TT ON T.TRANS_TYPE_ID = TT.TRANS_TYPE_ID
INNER JOIN [RCMSTATIC].[dbo].[Register] R ON US.REGISTER_ID = R.REGISTER_ID
) sub
LEFT JOIN
[RCMSTATIC].[dbo].[DepositConfig] DC
ON sub.TRANS_CONFIG_ID = DC.DEPOSIT_ID
WHERE sub.rn = 1 AND (TRANS_TYPE NOT IN (4, 6, 21, 23) OR DEPOSIT_OPTION & 64 <> 64)
</code>```

I acquired the " most recent transaction" by using

row_number()
    over (partition by U.[USER_ID]
    order by T.CREATE_DATE desc) rn

However, what I really want is selecting the most recent transaction of TRANS_TYPE = 10 IF the most recent transaction met the previous condition.

The sub query in the previous code will return all transactions for all users and rank them in DESC order and the outer SELECT will display the users that meet the condition by checking their Rank 1 transaction.

What I want is having something like this

FOREACH user
IF the user rank 1 transaction meet the condition
THEN
FIND the user most recent transaction of TRANS_TYPE 10

it could be the transaction rank 1 or rank N

Example:

```<code>User_ID   TRANS_TYPE  DEPOSIT_OPTION Rank
   1           4           7          1
   1           10          7          2
   2           22          64         1
   2           23          4          2
   2           10          126        3
   2            4          7          4
   3           10          3          1
   4           6           64         1 -- doesn't meet the condition
   4           10          7          2
</code>```

form the previous results if the Rank 1 row satisfies the condition

```<code>WHERE sub.rn = 1 AND (TRANS_TYPE NOT IN (4, 6, 21, 23) OR DEPOSIT_OPTION & 64 <> 64)
</code>```

I want the TRANS_TYPE= 10 to be displayed so I would expect the result to be:

```<code> User_ID   TRANS_TYPE   Rank
   1           10        2
   2           10        3
   3           10        1
</code>```

I am sorry if the question is not very clear I tried my best!

答:
```<code>drop table if exists dbo.Deposits;

create table dbo.Deposits (
User_ID int
, Trans_Type int
, Deposit_Option int
, Rank int
);

insert into dbo.Deposits (User_ID, Trans_Type, Deposit_Option, Rank)
values (1, 4, 7, 1), (1, 10, 7, 2)
, (2, 22, 64, 1), (2, 23, 4, 2), (2, 10, 126, 3), (2, 4, 7, 4)
, (3, 10, 3, 1)
, (4, 6, 64, 1), (4, 10, 7, 2);

select
sub2.User_ID, sub2.Trans_Type, sub2.Rank
from dbo.Deposits sub
inner join dbo.Deposits sub2 on sub.User_ID = sub2.User_ID
        and sub2.Trans_Type = 10
where sub.Rank = 1 AND (sub.Trans_Type NOT IN (4, 6, 21, 23) OR sub.Deposit_Option & 64 <> 64)
</code>```

Body:
Hopefully I don't make this complicated.
I wrote the following SQL that returns the users that their most recent transactions meet a condition
(TRANS_TYPE NOT IN (4, 6, 21, 23) OR DEPOSIT_OPTION & 64 <> 64).

SELECT
TERMINAL_ID,REGISTER_ID,[USER_ID],sub.CREATE_DATE,sub.TRANS_TYPE_ID,BUS_DATE_ID
FROM (
SELECT
T.TERMINAL_ID
,US.REGISTER_ID
,U.[USER_ID]
,T.CREATE_DATE
,T.TRANS_TYPE_ID
,T.BUS_DATE_ID
,T.TRANS_CONFIG_ID
,TT.TRANS_TYPE
, row_number()
over (partition by U.[USER_ID]
order by T.CREATE_DATE desc) rn
From [RCMDYNAMIC].[dbo].[Transaction] T
INNER JOIN [RCMDYNAMIC].[dbo].[UserSession] US ON T.USER_SESSION_ID = US.USER_SESSION_ID
INNER JOIN [RCMSTATIC].[dbo].[User] U ON U.[USER_ID] = US.[USER_ID]
INNER JOIN [RCMSTATIC].[dbo].[TransactionType] TT ON T.TRANS_TYPE_ID = TT.TRANS_TYPE_ID
INNER JOIN [RCMSTATIC].[dbo].[Register] R ON US.REGISTER_ID = R.REGISTER_ID
) sub
LEFT JOIN
[RCMSTATIC].[dbo].[DepositConfig] DC
ON sub.TRANS_CONFIG_ID = DC.DEPOSIT_ID
WHERE sub.rn = 1 AND (TRANS_TYPE NOT IN (4, 6, 21, 23) OR DEPOSIT_OPTION & 64 <> 64)

I acquired the " most recent transaction" by using

row_number()
    over (partition by U.[USER_ID]
    order by T.CREATE_DATE desc) rn

However, what I really want is selecting the most recent transaction of TRANS_TYPE = 10 IF the most recent transaction met the previous condition.

The sub query in the previous code will return all transactions for all users and rank them in DESC order and the outer SELECT will display the users that meet the condition by checking their Rank 1 transaction.

What I want is having something like this

FOREACH user
IF the user rank 1 transaction meet the condition
THEN
FIND the user most recent transaction of TRANS_TYPE 10

it could be the transaction rank 1 or rank N

Example:

User_ID   TRANS_TYPE  DEPOSIT_OPTION Rank
   1           4           7          1
   1           10          7          2
   2           22          64         1
   2           23          4          2
   2           10          126        3
   2            4          7          4
   3           10          3          1
   4           6           64         1 -- doesn't meet the condition
   4           10          7          2

form the previous results if the Rank 1 row satisfies the condition

WHERE sub.rn = 1 AND (TRANS_TYPE NOT IN (4, 6, 21, 23) OR DEPOSIT_OPTION & 64 <> 64)

I want the TRANS_TYPE= 10 to be displayed so I would expect the result to be:

 User_ID   TRANS_TYPE   Rank
   1           10        2
   2           10        3
   3           10        1

I am sorry if the question is not very clear I tried my best!


问:
Using SpringBoot CrudRepository to find one known entry
I am currently working with a project that uses SpringBoot.

I have created a tabled called configuration_documents using Hibernate.  This table can store different types of document objects that I have created.

One of the document objects I have created is Index, and I want to retrieve Index data, so I created a repository like this:

```<code>public interface IndexRepository extends CrudRepository<Index, Long> {
}
</code>```

I know for a fact that the configuration_document table should only have one entry of Index, or else just return the 1st Index in the table.  What is best way of implementing this?

Without modifying IndexRepository, I am currently thinking of something like this (The IndexRepository is autowired in):

```<code>StreamSupport.stream(this.configurationRepository.findAll().spliterator(), false).
                map(
                    return Index;
                ).//A Collector here perhaps?
</code>```

Thanks.

答:
In spring jpa, you could limit the result as shown following:

```<code>public interface IndexRepository extends CrudRepository<Index, Long> {

           Index findFirstByOrderByIdAsc();
    }
</code>```

reference

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result

Body:
I am currently working with a project that uses SpringBoot.

I have created a tabled called configuration_documents using Hibernate.  This table can store different types of document objects that I have created.

One of the document objects I have created is Index, and I want to retrieve Index data, so I created a repository like this:

public interface IndexRepository extends CrudRepository<Index, Long> {
}

I know for a fact that the configuration_document table should only have one entry of Index, or else just return the 1st Index in the table.  What is best way of implementing this?

Without modifying IndexRepository, I am currently thinking of something like this (The IndexRepository is autowired in):

StreamSupport.stream(this.configurationRepository.findAll().spliterator(), false).
                map(
                    return Index;
                ).//A Collector here perhaps?

Thanks.

Body:
In spring jpa, you could limit the result as shown following:

public interface IndexRepository extends CrudRepository<Index, Long> {

           Index findFirstByOrderByIdAsc();
    }

reference

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result


问:
Ceph configuration file and ceph-deploy
I set up a test cluster and follow the documentation.

I created cluster with command ceph-deploy new node1. After that, ceph configuration file appeared in the current directory, which contains information about the monitor on the node with hostname node1. Then I added two OSDs to the cluster.

So now I have cluster with 1 monitor and 2 OSDs. ceph status command says that status is HEALTH_OK.

Following all the same documentation, I moved on to section "Expanding your cluster" and added two new monitors with commands ceph-deploy mon add node2 and ceph-deploy mon add node3. Now I have cluster with three monitors in the quorum and status HEALTH_OK, but there is one little discrepancy for me. The ceph.conf is still the same. It contains old information about only one monitor. Why ceph-deploy mon add {node-name} command didn't update configuration file? And the main question is why ceph status displays correct information about new cluster state with 3 monitors while ceph.conf doesn't contain this information. Where is real configuration file and why ceph-deploy knows it but I don't?

And it works even after a reboot. All ceph daemons start, read incorrect ceph.conf (I checked this with strace) and, ignoring this, work fine with new configuration.

And the last question. Why ceph-deploy osd activate {ceph-node}:/path/to/directory command didn't update configuration file too? After all why do we need ceph.conf file if we have so smart ceph-deploy now?

答:
You have multiple questions here.

1) ceph.conf doesn't need to be completely the same for all nodes to run. E.g. OSD only need osd configuration they care about, MON only need configuration mon care ( unless you run everything on the same node which is also not recommended) So maybe your MON1 has MON1 MON2 has MON2 MON3 has MON3

2) When MON being created and then added, the MON map being updated so MON itself already know which other MON require to have quorum. So MON doesn't counting on ceph.conf to get quorum information but to change run time configuration.

3) ceph-deploy just a python script to prepare and run the ceph command for you. If you read into the detail ceph-deploy use e.g. ceph-disk zap prepare activate.
Once you osd being prepared, and activate, once it is format to ceph partition, udev know where to mount. Then systemd ceph-osd.server will be activate ceph-osd at boot. That's why it doesn't need OSD information in ceph.conf at all

Title: Ceph configuration file and ceph-deploy


问:
How to implement such use case by Java Concurrency Lock
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

```<code>public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}
</code>```

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

答:
This is certainly a case where a ReadWriteLock should help.
Many concurrent readers can operate with miniscule contention and very infrequently a writer acquires the write-lock and updates.

However the key issue raised is that a thread must not read one old key and one new key in a single pass.

That's a classical problem. The easiest solution is to update both keys in the update thread.

```<code>ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock(true);
//If in doubt require a fair lock to avoid live-locking writes...

//...

public void update() {
    String new1=getFromFile();
    String new2=getFromFile();
    //That's the heavy lifting. Only now acquire the lock...
    Lock wlock=rwlock.writeLock();
    wlock.lock();
    try {
        key1=new1;
        key2=new2;
    } finally {
        wlock.unlock();
    }
}
</code>```

And in the readers:

```<code>public String[] getKeys() {
    String k1;
    String k2;
    Lock rlock=rwlock.readLock();
    rlock.lock();
    try {
        k1=key1;
        k2=key2;
    } finally {
        rlock.unlock();
    }
    String[] r={k1,k2};
    return r;
 }
</code>```

A read-write lock has two connected locks. Multiple readers can acquire the read-lock but the write lock is exclusive of readers and other writers. It is a common scenario and has established solutions.

It may be important to get from the file before acquiring the lock as I/O is often relatively slow and you should hold the lock for the minimum possible time.

It's also important to return both keys from the same acquisition of the lock. There's no other easy way to stop update happening between calls to getKey1() and getKey2().

You no longer need to use the volatile keyword because of the memory barrier guarantees of the lock (see doc.).

You don't actually need a re-entrant lock but that is what is provided out-of-the-box for a read-write lock.

This is a case where something called a sequential lock (Seqlock) could help but that will involve more coding and may be over-engineered here.

References:

https://en.wikipedia.org/wiki/Seqlock

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html

Body:
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

Body:
This is certainly a case where a ReadWriteLock should help.
Many concurrent readers can operate with miniscule contention and very infrequently a writer acquires the write-lock and updates.

However the key issue raised is that a thread must not read one old key and one new key in a single pass.

That's a classical problem. The easiest solution is to update both keys in the update thread.

ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock(true);
//If in doubt require a fair lock to avoid live-locking writes...

//...

public void update() {
    String new1=getFromFile();
    String new2=getFromFile();
    //That's the heavy lifting. Only now acquire the lock...
    Lock wlock=rwlock.writeLock();
    wlock.lock();
    try {
        key1=new1;
        key2=new2;
    } finally {
        wlock.unlock();
    }
}

And in the readers:

public String[] getKeys() {
    String k1;
    String k2;
    Lock rlock=rwlock.readLock();
    rlock.lock();
    try {
        k1=key1;
        k2=key2;
    } finally {
        rlock.unlock();
    }
    String[] r={k1,k2};
    return r;
 }

A read-write lock has two connected locks. Multiple readers can acquire the read-lock but the write lock is exclusive of readers and other writers. It is a common scenario and has established solutions.

It may be important to get from the file before acquiring the lock as I/O is often relatively slow and you should hold the lock for the minimum possible time.

It's also important to return both keys from the same acquisition of the lock. There's no other easy way to stop update happening between calls to getKey1() and getKey2().

You no longer need to use the volatile keyword because of the memory barrier guarantees of the lock (see doc.).

You don't actually need a re-entrant lock but that is what is provided out-of-the-box for a read-write lock.

This is a case where something called a sequential lock (Seqlock) could help but that will involve more coding and may be over-engineered here.

References:

https://en.wikipedia.org/wiki/Seqlock

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html


问:
How to loop over form field choices and display associated model instance fields
I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How  do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

```<code>#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}
</code>```

答:
This answer provides a custom form widget - TableSelectMultiple - which sounds like what you want:

Formsets with checkboxes

There's also the original Django Snippet.

Body:
I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How  do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}


答:
When you define an array like this:

```<code>int[] a = new int[13];
</code>```

you get an array that contains 13 elements. All of them have the value zero because that's the default value for an int.

So what you could do is:

```<code>bool hasElements = a.Any(x => x != 0);
</code>```

Title: How can I check wether an array contains any item or is completely empty?

Body:
When you define an array like this:

int[] a = new int[13];

you get an array that contains 13 elements. All of them have the value zero because that's the default value for an int.

So what you could do is:

bool hasElements = a.Any(x => x != 0);


问:
How to Pass information Back in iOS when reversing a Segue using Swift?
I have two view controllers, One and Two. I go from VC One to VC Two. On VC Two, I select some data that I store in an array. When I press the "Back" button on the navigation bar, I would like to send that array back to VC One.

What's the best way to do this using Swift & Storyboards?

Thanks!

答:
Here is my solution in Swift 3

1) Create a protocol inside the SecondController.swift file. We preferably create the protocol from where we will be getting data from.

```<code>protocol Protocol {
        func passingDataBack(withString: String)
}
</code>```

2) Create a variable of type Protocol

```<code>var proto: Protocol!
</code>```

3) Switch to the ViewController.swift file and inherit the Protocol we made from the SecondController.swift file.

```<code>class ViewController: UIViewController, Protocol {

}
</code>```

4) We then want to conform to the Protocol we made by creating the function we made

```<code>    func passingDataBack(withString: String) {
//        withString will return the value that has been passed from our SecondController class
        self.title = withString

    }
</code>```

5) Use the prepareForSegue method and segue to the SecondController class

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as? SecondController
        vc?.proto = self //This line will instantiate the protocol to our ViewController class
    }
</code>```

6) Go back to our SecondController.swift file and use the didSelectRow method and pass our data

```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.
    _ = self.navigationController?.popViewController(animated: true) //This will pop back to our previous controller.

}
</code>```

* Important Things To Remember!!! *

You must set the protocol from controllerB to instantiate to controllerA when switching from controllerA to controllerB

In our example, we moved from ViewController to SecondController. We instantiate our protocol from our SecondController by doing

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as? SecondController
    vc?.proto = self //This line will instantiate the protocol to our ViewController class
}
</code>```

If you do not do this, you will get a Thread 001 error on this line

```<code>proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.
</code>```

Source code Github

Body:
Here is my solution in Swift 3

1) Create a protocol inside the SecondController.swift file. We preferably create the protocol from where we will be getting data from.

protocol Protocol {
        func passingDataBack(withString: String)
}

2) Create a variable of type Protocol

var proto: Protocol!

3) Switch to the ViewController.swift file and inherit the Protocol we made from the SecondController.swift file.

class ViewController: UIViewController, Protocol {

}

4) We then want to conform to the Protocol we made by creating the function we made

    func passingDataBack(withString: String) {
//        withString will return the value that has been passed from our SecondController class
        self.title = withString

    }

5) Use the prepareForSegue method and segue to the SecondController class

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as? SecondController
        vc?.proto = self //This line will instantiate the protocol to our ViewController class
    }

6) Go back to our SecondController.swift file and use the didSelectRow method and pass our data

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.
    _ = self.navigationController?.popViewController(animated: true) //This will pop back to our previous controller.

}

* Important Things To Remember!!! *

You must set the protocol from controllerB to instantiate to controllerA when switching from controllerA to controllerB

In our example, we moved from ViewController to SecondController. We instantiate our protocol from our SecondController by doing

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as? SecondController
    vc?.proto = self //This line will instantiate the protocol to our ViewController class
}

If you do not do this, you will get a Thread 001 error on this line

proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.

Source code Github


问:
Distribute msvcr120.dll with a c++ app that was created with Visual Studio 2015
I have created a c++ app using visual studio 2015. My distribution package requires files msvcp140.dll and vcruntime140.dll in order for my app to run correctly on another pc. According to https://www.visualstudio.com/license-terms/distributable-code-microsoft-visual-studio-2015-rc-microsoft-visual-studio-2015-sdk-rc-includes-utilities-buildserver-files/:

Visual C++ Runtime Files Subject to the License Terms for the
  software, you may copy and distribute with your program any of the
  files within the followng folder and its subfolders except as noted
  below. You may not modify these files. C:\Program Files
  (x86)\Microsoft Visual Studio 14.0\VC\redist

Since both of the above files reside in C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist I can distribute these two files with my executable.
However  I also need file msvcr120.dll due to a precompiled third party library that I also use. This file resides in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Performance Tools.

I know that there is an option by using specific inno setup file to check which vc++ redistributables are needed and to installed the correct ones. However for the time being I just need to include the relevant dll in my executable setup package.

So my question is whether I'm allowed to distribute msvcr120.dll with my package as well?

答:
If you have VS 2013 and you can find the msvcr120.dll file under C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\redist\arm\Microsoft.VC120.CRT, for the detail information, please check this: Determining Which DLLs to Redistribute

If you do not install the VS 2013, their DLLS are also available as stand-alone redistributable packages from the Microsoft Download Center.

Refer to Distributable Code for Microsoft Visual Studio 2013 and Microsoft Visual Studio 2013 SDK (Includes Utilities & BuildServer Files) and you should be able to distribute the  msvcr120.dll file from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\redist\arm\Microsoft.VC120.CRT.


问:
How to change app:elevation programmatically
My app is work for API 19. So I can't use android:elevation. So I app:elevation in my layout.

Android XML: android:elevation vs. app:elevation

For exemple :

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"
    app:elevation="5dp">
</code>```

How to change app:elevation programmatically ? I can change android:elevation but I can't find how to change app:elevation !

答:
Accepted answer didn't work for me.

To remove shadow in Toolbar use

app:elevation="0" in AppBarLayout xml or

use mAppBarLayout.setTargetElevation(0) in java.

It worked in my case.

Body:
My app is work for API 19. So I can't use android:elevation. So I app:elevation in my layout.

Android XML: android:elevation vs. app:elevation

For exemple :

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"
    app:elevation="5dp">

How to change app:elevation programmatically ? I can change android:elevation but I can't find how to change app:elevation !


问:
UITextView text content doesn't start from the top
I have a long text coming from my JSON file but when I click the link from my UITableViewCell to go to my UIViewController page, the UITextView text loads the string content but it does not show the content from the beginning and I have to scroll up all the time.

What I need to do?

答:
This worked the best for me! I placed this within viewDidLoad().</p>

```<code>//TextView Scroll starts from the top
myTextView.contentOffset.y = 0
</code>```

Body:
This worked the best for me! I placed this within viewDidLoad().

//TextView Scroll starts from the top
myTextView.contentOffset.y = 0


问:
can't import android.os.SystemProperties in Camera app
In camera.java, I need to get property in system. However, I can't import android.os.SystemProperties, compile camera always complains:

```<code>packages/apps/Camera/src/com/android/camera/Camera.java:53: cannot find symbol
symbol  : class SystemProperties
location: package android.os
import android.os.SystemProperties;
</code>```

In the beginning of camera.java, I included:

```<code>import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.os.SystemProperties; /* (this is in line 53)*/
</code>```

It seems SystemProperties is not in android.os package, but I have checked the frameworks source code, it's indeed in it.

This happen in camera app. I found many apps under packages/app dir using SystemProperties in this manner. It's really strange.

答:
i have encounter the same problem as you have, and i use the code below, and solve the problem by using refelection. hope it would be help</p>

```<code>//set SystemProperties as you want
public static void setProperty(String key, String value) {
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method set = c.getMethod("set", String.class, String.class);
            set.invoke(c, key, value );
        } catch (Exception e) {
            Log.d(LOGTAG, "setProperty====exception=");
            e.printStackTrace();
        }
    }
</code>```

Body:
In camera.java, I need to get property in system. However, I can't import android.os.SystemProperties, compile camera always complains:

packages/apps/Camera/src/com/android/camera/Camera.java:53: cannot find symbol
symbol  : class SystemProperties
location: package android.os
import android.os.SystemProperties;

In the beginning of camera.java, I included:

import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.os.SystemProperties; /* (this is in line 53)*/

It seems SystemProperties is not in android.os package, but I have checked the frameworks source code, it's indeed in it.

This happen in camera app. I found many apps under packages/app dir using SystemProperties in this manner. It's really strange.

Body:
i have encounter the same problem as you have, and i use the code below, and solve the problem by using refelection. hope it would be help

//set SystemProperties as you want
public static void setProperty(String key, String value) {
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method set = c.getMethod("set", String.class, String.class);
            set.invoke(c, key, value );
        } catch (Exception e) {
            Log.d(LOGTAG, "setProperty====exception=");
            e.printStackTrace();
        }
    }


问:
"Failed - Network error" message when exporting data to Excel in ASP.NET MVC
I am trying to export data to excel file asp.net mvc using the Response.ContenType approach. Below is my code:

```<code> StringBuilder sb = new StringBuilder();
 sb.Append("<table><tr><td>");
 //some code to convert database records to html table in stringbuilder

 Response.Clear();
 Response.ClearContent();
 Response.ClearHeaders();
 Response.Charset = "";
 Response.Buffer = true;
 Response.ContentType = "application/vnd.ms-excel";
 Response.AddHeader("content-disposition", "attachment;filename=UserReport.xls");
 Response.Write(sb.ToString());
 Response.Flush();
 Response.Close();
</code>```

This code is working on my local pc but on server it is not working. On server i am getting "Failed - Network error" on chrome browser.

If I do not put Response.Clear(); and Response.Close(); as said in other similar answers. The excel file is wrongly generated. See the below image.

Update: I checked it on other browsers and found out that it is working on IE and Firefox but on Chrome it is now working. So why chrome is not behaving like other browsers ?

答:
```<code><system.webServer>
  <staticContent>
    <remove fileExtension="xls"/>
    <mimeMap fileExtension="xls" mimeType="application/vnd.ms-excel"/>
  </staticContent>
</system.webServer>
</code>```

OR

```<code><configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".xslx" mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
        </staticContent>
    </system.webServer>
</configuration>
</code>```

Check your MIME-Types in IIS  the webserver is not aware of the Office 2007 and higher file extensions and refuses to serve them.

Body:
I am trying to export data to excel file asp.net mvc using the Response.ContenType approach. Below is my code:

 StringBuilder sb = new StringBuilder();
 sb.Append("

");
 //some code to convert database records to html table in stringbuilder

 Response.Clear();
 Response.ClearContent();
 Response.ClearHeaders();
 Response.Charset = "";
 Response.Buffer = true;
 Response.ContentType = "application/vnd.ms-excel";
 Response.AddHeader("content-disposition", "attachment;filename=UserReport.xls");
 Response.Write(sb.ToString());
 Response.Flush();
 Response.Close();

This code is working on my local pc but on server it is not working. On server i am getting "Failed - Network error" on chrome browser.

If I do not put Response.Clear(); and Response.Close(); as said in other similar answers. The excel file is wrongly generated. See the below image.

Update: I checked it on other browsers and found out that it is working on IE and Firefox but on Chrome it is now working. So why chrome is not behaving like other browsers ?

Body:
<system.webServer>
  <staticContent>
    <remove fileExtension="xls"/>
    <mimeMap fileExtension="xls" mimeType="application/vnd.ms-excel"/>
  </staticContent>
</system.webServer>

OR

<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".xslx" mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
        </staticContent>
    </system.webServer>
</configuration>

Check your MIME-Types in IIS  the webserver is not aware of the Office 2007 and higher file extensions and refuses to serve them.


问:
css odd and even selector not working
I'm creating a rating control made of half stars and I want to be able to select odd and even labels inside the .rating control. The selector shoudl look like this but it's not working here is my codepen check my html out while your there

```<code>.rating {
    label:nth-child(odd)::before {} // not working
}
.rating {
    label:nth-child(even)::before {} // not working
}
</code>```

Full CSS:

```<code>@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css);

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

body {
  background: #272727;
}

.rating {
position: absolute;
display: inline-block;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

label {
  font-size: 24px;
  font-family: FontAwesome;
  color: #afa302;
}

label.half_l::before {
  content: '\f006';
  display: inline-block;
  width: 11px;
  overflow: hidden;
}

label.half_r {

  width: 12px;
  position: relative;
  overflow: hidden;
  display: inline-block;
  margin-right: 3px;
}
label.half_r::before {
  content: '\f006';
  display: inline-block;
  left: -11px;
  position: relative;
}

label {
  float: right;
}

label:hover {
  color: #fff239;
}

> input {
  display: none;
}

label.half_l:hover:before,
label.half_l:hover ~ label.half_l:before {
  content: '\f089';
  color: #fff239;
}

label.half_l:hover ~ label.half_r::before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover:before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover ~ label.half_r::before,
label.half_r:hover ~ label.half_l:before {
  content: '\f005';
  color: #fff239;
}

input[type=radio]:checked ~ label.half_l:before,
input[type=radio]:checked ~ label.half_r:before{
  content: '\f005';
}
</code>```

}

答:
Use nth-of-type instead of nth-child

```<code>label:nth-of-type(odd) {
  background-color:red;
}
</code>```

nth-child looks for all children, regardless their type, where nth-of-type looks for a certain type

Title: css odd and even selector not working

Body:
I'm creating a rating control made of half stars and I want to be able to select odd and even labels inside the .rating control. The selector shoudl look like this but it's not working here is my codepen check my html out while your there

.rating {
    label:nth-child(odd)::before {} // not working
}
.rating {
    label:nth-child(even)::before {} // not working
}

Full CSS:

@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css);

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

body {
  background: #272727;
}

.rating {
position: absolute;
display: inline-block;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

label {
  font-size: 24px;
  font-family: FontAwesome;
  color: #afa302;
}

label.half_l::before {
  content: '\f006';
  display: inline-block;
  width: 11px;
  overflow: hidden;
}

label.half_r {

  width: 12px;
  position: relative;
  overflow: hidden;
  display: inline-block;
  margin-right: 3px;
}
label.half_r::before {
  content: '\f006';
  display: inline-block;
  left: -11px;
  position: relative;
}

label {
  float: right;
}

label:hover {
  color: #fff239;
}

> input {
  display: none;
}

label.half_l:hover:before,
label.half_l:hover ~ label.half_l:before {
  content: '\f089';
  color: #fff239;
}

label.half_l:hover ~ label.half_r::before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover:before {
  content: '\f005';
  color: #fff239;
}

label.half_r:hover ~ label.half_r::before,
label.half_r:hover ~ label.half_l:before {
  content: '\f005';
  color: #fff239;
}

input[type=radio]:checked ~ label.half_l:before,
input[type=radio]:checked ~ label.half_r:before{
  content: '\f005';
}

}

Body:
Use nth-of-type instead of nth-child

label:nth-of-type(odd) {
  background-color:red;
}

nth-child looks for all children, regardless their type, where nth-of-type looks for a certain type


问:
How to get Time offset (diffrence) b/w time.strftime and datetime.datetime?
I am getting time input in unix (milliseconds) and want to get time difference b/w given value and current time for that I did following. 1st convert posix into human readable then tried to minus 2 values but - doesn't go well with str.

```<code>/1000 is for millisecond reduction

t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1496814300000/1000))
k = datetime.datetime.now()

j = k -t
print j
</code>```

答:
Found solution here

how to convert a string date into datetime format in python?

strptime is the key to convert string into datetime

Body:
I am getting time input in unix (milliseconds) and want to get time difference b/w given value and current time for that I did following. 1st convert posix into human readable then tried to minus 2 values but - doesn't go well with str.

/1000 is for millisecond reduction

t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1496814300000/1000))
k = datetime.datetime.now()

j = k -t
print j