问:
Integrated nuget, how to include dependant project into package
Let's consider project A and project B. I would like to publish project A as a nuget package without having to publish project B. In the old time I would use manually nuget ... A.csproj -IncludeReferencedProjects. Currently, when nuget is integrated with visual studio, it just interpret .csproj on build with some options like authors, tags etc... However it looks like there is no option to use IncludeReferencedProjects here. How would I use it? Is it possible to change default command that msbuild is running with and add this switch?

答:
There is currently no official solution for having multiple projects in one nuget package, similar to IncludeReferencedProjects for "nuget pack".

But you can do:

```<code>1. Add 'PrivateAssets="all" to all 'ProjectReference' XmlElements.

2. Add ItemGroup to include DLL's:
  <ItemGroup>
    <Content Include="$(OutputPath)$(MSBuildProjectName).*.dll" Pack="true" PackagePath="lib/$(TargetFramework)" />
  </ItemGroup>
</code>```

Body:
There is currently no official solution for having multiple projects in one nuget package, similar to IncludeReferencedProjects for "nuget pack".

But you can do:

1. Add 'PrivateAssets="all" to all 'ProjectReference' XmlElements.

2. Add ItemGroup to include DLL's:
  <ItemGroup>
    <Content Include="$(OutputPath)$(MSBuildProjectName).*.dll" Pack="true" PackagePath="lib/$(TargetFramework)" />
  </ItemGroup>


来源: stackexchange

问:
Rotativa MVC not loading CSS or Images on PDF
I have a action which works well ( loads all images and CSS) as a normal action but when I use Rotativa.MVC.ViewAsPdf to produce a PDF it don't load the CSS. and the application doesn't show any errors

```<code>public ActionResult DownloadNonProfessionalDeputy(int id)
  {
      Application_Attorney_NonProfessional oAP = db.Application_Attorney_NonProfessional.Find(id);
      return new Rotativa.MVC.ViewAsPdf(oAP) { FileName = string.Format("DCM_Attorney_Non_Professional_Application.pdf", new { CustomSwitches = "--print-media-type --header-center \"text\"" }) };// {   =  "--header-right \"Page [page] of [toPage]\""};

      //return View(oAP);
  }
</code>```

help appreciated

Image from PDF

Image from HTML View

The View

```<code>@model DCM_Intranet.Models.Application_Attorney_NonProfessional
@{
    Layout = null;
    int nPage = 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="~/images/gale_phillipson_corn.ico" type="image/x-icon">
<title>Attorney Non-Professional Application</title>
<link href="~/css/style.default.css" rel="stylesheet">
<link href="~/css/jquery.datatables.css" rel="stylesheet">
<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/js/bootstrap.min.js"></script>
<script src="~/js/modernizr.min.js"></script>
<script src="~/js/jquery-migrate-1.2.1.min.js"></script>
<script src="~/js/jquery.sparkline.min.js"></script>
<script src="~/js/toggles.min.js"></script>
<script src="~/js/retina.min.js"></script>
<script src="~/js/jquery.cookies.js"></script>
<script src="~/js/morris.min.js"></script>
<script src="~/js/raphael-2.1.0.min.js"></script>
<script src="~/js/jquery.datatables.min.js"></script>
<script src="~/js/chosen.jquery.min.js"></script>
<script src="~/js/custom.js"></script>
<script src="~/js/jquery.capslockstate.js"></script>
<script src="~/js/jspdf.js"></script>
    </head>
    <body>
      <div class="container-fluid" id="content">
            <!-- Top Header -->
            <div class="row">
                <div class="col-md-12">
                    <table class="table">
                        <tr>
                            <td valign="middle" align="left"><h2>Data Capture</h2></td>
                            <td valign="middle" align="right"><img src="~/Images/dcm.png" width="403" height="100" class="pull-right" />
                        </tr>
                    </table>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    @{nPage++;}
                    <div class="row">
                        <div class="col-sm-6 pull-left"><h2>Court of Protection/Power of Attorney - Non-Professional </h2></div>
                        <div class="col-sm-6 pull-right vcenter"><strong>Page @nPage</strong></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="alert alert-info" role="alert">
                        <strong>Should you require any guidance in completing this form please contact the DCM New Business Team on 01748 825971 or dcm@dcmcash.com</strong>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="well well-sm">
                        <p>This form is for use for Court of Protection/Power of Attorney case where the deputy is Not Acting in a Professional Capacity.</p>
                        <p>
                            This form is intended for professional Introducer/Adviser use only—please do not pass it to your client. The objective of this form is to collect all of the data required to operate Dynamic Cash Management efficiently without any need for your input at a later date.
                        </p>
                        <p>Please ensure that the form is completed in full, as any omissions may lead to a delay in setting up your client’s Dynamic Cash Management account.</p>
                        <p>
                            <b>
                                It is particularly important to ensure that your client is consulted on Sections 8 (ATRI) and 9 (Liquidity) as they are used to determine the types of institutions and accounts that we will deposit your client’s cash with. Proper consultation will ensure that Dynamic Cash Management use only those institutions that your client is comfortable with and that they are able to withdraw funds when they need them.
                            </b>
                        </p>
                    </div>
                </div>
            </div>
</div>
    </body>
    </html>
</code>```

答:
For the CSS Part, I did the following:
In Action,

```<code>return new PartialViewAsPdf("_PartialViewName", model);
</code>```

In _PartialViewName.cshtml,

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    @Styles.Render("~/Content/css")
</head>
<body>
    // code here
</body>
</html>
</code>```

In BundleConfig.cs

```<code>bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
//other css libraries
));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a action which works well ( loads all images and CSS) as a normal action but when I use Rotativa.MVC.ViewAsPdf to produce a PDF it don't load the CSS. and the application doesn't show any errors

public ActionResult DownloadNonProfessionalDeputy(int id)
  {
      Application_Attorney_NonProfessional oAP = db.Application_Attorney_NonProfessional.Find(id);
      return new Rotativa.MVC.ViewAsPdf(oAP) { FileName = string.Format("DCM_Attorney_Non_Professional_Application.pdf", new { CustomSwitches = "--print-media-type --header-center \"text\"" }) };// {   =  "--header-right \"Page [page] of [toPage]\""};

      //return View(oAP);
  }

help appreciated

Image from PDF

Image from HTML View

The View

@model DCM_Intranet.Models.Application_Attorney_NonProfessional
@{
    Layout = null;
    int nPage = 0;
}
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="~/images/gale_phillipson_corn.ico" type="image/x-icon">
<title>Attorney Non-Professional Application</title>
<link href="~/css/style.default.css" rel="stylesheet">
<link href="~/css/jquery.datatables.css" rel="stylesheet">

Data Capture

                    @{nPage++;}

Court of Protection/Power of Attorney - Non-Professional

Page @nPage

                        Should you require any guidance in completing this form please contact the DCM New Business Team on 01748 825971 or dcm@dcmcash.com

This form is for use for Court of Protection/Power of Attorney case where the deputy is Not Acting in a Professional Capacity.

                            This form is intended for professional Introducer/Adviser use only—please do not pass it to your client. The objective of this form is to collect all of the data required to operate Dynamic Cash Management efficiently without any need for your input at a later date.

Please ensure that the form is completed in full, as any omissions may lead to a delay in setting up your client’s Dynamic Cash Management account.

                                It is particularly important to ensure that your client is consulted on Sections 8 (ATRI) and 9 (Liquidity) as they are used to determine the types of institutions and accounts that we will deposit your client’s cash with. Proper consultation will ensure that Dynamic Cash Management use only those institutions that your client is comfortable with and that they are able to withdraw funds when they need them.

Body:
For the CSS Part, I did the following:
In Action,

return new PartialViewAsPdf("_PartialViewName", model);

In _PartialViewName.cshtml,

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    @Styles.Render("~/Content/css")
</head>
<body>
    // code here
</body>
</html>

In BundleConfig.cs

bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
//other css libraries
));


问:
Vaadin Grid Column setMaximumWidth ignored
I have the following code running where myGridExample is a Vaadin 8 grid object.

```<code>           this.myGridExample
                    .addColumn(MapQueryService.RowResult::getFacilityType)
                    .setMinimumWidth(130)
                    .setWidth(160)
                    .setMaximumWidth(170)
                    .setCaption("Facility Type");
</code>```

The setMaximumWidth(170) does not appear to do anything. however .setMinimumWidth(130) works as expected.  Is this a bug?

答:
From Vaadin8-docs:

setMaximumWidth

Sets the maximum width for this column.
  This defines the maximum
  allowed pixel width of the column when it is set to expand.

...

See Also:
  setExpandRatio(int)

If it's about setMinimumWidth - it also works only with expanding. I made some mensuration in your gif and it looks like your minimumWidth of resizing is ~110px (assuming that column at gif start position has 160px width). So it's probably adjusts by itself to longest column value.

Workaround for you:

```<code>grid.addColumnResizeListener(event -> {
   Grid.Column c = event.getColumn();
   if(c.getWidth() > c.getMaximumWidth())
      c.setWidth(c.getMaximumWidth());
   if(c.getWidth() < c.getMinimumWidth())
      c.setWidth(c.getMinimumWidth());
});
</code>```

Body:
I have the following code running where myGridExample is a Vaadin 8 grid object.

           this.myGridExample
                    .addColumn(MapQueryService.RowResult::getFacilityType)
                    .setMinimumWidth(130)
                    .setWidth(160)
                    .setMaximumWidth(170)
                    .setCaption("Facility Type");

The setMaximumWidth(170) does not appear to do anything. however .setMinimumWidth(130) works as expected.  Is this a bug?

Body:
From Vaadin8-docs:

setMaximumWidth

Sets the maximum width for this column.
  This defines the maximum
  allowed pixel width of the column when it is set to expand.

...

See Also:
  setExpandRatio(int)

If it's about setMinimumWidth - it also works only with expanding. I made some mensuration in your gif and it looks like your minimumWidth of resizing is ~110px (assuming that column at gif start position has 160px width). So it's probably adjusts by itself to longest column value.

Workaround for you:

grid.addColumnResizeListener(event -> {
   Grid.Column c = event.getColumn();
   if(c.getWidth() > c.getMaximumWidth())
      c.setWidth(c.getMaximumWidth());
   if(c.getWidth() < c.getMinimumWidth())
      c.setWidth(c.getMinimumWidth());
});


问:
React Native Incompatible With Google VR SDK
I'm having a trouble with React Native when I try to add the Google VR SDK ('GVRSDK') as a Podfile dependency, and it's quite easy to replicate.

Steps:

Create a new blank React Native project. Run it with react-native run-ios to ensure it worked.

cd ios

pod init

Add pod 'GVRSDK' to Podfile, execute pod update

cd ..

react-native run-ios

The project crashed with the following error:

```<code>duplicate symbol __ZN3fLI9FLAGS_novE in:
/foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(vlog_is_on.o)
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(vlog_is_on.o)
duplicate symbol __ZN3fLI7FLAGS_vE in:
/foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(vlog_is_on.o)
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(vlog_is_on.o)
duplicate symbol __ZN6google13RemoveLogSinkEPNS_7LogSinkE in:
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(logging.o)
/foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(logging.o)
duplicate symbol __ZN6google10AddLogSinkEPNS_7LogSinkE in:
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(logging.o)
    /foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(logging.o)
ld: 4 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

** BUILD FAILED **

The following build commands failed:

Ld build/Build/Products/Debug-iphonesimulator/foo.app/foo normal x86_64
(1 failure)
</code>```

答:
You can resolve it by removing the duplicated symbol in libGVRSDK.a.
The lipo and ar commands are used to disassemble the library file in the several architectures and rearchive them into another file.

I made the shell script as follows:

pod_post_install.sh

```<code>#!/bin/bash

cd ./Pods/GVRSDK/Libraries/
lipo -info libGVRSDK.a

# Divide to each platform
lipo -thin armv7 libGVRSDK.a -output libGVRSDK_armv7
lipo -thin i386 libGVRSDK.a -output libGVRSDK_i386
lipo -thin x86_64 libGVRSDK.a -output libGVRSDK_x86_64
lipo -thin arm64 libGVRSDK.a -output libGVRSDK_arm64

# Delete duplicate file
chmod 777 libGVRSDK_armv7
chmod 777 libGVRSDK_i386
chmod 777 libGVRSDK_x86_64
chmod 777 libGVRSDK_arm64

ar -dv libGVRSDK_armv7 vlog_is_on.o
ar -dv libGVRSDK_i386 vlog_is_on.o
ar -dv libGVRSDK_x86_64 vlog_is_on.o
ar -dv libGVRSDK_arm64 vlog_is_on.o

# rm libGVRSDK.a
lipo -create libGVRSDK_armv7 libGVRSDK_i386 libGVRSDK_x86_64 libGVRSDK_arm64 -output libGVRSDK.a

# Delete media
rm libGVRSDK_armv7
rm libGVRSDK_i386
rm libGVRSDK_x86_64
rm libGVRSDK_arm64

cd ../../../
</code>```

It can be more useful if this script is invoked when every pod install is run.

Podfile

```<code>post_install do |installer|
    system(". ./pod_post_install.sh")
end
</code>```

I believe it helps.

Body:
I'm having a trouble with React Native when I try to add the Google VR SDK ('GVRSDK') as a Podfile dependency, and it's quite easy to replicate.

Steps:

Create a new blank React Native project. Run it with react-native run-ios to ensure it worked.

cd ios

pod init

Add pod 'GVRSDK' to Podfile, execute pod update

cd ..

react-native run-ios

The project crashed with the following error:

duplicate symbol __ZN3fLI9FLAGS_novE in:
/foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(vlog_is_on.o)
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(vlog_is_on.o)
duplicate symbol __ZN3fLI7FLAGS_vE in:
/foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(vlog_is_on.o)
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(vlog_is_on.o)
duplicate symbol __ZN6google13RemoveLogSinkEPNS_7LogSinkE in:
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(logging.o)
/foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(logging.o)
duplicate symbol __ZN6google10AddLogSinkEPNS_7LogSinkE in:
/foo/ios/build/Build/Products/Debug-iphonesimulator/libReact.a(logging.o)
    /foo/ios/Pods/GVRSDK/Libraries/libGVRSDK.a(logging.o)
ld: 4 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

** BUILD FAILED **

The following build commands failed:

Ld build/Build/Products/Debug-iphonesimulator/foo.app/foo normal x86_64
(1 failure)

Body:
You can resolve it by removing the duplicated symbol in libGVRSDK.a.
The lipo and ar commands are used to disassemble the library file in the several architectures and rearchive them into another file.

I made the shell script as follows:

pod_post_install.sh

#!/bin/bash

cd ./Pods/GVRSDK/Libraries/
lipo -info libGVRSDK.a

# Divide to each platform
lipo -thin armv7 libGVRSDK.a -output libGVRSDK_armv7
lipo -thin i386 libGVRSDK.a -output libGVRSDK_i386
lipo -thin x86_64 libGVRSDK.a -output libGVRSDK_x86_64
lipo -thin arm64 libGVRSDK.a -output libGVRSDK_arm64

# Delete duplicate file
chmod 777 libGVRSDK_armv7
chmod 777 libGVRSDK_i386
chmod 777 libGVRSDK_x86_64
chmod 777 libGVRSDK_arm64

ar -dv libGVRSDK_armv7 vlog_is_on.o
ar -dv libGVRSDK_i386 vlog_is_on.o
ar -dv libGVRSDK_x86_64 vlog_is_on.o
ar -dv libGVRSDK_arm64 vlog_is_on.o

# rm libGVRSDK.a
lipo -create libGVRSDK_armv7 libGVRSDK_i386 libGVRSDK_x86_64 libGVRSDK_arm64 -output libGVRSDK.a

# Delete media
rm libGVRSDK_armv7
rm libGVRSDK_i386
rm libGVRSDK_x86_64
rm libGVRSDK_arm64

cd ../../../

It can be more useful if this script is invoked when every pod install is run.

Podfile

post_install do |installer|
    system(". ./pod_post_install.sh")
end

I believe it helps.


问:
Function that would return the data retrieved from a select query - Oracle
I am trying to write a function that would return the result of a select query. I have worked with very basic functions that would return a number and a varchar2(string). But now I want to return the result of a select, which would be like 10 rows and their corresponding columns.

How would I write the function and what would the return type be?

An example function that I have written is:

create or replace function func1
  return varchar2 as   begin
      return('hello from func1');   end func1;

I am still at a basic level, so can anybody help me out with returning the result of a select query? I believe cursors are to be used, as there would be more than one row.

答:
Well, if you're just learning, you should know about pipelined functions.  A pipelined function lets you return dynamically generated tables within PLSQL.

For example...

```<code>  create function
      gen_numbers(n in number default null)
      return array
      PIPELINED
  as
  begin
     for i in 1 .. nvl(n,999999999)
         loop
         pipe row(i);
     end loop;
    return;
  end;
</code>```

Which I borrowed from http://www.akadia.com/services/ora_pipe_functions.html :-)

Body:
Well, if you're just learning, you should know about pipelined functions.  A pipelined function lets you return dynamically generated tables within PLSQL.

For example...

  create function
      gen_numbers(n in number default null)
      return array
      PIPELINED
  as
  begin
     for i in 1 .. nvl(n,999999999)
         loop
         pipe row(i);
     end loop;
    return;
  end;

Which I borrowed from http://www.akadia.com/services/ora_pipe_functions.html :-)

ContentLicense: CC BY-SA 2.5


问:
Issue in rendering data in table as per the number input
I want to apply input number ng-model as the length of below table.

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.myObj =[ {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},

    ]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
Display Rows in Table : <input type="number" ng-model="numberOfRows"/>
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in myObj">
  <td>{{x.Name}}</td>
  <td>{{x.Country}}</td>
  <td>{{x.City}}</td>
</tr>
</table>
</body></code>```

答:
Best and easiest solution is to use limitTo filter. This is a AngularJS native filter that limit iterated results in ngRepeat.

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.myObj =[ {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},

    ]

$scope.numberOfRows = 1;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
  Display rows in Table : <input type="number" min="0" max="{{myObj.length}}" ng-model="numberOfRows"/>
  <table border="1">
    <tr ng-repeat="x in myObj | limitTo:numberOfRows">
      <td>{{x.Name}}</td>
      <td>{{x.Country}}</td>
      <td>{{x.City}}</td>
    </tr>
  </table>
</div>
</body></code>```

Body:
I want to apply input number ng-model as the length of below table.

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.myObj =[ {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},

    ]
});

Display Rows in Table : <input type="number" ng-model="numberOfRows"/>

  {{x.Name}}
  {{x.Country}}
  {{x.City}}

Body:
Best and easiest solution is to use limitTo filter. This is a AngularJS native filter that limit iterated results in ngRepeat.

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.myObj =[ {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},
      {"Name" : "Alfreds Futterkiste", "Country" : "Germany","City" : "Berlin"},

    ]

$scope.numberOfRows = 1;
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
  Display rows in Table : <input type="number" min="0" max="{{myObj.length}}" ng-model="numberOfRows"/>
  <table border="1">
    <tr ng-repeat="x in myObj | limitTo:numberOfRows">
      <td>{{x.Name}}</td>
      <td>{{x.Country}}</td>
      <td>{{x.City}}</td>
    </tr>
  </table>
</div>
</body>


问:
Difference between geodist() and dist() for Geo-Spacial Search
What is the Difference between Geodist(sfield,x,y) and dist(2,x,y,a,b) in Apache Solr for Geo-Spacial Searches ??

dist(2,x,y,0,0) :- calculates the Euclidean distance between (0,0) and (x,y) for each document. Return the Distance between two Vectors (points) in an n-dimensional space.

I was earlier using geodist() distance function for Geo-Spatial searches on my website but its response time was large. so have done a POC(proof of concept) for different distance functions and found that dist(2,x,y,0,0) distance function is relatively taking half of the time. But I want to know the reason behind this and the algorithms which both functions are using to calculate the distance.

I have to make a difference matrix for the same to convey it further.

答:
An euclidean distance doesn't account for the curvature of the earth. If you're only sorting by the distance, the behavior can be OK - but only if your hits are within a small geographical area (the value of a unit compared to meters greatly change when you're getting closer to the poles).

There's an extensive and good answer that explains the difference between a Euclidean distance and a proper geographical distance (usually calculated using haversine) available at the GIS Stack Exchange.

Although at small scales any smooth surface looks like a plane, the accuracy of the Pythagorean formula depends on the coordinates used. When those coordinates are latitude and longitude on a sphere (or ellipsoid), we can expect that

Distances along lines of longitude will be reasonably accurate.

Distances along the Equator will be reasonably accurate.

All other distances will be erroneous, in rough proportion to the differences in latitude and longitude.

ContentLicense: CC BY-SA 4.0


问:
how to encrypt a string in aes waywith mbedtls?
We all know that mbedtls library is a very lightweight c library. I want to use the library to encrypt a string. So I have a function like this:

aes_encrypt.h:

```<code>#ifndef AES_ENCRYPT_H
#define AES_ENCRYPT_H

#define BOOL int
#define TRUE 1
#define FALSE 0

extern const unsigned char key[16];

BOOL ENC_STR(unsigned char *plain, size_t plain_len,
             unsigned char *cipher, size_t *cipher_len);
#endif
</code>```

and the implementation:

```<code>const unsigned char KEY[16] = { 0x00, 0x01, 0x02, 0x03,
                                0x04, 0x05, 0x06, 0x07,
                                0x08, 0x09, 0x0A, 0x0B,
                                0x0C, 0x0D, 0x0F, 0xA0 };

BOOL ENC_STR(unsigned char *plain, size_t plain_len, unsigned char *cipher, size_t *cipher_len)
{
BOOL ret = FALSE;

// Prepare the cipher context
const mbedtls_cipher_info_t *cipher_info;
mbedtls_cipher_context_t cipher_ctx;
mbedtls_cipher_init(&cipher_ctx);

if ((cipher_info = mbedtls_cipher_info_from_type(AES_PARM)) == NULL)
{
    printf("Cipher Info ERR!\n");
    ret = -1;
    goto EXIT;
}

if ( (ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0)
{
    printf("Cipher Setup ERR!\n");
    goto EXIT;
}

if ( (ret = mbedtls_cipher_setkey(&cipher_ctx, KEY, cipher_info->key_bitlen, MBEDTLS_ENCRYPT)) != 0)
{
    printf("Cipher SetKey ERR!\n");
    goto EXIT;
}

// if ( (ret = mbedtls_cipher_set_padding_mode(&cipher_ctx, 1)) != 0) {
//     printf("Cipher SetPadding ERR!\n");
//     goto EXIT;
// }

if ( (ret = mbedtls_cipher_reset(&cipher_ctx)) != 0)
{
    printf("Cipher Reset ERR!\n");
    goto EXIT;
}

// encrypt
if ((ret = mbedtls_cipher_update(&cipher_ctx, plain, plain_len, cipher, cipher_len)) != 0) {
    printf("Cipher Update ERR!\n");
    goto EXIT;
}

EXIT:
    if (ret != TRUE) {
        char buf[1024] = {0};
        mbedtls_strerror(ret, buf, 1024);
        printf("Error Msg:\t%s\n", buf);
    }

    mbedtls_cipher_free(&cipher_ctx);
    return ret;
}
</code>```

I call the function like bellow:

```<code>unsigned char *plain = (unsigned char*)"hello world";
size_t plain_len = 12;
unsigned char cipher[128] = {0};
size_t cipher_len = -1;
printf("the encrypt result is:\t%d\n", ENC_STR(plain, plain_len, cipher, &cipher_len));
</code>```

And I get the err msg like below:

```<code>CIPHER - Decryption of block requires a full block
</code>```

Can anyone help me out and explain what is the meaning of the error message? Thanks.

答:
Explanation:

CIPHER - Decryption of block requires a full block

  Can anyone help me out and explain what is the meaning of the error message?

AES is a block cipher it means it is implemented to encrypt 128 bit block at the time. Not more, not less.

So if you have source data shorter than a single block, you will need to use some padding to ensure you prolong your data to a required length.

Generally to encrypt data of any length we use mode of operation. There are some which do not require any padding (CTR, CFB, OFB, ..)

Still your encryption will be far from secure - you will need IV (salt) and authentication tag.

We all know that mbedtls library is a very lightweight c library

apparently the mbedtls already support multiple modes of operations, it's up to you to choose

Body:
We all know that mbedtls library is a very lightweight c library. I want to use the library to encrypt a string. So I have a function like this:

aes_encrypt.h:

#ifndef AES_ENCRYPT_H
#define AES_ENCRYPT_H

#define BOOL int
#define TRUE 1
#define FALSE 0

extern const unsigned char key[16];

BOOL ENC_STR(unsigned char *plain, size_t plain_len,
             unsigned char *cipher, size_t *cipher_len);
#endif

and the implementation:

const unsigned char KEY[16] = { 0x00, 0x01, 0x02, 0x03,
                                0x04, 0x05, 0x06, 0x07,
                                0x08, 0x09, 0x0A, 0x0B,
                                0x0C, 0x0D, 0x0F, 0xA0 };

BOOL ENC_STR(unsigned char *plain, size_t plain_len, unsigned char *cipher, size_t *cipher_len)
{
BOOL ret = FALSE;

// Prepare the cipher context
const mbedtls_cipher_info_t *cipher_info;
mbedtls_cipher_context_t cipher_ctx;
mbedtls_cipher_init(&cipher_ctx);

if ((cipher_info = mbedtls_cipher_info_from_type(AES_PARM)) == NULL)
{
    printf("Cipher Info ERR!\n");
    ret = -1;
    goto EXIT;
}

if ( (ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0)
{
    printf("Cipher Setup ERR!\n");
    goto EXIT;
}

if ( (ret = mbedtls_cipher_setkey(&cipher_ctx, KEY, cipher_info->key_bitlen, MBEDTLS_ENCRYPT)) != 0)
{
    printf("Cipher SetKey ERR!\n");
    goto EXIT;
}

// if ( (ret = mbedtls_cipher_set_padding_mode(&cipher_ctx, 1)) != 0) {
//     printf("Cipher SetPadding ERR!\n");
//     goto EXIT;
// }

if ( (ret = mbedtls_cipher_reset(&cipher_ctx)) != 0)
{
    printf("Cipher Reset ERR!\n");
    goto EXIT;
}

// encrypt
if ((ret = mbedtls_cipher_update(&cipher_ctx, plain, plain_len, cipher, cipher_len)) != 0) {
    printf("Cipher Update ERR!\n");
    goto EXIT;
}

EXIT:
    if (ret != TRUE) {
        char buf[1024] = {0};
        mbedtls_strerror(ret, buf, 1024);
        printf("Error Msg:\t%s\n", buf);
    }

    mbedtls_cipher_free(&cipher_ctx);
    return ret;
}

I call the function like bellow:

unsigned char *plain = (unsigned char*)"hello world";
size_t plain_len = 12;
unsigned char cipher[128] = {0};
size_t cipher_len = -1;
printf("the encrypt result is:\t%d\n", ENC_STR(plain, plain_len, cipher, &cipher_len));

And I get the err msg like below:

CIPHER - Decryption of block requires a full block

Can anyone help me out and explain what is the meaning of the error message? Thanks.


问:
Using custom restClient in saga
I want to select all locales from my API (api/locales).

My problem is that the yield call() return the function as a plan string (yes yes plain string) and I don't have a clue why!

Maybe I missed something with yield + call + restClient response?? =\

My Saga file look like this:

```<code>import types from './types';
import actions from './actions';
import { call, put, takeEvery } from 'redux-saga/effects';
import restClient from './../../restClient';

function* getLocalesSaga() {
  try {

    yield put({type: types.GET_LOCALES_LOADING});
    let locales;
    locales = yield call(restClient, 'GET', 'locales');
    console.log(locales); // this show the function string!!!
    if (!locales.data) {
      throw new Error('REST response must contain a data key');
    }
    yield put( {type: types.LOCALES_RECEIVED, locales } )

  } catch (error) {

    console.log(error);
    yield put({type: types.GET_LOCALES_FAILURE, error})

  }
}

export default function* localesSaga() {
  yield [
    takeEvery(types.GET_LOCALES, getLocalesSaga),
    takeEvery(types.GET_LOCALES_LOADING, actions.loadingLocales),
    takeEvery(types.LOCALES_RECEIVED, actions.localesReceived),
    takeEvery(types.GET_LOCALES_FAILURE, actions.failedLocales),
  ];
}
</code>```

The console.log output is:

```<code>ƒ (type, resource, params) {
    if (type === __WEBPACK_IMPORTED_MODULE_0_admin_on_rest__["GET_MANY"]) {
      return Promise.all(params.ids.map(function (id) {
        return httpClient(apiUrl + '/' +…
</code>```

There is no request in the browser networks tab.
No JS errors in console apart the console.log.

I registered the saga with customSagas={customsSagas} on the Admin component.

When I use fetch() function it works!

I want to use my restClient which include the authentication token and all logic of request and response.
The restClient is custom and this is the code:

```<code>import {
  GET_LIST,
  GET_ONE,
  GET_MANY,
  GET_MANY_REFERENCE,
  CREATE,
  UPDATE,
  DELETE,
  fetchUtils
} from 'admin-on-rest';

const { queryParameters, fetchJson } = fetchUtils;

const apiUrl = process.env.REACT_APP_API_PATH;

const httpClient = (url, options = {}) => {
  if (!options.headers) {
    options.headers = new Headers({ Accept: 'application/json' });
  }
  const token = localStorage.getItem('token');
  options.headers.set('Authorization', `Bearer ${token}`);
  return fetchJson(url, options);
}
/**
 * Maps admin-on-rest queries to a json-server powered REST API
 *
 * @see https://github.com/typicode/json-server
 * @example
 * GET_LIST     => GET http://my.api.url/posts?_sort=title&_order=ASC&_start=0&_end=24
 * GET_ONE      => GET http://my.api.url/posts/123
 * GET_MANY     => GET http://my.api.url/posts/123, GET http://my.api.url/posts/456, GET http://my.api.url/posts/789
 * UPDATE       => PUT http://my.api.url/posts/123
 * CREATE       => POST http://my.api.url/posts/123
 * DELETE       => DELETE http://my.api.url/posts/123
 */
export default () => {
  /**
   * @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
   * @param {String} resource Name of the resource to fetch, e.g. 'posts'
   * @param {Object} params The REST request params, depending on the type
   * @returns {Object} { url, options } The HTTP request parameters
   */
  const convertRESTRequestToHTTP = (type, resource, params) => {
    let url = '';
    const options = {};
    switch (type) {
      case GET_LIST: {
        const { page, perPage } = params.pagination;
        const { field, order } = params.sort;
        const query = {
          ...params.filter,
          sort: field,
          order: order,
          page: page,
          per_page: perPage,
        };
        url = `${apiUrl}/${resource}?${queryParameters(query)}`;
        break;
      }
      case GET_ONE:
        url = `${apiUrl}/${resource}/${params.id}`;
        break;
      case GET_MANY_REFERENCE: {
        const { page, perPage } = params.pagination;
        const { field, order } = params.sort;
        const query = {
          ...params.filter,
          [params.target]: params.id,
          _sort: field,
          _order: order,
          _start: (page - 1) * perPage,
          _end: page * perPage,
        };
        url = `${apiUrl}/${resource}?${queryParameters(query)}`;
        break;
      }
      case UPDATE:
        url = `${apiUrl}/${resource}/${params.id}`;
        options.method = 'PUT';
        options.body = JSON.stringify(params.data);
        break;
      case CREATE:
        url = `${apiUrl}/${resource}`;
        options.method = 'POST';
        options.body = JSON.stringify(params.data);
        break;
      case DELETE:
        url = `${apiUrl}/${resource}/${params.id}`;
        options.method = 'DELETE';
        break;
      default:
        throw new Error(`Unsupported fetch action type ${type}`);
    }
    return { url, options };
  };

  /**
   * @param {Object} response HTTP response from fetch()
   * @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
   * @param {String} resource Name of the resource to fetch, e.g. 'posts'
   * @param {Object} params The REST request params, depending on the type
   * @returns {Object} REST response
   */
  const convertHTTPResponseToREST = (response, type, resource, params) => {
    const { headers, json } = response;
    switch (type) {
      case GET_LIST:
      case GET_MANY_REFERENCE:
        if (!headers.has('x-total-count')) {
          throw new Error('The X-Total-Count header is missing in the HTTP Response. The jsonServer REST client expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?');
        }
        return {
          // change the primary key to uuid
          data: json.data.map(resource => resource = { ...resource, id: resource.uuid }),
          total: parseInt(headers.get('x-total-count').split('/').pop(), 10),
        };
      case UPDATE:
      case DELETE:
      case GET_ONE:
        return { data: json, id: json.uuid };
      case CREATE:
        return { data: { ...params.data, id: json.uuid } };
      default:
        return { data: json };
    }
  };

  /**
   * @param {string} type Request type, e.g GET_LIST
   * @param {string} resource Resource name, e.g. "posts"
   * @param {Object} payload Request parameters. Depends on the request type
   * @returns {Promise} the Promise for a REST response
   */
  return (type, resource, params) => {
    if (type === GET_MANY) {
      return Promise.all(params.ids.map(id => httpClient(`${apiUrl}/${resource}/${id}`)))
        .then(responses => ({ data: responses.map(response => response.json) }));
    }
    const { url, options } = convertRESTRequestToHTTP(type, resource, params);
    return httpClient(url, options)
      .then(response => convertHTTPResponseToREST(response, type, resource, params));
  };
};
</code>```

Any one can help here and tell me why the restClient is returned as a string instead of returning the json?

It is not a GET_LIST nor GET_ONE request. It is just a normal GET request.
I tried to use GET_ONE and GET_LIST but I still get the response as the function plain string.

Edit & Solution:

Thanks to @Gildas it is clearer to use fetch instead of restClient for a GET request. restClient is used just for <resource /> and it is not so clear by the docs.
Moreover, the actions creators were useless when I use put in my main saga function.

My fetch looks like this and it works:

```<code>function getLocales() {
  return fetch(process.env.REACT_APP_API_PATH + '/locales', { method: 'GET' })
      .then(response => (
          Promise.resolve(response)
      ))
      .then(response => (
          response.json()
      ))
      .catch((e) => {
        console.error(e);
      });
}
</code>```

When I called it like this:

```<code>const { languages, currentLocale } = yield call(getLocales);
</code>```

Thank you in advanced.
Leo.

答:
This part is really strange, it seems you're binding action creators as if they were sagas, though you do put them in the getLocalesSaga:

```<code>export default function* localesSaga() {
  yield [
    takeEvery(types.GET_LOCALES, getLocalesSaga),
    takeEvery(types.GET_LOCALES_LOADING, actions.loadingLocales),
    takeEvery(types.LOCALES_RECEIVED, actions.localesReceived),
    takeEvery(types.GET_LOCALES_FAILURE, actions.failedLocales),
  ];
}
</code>```

Moreover, the restClient is not fetch. GET is not a type recognized by it (see documentation). You should not use the restClient for anything that's not a resource in admin-on-rest terms. Here, you should indeed use fetch.

This should probably be rewritten like:

```<code>import types from './types';
import actions from './actions';
import { call, put, takeEvery } from 'redux-saga/effects';
import restClient from './../../restClient';

function fetchLocales() {
    return fetch(...);
}

function* getLocalesSaga() {
  try {

    yield put(actions.loadingLocales());
    let locales;
    locales = yield call(fetchLocales);
    console.log(locales); // this show the function string!!!
    if (!locales.data) {
      throw new Error('REST response must contain a data key');
    }
    yield put(actions.localesReceived(locales))

  } catch (error) {

    console.log(error);
    yield put(actions.failedLocales(error))

  }
}

export default function* localesSaga() {
  yield takeEvery(types.GET_LOCALES, getLocalesSaga);
}
</code>```

Title: Using custom restClient in saga

Body:
I want to select all locales from my API (api/locales).

My problem is that the yield call() return the function as a plan string (yes yes plain string) and I don't have a clue why!

Maybe I missed something with yield + call + restClient response?? =\

My Saga file look like this:

import types from './types';
import actions from './actions';
import { call, put, takeEvery } from 'redux-saga/effects';
import restClient from './../../restClient';

function* getLocalesSaga() {
  try {

    yield put({type: types.GET_LOCALES_LOADING});
    let locales;
    locales = yield call(restClient, 'GET', 'locales');
    console.log(locales); // this show the function string!!!
    if (!locales.data) {
      throw new Error('REST response must contain a data key');
    }
    yield put( {type: types.LOCALES_RECEIVED, locales } )

  } catch (error) {

    console.log(error);
    yield put({type: types.GET_LOCALES_FAILURE, error})

  }
}

export default function* localesSaga() {
  yield [
    takeEvery(types.GET_LOCALES, getLocalesSaga),
    takeEvery(types.GET_LOCALES_LOADING, actions.loadingLocales),
    takeEvery(types.LOCALES_RECEIVED, actions.localesReceived),
    takeEvery(types.GET_LOCALES_FAILURE, actions.failedLocales),
  ];
}

The console.log output is:

ƒ (type, resource, params) {
    if (type === __WEBPACK_IMPORTED_MODULE_0_admin_on_rest__["GET_MANY"]) {
      return Promise.all(params.ids.map(function (id) {
        return httpClient(apiUrl + '/' +…

There is no request in the browser networks tab.
No JS errors in console apart the console.log.

I registered the saga with customSagas={customsSagas} on the Admin component.

When I use fetch() function it works!

I want to use my restClient which include the authentication token and all logic of request and response.
The restClient is custom and this is the code:

import {
  GET_LIST,
  GET_ONE,
  GET_MANY,
  GET_MANY_REFERENCE,
  CREATE,
  UPDATE,
  DELETE,
  fetchUtils
} from 'admin-on-rest';

const { queryParameters, fetchJson } = fetchUtils;

const apiUrl = process.env.REACT_APP_API_PATH;

const httpClient = (url, options = {}) => {
  if (!options.headers) {
    options.headers = new Headers({ Accept: 'application/json' });
  }
  const token = localStorage.getItem('token');
  options.headers.set('Authorization', `Bearer ${token}`);
  return fetchJson(url, options);
}
/**
 * Maps admin-on-rest queries to a json-server powered REST API
 *
 * @see https://github.com/typicode/json-server
 * @example
 * GET_LIST     => GET http://my.api.url/posts?_sort=title&_order=ASC&_start=0&_end=24
 * GET_ONE      => GET http://my.api.url/posts/123
 * GET_MANY     => GET http://my.api.url/posts/123, GET http://my.api.url/posts/456, GET http://my.api.url/posts/789
 * UPDATE       => PUT http://my.api.url/posts/123
 * CREATE       => POST http://my.api.url/posts/123
 * DELETE       => DELETE http://my.api.url/posts/123
 */
export default () => {
  /**
   * @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
   * @param {String} resource Name of the resource to fetch, e.g. 'posts'
   * @param {Object} params The REST request params, depending on the type
   * @returns {Object} { url, options } The HTTP request parameters
   */
  const convertRESTRequestToHTTP = (type, resource, params) => {
    let url = '';
    const options = {};
    switch (type) {
      case GET_LIST: {
        const { page, perPage } = params.pagination;
        const { field, order } = params.sort;
        const query = {
          ...params.filter,
          sort: field,
          order: order,
          page: page,
          per_page: perPage,
        };
        url = `${apiUrl}/${resource}?${queryParameters(query)}`;
        break;
      }
      case GET_ONE:
        url = `${apiUrl}/${resource}/${params.id}`;
        break;
      case GET_MANY_REFERENCE: {
        const { page, perPage } = params.pagination;
        const { field, order } = params.sort;
        const query = {
          ...params.filter,
          [params.target]: params.id,
          _sort: field,
          _order: order,
          _start: (page - 1) * perPage,
          _end: page * perPage,
        };
        url = `${apiUrl}/${resource}?${queryParameters(query)}`;
        break;
      }
      case UPDATE:
        url = `${apiUrl}/${resource}/${params.id}`;
        options.method = 'PUT';
        options.body = JSON.stringify(params.data);
        break;
      case CREATE:
        url = `${apiUrl}/${resource}`;
        options.method = 'POST';
        options.body = JSON.stringify(params.data);
        break;
      case DELETE:
        url = `${apiUrl}/${resource}/${params.id}`;
        options.method = 'DELETE';
        break;
      default:
        throw new Error(`Unsupported fetch action type ${type}`);
    }
    return { url, options };
  };

  /**
   * @param {Object} response HTTP response from fetch()
   * @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
   * @param {String} resource Name of the resource to fetch, e.g. 'posts'
   * @param {Object} params The REST request params, depending on the type
   * @returns {Object} REST response
   */
  const convertHTTPResponseToREST = (response, type, resource, params) => {
    const { headers, json } = response;
    switch (type) {
      case GET_LIST:
      case GET_MANY_REFERENCE:
        if (!headers.has('x-total-count')) {
          throw new Error('The X-Total-Count header is missing in the HTTP Response. The jsonServer REST client expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?');
        }
        return {
          // change the primary key to uuid
          data: json.data.map(resource => resource = { ...resource, id: resource.uuid }),
          total: parseInt(headers.get('x-total-count').split('/').pop(), 10),
        };
      case UPDATE:
      case DELETE:
      case GET_ONE:
        return { data: json, id: json.uuid };
      case CREATE:
        return { data: { ...params.data, id: json.uuid } };
      default:
        return { data: json };
    }
  };

  /**
   * @param {string} type Request type, e.g GET_LIST
   * @param {string} resource Resource name, e.g. "posts"
   * @param {Object} payload Request parameters. Depends on the request type
   * @returns {Promise} the Promise for a REST response
   */
  return (type, resource, params) => {
    if (type === GET_MANY) {
      return Promise.all(params.ids.map(id => httpClient(`${apiUrl}/${resource}/${id}`)))
        .then(responses => ({ data: responses.map(response => response.json) }));
    }
    const { url, options } = convertRESTRequestToHTTP(type, resource, params);
    return httpClient(url, options)
      .then(response => convertHTTPResponseToREST(response, type, resource, params));
  };
};

Any one can help here and tell me why the restClient is returned as a string instead of returning the json?

It is not a GET_LIST nor GET_ONE request. It is just a normal GET request.
I tried to use GET_ONE and GET_LIST but I still get the response as the function plain string.

Edit & Solution:

Thanks to @Gildas it is clearer to use fetch instead of restClient for a GET request. restClient is used just for <resource /> and it is not so clear by the docs.
Moreover, the actions creators were useless when I use put in my main saga function.

My fetch looks like this and it works:

function getLocales() {
  return fetch(process.env.REACT_APP_API_PATH + '/locales', { method: 'GET' })
      .then(response => (
          Promise.resolve(response)
      ))
      .then(response => (
          response.json()
      ))
      .catch((e) => {
        console.error(e);
      });
}

When I called it like this:

const { languages, currentLocale } = yield call(getLocales);

Thank you in advanced.
Leo.

Body:
This part is really strange, it seems you're binding action creators as if they were sagas, though you do put them in the getLocalesSaga:

export default function* localesSaga() {
  yield [
    takeEvery(types.GET_LOCALES, getLocalesSaga),
    takeEvery(types.GET_LOCALES_LOADING, actions.loadingLocales),
    takeEvery(types.LOCALES_RECEIVED, actions.localesReceived),
    takeEvery(types.GET_LOCALES_FAILURE, actions.failedLocales),
  ];
}

Moreover, the restClient is not fetch. GET is not a type recognized by it (see documentation). You should not use the restClient for anything that's not a resource in admin-on-rest terms. Here, you should indeed use fetch.

This should probably be rewritten like:

import types from './types';
import actions from './actions';
import { call, put, takeEvery } from 'redux-saga/effects';
import restClient from './../../restClient';

function fetchLocales() {
    return fetch(...);
}

function* getLocalesSaga() {
  try {

    yield put(actions.loadingLocales());
    let locales;
    locales = yield call(fetchLocales);
    console.log(locales); // this show the function string!!!
    if (!locales.data) {
      throw new Error('REST response must contain a data key');
    }
    yield put(actions.localesReceived(locales))

  } catch (error) {

    console.log(error);
    yield put(actions.failedLocales(error))

  }
}

export default function* localesSaga() {
  yield takeEvery(types.GET_LOCALES, getLocalesSaga);
}


问:
use SIFT or ORB for template match
with inspire of this tutorial:
Feature Matching, I'm trying to do template matching and clustering of image set I have.

The dataset I have in most of it, the image is straight ( maybe 10-degree rotate max )
I would like to use this information to have better matches,
I have noticed that sometimes I have a false match that when I display the match I can see the match vectors are all in different angles (not straight line ) how can I check if the match it's got is a straight line or rotate?

Thanks for the help

答:
I'm not sure to understand everything, what do you mean by straight image?

And for the matches, when you compare two images, you will probably have many features that correspond between those two images, and you cannot ensure that they all describe a straight line, you can just assume having kind of straight lines when you try to find an object in an image as in the example, but this is just a representation...

If you only want to do clustering, I advise you to compare features only without doing some matching, you'll probably find a cluster of common features for some images that you can regroup

Title: use SIFT or ORB for template match


问:
PHP redirect without header() or meta
I'm trying to design a page which does some database actions, then redirects to user back to the page they came from. The problem is that I use a require() function to get the connection to the database, so the headers are already sent. A meta tag is out of the question since I want it to look like all the processes are done from the page they came from. Any tips? Is there a way I can use the require() and the header() or do I have to drop one? Is there an alternative to header()?

答: You cannot send any headers after some content has already been sent. Move the header() call to be before the require() call.

Title: PHP redirect without header() or meta


问:
How do GC work in middle of scope
I have code like:

```<code>public void foo()
{
    Object x = new LongObject();
    doSomething(x);
    //More Code

    // x is never used again
    // x = null helps GB??
    Object x2 = new LongObject();
    doSomething(x2);
}
</code>```

I would like that memory alocated by x could be free by GC if it's needed. But I don't know if set to null is necesary or compiler do it.

答:
To answer your questions literally, the compiler (speaking of source code to bytecode compiler) never inserts null assignments, but still, assigning a variable to null is not necessary—usually.

As this answer explains, scope is a compile time thing and formally, an object is eligible to garbage collection, if it can not “be accessed in any potential continuing computation from any live thread”. But there is no guaranty about which eligible object will be identified by a particular implementation. As the linked answer also explains, JIT compiled code will only keep references to objects which will be subsequently accessed. This may go even further than you expect, allow garbage collection of objects that look like being in use in the source code, as runtime optimization may transform the code and reduce actual memory accesses.

But in interpreted mode, the analysis will not go so far and there might be object references in the current stack frame preventing the collection of the referent, despite the variable is not being used afterwards or even out of scope in the source code. There is no guaranty that switching from interpreted to compiled code while the method is executed is capable of getting rid of such a dangling references. It’s even unlikely that the hotspot optimizer considers compiling foo() when the actual heavy computation happens within doSomething.

Still, this is rarely an issue. Running interpreted happens only during the initialization or first time execution and even if these objects are large, there’s rarely a problem if such an object gets collected a bit later than it could. An average application consists of millions of objects.

However, if you ever think there could be an issue, you can easily fix this, without assigning null to the variable. Limit the scope:

```<code>public void foo()
{
    {
        Object x = new LongObject();
        doSomething(x);
        //More Code
    }
    {
        Object x2 = new LongObject();
        doSomething(x2);
    }
}
</code>```

Other than assigning null, limiting the scope of variables to the actual use is improving the source code quality, even in cases where it has no impact on the compiled code. While the scope is purely a source code thing, it can have an impact on the bytecode though. In the code above, compilers will reuse the location of x within the stack frame to store x2, so no dangling reference to the first LongObject exists during the second doSomething execution.

As said, this is rarely needed for memory management and improving source code quality should be driving you decisions, not attempts to help the garbage collector.

Title: How do GC work in middle of scope

Body:
I have code like:

public void foo()
{
    Object x = new LongObject();
    doSomething(x);
    //More Code

    // x is never used again
    // x = null helps GB??
    Object x2 = new LongObject();
    doSomething(x2);
}

I would like that memory alocated by x could be free by GC if it's needed. But I don't know if set to null is necesary or compiler do it.

Body:
To answer your questions literally, the compiler (speaking of source code to bytecode compiler) never inserts null assignments, but still, assigning a variable to null is not necessary—usually.

As this answer explains, scope is a compile time thing and formally, an object is eligible to garbage collection, if it can not “be accessed in any potential continuing computation from any live thread”. But there is no guaranty about which eligible object will be identified by a particular implementation. As the linked answer also explains, JIT compiled code will only keep references to objects which will be subsequently accessed. This may go even further than you expect, allow garbage collection of objects that look like being in use in the source code, as runtime optimization may transform the code and reduce actual memory accesses.

But in interpreted mode, the analysis will not go so far and there might be object references in the current stack frame preventing the collection of the referent, despite the variable is not being used afterwards or even out of scope in the source code. There is no guaranty that switching from interpreted to compiled code while the method is executed is capable of getting rid of such a dangling references. It’s even unlikely that the hotspot optimizer considers compiling foo() when the actual heavy computation happens within doSomething.

Still, this is rarely an issue. Running interpreted happens only during the initialization or first time execution and even if these objects are large, there’s rarely a problem if such an object gets collected a bit later than it could. An average application consists of millions of objects.

However, if you ever think there could be an issue, you can easily fix this, without assigning null to the variable. Limit the scope:

public void foo()
{
    {
        Object x = new LongObject();
        doSomething(x);
        //More Code
    }
    {
        Object x2 = new LongObject();
        doSomething(x2);
    }
}

Other than assigning null, limiting the scope of variables to the actual use is improving the source code quality, even in cases where it has no impact on the compiled code. While the scope is purely a source code thing, it can have an impact on the bytecode though. In the code above, compilers will reuse the location of x within the stack frame to store x2, so no dangling reference to the first LongObject exists during the second doSomething execution.

As said, this is rarely needed for memory management and improving source code quality should be driving you decisions, not attempts to help the garbage collector.


问:
How to access headers from a HttpClient response? (Angular / Ionic)
I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

```<code>Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)
</code>```

However, when I try to print "headers" from the response using a HttpClient instance:

```<code>  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }
</code>```

I get a completely different structure:

```<code>HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}
</code>```

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

答:
Are you sure you are adding it as a part of the response? You need to add the header in the response:

```<code>public void methodJava(HttpServletResponse response){
  ...
 response.addHeader("access-control-expose-headers", "Authorization");
}
</code>```

And then you can do what you have been trying. I think headers.get('Authorization') should give you the desired value

Body:
I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)

However, when I try to print "headers" from the response using a HttpClient instance:

  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }

I get a completely different structure:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

Body:
Are you sure you are adding it as a part of the response? You need to add the header in the response:

public void methodJava(HttpServletResponse response){
  ...
 response.addHeader("access-control-expose-headers", "Authorization");
}

And then you can do what you have been trying. I think headers.get('Authorization') should give you the desired value


问:
How to get gridview multiple positions and store into array variable
Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position  in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.

Activity

```<code>public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {

String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;

ImageView Ivseats;

public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.em_event_total_user_seats);
    initviews();
    callSeatsApi();

    GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

            String a = String.valueOf(position);

            Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
            v.setBackgroundColor(Color.GREEN);
            adapter.notifyDataSetChanged();
        }
    });

}

private void initviews() {

    GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
    GridUserSeats.setOnItemClickListener(this);

    textView1=(TextView) findViewById(R.id.textView1);

   // textView2=(TextView) findViewById(R.id.textView2);

    Intent intent = getIntent();

    first_name = intent.getStringExtra("first_name");
    last_name = intent.getStringExtra("last_name");

}

private void callSeatsApi() {

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("events", event_id);
    RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
            EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}

@Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {

}

@Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
    switch (mode)
    {
        case EM_SEATS:
            EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
            adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
            GridUserSeats.setAdapter(adapter);
            break;
    }

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

}
</code>```

Adapter

```<code>    import android.content.Context;
    import android.content.Intent;
     import android.support.annotation.NonNull;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.squareup.picasso.Picasso;
    import java.util.ArrayList;
    import java.util.List;
    import cfirst.live.com.R;
    import cfirst.live.com.model.BasketModel;
    import cfirst.live.com.model.EM_event_total_UserSeatsModel;

public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private  String[] mobileValuesD;

private static class ViewHolder {
    TextView TvEmUserSeats;
    ImageView IvUsreSeats,available,selctedimag;

}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();

public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
    super(context, R.layout.list_em_get_seats, data);
    this.dataSet = data;
    this.mContext=context;

}
public int getTagFromPosition(int position) {
    return tagCollection[position];
}

@Override
public void onClick(View v) {
    int position=(Integer) v.getTag();
    Object object= getItem(tagCollection[position]);

    EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    EM_event_total_UserSeatsModel dataModel = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    ViewHolder viewHolder; // view lookup cache stored in tag

    final View result;

    if (convertView == null) {

        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);

        viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
        viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);

        result=convertView;

        convertView.setTag(viewHolder);
      } else {
        viewHolder = (ViewHolder) convertView.getTag();
        result=convertView;
      }

    String blue_available = "seat3.png";
    String red_booked = "seat1.png";

    String get_seat = dataModel.getBookedStatus();
    viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
    if(Integer.parseInt(get_seat) == 1){
        Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);

    }else
    {

        Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);

    }
    return convertView;
}
}
</code>```

答:
It's simple. You can use SparseBooleanArray for this purpose. Just add the following methods as is in your adapter:

```<code>public void toggleSelection(int item) {
    if (selectedItems.get(item, false)) {
        selectedItems.delete(item);
    } else {
        selectedItems.put(item, true);
    }

    notifyDataSetChanged();
}

public void setSelectedItems(List<Object> objects) {
    if (objects != null) {
        for (Object object : objects) {
            toggleSelection(object.getId());
        }

        notifyDataSetChanged();
    }
}

public void clearSelections() {
    selectedItems.clear();
    notifyDataSetChanged();
}

public int getSelectedItemCount() {
    return selectedItems.size();
}

public List<Integer> getSelectedItems() {
    List<Integer> items =
            new ArrayList<Integer>(selectedItems.size());
    for (int i = 0; i < selectedItems.size(); i++) {
        items.add(selectedItems.keyAt(i));
    }
    return items;
}
</code>```

Use the set selection method to store the selected status of your item.
Don't forget to initialize SparseBooleanArray in your constructor.

```<code>SparseBooleanArray SparseBooleanArray = new SparseBooleanArray();
</code>```

After that, use toggleSelection(position); to change the selected status of an item, then after performing selections, call getSelectedItem() to get the selected items in an array.

Body:
Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position  in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.

Activity

public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {

String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;

ImageView Ivseats;

public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.em_event_total_user_seats);
    initviews();
    callSeatsApi();

    GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

            String a = String.valueOf(position);

            Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
            v.setBackgroundColor(Color.GREEN);
            adapter.notifyDataSetChanged();
        }
    });

}

private void initviews() {

    GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
    GridUserSeats.setOnItemClickListener(this);

    textView1=(TextView) findViewById(R.id.textView1);

   // textView2=(TextView) findViewById(R.id.textView2);

    Intent intent = getIntent();

    first_name = intent.getStringExtra("first_name");
    last_name = intent.getStringExtra("last_name");

}

private void callSeatsApi() {

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("events", event_id);
    RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
            EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}

@Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {

}

@Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
    switch (mode)
    {
        case EM_SEATS:
            EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
            adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
            GridUserSeats.setAdapter(adapter);
            break;
    }

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

}

Adapter

    import android.content.Context;
    import android.content.Intent;
     import android.support.annotation.NonNull;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.squareup.picasso.Picasso;
    import java.util.ArrayList;
    import java.util.List;
    import cfirst.live.com.R;
    import cfirst.live.com.model.BasketModel;
    import cfirst.live.com.model.EM_event_total_UserSeatsModel;

public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private  String[] mobileValuesD;

private static class ViewHolder {
    TextView TvEmUserSeats;
    ImageView IvUsreSeats,available,selctedimag;

}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();

public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
    super(context, R.layout.list_em_get_seats, data);
    this.dataSet = data;
    this.mContext=context;

}
public int getTagFromPosition(int position) {
    return tagCollection[position];
}

@Override
public void onClick(View v) {
    int position=(Integer) v.getTag();
    Object object= getItem(tagCollection[position]);

    EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    EM_event_total_UserSeatsModel dataModel = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    ViewHolder viewHolder; // view lookup cache stored in tag

    final View result;

    if (convertView == null) {

        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);

        viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
        viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);

        result=convertView;

        convertView.setTag(viewHolder);
      } else {
        viewHolder = (ViewHolder) convertView.getTag();
        result=convertView;
      }

    String blue_available = "seat3.png";
    String red_booked = "seat1.png";

    String get_seat = dataModel.getBookedStatus();
    viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
    if(Integer.parseInt(get_seat) == 1){
        Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);

    }else
    {

        Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);

    }
    return convertView;
}
}

Body:
It's simple. You can use SparseBooleanArray for this purpose. Just add the following methods as is in your adapter:

public void toggleSelection(int item) {
    if (selectedItems.get(item, false)) {
        selectedItems.delete(item);
    } else {
        selectedItems.put(item, true);
    }

    notifyDataSetChanged();
}

public void setSelectedItems(List<Object> objects) {
    if (objects != null) {
        for (Object object : objects) {
            toggleSelection(object.getId());
        }

        notifyDataSetChanged();
    }
}

public void clearSelections() {
    selectedItems.clear();
    notifyDataSetChanged();
}

public int getSelectedItemCount() {
    return selectedItems.size();
}

public List<Integer> getSelectedItems() {
    List<Integer> items =
            new ArrayList<Integer>(selectedItems.size());
    for (int i = 0; i < selectedItems.size(); i++) {
        items.add(selectedItems.keyAt(i));
    }
    return items;
}

Use the set selection method to store the selected status of your item.
Don't forget to initialize SparseBooleanArray in your constructor.

SparseBooleanArray SparseBooleanArray = new SparseBooleanArray();

After that, use toggleSelection(position); to change the selected status of an item, then after performing selections, call getSelectedItem() to get the selected items in an array.


问:
Missing values imputation in python
After applying Imputer.fit_transform() on my dataset I am losing the column names on the transformed data frame. Is there any way to impute it without losing column names??

答:
As I said in the comment to the question, just replace (re-assign) the values in the dataframe with the data returned from the Imputer.

Lets say this is your dataframe:

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame(data=[[1,2,3],
                        [3,4,4],
                        [3,5,np.nan],
                        [6,7,8],
                        [3,np.nan,1]],
                  columns=['A', 'B', 'C'])
</code>```

Current df:

```<code>   A    B    C
0  1  2.0  3.0
1  3  4.0  4.0
2  3  5.0  NaN
3  6  7.0  8.0
4  3  NaN  1.0
</code>```

If you are sending whole the df to Imputer, just use this:

```<code>df[df.columns] = Imputer().fit_transform(df)
</code>```

If you are sending only some columns, then use those columns only to assign the results:

```<code>columns_to_impute = ['B', 'C']
df[columns_to_impute] = Imputer().fit_transform(df[columns_to_impute])
</code>```

Output:

```<code>     A    B    C
0  1.0  2.0  3.0
1  3.0  4.0  4.0
2  3.0  5.0  4.0
3  6.0  7.0  8.0
4  3.0  4.5  1.0
</code>```

Title: Missing values imputation in python

Body:
As I said in the comment to the question, just replace (re-assign) the values in the dataframe with the data returned from the Imputer.

Lets say this is your dataframe:

import numpy as np
import pandas as pd

df = pd.DataFrame(data=[[1,2,3],
                        [3,4,4],
                        [3,5,np.nan],
                        [6,7,8],
                        [3,np.nan,1]],
                  columns=['A', 'B', 'C'])

Current df:

   A    B    C
0  1  2.0  3.0
1  3  4.0  4.0
2  3  5.0  NaN
3  6  7.0  8.0
4  3  NaN  1.0

If you are sending whole the df to Imputer, just use this:

df[df.columns] = Imputer().fit_transform(df)

If you are sending only some columns, then use those columns only to assign the results:

columns_to_impute = ['B', 'C']
df[columns_to_impute] = Imputer().fit_transform(df[columns_to_impute])

Output:

     A    B    C
0  1.0  2.0  3.0
1  3.0  4.0  4.0
2  3.0  5.0  4.0
3  6.0  7.0  8.0
4  3.0  4.5  1.0


问:
Gradle Connection timed out
after updating android studio 2.3 to 3.0 i got lots of errors so many work i done it but didn't work

Error:Could not resolve all files for configuration ':app:debugCompileClasspath'.

Could not resolve com.android.support:appcompat-v7:26.1.0.
    Required by:
        project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not HEAD 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to jcenter.bintray.com:443 [jcenter.bintray.com/108.168.243.150] failed: Connection timed out: connect

gradle wrapper properties

```<code>#Mon Nov 06 17:20:27 IRST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
</code>```

my gradle  (module app)

```<code> apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "curlpagetutorial.example.com.mydd"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

New errors

Required by:
    project :app

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.

Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support.test:runner:1.0.1.

Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.

I'm stuck here for long time please help me

答:
Download gradle from:http://services.gradle.org/distributions/

choose the file such as gradle-4.1-rc-1-all.zip

Find your gradle directory in AndroidStudio
    setting-->Build,Execution,Deployment -->Gradle

Unzip the file to "(your gradle path)\wrapper\dists\gradle-4.1-all\bzyivzo6n839fup2jbap0tjew"

Title: Gradle Connection timed out

Body:
after updating android studio 2.3 to 3.0 i got lots of errors so many work i done it but didn't work

Error:Could not resolve all files for configuration ':app:debugCompileClasspath'.

Could not resolve com.android.support:appcompat-v7:26.1.0.
    Required by:
        project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not HEAD 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to jcenter.bintray.com:443 [jcenter.bintray.com/108.168.243.150] failed: Connection timed out: connect

gradle wrapper properties

#Mon Nov 06 17:20:27 IRST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

my gradle  (module app)

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "curlpagetutorial.example.com.mydd"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

New errors

Required by:
    project :app

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not parse POM https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom
  Already seen doctype.

Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support.test:runner:1.0.1.

Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.

I'm stuck here for long time please help me


问:
local rails engine running server but not console
An application can start the Thin web server

```<code>rails s
</code>```

However, launching the console

```<code>rails c
</code>```

hangs and never returns to a prompt.

Obviously, I need it to run!

note 1: I believe this is a consequence of an external disk that houses the application, that lost its connection to the main computer

note 2: I had read incidentally that the spring gem has some un-robust behaviours. Could this be a motive?

答:
run following command & it should be fix</p>

```<code>spring stop
</code>```

Body:
An application can start the Thin web server

rails s

However, launching the console

rails c

hangs and never returns to a prompt.

Obviously, I need it to run!

note 1: I believe this is a consequence of an external disk that houses the application, that lost its connection to the main computer

note 2: I had read incidentally that the spring gem has some un-robust behaviours. Could this be a motive?

Body:
run following command & it should be fix

spring stop


问:
How to Restore DataBase Backup that found in another server?

using sqlServer 2012 ..I have abackup File (MyDataBase.Bak) found in server Ip=(134.122.123:4454) .. and I want to restore this backup to another server .. the same dataBase in another server (MyDataBase) ,, server IP (134.122.124:4455) .. How can I do that , how can I restore database Found in another server ??
</p>

答:
If you are unable to restore your backup file in different server then other option is generate script and just you have to run on different server.

Right click database → Tasks → Generate Scripts → Select your table → Click on Advance button → Types of Data to script - Select Schema and Data → Click on Next button.

Now run your generated script on different server.