问:
Debug Iphone Program received signal: "EXC_BAD_ACCESS"
My iphone app randomly received this message. I know certain it is memory release problem. However what is the best way to find which object leads this problem. Here are what I have tried

Use Instrument Leak and
ObjectAllocation Trace. Dont saw any
help to know which object have this
problem

Put NSZombieEnabled=YES and project executive ... Dont saw any
help either

Put NSLog everywhere but the EXE_BAD_ACCESS just appear anywhere.
in the debuger, just saw the code
happened in the assembly. like
objc-msg send.

review code many times and read memory management a lot time
and research online a lot time. but
no surprise.

Is there a completed solution to figure out this problem easily. I am a previous Visual C++ programmer, I deal with memory management with years and it is easy to debug and figure out in Visual C++.

答: You will also receive the message when you don't pass enough parameters to a variable argument method.  For example having a NSLog statement like this:    NSLog(@"Hello %@"); </p>

OwnerDisplayName: angrysword


来源: stackexchange

问:
drawing straight line which passes through a point in between
I need to draw a straight line from Point A to point C, which has to pass through point B somewhere in between.

The problem is that I got coordinates of just A and B, not C. For point C I only has "x" coordinate.

Its like I have to draw a line from A to B, and extend it to C.

```<code><?php
$im = imagecreate( 600, 600 );
$background= imagecolorallocate( $im, 25, 25, 75 );
imagefill( $im, 0,0, $background );
$white= imagecolorallocate( $im, 255, 255, 255 );

$a= array( 100, 200 );
$b= array( 200, 176 );
$c= array( 300, '' ); // This is to be calculated

imageline( $im, $a[0], $a[1], $c[0], $c[1], $white );

header("Content-Type: image/jpeg"); imagejpeg($im); exit();
?>
</code>```

The straight line has to start at A, touch B, and end at C...  How do I calculate the "y" coord of point c?
Thanks

答:
The math for this is relatively simple. You can calculate the y-value of c as follows:

```<code>cy = ay + (by - ay) * (cx - ax) / (bx - ax)
</code>```

This works by "extending" the y-value by the same ratio as we've extended the x-value. We know the ratio of the vector a->c to a->b since we have all three x values. We just need to apply that same ratio to the y values.

For your given data, that's:

                          ______________________
                         /  This is the ratio   \
                         |                      |
cy = ay  + (by  - ay)  * (cx  - ax)  / (bx  - ax)
   = 200 + (176 - 200) * (300 - 100) / (300 - 200)
   = 200 +    -24      *    200      /    100
   =                 152
```

Note that this won't work if the line is vertical (a and b share the same x value) since that results in division by zero. That's not fixable since it means c must also have the same x-value and therefore its y-value could be anything.

ContentLicense: CC BY-SA 3.0

Body:
I need to draw a straight line from Point A to point C, which has to pass through point B somewhere in between.

The problem is that I got coordinates of just A and B, not C. For point C I only has "x" coordinate.

Its like I have to draw a line from A to B, and extend it to C.

<?php
$im = imagecreate( 600, 600 );
$background= imagecolorallocate( $im, 25, 25, 75 );
imagefill( $im, 0,0, $background );
$white= imagecolorallocate( $im, 255, 255, 255 );

$a= array( 100, 200 );
$b= array( 200, 176 );
$c= array( 300, '' ); // This is to be calculated

imageline( $im, $a[0], $a[1], $c[0], $c[1], $white );

header("Content-Type: image/jpeg"); imagejpeg($im); exit();
?>

The straight line has to start at A, touch B, and end at C...  How do I calculate the "y" coord of point c?
Thanks

Body:
The math for this is relatively simple. You can calculate the y-value of c as follows:

cy = ay + (by - ay) * (cx - ax) / (bx - ax)

This works by "extending" the y-value by the same ratio as we've extended the x-value. We know the ratio of the vector a->c to a->b since we have all three x values. We just need to apply that same ratio to the y values.

For your given data, that's:

                          ______________________
                         /  This is the ratio   \
                         |                      |
cy = ay  + (by  - ay)  * (cx  - ax)  / (bx  - ax)
   = 200 + (176 - 200) * (300 - 100) / (300 - 200)
   = 200 +    -24      *    200      /    100
   =                 152

Note that this won't work if the line is vertical (a and b share the same x value) since that results in division by zero. That's not fixable since it means c must also have the same x-value and therefore its y-value could be anything.


问:
C++ Builder: Abnormal program termination. How to investigate?
I'm trying to move a project that was done in a previous version of C++Builder to 10.1 Berlin (I am using the trial version of C++Builder).

The project was converted and compiled succefully with minimal efforts. Then I got the well-known linker LME288 problem, but it was resolved by starting C++Builder as an administrator.

But now, when I start the application, I get a message box saying "Abnormal program termination" at the very beginning - even before the main window appears on screen.

The situation is the same for debug and release versions, under IDE and as standalone. When I start the program inside the IDE, and set a breakpoint at the very first statement, the error message appears before this statement.

I have Windows 10 Pro, 64-bit. C++Builer 10.1 Berlin trial.  It shows the only accessible platform is Win32, but I don't know if this is a reason for an error. The program worked fine for previous versions.

Could anybody advise me what to do? Is there a systematic way of investigating the problem?

I have tried all recommendations I could found - use debugger, show us the code, try reinstalling software or Windows, upgrade to latest updates, etc. But I have never seen a systematic approach.

答:
Here are a couple of things I had to do to get my project working.

1) Start a new project.  For some reason old projects can get corrupted and produce strange errors.  I recommend starting a new project and adding your files to it.
2) Use an old version of borlndmm.dll  The version provided with C++ Builder 10 produced crashes for me that made no sense.  I overwrote the provided copy of borlndmm.dll with a copy from XE6 or XE8.  That solved my problem.

Hopefully one of these will help you.


问:
Using spark ML models outside of spark [hdfs DistributedFileSystem could not be instantiated]
I've been trying to follow along things blog post:

https://www.phdata.io/exploring-spark-mllib-part-4-exporting-the-model-for-use-outside-of-spark/

Using spark 2.1 with built in Hadoop 2.7 run locally I can save a model:

```<code>trainedModel.save("mymodel.model"))
</code>```

However if I try to load the model from a regular scala (sbt) shell hdfs fails to load.

```<code>import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.ml.{PipelineModel, Predictor}

val sc = new SparkContext(new SparkConf().setMaster("local[1]").setAppName("myApp"))

val model = PipelineModel.load("mymodel.model")
</code>```

I get this is error:

```<code>java.util.ServiceConfigurationError: org.apache.hadoop.fs.FileSystem: Provider org.apache.hadoop.hdfs.DistributedFileSystem could not be instantiated
</code>```

Is it in fact possible to use a spark model without calling spark-submit, or spark-shell? The article I linked to was the only one I'd seen mentioning such functionality.

My build.sbt is using the following dependencies:

```<code>"org.apache.spark" %% "spark-core" % "2.1.0",
"org.apache.spark" % "spark-sql_2.11" % "2.1.0",
"org.apache.spark" % "spark-hive_2.11" % "2.1.0",
"org.apache.spark" % "spark-mllib_2.11" % "2.1.0",
"org.apache.hadoop" % "hadoop-hdfs" % "2.7.0"
</code>```

In both cases I am using Scala 2.11.8.

Edit: Okay it looks including this was the source of the problem

```<code>"org.apache.hadoop" % "hadoop-hdfs" % "2.7.0"
</code>```

I removed that line and the problem went away

答:
try:

```<code>trainedModel.write.overwrite().save("mymodel.model"))
</code>```

Also if your model is saved locally, you can remove hdfs in your configuration. This should prevent spark from attempting to instantiate hdfs.

Body:
I've been trying to follow along things blog post:

https://www.phdata.io/exploring-spark-mllib-part-4-exporting-the-model-for-use-outside-of-spark/

Using spark 2.1 with built in Hadoop 2.7 run locally I can save a model:

trainedModel.save("mymodel.model"))

However if I try to load the model from a regular scala (sbt) shell hdfs fails to load.

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.ml.{PipelineModel, Predictor}

val sc = new SparkContext(new SparkConf().setMaster("local[1]").setAppName("myApp"))

val model = PipelineModel.load("mymodel.model")

I get this is error:

java.util.ServiceConfigurationError: org.apache.hadoop.fs.FileSystem: Provider org.apache.hadoop.hdfs.DistributedFileSystem could not be instantiated

Is it in fact possible to use a spark model without calling spark-submit, or spark-shell? The article I linked to was the only one I'd seen mentioning such functionality.

My build.sbt is using the following dependencies:

"org.apache.spark" %% "spark-core" % "2.1.0",
"org.apache.spark" % "spark-sql_2.11" % "2.1.0",
"org.apache.spark" % "spark-hive_2.11" % "2.1.0",
"org.apache.spark" % "spark-mllib_2.11" % "2.1.0",
"org.apache.hadoop" % "hadoop-hdfs" % "2.7.0"

In both cases I am using Scala 2.11.8.

Edit: Okay it looks including this was the source of the problem

"org.apache.hadoop" % "hadoop-hdfs" % "2.7.0"

I removed that line and the problem went away

Body:
try:

trainedModel.write.overwrite().save("mymodel.model"))

Also if your model is saved locally, you can remove hdfs in your configuration. This should prevent spark from attempting to instantiate hdfs.


问:
Get attribute values from matching XML nodes using XPath query
This doesn't seem like it should be difficult, but I'm stuck currently.  I'm trying to get the attribute values for a particular attribute from nodes that match a given XPath query string.  Here's what I have so far:

```<code>    public static IEnumerable<string> GetAttributes(this XmlDocument xml,
        string xpathQuery, string attributeName)
    {
        var doc = new XPathDocument(new XmlNodeReader(xml));
        XPathNavigator nav = doc.CreateNavigator();
        XPathExpression expr = nav.Compile(xpathQuery);
        XPathNodeIterator iterator = nav.Select(expr);
        while (iterator.MoveNext())
        {
            XPathNavigator curNav = iterator.Current;
            if (curNav.HasAttributes)
            {
                XmlNode curNode = ((IHasXmlNode)curNav).GetNode();
                if (null != curNode)
                {
                    XmlAttribute attrib = curNode.Attributes[attributeName];
                    if (null != attrib)
                    {
                        yield return attrib.Value;
                    }
                }
            }
        }
    }
</code>```

This currently throws an exception:

System.InvalidCastException: Unable to cast object of type 'MS.Internal.Xml.Cache.XPathDocumentNavigator' to type 'System.Xml.IHasXmlNode'.

Am I going about this wrong?  Is there a simpler way to get attribute values from matching nodes?

答:
If you're using .net 3.5 or later you could use linq to Xml

For a given xml document

```<code><?xml version="1.0" encoding="utf-8" ?>
<root>
  <storedProcedures>
    <storedProcedure name="usp_GET_HOME_PAGE_DATA">
      <resultSet name="Features"/>
      <resultSet name="Highlights"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_FEATURES" />
    <storedProcedure name="usp_GET_FEATURE" />
    <storedProcedure name="usp_UPDATE_FEATURE" />
    <storedProcedure name="usp_GET_FEATURE_FOR_DISPLAY">
      <resultSet name="CurrentFeature"/>
      <resultSet name="OtherFeatures"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_HIGHLIGHT_TITLES">
      <resultSet name="Highlights"/>
    </storedProcedure>
  </storedProcedures>
</root>
</code>```

The following linq expression will get you the values of the "name" attributes of all storedProcedure node

```<code>XDocument xDcoument = XDocument.Load(xmlStoredProcSchemeFile);

  var storedProcedureNames = from doc in xDcoument.Descendants("storedProcedure")
                             select doc.Attribute("name").Value;
</code>```

you could also use regular XPath syntax. In the code below the variable node holds the node identified by the "usp_GET_HOME_PAGE_DATA" name and then the attributes variable holds all child nodes (the attributes) of the selected node and it's children.

```<code>  XmlDocument xmlDocument = new XmlDocument();
  xmlDocument.Load(@"C:\inetpub\wwwroot\ASPNETBuilder\BusinessLayer\DataAccessCodeGenerationSchema.xml");
  var node = xmlDocument.DocumentElement.SelectSingleNode("./storedProcedures/storedProcedure[@name='usp_GET_HOME_PAGE_DATA']");
  var attributes = node.SelectNodes("./resultSet/@name");
</code>```

Body:
This doesn't seem like it should be difficult, but I'm stuck currently.  I'm trying to get the attribute values for a particular attribute from nodes that match a given XPath query string.  Here's what I have so far:

    public static IEnumerable<string> GetAttributes(this XmlDocument xml,
        string xpathQuery, string attributeName)
    {
        var doc = new XPathDocument(new XmlNodeReader(xml));
        XPathNavigator nav = doc.CreateNavigator();
        XPathExpression expr = nav.Compile(xpathQuery);
        XPathNodeIterator iterator = nav.Select(expr);
        while (iterator.MoveNext())
        {
            XPathNavigator curNav = iterator.Current;
            if (curNav.HasAttributes)
            {
                XmlNode curNode = ((IHasXmlNode)curNav).GetNode();
                if (null != curNode)
                {
                    XmlAttribute attrib = curNode.Attributes[attributeName];
                    if (null != attrib)
                    {
                        yield return attrib.Value;
                    }
                }
            }
        }
    }

This currently throws an exception:

System.InvalidCastException: Unable to cast object of type 'MS.Internal.Xml.Cache.XPathDocumentNavigator' to type 'System.Xml.IHasXmlNode'.

Am I going about this wrong?  Is there a simpler way to get attribute values from matching nodes?

Body:
If you're using .net 3.5 or later you could use linq to Xml

For a given xml document

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <storedProcedures>
    <storedProcedure name="usp_GET_HOME_PAGE_DATA">
      <resultSet name="Features"/>
      <resultSet name="Highlights"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_FEATURES" />
    <storedProcedure name="usp_GET_FEATURE" />
    <storedProcedure name="usp_UPDATE_FEATURE" />
    <storedProcedure name="usp_GET_FEATURE_FOR_DISPLAY">
      <resultSet name="CurrentFeature"/>
      <resultSet name="OtherFeatures"/>
    </storedProcedure>
    <storedProcedure name="usp_GET_HIGHLIGHT_TITLES">
      <resultSet name="Highlights"/>
    </storedProcedure>
  </storedProcedures>
</root>

The following linq expression will get you the values of the "name" attributes of all storedProcedure node

XDocument xDcoument = XDocument.Load(xmlStoredProcSchemeFile);

  var storedProcedureNames = from doc in xDcoument.Descendants("storedProcedure")
                             select doc.Attribute("name").Value;

you could also use regular XPath syntax. In the code below the variable node holds the node identified by the "usp_GET_HOME_PAGE_DATA" name and then the attributes variable holds all child nodes (the attributes) of the selected node and it's children.

  XmlDocument xmlDocument = new XmlDocument();
  xmlDocument.Load(@"C:\inetpub\wwwroot\ASPNETBuilder\BusinessLayer\DataAccessCodeGenerationSchema.xml");
  var node = xmlDocument.DocumentElement.SelectSingleNode("./storedProcedures/storedProcedure[@name='usp_GET_HOME_PAGE_DATA']");
  var attributes = node.SelectNodes("./resultSet/@name");

ContentLicense: CC BY-SA 2.5


问:
Android Studio Error,
When I launch an Android Studio Project I get this Error

```<code>Error:The newly created daemon process has a different context than expected.
Java home is different.
Expecting: 'D:\Program Files\Android\Android Studio\jre' but was: 'C:\Program Files (x86)\Java\jre1.8.0_101'.
Please configure the JDK to match the expected one.
Open JDK Settings
</code>```

But my JDK file is the same as the expected file location, as you can see in this picture

Edit: Now I'm getting a new error

Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap

答: Try to uncheck the Use Embedded JDK then change the path "C:\Program Files (x86)\Java\jre1.8.0_101"

Title: Android Studio Error,

Body:
When I launch an Android Studio Project I get this Error

Error:The newly created daemon process has a different context than expected.
Java home is different.
Expecting: 'D:\Program Files\Android\Android Studio\jre' but was: 'C:\Program Files (x86)\Java\jre1.8.0_101'.
Please configure the JDK to match the expected one.
Open JDK Settings

But my JDK file is the same as the expected file location, as you can see in this picture

Edit: Now I'm getting a new error

Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap


问:
C socket programming receiving unknown length of data
Hi I designed a code to get the length of unknown data coming in to the socket
I need help because I can't find where my code get stuck in this function.
Thanks for any help</p>

```<code>int recvlen(int s){ //peak all received data and returns the length
  char *request;
  int total;
  total= 1024;//initial size
  int numbytes;
  printf("\n entered recvlen\n");
  while(1){
    if(( request= (char *)realloc(request,sizeof(char)*total+1)) <=0){
      fprintf(stderr,"error in realloc no memory or fail");
      return -1;
    }
    if((numbytes= recv(s,request,sizeof(request),MSG_PEEK))==-1){//get request
      fprintf(stderr,"\n error in receiveall \n");
      free(request);
      return -1;
    }
   if(numbytes != strlen(request)){
    total = numbytes+1;
    free(request);
    printf("\n recvlen returned total: %d\n",total);
    return total;//when the size is found
   }
  total += total;
  }
    }
</code>```

答:
I can't find where my code get stuck in this function

It doesn't 'get stuck'. It loops forever, because you aren't actually reading anything, because you used MSG_PEEK. Solution: don't.

NB if(numbytes != strlen(request)){ makes no sense whatsoever. There is no guarantee that request is ever null-terminated: in any case the test seems pointless.

Body:
Hi I designed a code to get the length of unknown data coming in to the socket
I need help because I can't find where my code get stuck in this function.
Thanks for any help

int recvlen(int s){ //peak all received data and returns the length
  char *request;
  int total;
  total= 1024;//initial size
  int numbytes;
  printf("\n entered recvlen\n");
  while(1){
    if(( request= (char *)realloc(request,sizeof(char)*total+1)) <=0){
      fprintf(stderr,"error in realloc no memory or fail");
      return -1;
    }
    if((numbytes= recv(s,request,sizeof(request),MSG_PEEK))==-1){//get request
      fprintf(stderr,"\n error in receiveall \n");
      free(request);
      return -1;
    }
   if(numbytes != strlen(request)){
    total = numbytes+1;
    free(request);
    printf("\n recvlen returned total: %d\n",total);
    return total;//when the size is found
   }
  total += total;
  }
    }


问:
Why does PHP's DOMDocument remove leading whitespace from Processing Instruction nodes? (<?php ?>)
I am loading a XML-compliant PHP file into DOMDocument.

```<code>    $domDoc = new DOMDocument();
    $domDoc->recover            = TRUE;
    $domDoc->preserveWhiteSpace = TRUE;
    $domDoc->formatOutput       = FALSE;
    $domDoc->substituteEntities = FALSE;
    $domDoc->resolveExternals   = FALSE;
</code>```

Despite preserving whitespace and instructing it to not format the output, I am still finding the leading whitespace in <?php ?> blocks removed when I save the XML with $domDoc->saveXML().

Input:

```<code><?xml version="1.0" encoding="UTF-8"?>
<html>
<?php

// This is code.

// Something else.
    echo 'test';

?>
</html>
</code>```

Output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<html>
<?php // This is code.

// Something else.
    echo 'test';

?>
</html>
</code>```

I want the output to be as identical to the input as possible. Collapsing whitespace between attributes is acceptable, but collapsing whitespace between nodes or within a Processing Instruction is not okay. Why is PHP::DOMDocument() / libxml2 changing the contents of the PI? Will I need to resort to manual DOM echoing to keep the whitespace completely preserved?

答:
Leading white space in a PI node is actually okay to collapse, as the DOM considers the data portion of a processing instruction to be:

The content of this processing instruction. This is from the first non white space character after the target to the character immediately preceding the ?>.

(Emphasis mine.)

The preserveWhiteSpace setting only applies to text nodes, which is why that doesn't help you here.

In any case I would advise not relying on embedded PHP to be treated as a processing instruction as PHP can contain ?> within it (e.g. as part of a string literal) which would terminate the processing instruction early.

Body:
I am loading a XML-compliant PHP file into DOMDocument.

    $domDoc = new DOMDocument();
    $domDoc->recover            = TRUE;
    $domDoc->preserveWhiteSpace = TRUE;
    $domDoc->formatOutput       = FALSE;
    $domDoc->substituteEntities = FALSE;
    $domDoc->resolveExternals   = FALSE;

Despite preserving whitespace and instructing it to not format the output, I am still finding the leading whitespace in <?php ?> blocks removed when I save the XML with $domDoc->saveXML().

Input:

<?xml version="1.0" encoding="UTF-8"?>

<?php

// This is code.

// Something else.
    echo 'test';

?>

Output:

<?xml version="1.0" encoding="UTF-8"?>

<?php // This is code.

// Something else.
    echo 'test';

?>

I want the output to be as identical to the input as possible. Collapsing whitespace between attributes is acceptable, but collapsing whitespace between nodes or within a Processing Instruction is not okay. Why is PHP::DOMDocument() / libxml2 changing the contents of the PI? Will I need to resort to manual DOM echoing to keep the whitespace completely preserved?


问:
Linq-to-Entities/Linq-to-SQL, Is One Data Polling Method More Efficient?
Are the following two examples different and if so, which is more efficient?

```<code>var user = (from u in db.Users where u.Id == userId select u).Single();
</code>```

and

```<code>var user = db.Users.Single(p => p.Id == userId);
</code>```

答: They are the same.  The compiler should produce the same outcome for both LINQ syntax.</p>

Body:
Are the following two examples different and if so, which is more efficient?

var user = (from u in db.Users where u.Id == userId select u).Single();

and

var user = db.Users.Single(p => p.Id == userId);


问:
Switch timezone base on array value
I'm getting an array with about 200 records, each record has a datetime and timezone, my question is, how do I display each date-time accordingly to the city/country that the information is display.

```<code>array(
   'date'=>'2017-04-02T01:00:00',
   'timezone'=>'Europe/London'
)
</code>```

Say that you are in NYC, how do you display date value in America/New_York time zone?

I'd like to display the date value as Sun 2 of April at 1:00:00PM

答:
you can do it by setting the timezone</p>

```<code>$mytimezone='"America/New_York"';
date_default_timezone_set($mytimezone);
</code>```

Title: Switch timezone base on array value

Body:
I'm getting an array with about 200 records, each record has a datetime and timezone, my question is, how do I display each date-time accordingly to the city/country that the information is display.

array(
   'date'=>'2017-04-02T01:00:00',
   'timezone'=>'Europe/London'
)

Say that you are in NYC, how do you display date value in America/New_York time zone?

I'd like to display the date value as Sun 2 of April at 1:00:00PM

Body:
you can do it by setting the timezone

$mytimezone='"America/New_York"';
date_default_timezone_set($mytimezone);


问:
Add data from one table into another based on another value in MySQL
I need to take data from one table and add it to another. This is to link a supplier to a product, however it's not a simple query, so I'm not sure if this can be done.

I have a table which is xxx_product and then another table which is xxx_product_to_vendor.

I need to take each record in xxx_product and add it to xxx_product_to_vendor.

xxx_product_to_vendor has three columns.

```<code>product_to_vendor_id
product_id
vendor_id
</code>```

product_to_vendor_id must auto increment in numbers as it's the record number.

product_id must be taken from the product_id in table xxx_product.

vendor_id must be assigned as following. If supplier_id in xxx_vendor is 4 then vendor_id in xxx_product_to_vendor must be 1.

Here are images of my two tables.

答: I managed to solve my issue without the need of a query. I simply exported the table as CSV for MS through phpmyadmin and deleted the columns I didn't need and updated the data in excel. Imported the edited sheet into the other table without any issues.</p>

Body:
I need to take data from one table and add it to another. This is to link a supplier to a product, however it's not a simple query, so I'm not sure if this can be done.

I have a table which is xxx_product and then another table which is xxx_product_to_vendor.

I need to take each record in xxx_product and add it to xxx_product_to_vendor.

xxx_product_to_vendor has three columns.

product_to_vendor_id
product_id
vendor_id

product_to_vendor_id must auto increment in numbers as it's the record number.

product_id must be taken from the product_id in table xxx_product.

vendor_id must be assigned as following. If supplier_id in xxx_vendor is 4 then vendor_id in xxx_product_to_vendor must be 1.

Here are images of my two tables.


问:
Angular 2 fill variable with return JSON info from HTTP Request
I'm pretty new on Angular2, and I'm trying to obtain the key/value pair from a JSON file returned by a Http request. I want to store them on the objectResource property so I can retrieve them on the template.

This is my component.ts:

```<code>export class ResourceDetailComponent implements OnInit {

    objectResource: any = Array();
    id:any;
    sub:any;

    constructor(private contentService: ContentService, private route: ActivatedRoute) {

        this.sub = this.route.params.subscribe(params => {
            this.id = +params['id'];
        });

        this.getResource(this.id);
     }

    ngOnInit(){}

    private getResource(id:number) {
        return this.contentService.getSpecificResource(id).then(res => this.objectResource.push(res));
    }

}
</code>```

and this is mi service.ts:

```<code>public getSpecificResource(id:number) {
        return this.http.get(`http://resources.dev/v1/resources/show/${id}`)
        .toPromise()
        .then(res => res.json());
    }
</code>```

when I do console.log on res I obtain this log, which mean the service is doing the request as expected:

```<code>Object {
    id: 1,
    name: "quisquam",
    image: "http://lorempixel.com/480/480/?88330",
    description: "Consequuntur quo provident alias aut rerum.",
    author: "Marc Mann Sr."
}
</code>```

I've tried to retrieve these values on the template using {{objectResource.name}} but isn't working, and I don't know how can I access this values from the template.

答:
When the template is loaded, the objectResource might not be ready. Try to put ? from your objectResource like this

```<code> {{objectResource?.name}}
</code>```

or insert a div element like this

```<code>  <div *ngIf='objectResource'>
    {{objectResource.name}}
  </div>
</code>```

Hope this helps.

Body:
I'm pretty new on Angular2, and I'm trying to obtain the key/value pair from a JSON file returned by a Http request. I want to store them on the objectResource property so I can retrieve them on the template.

This is my component.ts:

export class ResourceDetailComponent implements OnInit {

    objectResource: any = Array();
    id:any;
    sub:any;

    constructor(private contentService: ContentService, private route: ActivatedRoute) {

        this.sub = this.route.params.subscribe(params => {
            this.id = +params['id'];
        });

        this.getResource(this.id);
     }

    ngOnInit(){}

    private getResource(id:number) {
        return this.contentService.getSpecificResource(id).then(res => this.objectResource.push(res));
    }

}

and this is mi service.ts:

public getSpecificResource(id:number) {
        return this.http.get(`http://resources.dev/v1/resources/show/${id}`)
        .toPromise()
        .then(res => res.json());
    }

when I do console.log on res I obtain this log, which mean the service is doing the request as expected:

Object {
    id: 1,
    name: "quisquam",
    image: "http://lorempixel.com/480/480/?88330",
    description: "Consequuntur quo provident alias aut rerum.",
    author: "Marc Mann Sr."
}

I've tried to retrieve these values on the template using {{objectResource.name}} but isn't working, and I don't know how can I access this values from the template.

Body:
When the template is loaded, the objectResource might not be ready. Try to put ? from your objectResource like this

 {{objectResource?.name}}

or insert a div element like this

  <div *ngIf='objectResource'>
    {{objectResource.name}}
  </div>

Hope this helps.


问:
SQL query using limit while considering duplicates
I'm using a query to get the top 3 records from a table using limit like so:

```<code>select name, salary
from employees
order by salary desc
limit 3;
</code>```

The problem is there could be employees with the same salary and I wouldn't want my limit to be 3 in that case

```<code>----------------------------
|    name    |    salary   |
----------------------------
|   Robert   |    10000    |
|     Jon    |    20000    |
| Alexander  |    30000    |
|    James   |    20000    |
|    Mike    |    40000    |
----------------------------
</code>```

So in this example I would want to have a limit of 4 since there are two employees with a salary of 20000. Is there a way to consider the duplicates without knowing in advance how many there will be?

答:
you need to first determine the salary ranges you want to include.</p>

```<code>select name, salary
  from employees
 where salary in ( select distinct salary
                from employees
                order by salary desc
                limit 3 )
 order by salary DESC ;
</code>```

Body:
I'm using a query to get the top 3 records from a table using limit like so:

select name, salary
from employees
order by salary desc
limit 3;

The problem is there could be employees with the same salary and I wouldn't want my limit to be 3 in that case

----------------------------
|    name    |    salary   |
----------------------------
|   Robert   |    10000    |
|     Jon    |    20000    |
| Alexander  |    30000    |
|    James   |    20000    |
|    Mike    |    40000    |
----------------------------

So in this example I would want to have a limit of 4 since there are two employees with a salary of 20000. Is there a way to consider the duplicates without knowing in advance how many there will be?

Body:
you need to first determine the salary ranges you want to include.

select name, salary
  from employees
 where salary in ( select distinct salary
                from employees
                order by salary desc
                limit 3 )
 order by salary DESC ;


问:
After installing Visual Studio 2017, I'm unable to debug smart device project in Visual Studio 2008
I recently installed Visual Studio 2017, just shortly after it was released (March 2017).

When I go to debug my smart device project in VS 2008 I get a error message dialog that just says "The operation could not be completed". , .

Here is a list of what I've observed:

The project output successfully deploys

no error message is displayed in the output window in Visual Studio

when I go to Debug=>Attach to Process and open the Transport drop down, it doesn't contain Smart Device like it usually does.

ProcMon shows that devenv is maintaining a open connection to the device on port 5355

What I've tried:

I tried debugging on multiple emulator types and devices that I know have worked in the past.

I tried creating an new solution with the default smart device project.

I tried deleting all the files in %localappdata%/Microsoft/CoreCon/1.0

答:
After trying to use Visual Studio to debug its self, I got the following error message

```<code>"A Visual Studio DLL, coloader8O.dll, is not correctly installed. Please
repairyour Visual Studio installation via ‘Add or Remove Programs’ in
Control Panel.
If the problem persists, you can manually register coloader8O.dll from
the command prompt with ‘regsvr32
“%CommonProgramFiles%\Microsoft
Shared\VS7Debug\coloader8O.dll”.
</code>```

I was able to fix the issue by following some instructions I found on developercommunity.visualstudio.com which involves changing the regestry values at HKEY_CLASSES_ROOT\TypeLib{6A1A7D39-8449-4287-8EF0-CE256582C940}\8.0\0\win32 to C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\\coloader80.tlb

Body:
After trying to use Visual Studio to debug its self, I got the following error message

"A Visual Studio DLL, coloader8O.dll, is not correctly installed. Please
repairyour Visual Studio installation via ‘Add or Remove Programs’ in
Control Panel.
If the problem persists, you can manually register coloader8O.dll from
the command prompt with ‘regsvr32
“%CommonProgramFiles%\Microsoft
Shared\VS7Debug\coloader8O.dll”.

I was able to fix the issue by following some instructions I found on developercommunity.visualstudio.com which involves changing the regestry values at HKEY_CLASSES_ROOT\TypeLib{6A1A7D39-8449-4287-8EF0-CE256582C940}\8.0\0\win32 to C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\\coloader80.tlb


问:
Anyone have syntax for removing all components at once from COM+ Application using Powershell
I am having problems trying to loop through and remove 91 components from my COM+ Application

This is my Powershell code:

```<code>$app = $apps | Where-Object {$_.Name -eq 'pkgAdap2'}
$compColl = $apps.GetCollection("Components", $app.Key)
$compColl.Populate()

$index = 0
foreach($component in $compColl) {

    $compColl.Remove($index)
    $compColl.SaveChanges()

    $index++
}
</code>```

The code appears to work but it only removes HALF of the components and for the rest of the $index the loop returns this error:

```<code>Value does not fall within the expected range.
At line:4 char:5
+     $compColl.Remove($index)
+     ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException
</code>```

So I keep running it and the number of components left keeps getting reduced by half.

I think the reason is that the array/collection I am "removing" from re-sorts the remaining indexes, moving them over every time. So I only get through half before $index is out of range. It is the only thing I can figure is doing this. Thus I also tried another approach:

```<code>while($compColl.Count > 0) {
    $compColl.Remove($compColl.Count)
}
</code>```

But it doesn't work either.

Does anyone know how to delete all components at once?

答:
It sounds like the indices of your collection are 0-based, so the following should work:

```<code>while($compColl.Count -gt 0) {
  $compColl.Remove($compColl.Count - 1) # remove last element, which updates .Count. Using 0 to remove the first one is a good option to.
}
$compColl.SaveChanges()
</code>```

If you're sure that the collection won't change while you're enumerating it, this variant is probably slightly more efficient:

```<code>for ($i = $compColl.Count - 1; $i -ge 0; --$i) {
  $compColl.Remove($i)
}
$compColl.SaveChanges()
</code>```

The problem with your original approach was that every $compColl.Remove($index) call implicitly decremented the indices of the remaining items, so that $index++ ended up skipping items until it reached a value beyond the remaining highest index and failed.

Generally, it's problematic to loop over a collection item by item while modifying that collection in the loop body.

Body:
I am having problems trying to loop through and remove 91 components from my COM+ Application

This is my Powershell code:

$app = $apps | Where-Object {$_.Name -eq 'pkgAdap2'}
$compColl = $apps.GetCollection("Components", $app.Key)
$compColl.Populate()

$index = 0
foreach($component in $compColl) {

    $compColl.Remove($index)
    $compColl.SaveChanges()

    $index++
}

The code appears to work but it only removes HALF of the components and for the rest of the $index the loop returns this error:

Value does not fall within the expected range.
At line:4 char:5
+     $compColl.Remove($index)
+     ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

So I keep running it and the number of components left keeps getting reduced by half.

I think the reason is that the array/collection I am "removing" from re-sorts the remaining indexes, moving them over every time. So I only get through half before $index is out of range. It is the only thing I can figure is doing this. Thus I also tried another approach:

while($compColl.Count > 0) {
    $compColl.Remove($compColl.Count)
}

But it doesn't work either.

Does anyone know how to delete all components at once?

Body:
It sounds like the indices of your collection are 0-based, so the following should work:

while($compColl.Count -gt 0) {
  $compColl.Remove($compColl.Count - 1) # remove last element, which updates .Count. Using 0 to remove the first one is a good option to.
}
$compColl.SaveChanges()

If you're sure that the collection won't change while you're enumerating it, this variant is probably slightly more efficient:

for ($i = $compColl.Count - 1; $i -ge 0; --$i) {
  $compColl.Remove($i)
}
$compColl.SaveChanges()

The problem with your original approach was that every $compColl.Remove($index) call implicitly decremented the indices of the remaining items, so that $index++ ended up skipping items until it reached a value beyond the remaining highest index and failed.

Generally, it's problematic to loop over a collection item by item while modifying that collection in the loop body.

ContentLicense: CC BY-SA 4.0


问:
How to view an HTML file in the browser with Visual Studio Code
How can I view my HTML code in a browser with the new Microsoft Visual Studio Code?

With Notepad++ you have the option to Run in a browser. How can I do the same thing with Visual Studio Code?

答:
You can now install an extension View In Browser. I tested it on windows with chrome and it is working.

vscode version: 1.10.2


问:
How to print colored text in .txt format
I am using python 3.5version. I need to print hello statement in colored format in a file of .txt format.(windows platform) Is there any way to do that. I have tried colorama but could not print colored text in .txt file.
Please help me out in this.

Thanks in advance

答:
The .txt format itself has no fonts/sizes/colors but you can use .rtf and if you are looking into printing colored text in console you can use ansi colors:

Regular colors:

```<code>ANSI_RESET = "\u001B[0m";
ANSI_BLACK = "\u001B[30m";
ANSI_RED = "\u001B[31m";
ANSI_GREEN = "\u001B[32m";
ANSI_YELLOW = "\u001B[33m";
ANSI_BLUE = "\u001B[34m";
ANSI_PURPLE = "\u001B[35m";
ANSI_CYAN = "\u001B[36m";
ANSI_WHITE = "\u001B[37m";
</code>```

Background colors:

```<code>ANSI_BLACK_BACKGROUND = "\u001B[40m";
ANSI_RED_BACKGROUND = "\u001B[41m";
ANSI_GREEN_BACKGROUND = "\u001B[42m";
ANSI_YELLOW_BACKGROUND = "\u001B[43m";
ANSI_BLUE_BACKGROUND = "\u001B[44m";
ANSI_PURPLE_BACKGROUND = "\u001B[45m";
ANSI_CYAN_BACKGROUND = "\u001B[46m";
ANSI_WHITE_BACKGROUND = "\u001B[47m";
</code>```

These were made in Java but they should work just fine in Python
Also, this could just be my mistake but if i'm not mistaken command prompt don't allow for ansi colors but linux does just fine

Body:
The .txt format itself has no fonts/sizes/colors but you can use .rtf and if you are looking into printing colored text in console you can use ansi colors:

Regular colors:

ANSI_RESET = "\u001B[0m";
ANSI_BLACK = "\u001B[30m";
ANSI_RED = "\u001B[31m";
ANSI_GREEN = "\u001B[32m";
ANSI_YELLOW = "\u001B[33m";
ANSI_BLUE = "\u001B[34m";
ANSI_PURPLE = "\u001B[35m";
ANSI_CYAN = "\u001B[36m";
ANSI_WHITE = "\u001B[37m";

Background colors:

ANSI_BLACK_BACKGROUND = "\u001B[40m";
ANSI_RED_BACKGROUND = "\u001B[41m";
ANSI_GREEN_BACKGROUND = "\u001B[42m";
ANSI_YELLOW_BACKGROUND = "\u001B[43m";
ANSI_BLUE_BACKGROUND = "\u001B[44m";
ANSI_PURPLE_BACKGROUND = "\u001B[45m";
ANSI_CYAN_BACKGROUND = "\u001B[46m";
ANSI_WHITE_BACKGROUND = "\u001B[47m";

These were made in Java but they should work just fine in Python
Also, this could just be my mistake but if i'm not mistaken command prompt don't allow for ansi colors but linux does just fine


问:
Drawer not covering header in react-navigation
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

```<code>import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);
</code>```

Other problem is how should I add 2 drawers in my app at the same screen

答:
Is this the issue you're trying to resolve?

https://blog.callstack.io/android-drawer-statusbar-done-right-for-react-native-7e85f01fc099

Body:
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);

Other problem is how should I add 2 drawers in my app at the same screen


问:
pulling information from xml but wont display
Nothing is getting written to the TextView screen.

I'm not sure what I'm doing wrong here but this is my following code:

```<code><?xml version="1.0"?>
 <news>
  <article title="TITLE HERE" link="*.php?showtopic=118" date="DATE HERE"></article>
 </news>
</code>```

JAVA CODE:

```<code>try {
    //open an URL connection make GET to the server and
    URL url = new URL("http://.../m_news.xml");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    InputStream is = conn.getInputStream();

    //DocumentBuilderFactory, DocumentBuilder are used for
    //xml parsing
    DocumentBuilderFactory dbf = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    //using db (Document Builder) parse xml data and assign
    //it to Element
    Document document = db.parse(is);
    Element element = document.getDocumentElement();

    NodeList nodeList = element.getElementsByTagName("news");
    NodeList nodeList2 = element.getElementsByTagName("article");

        if (nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList2.getLength(); i++) {
                Element entry = (Element) nodeList.item(0);

                Element _rowE = (Element) entry.getElementsByTagName("article").item(i);
                Node _rowTITLE = _rowE.getAttributes().getNamedItem("title");
                Node _rowLINK = _rowE.getAttributes().getNamedItem("link");

                TextView textview = new TextView(this);
                textview.setMovementMethod(LinkMovementMethod.getInstance());
                String text = "<a href='"+_rowLINK.getNodeValue()+"'>"+_rowTITLE.getNodeValue()+"</a>";
                textview.setText(Html.fromHtml(text));
                setContentView(textview);
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

答:
You are instantiating TextViews and calling setContentView() with each of them... this is never going to work. At the very least you need to give some layout instructions (i.e. call setLayoutParams on each TextView) but I'm not even sure that will work without some kind of container object.

Try this. Create a simple layout called news.xml which has this:

```<code><LinearLayout
    android:id="@+id/newsItems"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
/>
</code>```

Then change your code to include the following:

```<code>setContentView(R.layout.news);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.newsItems);
...
for (int i = 0; i < nodeList2.getLength(); i++) {
    ...
    TextView textview = new TextView(this);
    textview.setLayoutParams(new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
    ...
    textview.setText(Html.fromHtml(text));
    linearLayout.addView(textview);
}
</code>```

Body:
Nothing is getting written to the TextView screen.

I'm not sure what I'm doing wrong here but this is my following code:

<?xml version="1.0"?>
 <news>

 </news>

JAVA CODE:

try {
    //open an URL connection make GET to the server and
    URL url = new URL("http://.../m_news.xml");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    InputStream is = conn.getInputStream();

    //DocumentBuilderFactory, DocumentBuilder are used for
    //xml parsing
    DocumentBuilderFactory dbf = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    //using db (Document Builder) parse xml data and assign
    //it to Element
    Document document = db.parse(is);
    Element element = document.getDocumentElement();

    NodeList nodeList = element.getElementsByTagName("news");
    NodeList nodeList2 = element.getElementsByTagName("article");

        if (nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList2.getLength(); i++) {
                Element entry = (Element) nodeList.item(0);

                Element _rowE = (Element) entry.getElementsByTagName("article").item(i);
                Node _rowTITLE = _rowE.getAttributes().getNamedItem("title");
                Node _rowLINK = _rowE.getAttributes().getNamedItem("link");

                TextView textview = new TextView(this);
                textview.setMovementMethod(LinkMovementMethod.getInstance());
                String text = ""+_rowTITLE.getNodeValue()+"";
                textview.setText(Html.fromHtml(text));
                setContentView(textview);
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

Body:
You are instantiating TextViews and calling setContentView() with each of them... this is never going to work. At the very least you need to give some layout instructions (i.e. call setLayoutParams on each TextView) but I'm not even sure that will work without some kind of container object.

Try this. Create a simple layout called news.xml which has this:

<LinearLayout
    android:id="@+id/newsItems"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
/>

Then change your code to include the following:

setContentView(R.layout.news);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.newsItems);
...
for (int i = 0; i < nodeList2.getLength(); i++) {
    ...
    TextView textview = new TextView(this);
    textview.setLayoutParams(new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
    ...
    textview.setText(Html.fromHtml(text));
    linearLayout.addView(textview);
}


问:
Is it possible to run java application on android through openjdk
Disambiguation first: question is not about developing or compiling with openjdk code that would be run on dalvik in production. It is about using oracle runtime on android environment.

I'm using java for running small desktop utility application. I have no experience in Android and iOS development and I'm curious to which extent my classic java skills may be transferred to the mobile field.

I've googled couple of methods for running java application on iOS embedding runtime inside the application package. Android has its own partially incompatible and slow java virtual machine. It still is better than nothing, but I'm curious if it is possible to run application on genuine hotspot(openjdk) virtual machine. Android as well as iOS have the ability to run native code. May this ability be exploited to use third-party (non dalvik) jre on android?

I'm not interested on google play market so restrictions from it, if there are any, may not be taken into account.

Rooting is also possible since I'm going to write tools for myself. I would prefer methods that would be easy for installing. Like putting some package files and editing couple of options. And not build my own android distribution like CyanogenMod.

答:
Apparently, see http://openjdk.java.net/projects/mobile/android.html

The instructions are slightly out of date, I managed to do some hacking and get it to build though. Not sure if it runs yet


问:
Does atomic variables guarantee memory visibility?
Small question about memory visibility.

CodeSample1:

```<code>class CustomLock {

    private boolean locked = false;

    public boolean lock() {
        if(!locked) {
            locked = true;
            return true;
        }
        return false;
    }
}
</code>```

This code is prone to bugs in a multi-threaded environment, first because of the "if-then-act" which is not atomic, and second because of potential memory visibility issues where for example threadA sets the field to true, but threadB that later wishes to read the field's value might not see that, and still see the value false.

The simplest solution is to use the synchronized keyword, as in CodeSample2.

CodeSample2:

```<code>class CustomLock {

    private boolean locked = false;

    public synchronized boolean lock() {
        if(!locked) {
            locked = true;
            return true;
        }
        return false;
    }
}
</code>```

Now what if I wish to use an atomic variable, and for the example, an AtomicBoolean (question applies to all atomic variables),

CodeSample3:

```<code>   public static class CustomLock {
    private AtomicBoolean locked = new AtomicBoolean(false);

    public boolean lock() {
        return locked.compareAndSet(false, true);
    }
}
</code>```

Better performance considerations aside, we can see that now we've implemented similar logic to the "if-then-act" from CodeSample1, using AtomicBoolean.
It doesn't really matter what the code does logically, the question I have is what if 2 threads invoke the lock() method in CodeSample3 right about the same time, while it's clear that any write operation to the field will now be done atomically, does the use of AtomicBoolean also guarantees memory visibility?

Sorry for the long story, just wanted to make sure I'm coming across as clear as possible, Thanks guys...

答:
the question I have is what if 2 threads invoke the lock() method in CodeSample3 right about the same time, while it's clear that any write operation to the field will now be done atomically, does the use of AtomicBoolean also guarantees memory visibility?

For AtomicBoolean to handle multiple operations from different threads at the same time it has to guarantee memory visibility.  It can make the guarantee because it wraps a volatile field.  It is the language semantics of the volatile which ensures that memory barriers are crossed so that multiple threads see the most up to date value and that any updates will be published to main memory.

Btw, your lock(...) method should ready be tryLock(...) because it might not get the lock.

Body:
Small question about memory visibility.

CodeSample1:

class CustomLock {

    private boolean locked = false;

    public boolean lock() {
        if(!locked) {
            locked = true;
            return true;
        }
        return false;
    }
}

This code is prone to bugs in a multi-threaded environment, first because of the "if-then-act" which is not atomic, and second because of potential memory visibility issues where for example threadA sets the field to true, but threadB that later wishes to read the field's value might not see that, and still see the value false.

The simplest solution is to use the synchronized keyword, as in CodeSample2.

CodeSample2:

class CustomLock {

    private boolean locked = false;

    public synchronized boolean lock() {
        if(!locked) {
            locked = true;
            return true;
        }
        return false;
    }
}

Now what if I wish to use an atomic variable, and for the example, an AtomicBoolean (question applies to all atomic variables),

CodeSample3:

   public static class CustomLock {
    private AtomicBoolean locked = new AtomicBoolean(false);

    public boolean lock() {
        return locked.compareAndSet(false, true);
    }
}

Better performance considerations aside, we can see that now we've implemented similar logic to the "if-then-act" from CodeSample1, using AtomicBoolean.
It doesn't really matter what the code does logically, the question I have is what if 2 threads invoke the lock() method in CodeSample3 right about the same time, while it's clear that any write operation to the field will now be done atomically, does the use of AtomicBoolean also guarantees memory visibility?

Sorry for the long story, just wanted to make sure I'm coming across as clear as possible, Thanks guys...


问:
Waiting for PouchDB get to get a synced version from the server
I am using PouchDB to sync a database between a device and a server.

When installing my App on a new device I need to pull down the user's settings document from the server. If I do the following on a new device when the App has previously been run on another device and created the user settings:

```<code>var _DB = new PouchDB(localDBName);
_DB.sync(realRemoteDB, options);
_DB.get(userSettingsDocumentName);
</code>```

The _DB.get says the document doesn't exist. If I wait long enough the sync works and the server docs are loaded locally and the .get works. How can I handle this other than putting in a long timeout?

答:
PouchDB functions are mostly asynchronous. This means that when you fetch the document, the sync might not be complete yet.

Here's how you should write it with promises:

```<code>var _DB = new PouchDB(localDBName);
_DB.sync(realRemoteDB, options).on('complete',function(info){
    //Sync is complete
    return _DB.get(userSettingsDocumentName);
}).then(function(doc){
    //Here you will have the document

}).catch(function(err){
    //An error occured
})
</code>```

Body:
I am using PouchDB to sync a database between a device and a server.

When installing my App on a new device I need to pull down the user's settings document from the server. If I do the following on a new device when the App has previously been run on another device and created the user settings:

var _DB = new PouchDB(localDBName);
_DB.sync(realRemoteDB, options);
_DB.get(userSettingsDocumentName);

The _DB.get says the document doesn't exist. If I wait long enough the sync works and the server docs are loaded locally and the .get works. How can I handle this other than putting in a long timeout?

Body:
PouchDB functions are mostly asynchronous. This means that when you fetch the document, the sync might not be complete yet.

Here's how you should write it with promises:

var _DB = new PouchDB(localDBName);
_DB.sync(realRemoteDB, options).on('complete',function(info){
    //Sync is complete
    return _DB.get(userSettingsDocumentName);
}).then(function(doc){
    //Here you will have the document

}).catch(function(err){
    //An error occured
})


问:
Getting list functions in file that imported a module
This is for a project I am working on to help my own workflow, and nothing that is for production. So I understand that what I am doing is probably definitely not the right thing to do, but I am curious if it is possible anyways.

I have some code like this:

A.py:

```<code>from B import *

def f1():
    ...

def f2():
    ...

...
</code>```

Is there any way for module B, when imported, to get a list of the functions defined in the importer, A.py?

I thought about using the inspect module, to inspect the call stack. But I was unsure where the entry point would be, I assume it would be in the global scope of B.py. I am also unsure what the call stack looks like when importing a module.

Any help would be appreciated.

Thanks!

答:
If you know what module you are going to import B.py in then you could have something like this:

A.py

```<code>import B

def f1():
    return 1

def f2():
    return 1

def f3():
    return 1

if __name__=="__main__":
    print temp.allF()
</code>```

B.py

```<code>import inspect, A

def allF():
    return inspect.getmembers(A, inspect.isfunction)
</code>```

When you run A.py it will give you a list of functions.
I'm not sure if there is a way to access the script which imports a given module, but if this is possible then you could change B.py slightly to use this.

Body:
This is for a project I am working on to help my own workflow, and nothing that is for production. So I understand that what I am doing is probably definitely not the right thing to do, but I am curious if it is possible anyways.

I have some code like this:

A.py:

from B import *

def f1():
    ...

def f2():
    ...

...

Is there any way for module B, when imported, to get a list of the functions defined in the importer, A.py?

I thought about using the inspect module, to inspect the call stack. But I was unsure where the entry point would be, I assume it would be in the global scope of B.py. I am also unsure what the call stack looks like when importing a module.

Any help would be appreciated.

Thanks!

Body:
If you know what module you are going to import B.py in then you could have something like this:

A.py

import B

def f1():
    return 1

def f2():
    return 1

def f3():
    return 1

if __name__=="__main__":
    print temp.allF()

B.py

import inspect, A

def allF():
    return inspect.getmembers(A, inspect.isfunction)

When you run A.py it will give you a list of functions.
I'm not sure if there is a way to access the script which imports a given module, but if this is possible then you could change B.py slightly to use this.


问:
I am getting UnboundLocalError because I have the same variable inside functions and in main code
I am having a nightmare, I have created a code in Python to simulate a virtual queue.

The code is simplistic but should work, except for the reoccurring 'UnboundLocalError' I keep getting.

I think the issue is having 'aList' as a parameter for functions and having the variable in the main code as well as within def functions.

The code isn't that long and can be found on this link.

Please can somebody help? I've tried adding 'global aList' but it didn't solve it.

Thanks very much for any assistance.

Snapshot of code below :

```<code>def aRemove(aList):
    newlist = []
    for i in range(1,len(aList)):
        newlist.append(aList[i])
    aList = newlist
    return (aList)

user_request()
aList = ["mark","jon","peter"]
aList = (aRemove(aList))
print(aList)
</code>```

答:
Problem is that aList does not have an assigned value yet. I personally would just declare

```<code>aList = []
</code>```

in the very beggining of your code, but it will work as long as it is before the user_request declaration. Although you could pass it along to your function as well, as per Satish's solution.

Another issue you have is in the remove function.

```<code>for i in range(1,len(aList)):
</code>```

should be changed to

```<code>for i in range(1,len(aList)-1):
</code>```

Otherwise you're trying to append an element that does not exist.
Although since it's python you could just do this:

```<code>aList = aList[1:]
</code>```

Body:
I am having a nightmare, I have created a code in Python to simulate a virtual queue.

The code is simplistic but should work, except for the reoccurring 'UnboundLocalError' I keep getting.

I think the issue is having 'aList' as a parameter for functions and having the variable in the main code as well as within def functions.

The code isn't that long and can be found on this link.

Please can somebody help? I've tried adding 'global aList' but it didn't solve it.

Thanks very much for any assistance.

Snapshot of code below :

def aRemove(aList):
    newlist = []
    for i in range(1,len(aList)):
        newlist.append(aList[i])
    aList = newlist
    return (aList)

user_request()
aList = ["mark","jon","peter"]
aList = (aRemove(aList))
print(aList)

Body:
Problem is that aList does not have an assigned value yet. I personally would just declare

aList = []

in the very beggining of your code, but it will work as long as it is before the user_request declaration. Although you could pass it along to your function as well, as per Satish's solution.

Another issue you have is in the remove function.

for i in range(1,len(aList)):

should be changed to

for i in range(1,len(aList)-1):

Otherwise you're trying to append an element that does not exist.
Although since it's python you could just do this:

aList = aList[1:]


问:
Compare and reduce complex array of objects
I have a ``dataset which is an array of objects for some items in a database that has the details of how long it will take in estimatedDays for a specific item to be shipped:

```<code>items : [
    {
    id: '1'
    shippingMethods: [
        {
        id: 'STANDARD',
        estimatedDays: 3,
        },
        {
        id: 'TWODAY',
        estimatedDays: 2,
        },
        {
        id: 'NEXTDAY',
        estimatedDays: 1,
        },
    ]
    },
    {
    id: '2'
    // same shipping data as above but standard shipping will take 4 estimatedDays
    },
    {
    id: '3'
    // same shipping data as above but TWODAY shipping will take 3 estimatedDays
    },
]
</code>```

I am wondering if there is a reduce function that could compare each shippingMethod.id in each item and return a new array back only where shippingMethod.estimatedDays is greatest compared to all items.

So the end array would be an array of objects with (in this case) 3 shipping methods: STANDARD, TWODAY, and NEXTDAY.

答:
Here you go with the reduce method,

reduce

var items = [
    {
    id: '1',
    shippingMethods: [
        {
        id: 'STANDARD',
        estimatedDays: 3
        },
        {
        id: 'TWODAY',
        estimatedDays: 2
        },
        {
        id: 'NEXTDAY',
        estimatedDays: 1
        },
    ]
    },
    {
    id: '2',
    shippingMethods: [
        {
        id: 'STANDARD',
        estimatedDays: 4
        },
        {
        id: 'TWODAY',
        estimatedDays: 2
        },
        {
        id: 'NEXTDAY',
        estimatedDays: 1
        },
    ]
    },
    {
    id: '3',
    shippingMethods: [
        {
        id: 'STANDARD',
        estimatedDays: 3
        },
        {
        id: 'TWODAY',
        estimatedDays: 3
        },
        {
        id: 'NEXTDAY',
        estimatedDays: 1
        },
    ]
    },
];

var outItems = items.reduce(function(accu, curr){
   if(curr.shippingMethods) {
      if(accu.length > 0) {
         for(var i = 0; i < curr.shippingMethods.length; i++) {
            var current = curr.shippingMethods[i];
            if(accu[i].id === current.id && accu[i].estimatedDays < current.estimatedDays) {
               accu[i] = current;
            }
         }
      } else {
         accu = curr.shippingMethods;
      }
   }

   return accu;
}, []);

console.log(outItems);```

Body:
I have a ``dataset which is an array of objects for some items in a database that has the details of how long it will take in estimatedDays for a specific item to be shipped:

items : [
    {
    id: '1'
    shippingMethods: [
        {
        id: 'STANDARD',
        estimatedDays: 3,
        },
        {
        id: 'TWODAY',
        estimatedDays: 2,
        },
        {
        id: 'NEXTDAY',
        estimatedDays: 1,
        },
    ]
    },
    {
    id: '2'
    // same shipping data as above but standard shipping will take 4 estimatedDays
    },
    {
    id: '3'
    // same shipping data as above but TWODAY shipping will take 3 estimatedDays
    },
]

I am wondering if there is a reduce function that could compare each shippingMethod.id in each item and return a new array back only where shippingMethod.estimatedDays is greatest compared to all items.

So the end array would be an array of objects with (in this case) 3 shipping methods: STANDARD, TWODAY, and NEXTDAY.


问:
2 single digit lottery game, can't find where I went wrong
I am trying to design a lottery game where you choose 2 single digit numbers and they are compared to random numbers. I am going off of a code example given to me by my professor and have tried to tweak it to use it. I am stuck in figuring out how to get it to run or what I have wrong.</p>

```<code>import java.util.Scanner;

public class Lottery {

    private static Scanner input;

    public static void main(String[] args) {
        String lottery = "" + (int) (Math.random() * 10);
        String lottery1 = "" + (int) (Math.random() * 10);

        input = new Scanner(System.in);
        System.out.print("Enter your first single digit guess: ");
        String guess = input.nextLine();
        System.out.print("Enter your second single digit guess: ");
        String guess1 = input.nextLine();

        int lotteryDigit1 = lottery.charAt(0);
        int lottery1Digit1 = lottery.charAt(1);

        int guessDigit1 = guess.charAt(0);
        int guess1Digit1 = guess1.charAt(1);

        System.out.println("The lottery number is " + lottery);

        if (guess.equals(lottery))
            System.out.println("Exact match: you win $10,000");
        else if (guess1Digit1 == lotteryDigit1
                && guessDigit1 == lottery1Digit1)
            System.out.println("Match all digits: you win $3,000");
        else if (guessDigit1 == lotteryDigit1
                || guessDigit1 == lottery1Digit1
                || guess1Digit1 == lotteryDigit1
                || guess1Digit1 == lottery1Digit1)
            System.out.println("Match one digit: you win $1,000");
        else
            System.out.println("Sorry, no matches");
    }
}
</code>```

答:
I can only call this method of handling the functions of this program "interesting".  Nonetheless, you need to add the following changes:

```<code>import java.util.Scanner;

public class Lottery {

   private static Scanner input;

   public static void main(String[] args) {
      String lottery = "" + ((int) (Math.random() * 10)) + ((int) (Math.random() * 10));

      input = new Scanner(System.in);
      System.out.print("Enter your two digit guess: ");
      String guess = input.nextLine();

      int lotteryDigit1 = lottery.charAt(0);
      int lottery1Digit1 = lottery.charAt(1);

      int guessDigit1 = guess.charAt(0);
      int guess1Digit1 = guess.charAt(1);

      System.out.println("The lottery number is " + lottery);

      if (guess.equals(lottery))
         System.out.println("Exact match: you win $10,000");
      else if (guess1Digit1 == lotteryDigit1
             && guessDigit1 == lottery1Digit1)
         System.out.println("Match all digits: you win $3,000");
      else if (guessDigit1 == lotteryDigit1
           || guessDigit1 == lottery1Digit1
           || guess1Digit1 == lotteryDigit1
           || guess1Digit1 == lottery1Digit1)
         System.out.println("Match one digit: you win $1,000");
      else
         System.out.println("Sorry, no matches");
   }
}
</code>```

The issue with the original program is that it forgot to condense lottery and lottery1 into lottery, which I added, and it opted to take the digits separately, which was highly inefficient.  Now, both are two digit numbers, and the rest of the system stays intact.  The code is now simplified for its purposes.

Body:
I am trying to design a lottery game where you choose 2 single digit numbers and they are compared to random numbers. I am going off of a code example given to me by my professor and have tried to tweak it to use it. I am stuck in figuring out how to get it to run or what I have wrong.

import java.util.Scanner;

public class Lottery {

    private static Scanner input;

    public static void main(String[] args) {
        String lottery = "" + (int) (Math.random() * 10);
        String lottery1 = "" + (int) (Math.random() * 10);

        input = new Scanner(System.in);
        System.out.print("Enter your first single digit guess: ");
        String guess = input.nextLine();
        System.out.print("Enter your second single digit guess: ");
        String guess1 = input.nextLine();

        int lotteryDigit1 = lottery.charAt(0);
        int lottery1Digit1 = lottery.charAt(1);

        int guessDigit1 = guess.charAt(0);
        int guess1Digit1 = guess1.charAt(1);

        System.out.println("The lottery number is " + lottery);

        if (guess.equals(lottery))
            System.out.println("Exact match: you win $10,000");
        else if (guess1Digit1 == lotteryDigit1
                && guessDigit1 == lottery1Digit1)
            System.out.println("Match all digits: you win $3,000");
        else if (guessDigit1 == lotteryDigit1
                || guessDigit1 == lottery1Digit1
                || guess1Digit1 == lotteryDigit1
                || guess1Digit1 == lottery1Digit1)
            System.out.println("Match one digit: you win $1,000");
        else
            System.out.println("Sorry, no matches");
    }
}

Body:
I can only call this method of handling the functions of this program "interesting".  Nonetheless, you need to add the following changes:

import java.util.Scanner;

public class Lottery {

   private static Scanner input;

   public static void main(String[] args) {
      String lottery = "" + ((int) (Math.random() * 10)) + ((int) (Math.random() * 10));

      input = new Scanner(System.in);
      System.out.print("Enter your two digit guess: ");
      String guess = input.nextLine();

      int lotteryDigit1 = lottery.charAt(0);
      int lottery1Digit1 = lottery.charAt(1);

      int guessDigit1 = guess.charAt(0);
      int guess1Digit1 = guess.charAt(1);

      System.out.println("The lottery number is " + lottery);

      if (guess.equals(lottery))
         System.out.println("Exact match: you win $10,000");
      else if (guess1Digit1 == lotteryDigit1
             && guessDigit1 == lottery1Digit1)
         System.out.println("Match all digits: you win $3,000");
      else if (guessDigit1 == lotteryDigit1
           || guessDigit1 == lottery1Digit1
           || guess1Digit1 == lotteryDigit1
           || guess1Digit1 == lottery1Digit1)
         System.out.println("Match one digit: you win $1,000");
      else
         System.out.println("Sorry, no matches");
   }
}

The issue with the original program is that it forgot to condense lottery and lottery1 into lottery, which I added, and it opted to take the digits separately, which was highly inefficient.  Now, both are two digit numbers, and the rest of the system stays intact.  The code is now simplified for its purposes.


问:
Setup for ASP.NET web application
We have some ASP.NET web application which used in 2 ways:

enterprise solution (msi-like installer)

cloud solution (use same installer)

Currently we use home-grown installer, but consider if we can replace it with something more convenient and suitable for CI/CD development cycle.

What technologies/products can be used? Currently I think about webdeploy, but not sure how it can be applied for enterprise setup...

答:
Recently I saw a vendor offering customers who wanted on-premises deployments the same Docker image that they use for cloud deployments. Seemed like a good, clean, solution.

Another option is nuget packages - host your own repository. Then deploy with a tool like Octopus Deploy. I'm not terribly familiar with it, but both solutions look to be easy after an initial hump in setup.

Title: Setup for ASP.NET web application


问:
Different results for SHA-1 hashing between Groovy and Python
This question is related to my query titled "Create WS security headers for REST web service in SoapUI Pro". However that one is different as I raised that because I couldn't get the script to work at all, I came up with a solution for that but it only works about 66% of the time.

I have noticed that the code that I use to hash the string sometimes produces different results when compared to a python script hashing the same input.

Below is my groovy code that hashes an input value.

```<code>MessageDigest cript2 = MessageDigest.getInstance("SHA-1");
        cript2.update(nonce.getBytes("ASCII"));
        PasswordDigest = new String(cript2.digest());
</code>```

If I run it with the input nonce value 201703281329 it produces the below
ë±ËËÐùìÓ0¼ÕM�¹,óßP‹

If I use the same input value using the Python code below then it produces ëﾱËËÐùìÓ0ﾼÕMﾏﾹ,óßPﾋ

```<code>digest = sha.new(nonce).digest()
</code>```

However if I run the groovy and python scripts with input value 201703281350 then they both produce ..

iàvè©®É¹m:F Ë Â¾

Could someone tell me why I am seeing differences for some input values and not others and how I can modify my groovy code so that it produces same values as Python code?

much appreciated.

答:
If you compare the bytes returned by the digest method of both languages, you'll find that they are indeed the same. The reason is that some combinations of bytes do not result in printable Java Strings.

To compare them:

```<code>def hexString = PasswordDigest.collect { String.format('%02x', it) }.join()
</code>```

Compare to the output of sha.hexdigest():

```<code>def hexString = sha.new(nonce).hexdigest()
</code>```

Both should produce ebb1cbcbd0f9ecd330bcd51b4d8fb92cf3df508b

Edited

Perhaps I didn't make it clear that passwordDigest should not be converted to a String. Below is the complete groovy and python code. Both programs produce the same output:

Groovy:

```<code>import java.security.*

String nonce = '201703281329'
MessageDigest digest = MessageDigest.getInstance("SHA-1")
digest.update(nonce.getBytes("ASCII"))

byte[] passwordDigest = digest.digest() // byte[], not string

String hexString = passwordDigest.collect { String.format('%02x', it) }.join()

println hexString
</code>```

Python:

```<code>import sha

nonce = '201703281329'
sha.new(nonce).hexdigest()
print sha.new(nonce).hexdigest()
</code>```

The output of both: ebb1cbcbd0f9ecd330bcd51b4d8fb92cf3df508b.

Body:
This question is related to my query titled "Create WS security headers for REST web service in SoapUI Pro". However that one is different as I raised that because I couldn't get the script to work at all, I came up with a solution for that but it only works about 66% of the time.

I have noticed that the code that I use to hash the string sometimes produces different results when compared to a python script hashing the same input.

Below is my groovy code that hashes an input value.

MessageDigest cript2 = MessageDigest.getInstance("SHA-1");
        cript2.update(nonce.getBytes("ASCII"));
        PasswordDigest = new String(cript2.digest());

If I run it with the input nonce value 201703281329 it produces the below
ë±ËËÐùìÓ0¼ÕM�¹,óßP‹

If I use the same input value using the Python code below then it produces ëﾱËËÐùìÓ0ﾼÕMﾏﾹ,óßPﾋ

digest = sha.new(nonce).digest()

However if I run the groovy and python scripts with input value 201703281350 then they both produce ..

iàvè©®É¹m:F Ë Â¾

Could someone tell me why I am seeing differences for some input values and not others and how I can modify my groovy code so that it produces same values as Python code?

much appreciated.

Body:
If you compare the bytes returned by the digest method of both languages, you'll find that they are indeed the same. The reason is that some combinations of bytes do not result in printable Java Strings.

To compare them:

def hexString = PasswordDigest.collect { String.format('%02x', it) }.join()

Compare to the output of sha.hexdigest():

def hexString = sha.new(nonce).hexdigest()

Both should produce ebb1cbcbd0f9ecd330bcd51b4d8fb92cf3df508b

Edited

Perhaps I didn't make it clear that passwordDigest should not be converted to a String. Below is the complete groovy and python code. Both programs produce the same output:

Groovy:

import java.security.*

String nonce = '201703281329'
MessageDigest digest = MessageDigest.getInstance("SHA-1")
digest.update(nonce.getBytes("ASCII"))

byte[] passwordDigest = digest.digest() // byte[], not string

String hexString = passwordDigest.collect { String.format('%02x', it) }.join()

println hexString

Python:

import sha

nonce = '201703281329'
sha.new(nonce).hexdigest()
print sha.new(nonce).hexdigest()

The output of both: ebb1cbcbd0f9ecd330bcd51b4d8fb92cf3df508b.


问:
If a project has 100% unit test coverage, are integration tests still needed?
If a project has 100% unit test coverage, are integration tests still needed?

I have never worked on a project with 100% unit test coverage, but I'm wondering if your project obtains this (or in the 90%), was your experience that you still needed integration tests?  (did you need less?)

I ask because integration tests seem to suck.   They are often slow, fragile (break easily), opaque (when broken someone has to dive through all the layers to find out what is wrong) and are causing our project to slow way down...   I'm beginning to think that having only unit tests (and perhaps a small handful of smoke tests) is the way to go.

In the long run, it seems like integration tests (in my experience) cost more than they save.

Thanks for your consideration.

答:
I've not really seen an answer that covers these considerations. Now, I'm speaking from a holistic systems perspective, not form a SW development perspective, but...
Integration is basically the process of combining lower level products into a higher level product. Each level has its own set of requirements to comply with. Although it is possible that some requirements are the same, the overall requirements set will be different for different levels. This means that test objectives are different at different levels.
Also, the environment of the environment of the higher level product tends to be different from that of the lower level product (e.g. SW module testing may occur on a desktop environment, whereas a complete loadable SW item may be tested when loaded in its HW component).
Furthermore, lower level component developers may not have the same understanding of the `requirements and design as the higher level product developers, so integration testing also validates to a certain extend the lower level product development.</p>

OwnerDisplayName: Bob Herrmann


问:
Start a new text message from a link in a web browser
I know I can open an external program like Spotify with a link, but I'm wondering if it's possible to open the native text message app with a pre-populated the message the same way that the native share sheet does.

For example, this will open spotify:

Test link

答:
invoke intent for SMS app

```<code>Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", phoneNumber);
smsIntent.putExtra("sms_body", text);
context.startActivity(Intent.createChooser(smsIntent, "SMS:"));
</code>```

also you can check this answer for more options.

Body:
invoke intent for SMS app

Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", phoneNumber);
smsIntent.putExtra("sms_body", text);
context.startActivity(Intent.createChooser(smsIntent, "SMS:"));

also you can check this answer for more options.


问:
Does VS2010 or .NET 4.0 have any new tooling support for Accessibility?
What kind of tooling support or helpers does VS2010 or .NET 4.0 provide to developers in the way of accessibility?

Anything new for creating 508-compliant markup?

Anything new in the way of supporting WAI-ARIA specific attributes on AJAX-updatable elements?

答:
here are some links, if you have not already seen them:

ASP.NET Controls and Accessibility

Accessibility in Visual Studio 2010 and ASP.NET 4


问:
Run method from class in for loop
I am new so I am sorry for the confusion between TypeScript and JavaScript. I am suppose to be writing in TypeScript currently. I am trying to run the method in my class through the for loop at the end of the code. I have my basic structure from Mozilla Developer Network so I am not sure if that is correct, but from what I can tell it is. Either way, like I said I want to run my method through the loop below. I believe I need to use dot notation but I cannot find the error. Any help would be greatly appreciated. Thank you.

TypeScript/JavaScript

```<code>class Employee {
    name:string;
    age:number;
    timeInJob:number;
    stillEmployed:boolean;
  constructor(name:string, age:number, timeInJob:number, stillEmployed:boolean){
    this.name = name;
    this.age = age;
    this.timeInJob = timeInJob;
    this.stillEmployed = stillEmployed;
  }
  get extraVacay(){
    return this.vacay();
  }
  vacay(){
    return this.age + this.timeInJob;
  }
};

let myEmployees = [];

let justin = new Employee('Justin', 25, 3, true);
myEmployees.push(justin);
let derek = new Employee('Derek', 22, 8, true);
myEmployees.push(derek);
let taylor = new Employee('Taylor', 24, 9, true);
myEmployees.push(taylor);
let eli = new Employee('Eli', 29, 10, false);
myEmployees.push(eli);
let tyler = new Employee('Tyler', 25, 7, false);
myEmployees.push(tyler);

console.log(myEmployees);
console.log(justin.extraVacay);

for (i = 0; i < myEmployees.length; i++){
  let magicNumber = Employee.extraVacay();
  console.log(magicNumber);
}
</code>```

答:
You have two issues:

You're not getting access to the employee in your array properly.

You are not calling the property getter correctly:

Try this:

```<code>for (i = 0; i < myEmployees.length; i++){
  const employee = myEmployees[i];
  let magicNumber = employee.extraVacay;
  console.log(magicNumber);
}
</code>```

Title: Run method from class in for loop

Body:
I am new so I am sorry for the confusion between TypeScript and JavaScript. I am suppose to be writing in TypeScript currently. I am trying to run the method in my class through the for loop at the end of the code. I have my basic structure from Mozilla Developer Network so I am not sure if that is correct, but from what I can tell it is. Either way, like I said I want to run my method through the loop below. I believe I need to use dot notation but I cannot find the error. Any help would be greatly appreciated. Thank you.

TypeScript/JavaScript

class Employee {
    name:string;
    age:number;
    timeInJob:number;
    stillEmployed:boolean;
  constructor(name:string, age:number, timeInJob:number, stillEmployed:boolean){
    this.name = name;
    this.age = age;
    this.timeInJob = timeInJob;
    this.stillEmployed = stillEmployed;
  }
  get extraVacay(){
    return this.vacay();
  }
  vacay(){
    return this.age + this.timeInJob;
  }
};

let myEmployees = [];

let justin = new Employee('Justin', 25, 3, true);
myEmployees.push(justin);
let derek = new Employee('Derek', 22, 8, true);
myEmployees.push(derek);
let taylor = new Employee('Taylor', 24, 9, true);
myEmployees.push(taylor);
let eli = new Employee('Eli', 29, 10, false);
myEmployees.push(eli);
let tyler = new Employee('Tyler', 25, 7, false);
myEmployees.push(tyler);

console.log(myEmployees);
console.log(justin.extraVacay);

for (i = 0; i < myEmployees.length; i++){
  let magicNumber = Employee.extraVacay();
  console.log(magicNumber);
}

Body:
You have two issues:

You're not getting access to the employee in your array properly.

You are not calling the property getter correctly:

Try this:

for (i = 0; i < myEmployees.length; i++){
  const employee = myEmployees[i];
  let magicNumber = employee.extraVacay;
  console.log(magicNumber);
}


问:
How to parse to string to multidimensional array (regex?)
I need to pass the data to an array by blocks, how can I make this? Do I need to use regex? My script gives me errors because I can not separate it as I wish. Does anyone have any ideas?

Data:

```<code>~0
11111111
~1
222222222
~2
3333333333

        ~end
~0
aaaaaaaaaaa
~1
bbbbbbbbbb
~2
cccccccccc
~3
ddddddddddd

        ~end

~0
yyyyyyyyyyy
xxxxxxxx
ffffffffff
~1
rrrrrrrrrrrr
        ~end
</code>```

I need it like this:

```<code>Array (
  [0] => Array
                (
                    [0] => 11111111

                    [1] => 222222222

                    [2] => 3333333333

                )

        ),

  [1] => Array
                (
                    [0] => aaaaaaaaaaa

                    [1] => bbbbbbbbbb

                    [2] => cccccccccc

                    [3] => ddddddddddd
                )

        ),

  [2] => Array
                  (
                      [0] => yyyyyyyyyyy
xxxxxxxx
ffffffffff

                      [1] => rrrrrrrrrrrr

                  )

          ),

)
</code>```

My code (Fail):

```<code>$texto = "~0
11111111
~1
222222222
~2
3333333333

        ~end
~0
aaaaaaaaaaa
~1
bbbbbbbbbb
~2
cccccccccc
~3
ddddddddddd

        ~end

~0
yyyyyyyyyyy
xxxxxxxx
ffffffffff
~1
rrrrrrrrrrrr
        ~end";

preg_match_all("/(?ms)^~0.*?~end/", $texto, $coincidencias);

foreach ( $coincidencias[0] as $bloque ){
    preg_match_all("/\~.*\n/", $bloque, $sub_bloques);
    $hola[] = $sub_bloques;
}
</code>```

答:
Because you want to have your sub-blocks separated into blocks in your output array, there needs to be two-steps in the method.  The reason is that your sub-blocks have differing capture group counts and regex will not permit this variability.

Code:

```<code>// This delivers the sub-blocks in their relative blocks as requested in the OP
foreach (preg_split('/\s+~end\s*/',$texto) as $bloque) {
    if(preg_match_all('/(?:\~\d+\s+)\K.+?(?:\s+\S+)*?(?=\s+\~|$)/',$bloque,$sub_bloques)){
        $hola[]=$sub_bloques[0];
    }
}
var_export($hola);
</code>```

Output *reformatted/condensed to save space on this page (View Demo):

```<code>array(
    array('11111111','222222222','3333333333'),
    array('aaaaaaaaaaa','bbbbbbbbbb','cccccccccc','ddddddddddd'),
    array('yyyyyyyyyyy
xxxxxxxx
ffffffffff','rrrrrrrrrrrr')
)
</code>```

Alternatively, if you want to have all sub-blocks listed in a 1-dim array (not divided by blocks) the output array can be built in one step:

```<code>if(preg_match_all("/(?:\~\d+\s*)\K.+?(?:\s+\S+)*?(?=\s+\~)/s", $texto, $coincidencias)){
    var_export($coincidencias[0]);
}
</code>```

1-dim output:

```<code>array (
    0 => '11111111',
    1 => '222222222',
    2 => '3333333333',
    3 => 'aaaaaaaaaaa',
    4 => 'bbbbbbbbbb',
    5 => 'cccccccccc',
    6 => 'ddddddddddd',
    7 => 'yyyyyyyyyyy
xxxxxxxx
ffffffffff',
    8 => 'rrrrrrrrrrrr',
)
</code>```

Body:
I need to pass the data to an array by blocks, how can I make this? Do I need to use regex? My script gives me errors because I can not separate it as I wish. Does anyone have any ideas?

Data:

~0
11111111
~1
222222222
~2
3333333333

        ~end
~0
aaaaaaaaaaa
~1
bbbbbbbbbb
~2
cccccccccc
~3
ddddddddddd

        ~end

~0
yyyyyyyyyyy
xxxxxxxx
ffffffffff
~1
rrrrrrrrrrrr
        ~end

I need it like this:

Array (
  [0] => Array
                (
                    [0] => 11111111

                    [1] => 222222222

                    [2] => 3333333333

                )

        ),

  [1] => Array
                (
                    [0] => aaaaaaaaaaa

                    [1] => bbbbbbbbbb

                    [2] => cccccccccc

                    [3] => ddddddddddd
                )

        ),

  [2] => Array
                  (
                      [0] => yyyyyyyyyyy
xxxxxxxx
ffffffffff

                      [1] => rrrrrrrrrrrr

                  )

          ),

)

My code (Fail):

$texto = "~0
11111111
~1
222222222
~2
3333333333

        ~end
~0
aaaaaaaaaaa
~1
bbbbbbbbbb
~2
cccccccccc
~3
ddddddddddd

        ~end

~0
yyyyyyyyyyy
xxxxxxxx
ffffffffff
~1
rrrrrrrrrrrr
        ~end";

preg_match_all("/(?ms)^~0.*?~end/", $texto, $coincidencias);

foreach ( $coincidencias[0] as $bloque ){
    preg_match_all("/\~.*\n/", $bloque, $sub_bloques);
    $hola[] = $sub_bloques;
}

Body:
Because you want to have your sub-blocks separated into blocks in your output array, there needs to be two-steps in the method.  The reason is that your sub-blocks have differing capture group counts and regex will not permit this variability.

Code:

// This delivers the sub-blocks in their relative blocks as requested in the OP
foreach (preg_split('/\s+~end\s*/',$texto) as $bloque) {
    if(preg_match_all('/(?:\~\d+\s+)\K.+?(?:\s+\S+)*?(?=\s+\~|$)/',$bloque,$sub_bloques)){
        $hola[]=$sub_bloques[0];
    }
}
var_export($hola);

Output *reformatted/condensed to save space on this page (View Demo):

array(
    array('11111111','222222222','3333333333'),
    array('aaaaaaaaaaa','bbbbbbbbbb','cccccccccc','ddddddddddd'),
    array('yyyyyyyyyyy
xxxxxxxx
ffffffffff','rrrrrrrrrrrr')
)

Alternatively, if you want to have all sub-blocks listed in a 1-dim array (not divided by blocks) the output array can be built in one step:

if(preg_match_all("/(?:\~\d+\s*)\K.+?(?:\s+\S+)*?(?=\s+\~)/s", $texto, $coincidencias)){
    var_export($coincidencias[0]);
}

1-dim output:

array (
    0 => '11111111',
    1 => '222222222',
    2 => '3333333333',
    3 => 'aaaaaaaaaaa',
    4 => 'bbbbbbbbbb',
    5 => 'cccccccccc',
    6 => 'ddddddddddd',
    7 => 'yyyyyyyyyyy
xxxxxxxx
ffffffffff',
    8 => 'rrrrrrrrrrrr',
)


问:
Avoid significant amounts of packages and binaries when using Roslyn with Nuget
I'm trying to make use of Roslyn in my application. I added the NuGet package for that (Microsoft.CodeAnalysis.CSharp). It turns out that this package depends on many others:

Most of them seem unused on the .NET Framework (e.g. System.Runtime which provides types such as Int32).

There is an incredible contrast between the size of those packages and what is actually being used. A lot of the data appear to be translations:

(I'm not saying someone did a bad job here. I'm not competent enough to make that determination. I just want to find out how to deal with this, see below.)

It seems like a bad idea to check all of that in to source control. If I update those packages every few months then then repository will bloat by gigabytes from all those files over time. I'm also worried about IDE speed and frankly about confusing myself in this huge sea of packages.

Package restore cannot be used due to security concerns and reliance on another company's ongoing service for our source code to be able to build. By "other company" I mean that I need to trust Microsoft and the package authors to be available at all times, not send me a virus and not remove old versions causing my app to break. If I download just once, or every few month, the exposure is greatly reduced.

How would I best minimize the source control impact of using Roslyn?

I really hope I will be able to put the packages into source control. I hope there is a way to remove all the packages I don't need and restrict them to what ends up in the bin folder.

答:
You shouldn't check the packages folder to source control; that'll make you sad. It sounds like your real problem is concern of the reliability of nuget.org or packages existing. If that's a concern you might want to consider just storing the .nupkg files in a place where you control and can keep them around. You might want to take a look at these instructions of how you could run your own server, which can be as low tech as "have a network drive".

You could also check in the .nupkg files and then use that as your feed, which would at least reduce the number of files you need to manage. At least those will be smaller and compressed vs. the uncompressed folders.


问:
Updateing aws apigateway binaryMediaTypes
I'm attempting to configure and update the binary support options of an AWS API Gateway. I can do this through the web UI without issue, but I would like to script this.

Using the CLI Command Reference pages:
http://docs.aws.amazon.com/cli/latest/reference/apigateway/get-rest-api.html
http://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html

Able to issue a get-rest-api command just fine:

```<code>C:\> aws apigateway get-rest-api --rest-api-id [ID]

{
  "id": "[ID]",
    "createdDate": 1490723884,
    "name": "testbinarymediatypes"
}
</code>```

But when attempting to update the binaryMediaTypes:

```<code>PS C:\> aws apigateway update-rest-api --rest-api-id [ID] --patch-operations op=add,path=binaryMediaTypes,value='image/jpg'
</code>```

An error occurred (BadRequestException) when calling the UpdateRestApi
  operation: Invalid patch path binaryMediaTypes

Can this be done or am I stuck manually adding the types in the web UI every time?

答:
The format for adding these via the CLI is a little non-intuitive.</p>

```<code>aws apigateway update-rest-api --rest-api-id [ID]
          --patch-operations "op=add,path=/binaryMediaTypes/image~1jpg"
aws apigateway update-rest-api --rest-api-id [ID]
          --patch-operations "op=replace,path=/binaryMediaTypes/image~1jpg,value='image/gif'"
</code>```

Body:
I'm attempting to configure and update the binary support options of an AWS API Gateway. I can do this through the web UI without issue, but I would like to script this.

Using the CLI Command Reference pages:
http://docs.aws.amazon.com/cli/latest/reference/apigateway/get-rest-api.html
http://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html

Able to issue a get-rest-api command just fine:

C:\> aws apigateway get-rest-api --rest-api-id [ID]

{
  "id": "[ID]",
    "createdDate": 1490723884,
    "name": "testbinarymediatypes"
}

But when attempting to update the binaryMediaTypes:

PS C:\> aws apigateway update-rest-api --rest-api-id [ID] --patch-operations op=add,path=binaryMediaTypes,value='image/jpg'

An error occurred (BadRequestException) when calling the UpdateRestApi
  operation: Invalid patch path binaryMediaTypes

Can this be done or am I stuck manually adding the types in the web UI every time?

Body:
The format for adding these via the CLI is a little non-intuitive.

aws apigateway update-rest-api --rest-api-id [ID]
          --patch-operations "op=add,path=/binaryMediaTypes/image~1jpg"
aws apigateway update-rest-api --rest-api-id [ID]
          --patch-operations "op=replace,path=/binaryMediaTypes/image~1jpg,value='image/gif'"