问:
DataContract Serialize abstract class
I have an interface IServiceInfo and an abstract class ServiceInfo. There are several classes inherited from ServiceInfo, like CoreServiceInfo, ModuleServiceInfo etc. There is a service contract named RootService which returns IServiceInfo.

```<code> public IServiceInfo GetServiceInfo()
 {
     return (IServiceInfo)new CoreServiceInfo();
 }
</code>```

I am having problem serializing. I can use ServiceKnownType to identify base class, and KnownType to identify child class.

Problem is I do not know all the ServiceInfo child, since application can have plugins with different child inherited from ServiceInfo, so I cannot tell serializer to have all the child in serialized XML.

I can ignore abstract class, but it contains certain common implementation so I need to keep it. As a work around I can have another class say "sampleServiceInfo" and convert all the info classes to sampleServiceInfo and return it from Service method, and define KnownType to ServiceInfo class.

```<code>[KnownType(typeof(sampleServiceInfo))]
public class ServiceInfo : IServiceInfo
</code>```

But that does not sound pretty way to do it. Please suggest. Do I need to write custom serializer? Is there any way to serialize base only and ignoring the child when both has same members?

答:
Get all the types in all loaded assemblies that implement given abstract class or interface(ref:Implementations of interface through Reflection)

```<code> var allTypes =  AppDomain
            .CurrentDomain
            .GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .Where(type => typeof(A).IsAssignableFrom(type));
</code>```

Then create serializer passing allTypes as known types parameter, as below

```<code>var serializer = new DataContractSerializer(typeof(A), allTypes);
</code>```

that's it - you will be able to serialize and deserialize any type that derives from A (A could be class or interface, if interface, serializer writes elements as deriving from xs:anyType.

Title: DataContract Serialize abstract class

Body:
I have an interface IServiceInfo and an abstract class ServiceInfo. There are several classes inherited from ServiceInfo, like CoreServiceInfo, ModuleServiceInfo etc. There is a service contract named RootService which returns IServiceInfo.

 public IServiceInfo GetServiceInfo()
 {
     return (IServiceInfo)new CoreServiceInfo();
 }

I am having problem serializing. I can use ServiceKnownType to identify base class, and KnownType to identify child class.

Problem is I do not know all the ServiceInfo child, since application can have plugins with different child inherited from ServiceInfo, so I cannot tell serializer to have all the child in serialized XML.

I can ignore abstract class, but it contains certain common implementation so I need to keep it. As a work around I can have another class say "sampleServiceInfo" and convert all the info classes to sampleServiceInfo and return it from Service method, and define KnownType to ServiceInfo class.

[KnownType(typeof(sampleServiceInfo))]
public class ServiceInfo : IServiceInfo

But that does not sound pretty way to do it. Please suggest. Do I need to write custom serializer? Is there any way to serialize base only and ignoring the child when both has same members?

Body:
Get all the types in all loaded assemblies that implement given abstract class or interface(ref:Implementations of interface through Reflection)

 var allTypes =  AppDomain
            .CurrentDomain
            .GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .Where(type => typeof(A).IsAssignableFrom(type));

Then create serializer passing allTypes as known types parameter, as below

var serializer = new DataContractSerializer(typeof(A), allTypes);

that's it - you will be able to serialize and deserialize any type that derives from A (A could be class or interface, if interface, serializer writes elements as deriving from xs:anyType.


来源: stackexchange

问:
What better way to use CSS / JS in Laravel and where to put it?
What do I call style files? Are there good practices? Laravel v.5.4</p>

答:
You can use laravel mix to compile your all css and js if you have node installed, for that you have to put your css and js in resources/assets folder.

You have to install node dependencies by running npm install in your laravel folder.

For compiling your js and css you can use

```<code>mix.js(['resources/assets/js/app.js'], 'public/js');

mix.styles([
    'resources/assets/css/style.css',
    'resources/assets/css/style1.css'
], 'public/css/all.css');
</code>```

in webpack.mix.js file, it will compile all your css and js to public folder  into single css/js file.

you can use npm run dev to compile your files or npm run watch to add watcher when your js/css files change

more reference here

ContentLicense: CC BY-SA 3.0

Body:
You can use laravel mix to compile your all css and js if you have node installed, for that you have to put your css and js in resources/assets folder.

You have to install node dependencies by running npm install in your laravel folder.

For compiling your js and css you can use

mix.js(['resources/assets/js/app.js'], 'public/js');

mix.styles([
    'resources/assets/css/style.css',
    'resources/assets/css/style1.css'
], 'public/css/all.css');

in webpack.mix.js file, it will compile all your css and js to public folder  into single css/js file.

you can use npm run dev to compile your files or npm run watch to add watcher when your js/css files change

more reference here


问:
Parallel Stream in scala
is there any (hopefully out of the box) way to traverse an Scala stream in parallel?

for instance, see this java 8 code:

```<code>String[] s = {"a","b","c","d","e"};
List<String> list = Arrays.asList(s);
list.parallelStream().forEach(System.out::println);
</code>```

this will print all list stream contents in parallel..
however, to my understanding, streams in scala are sequential.

any workarounds for this?

EDIT:
please notice that, streams allows us to process data as they arrive. then, if data is not necessary, remove them from memory.
for instance:

```<code>"abcd".toStream.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block
</code>```

will output something like this:

1 filter a

1 filter b

2 filter->b

1 filter c

1 filter d

2 filter->d

on the other hand, the below code, will process data in blocks. keeping variables in memory on each transformation:

```<code>  "abcd".toVector.par.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block
</code>```

output:
1 filter c

1 filter a

1 filter b

1 filter d

2 filter->b

2 filter->d

答:
Many (most?) Scala collections have a par method that "returns a parallel implementation of this collection."

From the ScalaDocs:

For most collection types, this method creates a new parallel collection by copying all the elements. For these collections, par takes linear time.

A Scala Stream[] has no direct parallel implementation, so you get ParSeq[] instead, and since ParSeq is a trait, the REPL will instantiate it as a ParVector.

```<code>scala> Stream("a","b","c","d","e").par
res0: scala.collection.parallel.immutable.ParSeq[String] = ParVector(a, b, c, d, e)
</code>```

Also worth noting is the information elsewhere in the ScalaDocs:

The higher-order functions passed to certain operations may contain side-effects. Since implementations of bulk operations may not be sequential, this means that side-effects may not be predictable and may produce data-races, deadlocks or invalidation of state if care is not taken. It is up to the programmer to either avoid using side-effects or to use some form of synchronization when accessing mutable data.

So your foreach(println) code might have unpredictable/undesirable results.

Title: Parallel Stream in scala

Body:
is there any (hopefully out of the box) way to traverse an Scala stream in parallel?

for instance, see this java 8 code:

String[] s = {"a","b","c","d","e"};
List<String> list = Arrays.asList(s);
list.parallelStream().forEach(System.out::println);

this will print all list stream contents in parallel..
however, to my understanding, streams in scala are sequential.

any workarounds for this?

EDIT:
please notice that, streams allows us to process data as they arrive. then, if data is not necessary, remove them from memory.
for instance:

"abcd".toStream.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block

will output something like this:

1 filter a

1 filter b

2 filter->b

1 filter c

1 filter d

2 filter->d

on the other hand, the below code, will process data in blocks. keeping variables in memory on each transformation:

  "abcd".toVector.par.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block

output:
1 filter c

1 filter a

1 filter b

1 filter d

2 filter->b

2 filter->d

Body:
Many (most?) Scala collections have a par method that "returns a parallel implementation of this collection."

From the ScalaDocs:

For most collection types, this method creates a new parallel collection by copying all the elements. For these collections, par takes linear time.

A Scala Stream[] has no direct parallel implementation, so you get ParSeq[] instead, and since ParSeq is a trait, the REPL will instantiate it as a ParVector.

scala> Stream("a","b","c","d","e").par
res0: scala.collection.parallel.immutable.ParSeq[String] = ParVector(a, b, c, d, e)

Also worth noting is the information elsewhere in the ScalaDocs:

The higher-order functions passed to certain operations may contain side-effects. Since implementations of bulk operations may not be sequential, this means that side-effects may not be predictable and may produce data-races, deadlocks or invalidation of state if care is not taken. It is up to the programmer to either avoid using side-effects or to use some form of synchronization when accessing mutable data.

So your foreach(println) code might have unpredictable/undesirable results.


问:
Conflict control ID
I am having problem in publishing my custom project in Acumatica ERP. It prompts me the following message.

Conflict control ID:phG_tab_Items#0_grid_Levels#0 from page
  ~/pages/so/so303000.aspx Validation failed.

Here is what my code looks like in the Invoices page (ScreenID: SO303000)

```<code><Page path="~/pages/so/so303000.aspx" ControlId="2" pageSource="711Ft7m6F+foDk0z4+/8B">
    <PXGridLevel DataMember="Transactions" ParentId="phG_tab_Items#0_grid_Levels#0" TypeFullName="PX.Web.UI.PXGridLevel">
        <Children Key="Columns">
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrContractID" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrPhoneNumber" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrSIMCardID" />
                    <Prop Key="Width" Value="160" />
                </PXGridColumn>
            </AddItem>
        </Children>
    </PXGridLevel>
</Page>
</code>```

I have shortened the pageSource value for readability.

Since, I have another custom project as well, and got answer that that could cause this, I have no idea what changes should I do to make this work.

答:
I don't know if it's the best way to do it, but here is what I did.
I copied the changes from the my one custom project to another custom project in the same page screen. And it worked!

This worked for now. But please let me know if there is better way to do this.

Title: Conflict control ID

Body:
I am having problem in publishing my custom project in Acumatica ERP. It prompts me the following message.

Conflict control ID:phG_tab_Items#0_grid_Levels#0 from page
  ~/pages/so/so303000.aspx Validation failed.

Here is what my code looks like in the Invoices page (ScreenID: SO303000)

<Page path="~/pages/so/so303000.aspx" ControlId="2" pageSource="711Ft7m6F+foDk0z4+/8B">
    <PXGridLevel DataMember="Transactions" ParentId="phG_tab_Items#0_grid_Levels#0" TypeFullName="PX.Web.UI.PXGridLevel">
        <Children Key="Columns">
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrContractID" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrPhoneNumber" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrSIMCardID" />
                    <Prop Key="Width" Value="160" />
                </PXGridColumn>
            </AddItem>
        </Children>
    </PXGridLevel>
</Page>

I have shortened the pageSource value for readability.

Since, I have another custom project as well, and got answer that that could cause this, I have no idea what changes should I do to make this work.


问:
How can I add an alert when Geolocation Services are denied?
It had worked previously in my code, however with the recent changes I made it seems to be broken. I tried looking online for solutions, however this seems specific to me in terms of what I need. All i want is for an "alert();" to be showen if the browser Geolocation Services request is denied. Here is the code without the alert added in. Thank you.</p>

```<code>      if (navigator.geolocation) {
            // Locate position
            navigator.geolocation.getCurrentPosition(displayPosition);
        } else {
            alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
        }
        blacklisted_areas = {
            'area 51': [1, 2],
            'pink unicorn zoo': [1, 2],
        };
        // Success callback function
        function displayPosition(pos) {
  var mylat = pos.coords.latitude;
  var mylong = pos.coords.longitude;
  var thediv = document.getElementById('locationinfo');
  thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';

  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (mylat === x[0] && mylong === x[1]) {
      blacklisted = true;
    }
  }
  if(!blacklisted){
    window.location="insertURLHere";
  }

}
</code>```

答:
Pass a callback for on error.</p>

```<code>if (navigator.geolocation) {
  // Get user's geo position.
  navigator.geolocation.getCurrentPosition(function success(position) {
    // Success
  }, function error(err) {
    // Geolcoation denied.
    if (err.code === err.PERMISSION_DENIED) {
      // Determine reason for error.
      if (err.message.match(/secure/i)) {
        console.alert('INSECURE_ORIGIN');
      } else {
        console.alert('INSECURE_ORIGIN');
      }
    }
  });
}
</code>```

Body:
It had worked previously in my code, however with the recent changes I made it seems to be broken. I tried looking online for solutions, however this seems specific to me in terms of what I need. All i want is for an "alert();" to be showen if the browser Geolocation Services request is denied. Here is the code without the alert added in. Thank you.

      if (navigator.geolocation) {
            // Locate position
            navigator.geolocation.getCurrentPosition(displayPosition);
        } else {
            alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
        }
        blacklisted_areas = {
            'area 51': [1, 2],
            'pink unicorn zoo': [1, 2],
        };
        // Success callback function
        function displayPosition(pos) {
  var mylat = pos.coords.latitude;
  var mylong = pos.coords.longitude;
  var thediv = document.getElementById('locationinfo');
  thediv.innerHTML = '
Your longitude is :' + mylong + ' and your latitide is ' + mylat + '
';

  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (mylat === x[0] && mylong === x[1]) {
      blacklisted = true;
    }
  }
  if(!blacklisted){
    window.location="insertURLHere";
  }

}

Body:
Pass a callback for on error.

if (navigator.geolocation) {
  // Get user's geo position.
  navigator.geolocation.getCurrentPosition(function success(position) {
    // Success
  }, function error(err) {
    // Geolcoation denied.
    if (err.code === err.PERMISSION_DENIED) {
      // Determine reason for error.
      if (err.message.match(/secure/i)) {
        console.alert('INSECURE_ORIGIN');
      } else {
        console.alert('INSECURE_ORIGIN');
      }
    }
  });
}


问:
Grey Bar at bottom of Website Only On Mobile View
I have set a background on my website (www.brentleas.com) and it fills the screen on desktop but on mobile it doesn't. When I use the development tools on chrome it shows the image filling the screen. However when I load up the website on my phone it has a grey bar at the bottom of the page.

Image showing what I'm talking about: 1

Here's my css code:

```<code>html {

background-image: url("../images/cooper.png");

background-repeat: no-repeat;

background-position: center center;

background-attachment: fixed;

background-size: cover;

background-color: #464646;

color: white; }
</code>```

Any help would be greatly appreciated. Thanks in advance.

答:
use js like this and tweak it based on viewport size:</p>

```<code>//ON LOAD INITIALLY ASSUME PHONE
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
doc.getElementsByTagName("body")[0].style.padding = "2px";
var mainItems = doc.getElementsByClassName("main-item");
for (var i = 0; i < mainItems.length; i++) {
    mainItems[i].classList.add("full-width");
}
doc.getElementsByTagName("main")[0].classList.add("column");
// doc.getElementById("title-right").style.display = "none";
if (width >= 840) {
    //IT'S A DESKTOP
    doc.getElementsByTagName("body")[0].style.padding = "24px";
    for (var i = 0; i < mainItems.length; i++) {
        mainItems[i].classList.remove("full-width");
    }
    doc.getElementsByTagName("main")[0].classList.remove("column");
    // doc.getElementById("title").style.display = "none";
    // doc.getElementById("title-right").style.display = "flex";
}
else if (width >= 480) {
    //IT'S A TABLET
    // doc.getElementById("title").style.display = "flex";
    doc.getElementsByTagName("body")[0].style.padding = "24px";
    for (var i = 0; i < mainItems.length; i++) {
        mainItems[i].classList.remove("full-width");
    }
    doc.getElementsByTagName("main")[0].classList.remove("column");
}
//ON RESIZE INITIALLY ASSUME PHONE
window.addEventListener("resize", resizeThrottler, false);
var resizeTimeout;
function actualResizeHandler() {
    // assuming device is a phone
    doc.getElementsByTagName("body")[0].style.padding = "2px";
    for (var i = 0; i < mainItems.length; i++) {
        mainItems[i].classList.add("full-width");
    }
    doc.getElementsByTagName("main")[0].classList.add("column");
    // doc.getElementById("title").style.display = "flex";
    // doc.getElementById("title-right").style.display = "none";
    if (window.innerWidth >= 840) {
        //device is a desktop
        doc.getElementsByTagName("body")[0].style.padding = "24px";
        for (var i = 0; i < mainItems.length; i++) {
            mainItems[i].classList.remove("full-width");
        }
        doc.getElementsByTagName("main")[0].classList.remove("column");
        // doc.getElementById("title").style.display = "none";
        // doc.getElementById("title-right").style.display = "flex";
    }
    else if (window.innerWidth >= 480) {
        //device is a tablet
        doc.getElementByTagName("body")[0].style.padding = "24px";
        for (var i = 0; i < mainItems.length; i++) {
            mainItems[i].classList.remove("full-width");
        }
        doc.getElementsByTagName("main")[0].classList.remove("column");
        // doc.getElementById("title").style.display = "none";
        // doc.getElementById("title-right").style.display = "flex";
    }
}
function resizeThrottler() {
    // ignore resize events as long as an actualResizeHandler execution is in the queue
    if (!resizeTimeout) {
        resizeTimeout = setTimeout(function() {
            resizeTimeout = null;
            actualResizeHandler();
            // The actualResizeHandler will execute at a rate of 15fps
        }, 66);
    }
}
</code>```

Body:
I have set a background on my website (www.brentleas.com) and it fills the screen on desktop but on mobile it doesn't. When I use the development tools on chrome it shows the image filling the screen. However when I load up the website on my phone it has a grey bar at the bottom of the page.

Image showing what I'm talking about: 1

Here's my css code:

html {

background-image: url("../images/cooper.png");

background-repeat: no-repeat;

background-position: center center;

background-attachment: fixed;

background-size: cover;

background-color: #464646;

color: white; }

Any help would be greatly appreciated. Thanks in advance.

Body:
use js like this and tweak it based on viewport size:

//ON LOAD INITIALLY ASSUME PHONE
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
doc.getElementsByTagName("body")[0].style.padding = "2px";
var mainItems = doc.getElementsByClassName("main-item");
for (var i = 0; i < mainItems.length; i++) {
    mainItems[i].classList.add("full-width");
}
doc.getElementsByTagName("main")[0].classList.add("column");
// doc.getElementById("title-right").style.display = "none";
if (width >= 840) {
    //IT'S A DESKTOP
    doc.getElementsByTagName("body")[0].style.padding = "24px";
    for (var i = 0; i < mainItems.length; i++) {
        mainItems[i].classList.remove("full-width");
    }
    doc.getElementsByTagName("main")[0].classList.remove("column");
    // doc.getElementById("title").style.display = "none";
    // doc.getElementById("title-right").style.display = "flex";
}
else if (width >= 480) {
    //IT'S A TABLET
    // doc.getElementById("title").style.display = "flex";
    doc.getElementsByTagName("body")[0].style.padding = "24px";
    for (var i = 0; i < mainItems.length; i++) {
        mainItems[i].classList.remove("full-width");
    }
    doc.getElementsByTagName("main")[0].classList.remove("column");
}
//ON RESIZE INITIALLY ASSUME PHONE
window.addEventListener("resize", resizeThrottler, false);
var resizeTimeout;
function actualResizeHandler() {
    // assuming device is a phone
    doc.getElementsByTagName("body")[0].style.padding = "2px";
    for (var i = 0; i < mainItems.length; i++) {
        mainItems[i].classList.add("full-width");
    }
    doc.getElementsByTagName("main")[0].classList.add("column");
    // doc.getElementById("title").style.display = "flex";
    // doc.getElementById("title-right").style.display = "none";
    if (window.innerWidth >= 840) {
        //device is a desktop
        doc.getElementsByTagName("body")[0].style.padding = "24px";
        for (var i = 0; i < mainItems.length; i++) {
            mainItems[i].classList.remove("full-width");
        }
        doc.getElementsByTagName("main")[0].classList.remove("column");
        // doc.getElementById("title").style.display = "none";
        // doc.getElementById("title-right").style.display = "flex";
    }
    else if (window.innerWidth >= 480) {
        //device is a tablet
        doc.getElementByTagName("body")[0].style.padding = "24px";
        for (var i = 0; i < mainItems.length; i++) {
            mainItems[i].classList.remove("full-width");
        }
        doc.getElementsByTagName("main")[0].classList.remove("column");
        // doc.getElementById("title").style.display = "none";
        // doc.getElementById("title-right").style.display = "flex";
    }
}
function resizeThrottler() {
    // ignore resize events as long as an actualResizeHandler execution is in the queue
    if (!resizeTimeout) {
        resizeTimeout = setTimeout(function() {
            resizeTimeout = null;
            actualResizeHandler();
            // The actualResizeHandler will execute at a rate of 15fps
        }, 66);
    }
}


问:
SELECT PHP and MySQL not working
I have this code for the select and printing values.
mysql_numn_rows returns null :/</p>

```<code><?php
mysql_connect('localhost','root','');
mysql_select_db("db2517");

$username = "Cristoforo";
$query = mysql_query("SELECT * users WHERE username='$username' ");

$numberOfRows = mysql_num_rows($query);
echo "num: $numberOfRows";

?>
</code>```

答:
First I would like to suggest you user PDO or MYQLI

In your query you have missed the from so replace your query:

From

```<code>$query = mysql_query("SELECT * users WHERE username='$username' ");
</code>```

To

```<code>$query = mysql_query("SELECT * from users WHERE username='$username' ");
</code>```

Title: SELECT PHP and MySQL not working

Body:
I have this code for the select and printing values.
mysql_numn_rows returns null :/

<?php
mysql_connect('localhost','root','');
mysql_select_db("db2517");

$username = "Cristoforo";
$query = mysql_query("SELECT * users WHERE username='$username' ");

$numberOfRows = mysql_num_rows($query);
echo "num: $numberOfRows";

?>

Body:
First I would like to suggest you user PDO or MYQLI

In your query you have missed the from so replace your query:

From

$query = mysql_query("SELECT * users WHERE username='$username' ");

To

$query = mysql_query("SELECT * from users WHERE username='$username' ");


问:
mongod and mongo commands not working on windows 10
I've installed mongoDB on my windows 10 OS. Then I tried setting its database path to some directory by moving to it and typing mongod --datapath=data in cmd, where data is the folder which is to contain the db(I've used the relative path because I'm in that directory). But message comes that mongod is unrecognized command. After some searching I found that by specifying mongod path, i.e. "C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --datapath=data works. Similar thing happens for mongo.

I want to directly run mongod and mongo commands, I have seen people directly using it(without going to the directory or specifying the path).

答:
For a Windows installation, by default you have to use the full path to the exe unless you add it to the PATH.

To add it to the PATH:

01)  Get path to bin, something like:  C:\Program Files\MongoDB\Server\4.0\bin

02)  Press the Windows key, type env, select Edit the system environment variables

03)  On the Advanced tab, click Environment Variables

04)  In the User variables for xxxx section, select path and then click the Edit... button

05)  Click New and paste your path with a trailing slash, eg:

C:\Program Files\MongoDB\Server\4.0\bin\

06)  Click OK, OK, OK and restart your command window.

Source

The examples you have seen are probably based on UNIX installations which I think by default install mongo as a service (which Windows doesn't) and that is what is called in those examples.

To simplify startup and configuration on Windows, you can also install it as a service. See the Mongo documentation here and the
"Configure Windows Service for MongoDB' section".

This will then allow you to start and stop Mongo by simply calling

```<code>net start MongoDB
</code>```

Or

```<code>net stop MongoDB
</code>```

Body:
For a Windows installation, by default you have to use the full path to the exe unless you add it to the PATH.

To add it to the PATH:

01)  Get path to bin, something like:  C:\Program Files\MongoDB\Server\4.0\bin

02)  Press the Windows key, type env, select Edit the system environment variables

03)  On the Advanced tab, click Environment Variables

04)  In the User variables for xxxx section, select path and then click the Edit... button

05)  Click New and paste your path with a trailing slash, eg:

C:\Program Files\MongoDB\Server\4.0\bin\

06)  Click OK, OK, OK and restart your command window.

Source

The examples you have seen are probably based on UNIX installations which I think by default install mongo as a service (which Windows doesn't) and that is what is called in those examples.

To simplify startup and configuration on Windows, you can also install it as a service. See the Mongo documentation here and the
"Configure Windows Service for MongoDB' section".

This will then allow you to start and stop Mongo by simply calling

net start MongoDB

Or

net stop MongoDB

ContentLicense: CC BY-SA 4.0


问:
What is a good method for decrypting a packet being sent from a client over a local network? (Possible wireshark?)
At the moment I am working on a C# project that processes packets being sent from the client using a PacketReader I created. I log the packet and data being sent from the client into a textbox, but how do i really understand what is being sent?

Here is an example of one of the packets:

```<code>Client->Server
06 00 FD FF 3A 1A                                   ....:.
</code>```

What I really don't understand is the data to the right of the hex.

答:
Wireshark trying to treate the hex as ASCII and print it.

But in ASCII only 0x20 ~ 0x7E is printable, other hex would be displayed as ...

For reference: https://www.wireshark.org/docs/wsug_html_chunked/AppToolstext2pcap.html

Body:
At the moment I am working on a C# project that processes packets being sent from the client using a PacketReader I created. I log the packet and data being sent from the client into a textbox, but how do i really understand what is being sent?

Here is an example of one of the packets:

Client->Server
06 00 FD FF 3A 1A                                   ....:.

What I really don't understand is the data to the right of the hex.


问:
React-Native Modal does not show when Dom rerender
In my render function,I make a request,so 'loading' will show when loading.After received the data ,I called 'setState' to make the DOM rerender. I want to show the modal,but the modal do not present. What' wrong with me?</p>

```<code> render: function() {

    if (!this.props.data) {
           return (<View style={{flex:1}}>
                    <Text>loading</Text>
                </View>);
    }
    return (
        <View style={{flex:1, width:screenWidth}}>
         <Modal
                visible={true}
                transparent={true}
                onRequestClose={()=>{
                }}
                onShow={()=>{
                }}>
                <View
                    style={{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'rgba(0, 0, 0, 0.3)'}}>
                    <View style={{height:200,width:275,backgroundColor:'white'}}>
                        <Button title='confirm' onPress={()=>{}}/>
                        <Button title='cancel' onPress={()=>{}}/>
                    </View>
                </View>
            </Modal>
        </View>
    );
}
</code>```

答:
You can check condition in single return like:

```<code>render(){
    return(
        {(!this.props.data)
        ? (<View style={{flex:1}}>
              <Text>loading</Text>
          </View>)
        : (<View style={{flex:1, width:screenWidth}}>
            <Modal/> { /*your modal code */}
        </View>)
        }
    );
}
</code>```

First check your modal opens without condition or not, if yes then it is style or re-rending issue.

Body:
In my render function,I make a request,so 'loading' will show when loading.After received the data ,I called 'setState' to make the DOM rerender. I want to show the modal,but the modal do not present. What' wrong with me?

 render: function() {

    if (!this.props.data) {
           return (<View style={{flex:1}}>
                    <Text>loading</Text>
                </View>);
    }
    return (
        <View style={{flex:1, width:screenWidth}}>
         <Modal
                visible={true}
                transparent={true}
                onRequestClose={()=>{
                }}
                onShow={()=>{
                }}>
                <View
                    style={{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'rgba(0, 0, 0, 0.3)'}}>
                    <View style={{height:200,width:275,backgroundColor:'white'}}>
                        <Button title='confirm' onPress={()=>{}}/>
                        <Button title='cancel' onPress={()=>{}}/>
                    </View>
                </View>
            </Modal>
        </View>
    );
}

Body:
You can check condition in single return like:

render(){
    return(
        {(!this.props.data)
        ? (<View style={{flex:1}}>
              <Text>loading</Text>
          </View>)
        : (<View style={{flex:1, width:screenWidth}}>
            <Modal/> { /*your modal code */}
        </View>)
        }
    );
}

First check your modal opens without condition or not, if yes then it is style or re-rending issue.


问:
Heroku: How to push different local Git branches to Heroku/master
Heroku has a policy of ignoring all branches but 'master'.

While I'm sure Heroku's designers have excellent reasons for this policy (I'm guessing for storage and performance optimization), the consequence to me as a developer is that whatever local topic branch I may be working on, I would like an easy way to switch Heroku's master to that local topic branch and do a "git push heroku -f" to over-write master on Heroku.

What I got from reading the "Pushing Refspecs" section of http://progit.org/book/ch9-5.html is

```git push -f heroku local-topic-branch:refs/heads/master```

What I'd really like is a way to set this up in the configuration file so that "git push heroku" always does the above, replacing local-topic-branch with the name of whatever my current branch happens to be.  If anyone knows how to accomplish that, please let me know!

The caveat for this, of course, is that this is only sensible if I am the only one who can push to that Heroku app/repository. A test or QA team might manage such a repository to try out different candidate branches, but they would have to coordinate so that they all agree on what branch they are pushing to it on any given day.

Needless to say, it would also be a very good idea to have a separate remote repository (like GitHub) without this restriction for backing everything up to. I'd call that one "origin" and use "heroku" for Heroku so that "git push" always backs up everything to origin, and "git push heroku" pushes whatever branch I'm currently on to Heroku's master branch, overwriting it if necessary.

Would this work?

```
[remote "heroku"]
    url = git@heroku.com:my-app.git
    push = +refs/heads/*:refs/heads/master
```

I'd like to hear from someone more experienced before I begin to experiment, although I suppose I could create a dummy app on Heroku and experiment with that.

As for fetching, I don't really care if the Heroku repository is write-only. I still have a separate repository, like GitHub, for backup and cloning of all my work.

Footnote: This question is similar to, but not quite the same as Good Git deployment using branches strategy with Heroku?

答:
You should check out heroku_san, it solves this problem quite nicely.

For example, you could:

```<code>git checkout BRANCH
rake qa deploy
</code>```

It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:

```<code>git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates
</code>```

And of course you can make simpler rake tasks if you do something frequently.

Body:
Heroku has a policy of ignoring all branches but 'master'.

While I'm sure Heroku's designers have excellent reasons for this policy (I'm guessing for storage and performance optimization), the consequence to me as a developer is that whatever local topic branch I may be working on, I would like an easy way to switch Heroku's master to that local topic branch and do a "git push heroku -f" to over-write master on Heroku.

What I got from reading the "Pushing Refspecs" section of http://progit.org/book/ch9-5.html is

git push -f heroku local-topic-branch:refs/heads/master

What I'd really like is a way to set this up in the configuration file so that "git push heroku" always does the above, replacing local-topic-branch with the name of whatever my current branch happens to be.  If anyone knows how to accomplish that, please let me know!

The caveat for this, of course, is that this is only sensible if I am the only one who can push to that Heroku app/repository. A test or QA team might manage such a repository to try out different candidate branches, but they would have to coordinate so that they all agree on what branch they are pushing to it on any given day.

Needless to say, it would also be a very good idea to have a separate remote repository (like GitHub) without this restriction for backing everything up to. I'd call that one "origin" and use "heroku" for Heroku so that "git push" always backs up everything to origin, and "git push heroku" pushes whatever branch I'm currently on to Heroku's master branch, overwriting it if necessary.

Would this work?

[remote "heroku"]
    url = git@heroku.com:my-app.git
    push = +refs/heads/*:refs/heads/master

I'd like to hear from someone more experienced before I begin to experiment, although I suppose I could create a dummy app on Heroku and experiment with that.

As for fetching, I don't really care if the Heroku repository is write-only. I still have a separate repository, like GitHub, for backup and cloning of all my work.

Footnote: This question is similar to, but not quite the same as Good Git deployment using branches strategy with Heroku?

Body:
You should check out heroku_san, it solves this problem quite nicely.

For example, you could:

git checkout BRANCH
rake qa deploy

It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:

git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates

And of course you can make simpler rake tasks if you do something frequently.

ContentLicense: CC BY-SA 2.5


问:
Subset data frame to include only levels of one factor that have values in both levels of another factor
I am working with a data frame that deals with numeric measurements. Some individuals have been measured several times, both as juveniles and adults.
A reproducible example:

```<code>ID <- c("a1", "a2", "a3", "a4", "a1", "a2", "a5", "a6", "a1", "a3")
age <- rep(c("juvenile", "adult"), each=5)
size <- rnorm(10)

# e.g. a1 is measured 3 times, twice as a juvenile, once as an adult.
d <- data.frame(ID, age, size)
</code>```

My goal is to subset that data frame by selecting the IDs that appear at least once as a juvenile and at least once as an adult. Not sure how to do that..?

The resulting dataframe would contain all measurements for individuals a1, a2 and a3, but would exclude a4, a5 and a6, as they were not measured at both stages.

A similar question was asked 7 months ago but never had an answer (Subset data frame to include only levels one factor that have values in both levels of another factor)

Thanks!

答:
Here is one option with data.table

```<code>library(data.table)
setDT(d)[, .SD[all(c("juvenile", "adult") %in% age)], ID]
</code>```

Or a base R option with ave

```<code>d[with(d, ave(as.character(age), ID, FUN = function(x) length(unique(x)))>1),]
#   ID      age       size
#1  a1 juvenile -1.4545407
#2  a2 juvenile -0.4695317
#3  a3 juvenile  0.2271316
#5  a1 juvenile  0.2961210
#6  a2    adult -0.8331993
#9  a1    adult -0.6924967
#10 a3    adult -0.4619550
</code>```

Body:
I am working with a data frame that deals with numeric measurements. Some individuals have been measured several times, both as juveniles and adults.
A reproducible example:

ID <- c("a1", "a2", "a3", "a4", "a1", "a2", "a5", "a6", "a1", "a3")
age <- rep(c("juvenile", "adult"), each=5)
size <- rnorm(10)

# e.g. a1 is measured 3 times, twice as a juvenile, once as an adult.
d <- data.frame(ID, age, size)

My goal is to subset that data frame by selecting the IDs that appear at least once as a juvenile and at least once as an adult. Not sure how to do that..?

The resulting dataframe would contain all measurements for individuals a1, a2 and a3, but would exclude a4, a5 and a6, as they were not measured at both stages.

A similar question was asked 7 months ago but never had an answer (Subset data frame to include only levels one factor that have values in both levels of another factor)

Thanks!

Body:
Here is one option with data.table

library(data.table)
setDT(d)[, .SD[all(c("juvenile", "adult") %in% age)], ID]

Or a base R option with ave

d[with(d, ave(as.character(age), ID, FUN = function(x) length(unique(x)))>1),]
#   ID      age       size
#1  a1 juvenile -1.4545407
#2  a2 juvenile -0.4695317
#3  a3 juvenile  0.2271316
#5  a1 juvenile  0.2961210
#6  a2    adult -0.8331993
#9  a1    adult -0.6924967
#10 a3    adult -0.4619550


问:
Node.js connect only works on localhost
I have written a small Node.js app, using connect, that serves up a web page, then sends it regular updates.  It also accepts and logs user observations to a disk file.

It works fine as long as I am on localhost, but I can't get other computers on the same intranet to see it. I am using port 3000, but changing to port 8080 or 80 didn't help.

Here is the code I am using to set up the connection:

var io = require('socket.io'),
  connect = require('connect');

var app = connect().use(connect.static('public')).listen(3000);
var chat_room = io.listen(app);
```

As stated above, I've tried changing the port number to 8080 or to 80 and didn't see any difference, so I don't think that it is a firewall problem but I could be wrong.

I've also thought about, after reading similar questions dealing with HTTP, to add 0.0.0.0 to the listen() method but it doesn't seem that listen() takes an IP mask parameter.

答:
On your app, makes it reachable from any device in the network:

```<code>app.listen(3000, "0.0.0.0");
</code>```

For NodeJS in Azure, GCP & AWS

For Azure vm deployed in resource manager, check your virtual network security group and open ports or port ranges to make it reachable, otherwise in your cloud endpoints if vm is deployed in old version of azure.

Just look for equivalent of it for GCP and AWS

Title: Node.js connect only works on localhost

Body:
I have written a small Node.js app, using connect, that serves up a web page, then sends it regular updates.  It also accepts and logs user observations to a disk file.

It works fine as long as I am on localhost, but I can't get other computers on the same intranet to see it. I am using port 3000, but changing to port 8080 or 80 didn't help.

Here is the code I am using to set up the connection:

var io = require('socket.io'),
  connect = require('connect');

var app = connect().use(connect.static('public')).listen(3000);
var chat_room = io.listen(app);

As stated above, I've tried changing the port number to 8080 or to 80 and didn't see any difference, so I don't think that it is a firewall problem but I could be wrong.

I've also thought about, after reading similar questions dealing with HTTP, to add 0.0.0.0 to the listen() method but it doesn't seem that listen() takes an IP mask parameter.

Body:
On your app, makes it reachable from any device in the network:

app.listen(3000, "0.0.0.0");

For NodeJS in Azure, GCP & AWS

For Azure vm deployed in resource manager, check your virtual network security group and open ports or port ranges to make it reachable, otherwise in your cloud endpoints if vm is deployed in old version of azure.

Just look for equivalent of it for GCP and AWS


问:
Why doesn't the for loop in the code below run as an infinite loop (i continuing after -1 as 1 2 3...-3 -2 -1)?
```<code>    #include<stdio.h>
    int main()
    {
    char i = 0;
    for( i<=5 && i>=-1 ; ++i ; i>0)
        printf("%d ",i);
    return 0;
    }
</code>```

<p>output is 1 2 3 ...127 -128 -127 ... -3 -2 -1.Can anyone explain how it stops after printing -1? </p>

答:
You have your loop a bit off; it needs to be initialization, condition, increment. Try this:</p>

```<code>#include <stdio.h>

int main()
{
    for(int i = 0; i<=5 && i>=-1; ++i)
        printf("%d ",i);
    return 0;
}
</code>```

Body:
    #include<stdio.h>
    int main()
    {
    char i = 0;
    for( i<=5 && i>=-1 ; ++i ; i>0)
        printf("%d ",i);
    return 0;
    }

output is 1 2 3 ...127 -128 -127 ... -3 -2 -1.Can anyone explain how it stops after printing -1?

Body:
You have your loop a bit off; it needs to be initialization, condition, increment. Try this:

#include <stdio.h>

int main()
{
    for(int i = 0; i<=5 && i>=-1; ++i)
        printf("%d ",i);
    return 0;
}


问:
CAGradient using UIColor array
I have iCarousel set up to display a series of gradients.

```<code>    // Set gradient colours
    var gradientColours = [

    // First gradient
    UIColor(red:0.33, green:0.38, blue:0.44, alpha:1.0),
    UIColor(red:1.00, green:0.42, blue:0.42, alpha:1.0),

    //Second gradient
    UIColor(red:0.08, green:0.12, blue:0.19, alpha:1.0),
    UIColor(red:0.14, green:0.23, blue:0.33, alpha:1.0),

    // Third gradient
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),

    // Fourth gradient
    UIColor(red:0.12, green:0.11, blue:0.09, alpha:1.0),
    UIColor(red:0.56, green:0.05, blue:0.00, alpha:1.0),

    // Fifth gradient
    UIColor(red:0.09, green:0.75, blue:0.99, alpha:1.0),
    UIColor(red:0.80, green:0.19, blue:0.40, alpha:1.0)]

    func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
    let frontView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
    frontView.contentMode = .center

    frontView.layer.cornerRadius = 15;
    frontView.layer.masksToBounds = true;

    let gradient = CAGradientLayer()
    gradient.frame = frontView.bounds
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

    gradient.colors = [gradientColours[index].cgColor, gradientColours[index+1].cgColor]

    frontView.layer.addSublayer(gradient)
    return frontView
</code>```

The problem is, the first gradient is fine as it uses gradientColours[0] and gradientColours1, but any other ones after that don't work as they use 1 and 2, 2 and [3] and so on...

I feel as though this has an obvious answer but I cannot think of it at the moment...

Thanks for the help.

Edit:
Images for clarity:

First gradient works fine:

First gradient works fine:
Second gradient takes first colour value from previous gradient:

答:
I have solution for this by using simple odd/Even Logic see the below program </p>

```<code> import Foundation
var gradientColours = [

    // First gradient
    UIColor(red:0.33, green:0.38, blue:0.44, alpha:1.0),
    UIColor(red:1.00, green:0.42, blue:0.42, alpha:1.0),

    //Second gradient
    UIColor(red:0.08, green:0.12, blue:0.19, alpha:1.0),
    UIColor(red:0.14, green:0.23, blue:0.33, alpha:1.0),

    // Third gradient
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),

    // Fourth gradient
    UIColor(red:0.12, green:0.11, blue:0.09, alpha:1.0),
    UIColor(red:0.56, green:0.05, blue:0.00, alpha:1.0),

    // Fifth gradient
    UIColor(red:0.09, green:0.75, blue:0.99, alpha:1.0),
    UIColor(red:0.80, green:0.19, blue:0.40, alpha:1.0)]

       var indexOfGradientColor = 0

     func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView
     {
        let frontView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
        frontView.contentMode = .center

        frontView.layer.cornerRadius = 15;
        frontView.layer.masksToBounds = true;

        let gradient = CAGradientLayer()
        gradient.frame = frontView.bounds
        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

        if (indexOfGradientColor%2 == 0)
        {
            gradient.colors = [gradientColours[indexOfGradientColor].cgColor, gradientColours[indexOfGradientColor+1].cgColor]

        }
        else
        { gradient.colors = [gradientColours[indexOfGradientColor+1].cgColor, gradientColours[indexOfGradientColor+2].cgColor]}
        if indexOfGradientColor < (gradientColours.count-2)
        {
                indexOfGradientColor += 2
        }
        else
        {
            indexOfGradientColor = 0
        }

        frontView.layer.addSublayer(gradient)
        return frontView
    }
</code>```

Title: CAGradient using UIColor array

Body:
I have iCarousel set up to display a series of gradients.

    // Set gradient colours
    var gradientColours = [

    // First gradient
    UIColor(red:0.33, green:0.38, blue:0.44, alpha:1.0),
    UIColor(red:1.00, green:0.42, blue:0.42, alpha:1.0),

    //Second gradient
    UIColor(red:0.08, green:0.12, blue:0.19, alpha:1.0),
    UIColor(red:0.14, green:0.23, blue:0.33, alpha:1.0),

    // Third gradient
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),

    // Fourth gradient
    UIColor(red:0.12, green:0.11, blue:0.09, alpha:1.0),
    UIColor(red:0.56, green:0.05, blue:0.00, alpha:1.0),

    // Fifth gradient
    UIColor(red:0.09, green:0.75, blue:0.99, alpha:1.0),
    UIColor(red:0.80, green:0.19, blue:0.40, alpha:1.0)]

    func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
    let frontView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
    frontView.contentMode = .center

    frontView.layer.cornerRadius = 15;
    frontView.layer.masksToBounds = true;

    let gradient = CAGradientLayer()
    gradient.frame = frontView.bounds
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

    gradient.colors = [gradientColours[index].cgColor, gradientColours[index+1].cgColor]

    frontView.layer.addSublayer(gradient)
    return frontView

The problem is, the first gradient is fine as it uses gradientColours[0] and gradientColours1, but any other ones after that don't work as they use 1 and 2, 2 and [3] and so on...

I feel as though this has an obvious answer but I cannot think of it at the moment...

Thanks for the help.

Edit:
Images for clarity:

First gradient works fine:

First gradient works fine:
Second gradient takes first colour value from previous gradient:

Body:
I have solution for this by using simple odd/Even Logic see the below program

 import Foundation
var gradientColours = [

    // First gradient
    UIColor(red:0.33, green:0.38, blue:0.44, alpha:1.0),
    UIColor(red:1.00, green:0.42, blue:0.42, alpha:1.0),

    //Second gradient
    UIColor(red:0.08, green:0.12, blue:0.19, alpha:1.0),
    UIColor(red:0.14, green:0.23, blue:0.33, alpha:1.0),

    // Third gradient
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),
    UIColor(red:0.83, green:0.84, blue:0.16, alpha:1.0),

    // Fourth gradient
    UIColor(red:0.12, green:0.11, blue:0.09, alpha:1.0),
    UIColor(red:0.56, green:0.05, blue:0.00, alpha:1.0),

    // Fifth gradient
    UIColor(red:0.09, green:0.75, blue:0.99, alpha:1.0),
    UIColor(red:0.80, green:0.19, blue:0.40, alpha:1.0)]

       var indexOfGradientColor = 0

     func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView
     {
        let frontView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
        frontView.contentMode = .center

        frontView.layer.cornerRadius = 15;
        frontView.layer.masksToBounds = true;

        let gradient = CAGradientLayer()
        gradient.frame = frontView.bounds
        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

        if (indexOfGradientColor%2 == 0)
        {
            gradient.colors = [gradientColours[indexOfGradientColor].cgColor, gradientColours[indexOfGradientColor+1].cgColor]

        }
        else
        { gradient.colors = [gradientColours[indexOfGradientColor+1].cgColor, gradientColours[indexOfGradientColor+2].cgColor]}
        if indexOfGradientColor < (gradientColours.count-2)
        {
                indexOfGradientColor += 2
        }
        else
        {
            indexOfGradientColor = 0
        }

        frontView.layer.addSublayer(gradient)
        return frontView
    }


问:
express js - how to set static file for multiple sub-folder?
How to set static file for multiple sub-folder ?
In app.js i set :

```<code>app.use(express.static(path.join(__dirname, 'public')))
</code>```

and my public structure :

```<code>- public
   - admin
      - images
      - css
      - js
   - site
      - images
      - css
      - js
</code>```

I can not get a image in admin/images with:

```<code>img(src="logo.png")
</code>```

答:
You should set absolute path, for exsample, you shared public folder then if you want to get image on you web site try

admin/images/logo.png

for get all path to the image

${hostname}:${port}/admin/images/logo.png

Body:
How to set static file for multiple sub-folder ?
In app.js i set :

app.use(express.static(path.join(__dirname, 'public')))

and my public structure :

- public
   - admin
      - images
      - css
      - js
   - site
      - images
      - css
      - js

I can not get a image in admin/images with:

img(src="logo.png")


问:
How do I use a sling service in sightly page without using javascript?
I have to use a sling service that I created e.g.

```<code>@Component
@Service
public class SearchServiceImpl implements SearchService {
    public SearchResults search() {
     SearchResults results = new SearchResults();
     .....
     return results;
    }
}
</code>```

Now I want to call this service in my sightly without using javascript as there are chances some users wont use javascript while accessing my service. How do I call this service?

答:
Best answer is to go for use of getSlingScriptHelper().getService() in WCMUSEPOJO class as per AEM 6.2

Below link is enough to explain it in better manner.

http://adobeaemclub.com/access-osgi-ser%C2%ADvice-from-the-wcmuse-class-in-sightly/

Body:
I have to use a sling service that I created e.g.

@Component
@Service
public class SearchServiceImpl implements SearchService {
    public SearchResults search() {
     SearchResults results = new SearchResults();
     .....
     return results;
    }
}

Now I want to call this service in my sightly without using javascript as there are chances some users wont use javascript while accessing my service. How do I call this service?


问:
Show more info in React
I want to show more info onclick, but I have different divs to show/hide .
So. I do it this way :
The state is :

```<code>this.state = {
        showMore: false,
        showRewards: false,
        fees: false,
        showFees: false
    };
</code>```

One of the divs:

```<code>                      <div className='some'>
                          <h3 >Rewards <i className="icon-im-rewards"></i></h3>
                                  <h5 className="showMoreDetails" onClick={ () => this.show('rewards') }>{ showRewards ? '-' : '+' } { showRewards ? 'Show Less' : 'Show More' }</h5>
                          {   showRewards && detail.rewards.reward.map((name, i) =>
                                  <p key={i}> { name }</p>
                              )
                          }
                      </div>
</code>```

The function :

show (name) {
    let { showMore, showRewards, showFees } = this.state;

```<code>if (name === 'hightlights' && showMore === false) {
    this.setState({
        showMore: true
    });
} else {
    this.setState({
        showMore: false
    });
}

if (name === 'rewards' && showRewards === false) {
    this.setState({
        showRewards: true
    });
} else {
    this.setState({
        showRewards: false
    });
}

if (name === 'fees' && showFees === false) {
    this.setState({
        showFees: true
    });
} else {
    this.setState({
        showFees: false
    });
}
</code>```

This is too long, ugly and doesn't work correct (I can only see one expanded div at a time) How to improve it?

答:
It could be easier if you could show us the structure of detail & rewards. I guess you are mapping a single element here that's why it is printing single element. However, try changing this line,

```<code>detail.rewards.reward.map((name, i) => <p key={i}> { name }</p> )
</code>```

replace with below code:

```<code>detail.rewards.map((reward, i) => <p key={i}> { reward.name }</p> )
</code>```

Title: Show more info in React

Body:
I want to show more info onclick, but I have different divs to show/hide .
So. I do it this way :
The state is :

this.state = {
        showMore: false,
        showRewards: false,
        fees: false,
        showFees: false
    };

One of the divs:

Rewards

 this.show('rewards') }>{ showRewards ? '-' : '+' } { showRewards ? 'Show Less' : 'Show More' }

                          {   showRewards && detail.rewards.reward.map((name, i) =>

 { name }

                              )
                          }

The function :

show (name) {
    let { showMore, showRewards, showFees } = this.state;

if (name === 'hightlights' && showMore === false) {
    this.setState({
        showMore: true
    });
} else {
    this.setState({
        showMore: false
    });
}

if (name === 'rewards' && showRewards === false) {
    this.setState({
        showRewards: true
    });
} else {
    this.setState({
        showRewards: false
    });
}

if (name === 'fees' && showFees === false) {
    this.setState({
        showFees: true
    });
} else {
    this.setState({
        showFees: false
    });
}

This is too long, ugly and doesn't work correct (I can only see one expanded div at a time) How to improve it?

Body:
It could be easier if you could show us the structure of detail & rewards. I guess you are mapping a single element here that's why it is printing single element. However, try changing this line,

detail.rewards.reward.map((name, i) => <p key={i}> { name }</p> )

replace with below code:

detail.rewards.map((reward, i) => <p key={i}> { reward.name }</p> )


问:
How create a mdl checkbox element
By getmdl.io, a checkbox element is:

#d{
padding:20px```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>
<div id="d">
<label for="chkbox1" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 <span class="mdl-checkbox__label">Checkbox</span>
</label></code>```

and i try to add this element with js

function addCB(){
  var cb = document.createElement('div');
  cb.innerHTML = `
 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 Checkbox
`;
  document.getElementById('d').appendChild(cb);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#d{
padding:20px</code>```

<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>

<button class="mdl-button mdl-js-button mdl-js-ripple-effect " onClick="addCB()">Add checkbox</button>```

but the design doesn't work, idk why, can anyone help me?

答: FYI MDL is deprecated for MDC-Web, however if you must use it, you get at it like any other checkbox, namely, document.getElementByID("checkbox1").checked which returns a boolean.</p>

Title: How create a mdl checkbox element

Body:
By getmdl.io, a checkbox element is:

#d{
padding:20px

<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>

 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 Checkbox

and i try to add this element with js

function addCB(){
  var cb = document.createElement('div');
  cb.innerHTML = `
 <input type="checkbox" id="chkbox1" class="mdl-checkbox__input">
 Checkbox
`;
  document.getElementById('d').appendChild(cb);
}

#d{
padding:20px

<link href="https://code.getmdl.io/1.3.0/material.deep_purple-blue.min.css" rel="stylesheet"/>

<button class="mdl-button mdl-js-button mdl-js-ripple-effect " onClick="addCB()">Add checkbox</button>

but the design doesn't work, idk why, can anyone help me?


问:
Group 2d array by column value and concatenate values within each group
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.

```<code>$new_arr = [
    [
        'name' => 'Jambi Selatan',
        'code' => '36139',
        'code_name' => '36139 - Jambi Selatan'
    ],
    [
        'name' => 'Jambi Selatan',
        'code' => '36137',
        'code_name' => '36137 - Jambi Selatan'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36129',
        'code_name' => '36129 - Bagan Pete'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36127',
        'code_name' => '36127 - Bagan Pete'
    ]
];
</code>```

I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.

```<code>Array (
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36139 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36127, 36129
            [code_name] => 36127, 36129 - Bagan Pete
        )
)
</code>```

I try this method, but not fix at 'code_name'

```<code>$out = array();
foreach ($new_arr as $key => $value){
    if (array_key_exists($value['name'], $out)){
        $out[$value['name']]['code'] .= ', '.$value['code'];
    } else {
        $out[$value['name']] = array(
            'name' => $value['name'],
            'code' => $value['code'],
            'code_name' => $value['code'] . ' - ' . $value['name']
        );
    }
}
$out = array_values($out);
</code>```

print_r($out);

答:
For someone have problem like me, this method for fix it:

```<code>$out = array();
            foreach ($new_arr as $key => $value){
                if (array_key_exists($value['name'], $out)){
                    $out[$value['name']]['code'] .= ', '.$value['code'];
                    $out[$value['name']]['code_name'] .= ', '.$value['code'] . ' - ' . $value['name'];
                } else {
                    $out[$value['name']] = array(
                        'name' => $value['name'],
                        'code' => $value['code'],
                        'code_name' => $value['code']
                    );
                }
            }
            $out = array_values($out);
            print_r($out);
</code>```

Final result;

```<code>Array
(
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36137 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36129, 36127
            [code_name] => 36129, 36127 - Bagan Pete
        )

)
</code>```

Body:
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.

$new_arr = [
    [
        'name' => 'Jambi Selatan',
        'code' => '36139',
        'code_name' => '36139 - Jambi Selatan'
    ],
    [
        'name' => 'Jambi Selatan',
        'code' => '36137',
        'code_name' => '36137 - Jambi Selatan'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36129',
        'code_name' => '36129 - Bagan Pete'
    ],
    [
        'name' => 'Bagan Pete',
        'code' => '36127',
        'code_name' => '36127 - Bagan Pete'
    ]
];

I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.

Array (
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36139 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36127, 36129
            [code_name] => 36127, 36129 - Bagan Pete
        )
)

I try this method, but not fix at 'code_name'

$out = array();
foreach ($new_arr as $key => $value){
    if (array_key_exists($value['name'], $out)){
        $out[$value['name']]['code'] .= ', '.$value['code'];
    } else {
        $out[$value['name']] = array(
            'name' => $value['name'],
            'code' => $value['code'],
            'code_name' => $value['code'] . ' - ' . $value['name']
        );
    }
}
$out = array_values($out);

print_r($out);

Body:
For someone have problem like me, this method for fix it:

$out = array();
            foreach ($new_arr as $key => $value){
                if (array_key_exists($value['name'], $out)){
                    $out[$value['name']]['code'] .= ', '.$value['code'];
                    $out[$value['name']]['code_name'] .= ', '.$value['code'] . ' - ' . $value['name'];
                } else {
                    $out[$value['name']] = array(
                        'name' => $value['name'],
                        'code' => $value['code'],
                        'code_name' => $value['code']
                    );
                }
            }
            $out = array_values($out);
            print_r($out);

Final result;

Array
(
    [0] => Array
        (
            [name] => Jambi Selatan
            [code] => 36139, 36137
            [code_name] => 36139, 36137 - Jambi Selatan
        )

    [1] => Array
        (
            [name] => Bagan Pete
            [code] => 36129, 36127
            [code_name] => 36129, 36127 - Bagan Pete
        )

)


问:
How to Draw a Rounded Rectangle with WinForms (.NET)?
Draw rectangle using C# and I need to draw the arc in every edges first of all I draw rectangle and then I need click button it will draw the arc at edges, how can I do it?</p>

答:
I know this post is old, but it's the top hit when searching for how to do rounded rectangles in C# and I've had some problems with it. The AddArc method is inaccurate and as such if you use the code from the accepted answer you will get a funky rounded rectangle. The top left corner is correct, the top right and bottom left are misshapen, and the bottom right is too small. I have adjusted some things in the code to compensate for AddArc's inaccuracies and I believe I have a working solution for creating a proper rounded rectangle. This version can also separate the rectangle into top-left-half and bottom-right-half sections which is handy for doing light/dark shading for 3d effect.

Example usage for setting a window region and also creating topleft/bottomright paths for tracing with light and dark pens for shading:

```<code>        Region = new Region(RoundedRectangles.RoundedRectangle.Create(new Rectangle(0, 0, Size.Width, Size.Height), 8, RoundedRectangles.RoundedRectangle.RectangleCorners.TopRight | RoundedRectangles.RoundedRectangle.RectangleCorners.TopLeft));
        TopLeftPath = RoundedRectangles.RoundedRectangle.Create(new Rectangle(0, 0, Size.Width, Size.Height), 8, RoundedRectangles.RoundedRectangle.RectangleCorners.TopRight | RoundedRectangles.RoundedRectangle.RectangleCorners.TopLeft, RoundedRectangles.RoundedRectangle.WhichHalf.TopLeft);
        BottomRightPath = RoundedRectangles.RoundedRectangle.Create(new Rectangle(0, 0, Size.Width-1, Size.Height-1), 8, RoundedRectangles.RoundedRectangle.RectangleCorners.TopRight | RoundedRectangles.RoundedRectangle.RectangleCorners.TopLeft, RoundedRectangles.RoundedRectangle.WhichHalf.BottomRight);
</code>```

And finally the code:

```<code>using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace RoundedRectangles
{
public abstract class RoundedRectangle
{
    [Flags]
    public enum RectangleCorners
    {
        None = 0, TopLeft = 1, TopRight = 2, BottomLeft = 4, BottomRight = 8,
        All = TopLeft | TopRight | BottomLeft | BottomRight
    }

    public enum WhichHalf
    {
        TopLeft,
        BottomRight,
        Both
    }

    static void Corner(GraphicsPath path, int x1, int y1, int x2, int y2, int x3, int y3)
    {
        path.AddLine(x1, y1, x2, y2);
        path.AddLine(x2, y2, x3, y3);
    }

    public static GraphicsPath Create(int x, int y, int width, int height, int radius, RectangleCorners corners, WhichHalf half)
    {
        if (radius <= 0)
        {
            GraphicsPath rectp = new GraphicsPath();
            rectp.AddRectangle(new Rectangle(x, y, width, height));
            return rectp;
        }

        int dia = radius * 2;

        Rectangle TLarc = new Rectangle(x, y, dia, dia);
        Rectangle TRarc = new Rectangle(x + width - dia - 1, y, dia, dia);
        Rectangle BRarc = new Rectangle(x + width - dia - 1, y + height - dia - 1, dia, dia);
        Rectangle BLarc = new Rectangle(x, y + height - dia - 1, dia, dia);

        Rectangle TLsquare = new Rectangle(x, y, radius, radius);
        Rectangle TRsquare = new Rectangle(x + width - radius, y, radius, radius);
        Rectangle BRsquare = new Rectangle(x + width - radius, y + height - radius, radius, radius);
        Rectangle BLsquare = new Rectangle(x, y + height - radius, radius, radius);

        GraphicsPath p = new GraphicsPath();
        p.StartFigure();

        if (half == WhichHalf.Both || half == WhichHalf.TopLeft)
        {
            if (corners.HasFlag(RectangleCorners.BottomLeft))
                p.AddArc(BLarc, 135, 45);
            else
                p.AddLine(BLsquare.Left, BLsquare.Bottom, BLsquare.Left, BLsquare.Top);

            p.AddLine(BLsquare.Left, BLsquare.Top - 1, TLsquare.Left, TLsquare.Bottom + 1);

            if (corners.HasFlag(RectangleCorners.TopLeft))
                p.AddArc(TLarc, 180, 90);
            else
                Corner(p, TLsquare.Left, TLsquare.Bottom, TLsquare.Left, TLsquare.Top, TLsquare.Right, TLsquare.Top);

            p.AddLine(TLsquare.Right + 1, TLsquare.Top, TRsquare.Left - 1, TRsquare.Top);

            if (corners.HasFlag(RectangleCorners.TopRight))
                p.AddArc(TRarc, -90, 45);
        }

        if (half == WhichHalf.Both || half == WhichHalf.BottomRight)
        {
            if (corners.HasFlag(RectangleCorners.TopRight))
                p.AddArc(TRarc, -45, 45);
            else
                p.AddLine(TRsquare.Right, TRsquare.Top, TRsquare.Right, TRsquare.Bottom);

            p.AddLine(TRsquare.Right, TRsquare.Bottom + 1, BRsquare.Right, BRsquare.Top - 1);

            if (corners.HasFlag(RectangleCorners.BottomRight))
                p.AddArc(BRarc, 0, 90);
            else
                Corner(p, BRsquare.Right, BRsquare.Top, BRsquare.Right, BRsquare.Bottom, BRsquare.Left, BRsquare.Bottom);

            p.AddLine(BRsquare.Left - 1, BRsquare.Bottom, BLsquare.Right + 1, BLsquare.Bottom);

            if (corners.HasFlag(RectangleCorners.BottomLeft))
                p.AddArc(BLarc, 90, 45);
            else
                p.AddLine(BLsquare.Right, BLsquare.Bottom, BLsquare.Left, BLsquare.Bottom);
        }

        return p;
    }

    public static GraphicsPath Create(Rectangle rect, int radius, RectangleCorners c, WhichHalf which_half)
    { return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, c, which_half); }

    public static GraphicsPath Create(Rectangle rect, int radius, RectangleCorners c)
    { return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, c, WhichHalf.Both); }

    public static GraphicsPath Create(Rectangle rect, int radius)
    { return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, RectangleCorners.All, WhichHalf.Both); }

}
</code>```

}

Body:
I know this post is old, but it's the top hit when searching for how to do rounded rectangles in C# and I've had some problems with it. The AddArc method is inaccurate and as such if you use the code from the accepted answer you will get a funky rounded rectangle. The top left corner is correct, the top right and bottom left are misshapen, and the bottom right is too small. I have adjusted some things in the code to compensate for AddArc's inaccuracies and I believe I have a working solution for creating a proper rounded rectangle. This version can also separate the rectangle into top-left-half and bottom-right-half sections which is handy for doing light/dark shading for 3d effect.

Example usage for setting a window region and also creating topleft/bottomright paths for tracing with light and dark pens for shading:

        Region = new Region(RoundedRectangles.RoundedRectangle.Create(new Rectangle(0, 0, Size.Width, Size.Height), 8, RoundedRectangles.RoundedRectangle.RectangleCorners.TopRight | RoundedRectangles.RoundedRectangle.RectangleCorners.TopLeft));
        TopLeftPath = RoundedRectangles.RoundedRectangle.Create(new Rectangle(0, 0, Size.Width, Size.Height), 8, RoundedRectangles.RoundedRectangle.RectangleCorners.TopRight | RoundedRectangles.RoundedRectangle.RectangleCorners.TopLeft, RoundedRectangles.RoundedRectangle.WhichHalf.TopLeft);
        BottomRightPath = RoundedRectangles.RoundedRectangle.Create(new Rectangle(0, 0, Size.Width-1, Size.Height-1), 8, RoundedRectangles.RoundedRectangle.RectangleCorners.TopRight | RoundedRectangles.RoundedRectangle.RectangleCorners.TopLeft, RoundedRectangles.RoundedRectangle.WhichHalf.BottomRight);

And finally the code:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace RoundedRectangles
{
public abstract class RoundedRectangle
{
    [Flags]
    public enum RectangleCorners
    {
        None = 0, TopLeft = 1, TopRight = 2, BottomLeft = 4, BottomRight = 8,
        All = TopLeft | TopRight | BottomLeft | BottomRight
    }

    public enum WhichHalf
    {
        TopLeft,
        BottomRight,
        Both
    }

    static void Corner(GraphicsPath path, int x1, int y1, int x2, int y2, int x3, int y3)
    {
        path.AddLine(x1, y1, x2, y2);
        path.AddLine(x2, y2, x3, y3);
    }

    public static GraphicsPath Create(int x, int y, int width, int height, int radius, RectangleCorners corners, WhichHalf half)
    {
        if (radius <= 0)
        {
            GraphicsPath rectp = new GraphicsPath();
            rectp.AddRectangle(new Rectangle(x, y, width, height));
            return rectp;
        }

        int dia = radius * 2;

        Rectangle TLarc = new Rectangle(x, y, dia, dia);
        Rectangle TRarc = new Rectangle(x + width - dia - 1, y, dia, dia);
        Rectangle BRarc = new Rectangle(x + width - dia - 1, y + height - dia - 1, dia, dia);
        Rectangle BLarc = new Rectangle(x, y + height - dia - 1, dia, dia);

        Rectangle TLsquare = new Rectangle(x, y, radius, radius);
        Rectangle TRsquare = new Rectangle(x + width - radius, y, radius, radius);
        Rectangle BRsquare = new Rectangle(x + width - radius, y + height - radius, radius, radius);
        Rectangle BLsquare = new Rectangle(x, y + height - radius, radius, radius);

        GraphicsPath p = new GraphicsPath();
        p.StartFigure();

        if (half == WhichHalf.Both || half == WhichHalf.TopLeft)
        {
            if (corners.HasFlag(RectangleCorners.BottomLeft))
                p.AddArc(BLarc, 135, 45);
            else
                p.AddLine(BLsquare.Left, BLsquare.Bottom, BLsquare.Left, BLsquare.Top);

            p.AddLine(BLsquare.Left, BLsquare.Top - 1, TLsquare.Left, TLsquare.Bottom + 1);

            if (corners.HasFlag(RectangleCorners.TopLeft))
                p.AddArc(TLarc, 180, 90);
            else
                Corner(p, TLsquare.Left, TLsquare.Bottom, TLsquare.Left, TLsquare.Top, TLsquare.Right, TLsquare.Top);

            p.AddLine(TLsquare.Right + 1, TLsquare.Top, TRsquare.Left - 1, TRsquare.Top);

            if (corners.HasFlag(RectangleCorners.TopRight))
                p.AddArc(TRarc, -90, 45);
        }

        if (half == WhichHalf.Both || half == WhichHalf.BottomRight)
        {
            if (corners.HasFlag(RectangleCorners.TopRight))
                p.AddArc(TRarc, -45, 45);
            else
                p.AddLine(TRsquare.Right, TRsquare.Top, TRsquare.Right, TRsquare.Bottom);

            p.AddLine(TRsquare.Right, TRsquare.Bottom + 1, BRsquare.Right, BRsquare.Top - 1);

            if (corners.HasFlag(RectangleCorners.BottomRight))
                p.AddArc(BRarc, 0, 90);
            else
                Corner(p, BRsquare.Right, BRsquare.Top, BRsquare.Right, BRsquare.Bottom, BRsquare.Left, BRsquare.Bottom);

            p.AddLine(BRsquare.Left - 1, BRsquare.Bottom, BLsquare.Right + 1, BLsquare.Bottom);

            if (corners.HasFlag(RectangleCorners.BottomLeft))
                p.AddArc(BLarc, 90, 45);
            else
                p.AddLine(BLsquare.Right, BLsquare.Bottom, BLsquare.Left, BLsquare.Bottom);
        }

        return p;
    }

    public static GraphicsPath Create(Rectangle rect, int radius, RectangleCorners c, WhichHalf which_half)
    { return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, c, which_half); }

    public static GraphicsPath Create(Rectangle rect, int radius, RectangleCorners c)
    { return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, c, WhichHalf.Both); }

    public static GraphicsPath Create(Rectangle rect, int radius)
    { return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, RectangleCorners.All, WhichHalf.Both); }

}

}


问:
Laravel Cannot Export Data to Excel After Passing Variables in AJAX
I have a button Export to Excel for exporting the data projected in the pagination table. The Export button is working properly until I used AJAX to pass the variables to my controller using AJAX. I am not sure if the I am doing it right but my AJAX function is throwing the

```<code>    success: function(data) {
      $('#messModal').delay(1000).fadeOut(450);
      $('#messcontent').text('Data exported successfully');
      $('#messModal').modal('show');
      setTimeout(function(){$('#messModal').modal('hide');}, 1500);
    }
</code>```

But the exporting is ignored after the modal message.

Here is my view, AJAX script and Controller. Please help me because I anot so familiar with AJAX.

View:

```<code><a href="#" class="btn btn-success btn-md" style="border-radius: 0px;text-align: left;" onclick="u_excel();"><span class="glyphicon glyphicon-export"></span> Export to Excel</a>
</code>```

AJAX script:

```<code><script type="text/javascript">
  function u_excel()
  {
      $.ajax({
      url: '/getExportEnrollExcel',
      type: 'get',
      data: {
        '_token': $('input[name=_token]').val(),
        'area_code': $('select[name=s]').val(),
        'sy': $('select[name=sys]').val(),
        'semester': $('select[name=sem]').val(),
        'gender': $('select[name=sgender]').val()
        },
        success: function(data) {
          $('#messModal').delay(1000).fadeOut(450);
          $('#messcontent').text('Data exported successfully');
          $('#messModal').modal('show');
          setTimeout(function(){$('#messModal').modal('hide');}, 1500);
        }
    });
  }
</script>
</code>```

and Controller:

```<code>public function getExportEnrollExcel(Request $request)
{
    Excel::create('Enrollment', function($excel) {

    $excel->sheet('Sheet 1', function($sheet) {

    $s = Input::get ( 's' );
    $sys = Input::get ( 'sys' );
    $sem = Input::get ( 'sem' );
    $sgender = Input::get ( 'sgender' );

        $enrollments=DB::table('enrollments')
        ->where('r_status','=','A')
        ->select("enrollments.*")
        ->get();
        foreach($enrollments as $enrollment) {
             $enroll_data[] = array(
                $enrollment->id,
                $enrollment->area_code,
                $enrollment->sy,
                $enrollment->semester,
                $enrollment->college,
                $enrollment->gender,
                $enrollment->tot_enroll
            );
             return response()->json($enrollment);
        }

    if ( !empty($enroll_data) )
    {
        $sheet->fromArray($enroll_data, null, 'A1', false, false);
        $headings = array('ID', 'Area Code','SY','Semester','College','Gender','Total');
        $sheet->prependRow(1, $headings);
    }else
    {
    return back()->with('info',' Sorry. No record to export.');
    }
    });
})->export('xls');
}
</code>```

答: Well i guess you are passing new variable names in your ajax request and getting the value of input, select name which you have declared in blade file in your controller file.</p>

Body:
I have a button Export to Excel for exporting the data projected in the pagination table. The Export button is working properly until I used AJAX to pass the variables to my controller using AJAX. I am not sure if the I am doing it right but my AJAX function is throwing the

    success: function(data) {
      $('#messModal').delay(1000).fadeOut(450);
      $('#messcontent').text('Data exported successfully');
      $('#messModal').modal('show');
      setTimeout(function(){$('#messModal').modal('hide');}, 1500);
    }

But the exporting is ignored after the modal message.

Here is my view, AJAX script and Controller. Please help me because I anot so familiar with AJAX.

View:

 Export to Excel

AJAX script:

and Controller:

public function getExportEnrollExcel(Request $request)
{
    Excel::create('Enrollment', function($excel) {

    $excel->sheet('Sheet 1', function($sheet) {

    $s = Input::get ( 's' );
    $sys = Input::get ( 'sys' );
    $sem = Input::get ( 'sem' );
    $sgender = Input::get ( 'sgender' );

        $enrollments=DB::table('enrollments')
        ->where('r_status','=','A')
        ->select("enrollments.*")
        ->get();
        foreach($enrollments as $enrollment) {
             $enroll_data[] = array(
                $enrollment->id,
                $enrollment->area_code,
                $enrollment->sy,
                $enrollment->semester,
                $enrollment->college,
                $enrollment->gender,
                $enrollment->tot_enroll
            );
             return response()->json($enrollment);
        }

    if ( !empty($enroll_data) )
    {
        $sheet->fromArray($enroll_data, null, 'A1', false, false);
        $headings = array('ID', 'Area Code','SY','Semester','College','Gender','Total');
        $sheet->prependRow(1, $headings);
    }else
    {
    return back()->with('info',' Sorry. No record to export.');
    }
    });
})->export('xls');
}


问:
C# Bad Request - Error in Query Syntax
Good day all. in my silverlight c# program, i tried to save some string with slash (/) into sql server. eg: 123/ABC but got bad request error...i am not sure whether this error because of c# or wcf limitation. anyone knows the solution for this issue, pls kindly help me out

i have a textbox with the value: 123/ABC
then i called this save function to connect to service:

```<code>_svc.BeginSaveChanges(SaveChangesOptions.Batch, OnChangesSaved, _svc);
</code>```

upon save, got this bad request error. i searched and found out that because of the slash (/)...

[enter image description here][1]

[1]: https://i.stack.imgur.com/y4zgs.png : Bad error img

答:
You need to debug the WCF service. Run it and put a break point in the method your client is calling to see why the error is being caused.

Most likely there is code that is building a SQL query from a string that is resulting in broken SQL code. The method should be updated to send your string values as a parameter query.

Title: C# Bad Request - Error in Query Syntax

Body:
Good day all. in my silverlight c# program, i tried to save some string with slash (/) into sql server. eg: 123/ABC but got bad request error...i am not sure whether this error because of c# or wcf limitation. anyone knows the solution for this issue, pls kindly help me out

i have a textbox with the value: 123/ABC
then i called this save function to connect to service:

_svc.BeginSaveChanges(SaveChangesOptions.Batch, OnChangesSaved, _svc);

upon save, got this bad request error. i searched and found out that because of the slash (/)...

[enter image description here][1]

[1]: https://i.stack.imgur.com/y4zgs.png : Bad error img


问:
How to write an Ansible playbook with Docker-compose
Please help, I have the docker-compose file below, and I want to write an Ansible playbook that runs the docker-compose file on localhost and a remote target.</p>

```<code>   version: '2.0'

services:
weather-backend:
  build: ./backend
  volumes:    #map backend dir and package inside container
    - './backend/:/usr/src/'
    - './backend/package.json:/usr/src/package.json'
  #ports:
 #  - "9000:9000" #expose backend port - Host:container
  ports:
     - "9000:9000"
  command: npm start

weather-frontend:
  build: ./frontend
  depends_on:
    - weather-backend
  volumes:
    - './frontend/:/usr/src/'
    - '/usr/src/node_modules'
  ports:
    - "8000:8000" #expose ports -Host:container
  environment:
    NODE_ENV: "development"
</code>```

答:
Since Ansible 2.1, you can have a look at the docker_compose, which can read directly a docker-compose.yml

playbook task:

```<code>- name: run the service defined in my_project's docker-compose.yml
  docker_compose:
    project_src: /path/to/my_project
</code>```

Body:
Please help, I have the docker-compose file below, and I want to write an Ansible playbook that runs the docker-compose file on localhost and a remote target.

   version: '2.0'

services:
weather-backend:
  build: ./backend
  volumes:    #map backend dir and package inside container
    - './backend/:/usr/src/'
    - './backend/package.json:/usr/src/package.json'
  #ports:
 #  - "9000:9000" #expose backend port - Host:container
  ports:
     - "9000:9000"
  command: npm start

weather-frontend:
  build: ./frontend
  depends_on:
    - weather-backend
  volumes:
    - './frontend/:/usr/src/'
    - '/usr/src/node_modules'
  ports:
    - "8000:8000" #expose ports -Host:container
  environment:
    NODE_ENV: "development"

Body:
Since Ansible 2.1, you can have a look at the docker_compose, which can read directly a docker-compose.yml

playbook task:

- name: run the service defined in my_project's docker-compose.yml
  docker_compose:
    project_src: /path/to/my_project


问:
How to load heavy data?
I am getting 5000 list of user and their details from server and am trying to show those records . Records are displayed but am seeing continues loading.. and after loading am not able to do anything. Is there any solution to load 5000 records without loading and crashing? </p>

答:
It is not advised to load 5000 records at once and try to display the same in the browser. You need to do use paging. You cannot load some heavy data onto browser. It might crash or does not respond. Use paging to bring only 10/20/30 records at a time and provide paging buttons , so user can click and navigate to the desired page.

An article on how you can do paging: http://www.c-sharpcorner.com/article/server-side-pagination-using-angularjs-web-api-and-sql-server/

--If you are using WebAPI

Title: How to load heavy data?


问:
How to set a default value in react-select
I have an issue using react-select. I use redux form and I've made my react-select component compatible with redux form. Here is the code:

```<code>const MySelect = props => (
    <Select
        {...props}
        value={props.input.value}
        onChange={value => props.input.onChange(value)}
        onBlur={() => props.input.onBlur(props.input.value)}
        options={props.options}
        placeholder={props.placeholder}
        selectedValue={props.selectedValue}
    />
);
</code>```

and here how I render it:

```<code><div className="select-box__container">
    <Field
    id="side"
    name="side"
    component={SelectInput}
    options={sideOptions}
    clearable={false}
    placeholder="Select Side"
    selectedValue={label: 'Any', value: 'Any'}
    />
</div>
</code>```

But the problem is that that my dropdown has not a default value as I wish. What I'm doing wrong? Any ideas?

答:
I was having a similar error.  Make sure your options have a value attribute.

```<code><option key={index} value={item}> {item} </option>
</code>```

Then match the selects element value initially to the options value.

```<code><select
    value={this.value} />
</code>```

Body:
I have an issue using react-select. I use redux form and I've made my react-select component compatible with redux form. Here is the code:

const MySelect = props => (
    <Select
        {...props}
        value={props.input.value}
        onChange={value => props.input.onChange(value)}
        onBlur={() => props.input.onBlur(props.input.value)}
        options={props.options}
        placeholder={props.placeholder}
        selectedValue={props.selectedValue}
    />
);

and here how I render it:

    <Field
    id="side"
    name="side"
    component={SelectInput}
    options={sideOptions}
    clearable={false}
    placeholder="Select Side"
    selectedValue={label: 'Any', value: 'Any'}
    />

But the problem is that that my dropdown has not a default value as I wish. What I'm doing wrong? Any ideas?

Body:
I was having a similar error.  Make sure your options have a value attribute.

<option key={index} value={item}> {item} </option>

Then match the selects element value initially to the options value.

<select
    value={this.value} />


问:
On linux ubuntu 16 32bit, DrPaulcarter assembly language tutorial, undefined reference error
I'm new in assembly language, so i am following Dr.Paul Carter's pcasm tutorial(
http://pacman128.github.io/pcasm/
).

Exactly pdf file(http://pacman128.github.io/static/pcasm-book.pdf) page-33, and book's page-23

From that site, i downloaded Linux Example (http://pacman128.github.io/static/linux-ex.zip)

and at the terminal i input

nasm -f coff first.asm

gcc -c driver.c

nasm -f coff asm_io.o

gcc -o first driver.o first.o asm_io.o

But it returned it

Where is problem?

(Screenshot's command -lc is no matter, if there is no -lc, it returned the same thing)

答:
For Linux asm_io doesn't work with 64-bit. You have to create 32-bit programs. Compile C files as 32-bit using the -m32 option. You also have to assemble asm_io.asm with a special define -d ELF_TYPE for this to work on Linux. Don't use coff. Commands like this should work:

```<code>nasm -f elf -d ELF_TYPE asm_io.asm
nasm -f elf first.asm
gcc -m32 -c driver.c
gcc -m32 -o first driver.o first.o asm_io.o
</code>```

If you are truly on 32-bit Linux you will be able to omit -m32

Body:
For Linux asm_io doesn't work with 64-bit. You have to create 32-bit programs. Compile C files as 32-bit using the -m32 option. You also have to assemble asm_io.asm with a special define -d ELF_TYPE for this to work on Linux. Don't use coff. Commands like this should work:

nasm -f elf -d ELF_TYPE asm_io.asm
nasm -f elf first.asm
gcc -m32 -c driver.c
gcc -m32 -o first driver.o first.o asm_io.o

If you are truly on 32-bit Linux you will be able to omit -m32


问:
Java replace JFrame with JPanel
I'm trying to 'embed' an existing Java app into my own application.
The existing app is a JFrame with a number of components added to it. I copied the code into my project and replaced the JFrame with a new JPanel that I then added to my own app.

The problem is everything painted in the JPanel appears to be shifted up by a small amount (e.g. ~20px). I wondered if it's anything to do with window menubars etc but so far haven't been able to find a solution apart from manually adding an offset when painting (definitely not ideal!).

I know without the code it can be difficult to offer helpful suggestions, but what I want to know is, do the JFrame and JPanel behave differently in a way that would cause this? Or is there anything else obvious to fix it?

答:
One solution is to create an empty border. Try something like this:

```<code>panelName.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));
</code>```

This will shift everything in the JPanel down 20 pixels, and it should solve your problem. Try adjusting the number of pixels until you find the center.

Take a look at this post.

Title: Java replace JFrame with JPanel

Body:
One solution is to create an empty border. Try something like this:

panelName.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));

This will shift everything in the JPanel down 20 pixels, and it should solve your problem. Try adjusting the number of pixels until you find the center.

Take a look at this post.


问:
HTML2pdf Css not supporting
I have used a html2pdf file for generating pdf.But it does not support css at all. Please let me know what is the issue.

1) Downloaded file from
https://sourceforge.net/projects/html2fpdf/?source=typ_redirect

2) placed in a folder and used below code to generate pdf (working fine)

```<code>require("html2fpdf.php");
$buffer = "<div>
<h1>Hello Friends</h1><br>
<p>This is a sample code</p>
</div>";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');
</code>```

but when i used css in this then generated pdf is not opened

```<code>require("html2fpdf.php");
$buffer = "<div style='width:950px;'>
<h1>Hello Friends</h1><br>
<p style='font-size:10'>This is a sample code</p>
</div>";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');
</code>```

My php version is PHP Version 5.3.8.

I am bowed  to use HTML2PDF. So please answer if you know(I have used same with TCPDF and thats working fine but i need to implement same in HTML2PDF)

答:
Got Your Issue : Just Remove

 from your code

Instead of using :

```<code>$buffer = "<div>
<h1>Hello Friends</h1><br>
<p>This is a sample code</p>
</div>";
</code>```

Use :

```<code>$buffer = "<h1>Hello Friends</h1><br>
<p>This is a sample code</p>";
</code>```

Title: HTML2pdf Css not supporting

Body:
I have used a html2pdf file for generating pdf.But it does not support css at all. Please let me know what is the issue.

1) Downloaded file from
https://sourceforge.net/projects/html2fpdf/?source=typ_redirect

2) placed in a folder and used below code to generate pdf (working fine)

require("html2fpdf.php");
$buffer = "

Hello Friends

This is a sample code

";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

but when i used css in this then generated pdf is not opened

require("html2fpdf.php");
$buffer = "

Hello Friends

This is a sample code

";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

My php version is PHP Version 5.3.8.

I am bowed  to use HTML2PDF. So please answer if you know(I have used same with TCPDF and thats working fine but i need to implement same in HTML2PDF)

Body:
Got Your Issue : Just Remove <div></div> from your code

Instead of using :

$buffer = "<div>
<h1>Hello Friends</h1><br>
<p>This is a sample code</p>
</div>";

Use :

$buffer = "<h1>Hello Friends</h1><br>
<p>This is a sample code</p>";


问:
System.out.print is overlapping the questions why?
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

```<code>"Enter the second student's name: Enter the student's score: "
</code>```

instead of

```<code>"Enter the second students's name: "

"Enter the student's score: "
</code>```

I also can not input data into the System.out.print method of the second student

My main code where the error is:

```<code>System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}
</code>```

the part that deals with the error from the class is as follows

```<code>public void setName(String nm){
    name = nm;
}
</code>```

答:
If what I understand is right, you may probaly have problems with the input of the java console. I can't tell much because there's not enough information, but maybe you can refer this link for getting input in java console: http://www.abbeyworkshop.com/howto/java/readLine/index.html

And I recommend clearing the un-affected code (about class Student), just check the input & output from console only.

Body:
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

"Enter the second student's name: Enter the student's score: "

instead of

"Enter the second students's name: "

"Enter the student's score: "

I also can not input data into the System.out.print method of the second student

My main code where the error is:

System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}

the part that deals with the error from the class is as follows

public void setName(String nm){
    name = nm;
}