答:
This is way too broad of a inquiry!

There's a few things that could be wrong but compiling and running has nothing to do with it. Compilers such as maven can generate sources or modify behaviors of compilation units and can be considered non-deterministic programming which because of its very essence, can't be analyzed.

You're referring to a Contextual IntelliSense operation; in the context you're in currently, dependencies etc may not be properly configured. You can't know what you don't know; similarly, Intellij can't either. Make sure all libraries are listed properly within the Project/Global -> Libraries section in order to have them properly function.

Alternatively, your cache could have become corrupted. Try File -> Invalidate Caches / Restart...

Lastly you could simply have the option disabled somehow. There's various settings which will disable the option. For example, Power Save Mode may be enabled. For the rest I suppose it'd be best to refer you to the help documentation.

Title: Intellij "go to > implementation/declaration" navigation feature not working

Body:
I have a maven java project that I would like to use IntelliJ for development on. One of my favorite navigation features of IntelliJ is the 'go to > implementation' feature that appears when you right click on a method or function.

My problem is that this feature is not working for me; when I choose it nothing happens, no error, it just sits right where it is. It also isn't suggesting functions and methods as I type, so it's as if IntelliJ is failing to recognize dependencies and relationships among the various classes in my project.

I know the code is fine because it compiles and runs, has anyone else experienced this? I made sure to open the project as a maven project using the pom.xml file but that made no difference.


来源: stackexchange

问:
DOCTYPE is deprecated and Xinclude does not do it
I need a way to include a fragmented XML not containing a global opening/closing tag/element. The fragment is growing because a program is appending data (more blocks) into it from time to time, so it neither going to have an ending tag nor an starting tag. I have used !DOCTYPE with a !ENTITY but this is being deprecated and the new Xinclude does not seem to have a way to import it as it forces the fragment to have "one" opening and closing tag.

More info: The following works fine with IE-10 but it does not work in IE-11. The latter does not import the file current.log.

Note: Microsoft Edge does not support it according to this web site: https://learn.microsoft.com/en-us/internet-explorer/ie11-deploy-guide/deprecated-document-modes

```<code><?xml version='1.0' encoding='ISO-8859-1'?>
<?xml-stylesheet type='text/xsl' href='IndexLog.xsl'?>

<!DOCTYPE myRoot [<!ENTITY thisMonthLog SYSTEM "current.log">]>

<myRoot>
    &thisMonthLog;
</myRoot>
</code>```

the log current.log looks like this:

```<code><block>
   <a>any text</a>
   <b>any text</b>
   <c>any text</c>
   <d>any text</d>
   <e>any text</e>
</block>
<block>
   <a>any text</a>
   <b>any text</b>
   <c>any text</c>
   <d>any text</d>
   <e>any text</e>
</block>
</code>```

答:
Based on your comments I understand you load an XML document from the file system directly with IE 11. I think IE has moved to use MSXML 6 instead of MSXML 3 by default for XSLT and MSXML 6 by default prohibits DTDs and does not load external entities. The only way I know to circumvent that is to use MSXML 6 with script and to set the properties it has to allow DTDs, load external resources (and for your case, as the DTD is only used to load an external entity, to disable validation):

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:output method="html" indent="yes" version="5" doctype-system="about:legacy-doctype"/>

    <xsl:template match="/">
        <html>
            <head>
                <title>Test</title>
                <script>
                    function runXslt(xmlUri, xsltUri, targetElement) {
                      var xmlDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
                      xmlDoc.async = false;
                      xmlDoc.resolveExternals = true;
                      xmlDoc.validateOnParse = false;
                      xmlDoc.setProperty('ProhibitDTD', false);
                      xmlDoc.load(xmlUri);

                      var xsltDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
                      xsltDoc.async = false;
                      xsltDoc.load(xsltUri);

                      targetElement.insertAdjacentHTML('beforeEnd', xmlDoc.documentElement.transformNode(xsltDoc));
                    }
                </script>
                <script>
                    document.addEventListener(
                      'DOMContentLoaded',
                      function() {
                        runXslt('test201706070101.xml', 'test2017060701.xsl', document.body);
                      },
                      false
                    );
                </script>
            </head>
            <body>
                <h1>Test</h1>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="myRoot">
        <section>
            <h2>Content</h2>
            <xsl:apply-templates/>
        </section>
    </xsl:template>

    <xsl:template match="block">
        <ul>
            <xsl:apply-templates/>
        </ul>
    </xsl:template>

    <xsl:template match="block/*">
        <li>
            <xsl:apply-templates/>
        </li>
    </xsl:template>

</xsl:stylesheet>
</code>```

That way, if the input document test201706070101.xml with the content

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test2017060701.xsl"?>
<!DOCTYPE myRoot [
  <!ENTITY thisMonthLog SYSTEM "test201706070102.xml">
]>
<myRoot>
    &thisMonthLog;
</myRoot>
</code>```

is loaded in IE 11 and scripting is enabled, the full log is parsed, e.g. with the second document having

```<code><?xml version="1.0" encoding="UTF-8"?>
<block>
    <a>any text</a>
    <b>any text</b>
    <c>any text</c>
    <d>any text</d>
    <e>any text</e>
</block>
<block>
    <a>any text</a>
    <b>any text</b>
    <c>any text</c>
    <d>any text</d>
    <e>any text</e>
</block>
</code>```

and the stylesheet being as already posted, the output in the IE window is

```<code>Test

Content
•any text
•any text
•any text
•any text
•any text
•any text
•any text
•any text
•any text
•any text
</code>```

so the external entity has been loaded. Major drawback is obviously that script is needed, another drawback is that the used script with MSXML and ActiveXObject is not compatible with Edge as that doesn't support ActiveXObject.

I post that answer as a suggestion on what might help if you want to rely on IE for XSLT transformation, in the long end it might be better to move the XSLT to HTML transformation to a platform like .NET where you better control how XML parsing and XSLT processing interact.

Example files are online at https://martin-honnen.github.io/xslt/2017/test201706070101.xml, https://martin-honnen.github.io/xslt/2017/test201706070102.xml and https://martin-honnen.github.io/xslt/2017/test2017060701.xsl although I understand you want to do that locally and not over HTTP(S).

ContentLicense: CC BY-SA 3.0

Body:
I need a way to include a fragmented XML not containing a global opening/closing tag/element. The fragment is growing because a program is appending data (more blocks) into it from time to time, so it neither going to have an ending tag nor an starting tag. I have used !DOCTYPE with a !ENTITY but this is being deprecated and the new Xinclude does not seem to have a way to import it as it forces the fragment to have "one" opening and closing tag.

More info: The following works fine with IE-10 but it does not work in IE-11. The latter does not import the file current.log.

Note: Microsoft Edge does not support it according to this web site: https://learn.microsoft.com/en-us/internet-explorer/ie11-deploy-guide/deprecated-document-modes

<?xml version='1.0' encoding='ISO-8859-1'?>
<?xml-stylesheet type='text/xsl' href='IndexLog.xsl'?>

<!DOCTYPE myRoot [<!ENTITY thisMonthLog SYSTEM "current.log">]>

<myRoot>
    &thisMonthLog;
</myRoot>

the log current.log looks like this:

<block>
   any text
   any text
   <c>any text</c>
   <d>any text</d>
   <e>any text</e>
</block>
<block>
   any text
   any text
   <c>any text</c>
   <d>any text</d>
   <e>any text</e>
</block>

Body:
Based on your comments I understand you load an XML document from the file system directly with IE 11. I think IE has moved to use MSXML 6 instead of MSXML 3 by default for XSLT and MSXML 6 by default prohibits DTDs and does not load external entities. The only way I know to circumvent that is to use MSXML 6 with script and to set the properties it has to allow DTDs, load external resources (and for your case, as the DTD is only used to load an external entity, to disable validation):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:output method="html" indent="yes" version="5" doctype-system="about:legacy-doctype"/>

    <xsl:template match="/">
        <html>
            <head>
                <title>Test</title>
                <script>
                    function runXslt(xmlUri, xsltUri, targetElement) {
                      var xmlDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
                      xmlDoc.async = false;
                      xmlDoc.resolveExternals = true;
                      xmlDoc.validateOnParse = false;
                      xmlDoc.setProperty('ProhibitDTD', false);
                      xmlDoc.load(xmlUri);

                      var xsltDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
                      xsltDoc.async = false;
                      xsltDoc.load(xsltUri);

                      targetElement.insertAdjacentHTML('beforeEnd', xmlDoc.documentElement.transformNode(xsltDoc));
                    }
                </script>
                <script>
                    document.addEventListener(
                      'DOMContentLoaded',
                      function() {
                        runXslt('test201706070101.xml', 'test2017060701.xsl', document.body);
                      },
                      false
                    );
                </script>
            </head>
            <body>
                <h1>Test</h1>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="myRoot">
        <section>
            <h2>Content</h2>
            <xsl:apply-templates/>
        </section>
    </xsl:template>

    <xsl:template match="block">
        <ul>
            <xsl:apply-templates/>
        </ul>
    </xsl:template>

    <xsl:template match="block/*">
        <li>
            <xsl:apply-templates/>
        </li>
    </xsl:template>

</xsl:stylesheet>

That way, if the input document test201706070101.xml with the content

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test2017060701.xsl"?>
<!DOCTYPE myRoot [
  <!ENTITY thisMonthLog SYSTEM "test201706070102.xml">
]>
<myRoot>
    &thisMonthLog;
</myRoot>

is loaded in IE 11 and scripting is enabled, the full log is parsed, e.g. with the second document having

<?xml version="1.0" encoding="UTF-8"?>
<block>
    <a>any text</a>
    <b>any text</b>
    <c>any text</c>
    <d>any text</d>
    <e>any text</e>
</block>
<block>
    <a>any text</a>
    <b>any text</b>
    <c>any text</c>
    <d>any text</d>
    <e>any text</e>
</block>

and the stylesheet being as already posted, the output in the IE window is

Test

Content
•any text
•any text
•any text
•any text
•any text
•any text
•any text
•any text
•any text
•any text

so the external entity has been loaded. Major drawback is obviously that script is needed, another drawback is that the used script with MSXML and ActiveXObject is not compatible with Edge as that doesn't support ActiveXObject.

I post that answer as a suggestion on what might help if you want to rely on IE for XSLT transformation, in the long end it might be better to move the XSLT to HTML transformation to a platform like .NET where you better control how XML parsing and XSLT processing interact.

Example files are online at https://martin-honnen.github.io/xslt/2017/test201706070101.xml, https://martin-honnen.github.io/xslt/2017/test201706070102.xml and https://martin-honnen.github.io/xslt/2017/test2017060701.xsl although I understand you want to do that locally and not over HTTP(S).


问:
*ngFor not working and no error in console
I went through most of the questions where "ngFor is not working". below are the details.

app.modules.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TweetComponent } from './tweet.component';
import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, TweetComponent],
    bootstrap: [AppComponent]
    })

export class AppModule { }
</code>```

app.components.ts

```<code>import { Component } from '@angular/core';
import { CommonModule } from "@angular/common";

@Component({
  selector: 'my-app',
  template: `<h1>List of tweets</h1>
            <tweets><tweets>`,
 })

export class AppComponent  { name = 'Angular'; }
</code>```

tweet.component.ts

```<code>import { Component } from "@angular/core"
@Component({
   selector: 'tweets',
   template: `<ul>
                <li *ngFor="let item of myList">
                     <span> {{ item}}</span>
                  </li>
              </ul> `
})

export class TweetComponent {
        myList: ['.net', 'C#', 'web services'];
}
</code>```

Output:

Elements:

And there are errors in console.

答:
There are two issues,

values in the array myList should be assigned using =,

```<code>myList= ['.net', 'C#', 'web services'];
</code>```

and you're missing  tag on template

```<code>@Component({
  selector: 'my-app',
  template: `<h1>List of tweets</h1>
            <tweets></tweets>`,
 })
</code>```

Body:
I went through most of the questions where "ngFor is not working". below are the details.

app.modules.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TweetComponent } from './tweet.component';
import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, TweetComponent],
    bootstrap: [AppComponent]
    })

export class AppModule { }

app.components.ts

import { Component } from '@angular/core';
import { CommonModule } from "@angular/common";

@Component({
  selector: 'my-app',
  template: `
List of tweets

            <tweets><tweets>`,
 })

export class AppComponent  { name = 'Angular'; }

tweet.component.ts

import { Component } from "@angular/core"
@Component({
   selector: 'tweets',
   template: `

                      {{ item}}

 `
})

export class TweetComponent {
        myList: ['.net', 'C#', 'web services'];
}

Output:

Elements:

And there are errors in console.

Body:
There are two issues,

values in the array myList should be assigned using =,

myList= ['.net', 'C#', 'web services'];

and you're missing  tag on template

@Component({
  selector: 'my-app',
  template: `<h1>List of tweets</h1>
            <tweets></tweets>`,
 })


问:
What is the error along with this code of GPIO
This Programming is based on the   L293D motor driver.

For example pins in the Pi 16,18,22 are the pins associated with the motors of one side.

It has pinA and pinB used to turn the on either directions pinE enables the motor which is at the pin22

```<code>from time import sleep
import thread
import RPi.GPIO as GPIO
class Motion:
    #this class is used to define the different motion of the wheel.
    def __init__(self,pinA,pinB,pinE):
        GPIO.setmode(GPIO.BOARD)
        Motor1A = pinA;
        Motor1B = pinB;
        Motor1E = pinE;
        GPIO.setup(Motor1A,GPIO.OUT)
        GPIO.setup(Motor1B,GPIO.OUT)
        GPIO.setup(Motor1E,GPIO.OUT)
    def forward(self):
        print "Moving Forward"
        GPIO.output(Motor1A,GPIO.HIGH)
        GPIO.output(Motor1B,GPIO.LOW)
        GPIO.output(Motor1E,GPIO.HIGH)
        GPIO.cleanup()
    sleep(2)
    def backword(self):
        print "Moving Backword"
        GPIO.output(Motor1A,GPIO.LOW)
        GPIO.output(Motor1B,GPIO.HIGH)
        GPIO.output(Motor1E,GPIO.HIGH)
        GPIO.cleanup()
    sleep(2)
    def stop(self):
        print "No Movements, Stoped"
        GPIO.output(Motor1E,GPIO.LOW)
        GPIO.cleanup()
</code>```

答:
One problem with your code is that you call GPIO.cleanup() after every method. This also cleans up the GPIO pin numbering system you set with GPIO.setmode(GPIO.BOARD) and so would cause problems if you call the methods more than once. It would be better to call GPIO.cleanup() only once at the end of your script. In the methods you could for example turn the pins low after a sleep to stop the motors after running them for the desired time.

If you post the actual error(s) you see when running your code, someone might be able to help you debug it further.

Body:
This Programming is based on the   L293D motor driver.

For example pins in the Pi 16,18,22 are the pins associated with the motors of one side.

It has pinA and pinB used to turn the on either directions pinE enables the motor which is at the pin22

from time import sleep
import thread
import RPi.GPIO as GPIO
class Motion:
    #this class is used to define the different motion of the wheel.
    def __init__(self,pinA,pinB,pinE):
        GPIO.setmode(GPIO.BOARD)
        Motor1A = pinA;
        Motor1B = pinB;
        Motor1E = pinE;
        GPIO.setup(Motor1A,GPIO.OUT)
        GPIO.setup(Motor1B,GPIO.OUT)
        GPIO.setup(Motor1E,GPIO.OUT)
    def forward(self):
        print "Moving Forward"
        GPIO.output(Motor1A,GPIO.HIGH)
        GPIO.output(Motor1B,GPIO.LOW)
        GPIO.output(Motor1E,GPIO.HIGH)
        GPIO.cleanup()
    sleep(2)
    def backword(self):
        print "Moving Backword"
        GPIO.output(Motor1A,GPIO.LOW)
        GPIO.output(Motor1B,GPIO.HIGH)
        GPIO.output(Motor1E,GPIO.HIGH)
        GPIO.cleanup()
    sleep(2)
    def stop(self):
        print "No Movements, Stoped"
        GPIO.output(Motor1E,GPIO.LOW)
        GPIO.cleanup()


问:
What is the initializing procedure underneath the __init__ method of python built-in list
My question is will the init method of list class calling other method such as append or insert to achieve its functionality.

like:

```<code>class test(list):

def __init__(self,values):
    super().__init__()

def append(self, value):
    self.append(value + 1)
</code>```

I want:

```<code>x = test([1,2,3])
x
[2,3,4]
</code>```

but I got:

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

I know I can make it work by overload init itself.

```<code>def __init__(self,values):
    super().__init__([x+1 for x in values])
</code>```

Can I just overload some basic value insert method like setitem, so all the insert operation like append, insert will call it, and therefore have that addition effect.

thanks for any suggestion.

答:
list.__init__ does not call any overrideable method. It makes a direct, un-overrideable call to the C function that implements the extend method:

```<code>if (arg != NULL) {
    PyObject *rv = listextend(self, arg);
    if (rv == NULL)
        return -1;
    Py_DECREF(rv);
}
</code>```

This is the case for most methods of most Python types implemented in C.

Body:
My question is will the init method of list class calling other method such as append or insert to achieve its functionality.

like:

class test(list):

def __init__(self,values):
    super().__init__()

def append(self, value):
    self.append(value + 1)

I want:

x = test([1,2,3])
x
[2,3,4]

but I got:

[1,2,3]

I know I can make it work by overload init itself.

def __init__(self,values):
    super().__init__([x+1 for x in values])

Can I just overload some basic value insert method like setitem, so all the insert operation like append, insert will call it, and therefore have that addition effect.

thanks for any suggestion.

Body:
list.__init__ does not call any overrideable method. It makes a direct, un-overrideable call to the C function that implements the extend method:

if (arg != NULL) {
    PyObject *rv = listextend(self, arg);
    if (rv == NULL)
        return -1;
    Py_DECREF(rv);
}

This is the case for most methods of most Python types implemented in C.


问:
R coxph() Error: object 'Ccoxmart' not found
I am getting the following error every time I run a Cox model using the survival package in R. This error arose within the last few days. To illustrate the error, I am using a standard example command which is given at https://stat.ethz.ch/R-manual/R-devel/library/survival/html/coxph.html:

```<code># Fit a stratified model, clustered on patients
library(survival)
bladder1 <- bladder[bladder$enum < 5, ]
coxph(Surv(stop, event) ~ (rx + size + number) * strata(enum) +
      cluster(id), bladder1)
</code>```

The error I get is as follows:

```<code>Error in fitter(X, Y, strats, offset, init, control, weights = weights,  :
  object 'Ccoxmart' not found
</code>```

I am using latest version of R [3.4.0 (2017-04-21) -- "You Stupid Darkness"].

I have tried to consult the survival package manual for R and researched on the internet. I am grateful for any resource or solution you may recommend.

答:
You have to re-install packages that use C or Fortran in R 3.4.0:

```<code>update.packages(checkBuild=TRUE)
</code>```

See this post

Packages which register native routines for .C or .Fortran need
  to be re-installed for this version (unless installed with
  R-devel SVN revision r72375 or later)

Body:
I am getting the following error every time I run a Cox model using the survival package in R. This error arose within the last few days. To illustrate the error, I am using a standard example command which is given at https://stat.ethz.ch/R-manual/R-devel/library/survival/html/coxph.html:

# Fit a stratified model, clustered on patients
library(survival)
bladder1 <- bladder[bladder$enum < 5, ]
coxph(Surv(stop, event) ~ (rx + size + number) * strata(enum) +
      cluster(id), bladder1)

The error I get is as follows:

Error in fitter(X, Y, strats, offset, init, control, weights = weights,  :
  object 'Ccoxmart' not found

I am using latest version of R [3.4.0 (2017-04-21) -- "You Stupid Darkness"].

I have tried to consult the survival package manual for R and researched on the internet. I am grateful for any resource or solution you may recommend.

Body:
You have to re-install packages that use C or Fortran in R 3.4.0:

update.packages(checkBuild=TRUE)

See this post

Packages which register native routines for .C or .Fortran need
  to be re-installed for this version (unless installed with
  R-devel SVN revision r72375 or later)


问:
Inverted View in VR sphere in Unity
I've been trying to project a 360 video inside a Sphere with flipped normals for Google Cardboard VR. The Video works fine, only it is inverted horizontally, which is noticeable only when there is some text on the screen. I've included a screen shot of video and a UI.Text element in front of it to compare it with.

I've tried to invert the view of the camera through projectionMatrix but then it just ends up in blank space. Screenshot :

I can't figure out a way to make the video project the right way. Please help!

答:
Flipping the normals on a sphere is insufficient, you also need to reverse the U part of the UV coordinates (that is, change all the values U such that they are 1-U).  A sphere is set up so that the outside renders text correctly from right to left. When you flip the normals "right" is still on the right from the outside...meaning that it's on the left when viewed from the inside.

You will either need to manually edit the UV coordinates yourself or get a premade inverted sphere off the asset store (IIRC there are two that are available for free).

Title: Inverted View in VR sphere in Unity


问:
Turn PHP MySQL query output into variable
I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.

The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.

This part of the code works just fine.

```<code>$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
            $result =  mysqli_query($conn, $sql);
            if (mysqli_num_rows($result) > 0){
                while($row = mysqli_fetch_assoc($result)){
                    echo "Nome: "."<span style='color: red;'>".$row["nome"].
                    "</span>".
                    "<br>"."Preço: "."<span style='color: red;'>".
                    "R$".$row["preco"]."</span>"."<br><br>".$row["status"];
                }
            }
</code>```

What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.

```<code><form method="post" action="?p=venda">
        <input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
        <input type="text" name="preco" value="<?php echo $row["preco"]; ?>">

        <input type="submit" name="change" value="Efetuar">
    </form>
</code>```

I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).

Thanks in advance.

答:
here is my table example if I was going to list the whole db table in a scrollable list, and submit it to a file called detail.php</p>

```<code>     <?php
    $sql = "SELECT nome, preco, status FROM produtos";
    $result = $conn->query($sql);

    echo "<table align=center bgcolor=e3fab5 ><td>";

    echo '<div style="width: 500px; height: 450px; overflow: auto; border 5px dashed black; background color: #ccc;">';
    echo "<table align=center bgcolor=fff2e2 border=1>\n";
     while ($data = $result->fetch_row()) {
  echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
   echo '<tr>';
      for ($m=0; $m<$result->field_count; $m++) {
        if ($m==0){
        $nome='';
        $nome=$data[$m];
        echo '<td bgcolor="#ff0000"><form action="detail.php" method="post"><input type="submit" name="id" value="'.$nome.'"></td>';
         } else if ($m==1){
        $preco='';
         $preco=$data[$m];
        echo '<td bgcolor="#ff0000">'.$preco.'<input type="hidden" name="preco" value="'.$preco.'"></td>';
          }else if ($m==2){
         $status='';
         $status=$data[$m];
        echo '<td bgcolor="#ffffff">'.$status.'<input type="hidden" name="status" value="'.$status.'"></td>';
           }
        }

        echo  "</form></tr>";

          }
          echo "</table>";
          echo "</div></table>";
    ?>
</code>```

Body:
I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.

The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.

This part of the code works just fine.

$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
            $result =  mysqli_query($conn, $sql);
            if (mysqli_num_rows($result) > 0){
                while($row = mysqli_fetch_assoc($result)){
                    echo "Nome: "."".$row["nome"].
                    "".
                    "
"."Preço: "."".
                    "R$".$row["preco"].""."

".$row["status"];
                }
            }

What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.

<form method="post" action="?p=venda">
        <input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
        <input type="text" name="preco" value="<?php echo $row["preco"]; ?>">

        <input type="submit" name="change" value="Efetuar">
    </form>

I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).

Thanks in advance.

Body:
here is my table example if I was going to list the whole db table in a scrollable list, and submit it to a file called detail.php

     <?php
    $sql = "SELECT nome, preco, status FROM produtos";
    $result = $conn->query($sql);

    echo "<table align=center bgcolor=e3fab5 ><td>";

    echo '<div style="width: 500px; height: 450px; overflow: auto; border 5px dashed black; background color: #ccc;">';
    echo "<table align=center bgcolor=fff2e2 border=1>\n";
     while ($data = $result->fetch_row()) {
  echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
   echo '<tr>';
      for ($m=0; $m<$result->field_count; $m++) {
        if ($m==0){
        $nome='';
        $nome=$data[$m];
        echo '<td bgcolor="#ff0000"><form action="detail.php" method="post"><input type="submit" name="id" value="'.$nome.'"></td>';
         } else if ($m==1){
        $preco='';
         $preco=$data[$m];
        echo '<td bgcolor="#ff0000">'.$preco.'<input type="hidden" name="preco" value="'.$preco.'"></td>';
          }else if ($m==2){
         $status='';
         $status=$data[$m];
        echo '<td bgcolor="#ffffff">'.$status.'<input type="hidden" name="status" value="'.$status.'"></td>';
           }
        }

        echo  "</form></tr>";

          }
          echo "</table>";
          echo "</div></table>";
    ?>


问:
Find pattern in binary file/ Find match in binary file (C)
I don't know why this code isn't working.

```<code>while (TRUE)
{
    do
    {
        fread(buffer1, BUFFER_LEN - 1, 1, pFile);
        fread(buffer2, BUFFER_LEN - 1, 1, pVirus);
        if (feof(pVirus))
        {
            printf("MATCH!\n");
            flag = 1;
            break;
        }
    } while (strcmp(buffer1, buffer2) == 0);

    if (buffer1 != buffer2)
    {
        rewind(pVirus);
    }

    if (feof(pFile) || flag == 1)
    {
        break;
    }
}

fclose(pFile);
fclose(pVirus);
</code>```

The code finding match in small file in bigger file the code isn't working.

答:
the following proposed code:

performs the desired function

cannot say it cleanly compiles as the OPs posted code is not complete

will not seg fault

and now the proposed code:

```<code>    rewind( pFile );
    do
    {
        size_t buf1Count = fread(buffer1, 1, BUFFER_LEN, pFile);
        if( !buf1Count )
        {
            if( feof( pFile ) )
            { // reached end of pFile
                ???
                break;
            }

            else
            { // error event
                perror( "fread of pFile failed" );
                fclose( pFile );
                fclose( pVirus );
                exit( EXIT_FAILURE );
            }
        }

        rewind( pVirus );
        do
        {
            size_t buf2Count = fread(buffer2, 1, BUFFER_LEN, pVirus);

            if( !buf2Count )
            {
                if( feof( pVirus ) )
                { // reached end of pVirus
                    printf( "NO MATCH\n" );
                    break;
                }

                else
                { // error event
                    perror( "fread of pVirus failed" );
                    fclose( pFile );
                    fclose( pVirus );
                    exit( EXIT_FAILURE );
                }
            }

            if( memcmp(buffer1, buffer2, buf1Count) == 0)
            {
                printf( "MATCH\n" );
                break;
            }
        } while(1);
    } while (1);

    fclose(pFile);
    fclose(pVirus);
</code>```

Body:
I don't know why this code isn't working.

while (TRUE)
{
    do
    {
        fread(buffer1, BUFFER_LEN - 1, 1, pFile);
        fread(buffer2, BUFFER_LEN - 1, 1, pVirus);
        if (feof(pVirus))
        {
            printf("MATCH!\n");
            flag = 1;
            break;
        }
    } while (strcmp(buffer1, buffer2) == 0);

    if (buffer1 != buffer2)
    {
        rewind(pVirus);
    }

    if (feof(pFile) || flag == 1)
    {
        break;
    }
}

fclose(pFile);
fclose(pVirus);

The code finding match in small file in bigger file the code isn't working.

Body:
the following proposed code:

performs the desired function

cannot say it cleanly compiles as the OPs posted code is not complete

will not seg fault

and now the proposed code:

    rewind( pFile );
    do
    {
        size_t buf1Count = fread(buffer1, 1, BUFFER_LEN, pFile);
        if( !buf1Count )
        {
            if( feof( pFile ) )
            { // reached end of pFile
                ???
                break;
            }

            else
            { // error event
                perror( "fread of pFile failed" );
                fclose( pFile );
                fclose( pVirus );
                exit( EXIT_FAILURE );
            }
        }

        rewind( pVirus );
        do
        {
            size_t buf2Count = fread(buffer2, 1, BUFFER_LEN, pVirus);

            if( !buf2Count )
            {
                if( feof( pVirus ) )
                { // reached end of pVirus
                    printf( "NO MATCH\n" );
                    break;
                }

                else
                { // error event
                    perror( "fread of pVirus failed" );
                    fclose( pFile );
                    fclose( pVirus );
                    exit( EXIT_FAILURE );
                }
            }

            if( memcmp(buffer1, buffer2, buf1Count) == 0)
            {
                printf( "MATCH\n" );
                break;
            }
        } while(1);
    } while (1);

    fclose(pFile);
    fclose(pVirus);


问:
Having an issue with passing user name and password to ssh
I have the following code on a Debian VirtualBox :

```<code>#!/usr/bin/env python

import paramiko
import time
import re
import sys

#Open SSHv2 connection to devices
def open_ssh_conn(ip):
    #Change exception message
    try:
        #Defining the credentials file
        user_file = sys.argv[1]

        #Defining the commands file
        cmd_file = sys.argv[2]

        #define the SSH parameters
        selected_user_file = open(user_file, 'r')

        #Starting from beginning of file
        selected_user_file.seek(0)

        #Reading the username from file
        username = selected_user_file.readline()[0].split(',')[0]

        #Starting from the beginning of file
        selected_user_file.seek(0)

        #Reading password from file
        password = selected_user_file.readlines()[0].split(',').rstrip("\n")

        #Logging into device
        session = paramiko.SSHClient()

        #For testing purposes, this allows auto-accepting unknown host keys
        #Do not use in production!! The default would be RejectPolicy
        session.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        #Start and interactive shell session on the router
        connection = session.invoke_shell()

        #Setting terminal length for entire output - disable pagination
        connection.send("\n")
        connection.send("configure terminal\n")
        time.sleep(1)

        #Open user selected file for reading
        selected_cmd_fil = open(cmd_file, 'r')

        #Writing each linein the file to the device
        for each_line in selected_cmd_file.readlines():
            connection.send(each_line + '\n')
            time.sleep(2)

        #Closing the user file
        selected_user_file.close()

        #closint the command file
        selected_cmd_file.close()

        #Expect to receive a maximum amount of 65535 bytes of data and store in a variable
        router_output = connection.recv(65535)

        #Checking command output for IOS syntax errors
        if re.search(r"% Invalid input detected at", router_output):
            print "*There was at lease one IOS syntax error on device %s" % ip
        else:
            print "\nDone for device %s" % ip

        #Test for reading command output
        print router_output + "\n"

        #closing the connection
        session.close
    except paramiko.AuthenticationException:
        print "* Invaliid username or password. \n Please check the usernmame/password file or the device configuration"
        print "* Closing program...\n"

#Calling the SSH function
open_ssh_conn("192.168.2.102")
</code>```

With the following user_file :

root@debian:/home/debian/workingdir# cat ssh_credentials.txt
teopy,python

When I try to run the code I receive the following error message :

```<code>root@debian:/home/debian/workingdir# python SSHTemplate_2.py
Traceback (most recent call last):
  File "SSHTemplate_2.py", line 81, in <module>
    open_ssh_conn("192.168.2.102")
  File "SSHTemplate_2.py", line 13, in open_ssh_conn
    user_file = sys.argv[1]
IndexError: list index out of range
</code>```

Any assistance is greatly appreciated.

python SSHTemplate_2.py ssh_credentials telnet_commands.txt is what I am running and receiving the following error:

```<code>root@debian:/home/debian/workingdir# python SSHTemplate_2.py ssh_credentials.txt telnet_commands.txt
</code>```

Traceback (most recent call last):

```<code>File "SSHTemplate_2.py", line 82, in <module> open_ssh_conn("192.168.2.102")
File "SSHTemplate_2.py", line 31, in open_ssh_conn
password = selected_user_file.readlines()[0].split(',').rstrip("\n")
AttributeError: 'list' object has no attribute 'rstrip'
</code>```

答:
This is your fault:

```<code>#Reading password from file
password = selected_user_file.readlines()[0].split(',').rstrip("\n")
</code>```

I assume your user_file Data Line is Username,Password
change to

```<code># Using `with` block will auto close the file on leave the block
with  open(user_file) as fh:
    # Read one Line,
    # assign to var without the trailing NewLine
    data = fh.readline()[:-1]
    # Change var to Type List of String
    data = data.split(',')
    username = data[0]
    password = data[1]

#Logging into device
session = paramiko.SSHClient()
   ...
</code>```

Body:
I have the following code on a Debian VirtualBox :

#!/usr/bin/env python

import paramiko
import time
import re
import sys

#Open SSHv2 connection to devices
def open_ssh_conn(ip):
    #Change exception message
    try:
        #Defining the credentials file
        user_file = sys.argv[1]

        #Defining the commands file
        cmd_file = sys.argv[2]

        #define the SSH parameters
        selected_user_file = open(user_file, 'r')

        #Starting from beginning of file
        selected_user_file.seek(0)

        #Reading the username from file
        username = selected_user_file.readline()[0].split(',')[0]

        #Starting from the beginning of file
        selected_user_file.seek(0)

        #Reading password from file
        password = selected_user_file.readlines()[0].split(',').rstrip("\n")

        #Logging into device
        session = paramiko.SSHClient()

        #For testing purposes, this allows auto-accepting unknown host keys
        #Do not use in production!! The default would be RejectPolicy
        session.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        #Start and interactive shell session on the router
        connection = session.invoke_shell()

        #Setting terminal length for entire output - disable pagination
        connection.send("\n")
        connection.send("configure terminal\n")
        time.sleep(1)

        #Open user selected file for reading
        selected_cmd_fil = open(cmd_file, 'r')

        #Writing each linein the file to the device
        for each_line in selected_cmd_file.readlines():
            connection.send(each_line + '\n')
            time.sleep(2)

        #Closing the user file
        selected_user_file.close()

        #closint the command file
        selected_cmd_file.close()

        #Expect to receive a maximum amount of 65535 bytes of data and store in a variable
        router_output = connection.recv(65535)

        #Checking command output for IOS syntax errors
        if re.search(r"% Invalid input detected at", router_output):
            print "*There was at lease one IOS syntax error on device %s" % ip
        else:
            print "\nDone for device %s" % ip

        #Test for reading command output
        print router_output + "\n"

        #closing the connection
        session.close
    except paramiko.AuthenticationException:
        print "* Invaliid username or password. \n Please check the usernmame/password file or the device configuration"
        print "* Closing program...\n"

#Calling the SSH function
open_ssh_conn("192.168.2.102")

With the following user_file :

root@debian:/home/debian/workingdir# cat ssh_credentials.txt
teopy,python

When I try to run the code I receive the following error message :

root@debian:/home/debian/workingdir# python SSHTemplate_2.py
Traceback (most recent call last):
  File "SSHTemplate_2.py", line 81, in <module>
    open_ssh_conn("192.168.2.102")
  File "SSHTemplate_2.py", line 13, in open_ssh_conn
    user_file = sys.argv[1]
IndexError: list index out of range

Any assistance is greatly appreciated.

python SSHTemplate_2.py ssh_credentials telnet_commands.txt is what I am running and receiving the following error:

root@debian:/home/debian/workingdir# python SSHTemplate_2.py ssh_credentials.txt telnet_commands.txt

Traceback (most recent call last):

File "SSHTemplate_2.py", line 82, in <module> open_ssh_conn("192.168.2.102")
File "SSHTemplate_2.py", line 31, in open_ssh_conn
password = selected_user_file.readlines()[0].split(',').rstrip("\n")
AttributeError: 'list' object has no attribute 'rstrip'

Body:
This is your fault:

#Reading password from file
password = selected_user_file.readlines()[0].split(',').rstrip("\n")

I assume your user_file Data Line is Username,Password
change to

# Using `with` block will auto close the file on leave the block
with  open(user_file) as fh:
    # Read one Line,
    # assign to var without the trailing NewLine
    data = fh.readline()[:-1]
    # Change var to Type List of String
    data = data.split(',')
    username = data[0]
    password = data[1]

#Logging into device
session = paramiko.SSHClient()
   ...


问:
In python, what's the most efficient way to identify clusters of n-events t-time apart?
For example, if I have the following event data, and want to find clusters of at least 2 events that are within 1 minute of each other in which id_1, id_2, and id_3 are all the same. For reference, I have the epoch timestamp (in microseconds) in addition to the date-time timestamp.

```<code>event_id       timestamp          id_1 id_2  id_3
9442823 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442821 Jun 15, 2015 10:22 PM PDT   A   2   12345
9442817 Jun 15, 2015 10:22 PM PDT   A   3   34567
9442814 Jun 15, 2015 10:22 PM PDT   A   1   12345
9442813 Jun 15, 2015 10:22 PM PDT   A   2   34567
9442810 Jun 15, 2015 10:22 PM PDT   A   3   12345
9442805 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442876 Jun 15, 2015 10:23 PM PDT   A   2   12345
9442866 Jun 15, 2015 10:23 PM PDT   A   3   34567
9442858 Jun 15, 2015 10:23 PM PDT   A   1   12345
9442845 Jun 15, 2015 10:23 PM PDT   C   2   34567
9442840 Jun 15, 2015 10:23 PM PDT   C   3   12345
9442839 Jun 15, 2015 10:23 PM PDT   C   1   34567
9442838 Jun 15, 2015 10:23 PM PDT   C   2   12345
9442907 Jun 15, 2015 10:24 PM PDT   C   3   34567
9442886 Jun 15, 2015 10:24 PM PDT   C   1   12345
9442949 Jun 15, 2015 10:25 PM PDT   C   2   34567
9442934 Jun 15, 2015 10:25 PM PDT   C   3   12345
</code>```

For each cluster found, I want to return a set of (id_1, id_2, id_3, [list of event_ids], min_timestamp_of_cluster, max_timestamp_of_cluster). Additionally, if there's a cluster with (e.g.) 6 events, I'd only want to return a single result with all events, not one for each grouping of 3 events.

答:
If I understood your problem correctly, you can make use of scikit-learn's DBSCAN clustering algorithm with a custom distance (or metric) function. Your distance function should return a very large number if either of the id_1, id_2 or id_3's are different. Otherwise is should return the time difference.

But with this method, the number of clusters are determined by the algorithm and not as an input given to the algorithm. If you are determined to pass the number of clusters as an input, k-means is the clustering algorithm you may need to look into.

Body:
For example, if I have the following event data, and want to find clusters of at least 2 events that are within 1 minute of each other in which id_1, id_2, and id_3 are all the same. For reference, I have the epoch timestamp (in microseconds) in addition to the date-time timestamp.

event_id       timestamp          id_1 id_2  id_3
9442823 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442821 Jun 15, 2015 10:22 PM PDT   A   2   12345
9442817 Jun 15, 2015 10:22 PM PDT   A   3   34567
9442814 Jun 15, 2015 10:22 PM PDT   A   1   12345
9442813 Jun 15, 2015 10:22 PM PDT   A   2   34567
9442810 Jun 15, 2015 10:22 PM PDT   A   3   12345
9442805 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442876 Jun 15, 2015 10:23 PM PDT   A   2   12345
9442866 Jun 15, 2015 10:23 PM PDT   A   3   34567
9442858 Jun 15, 2015 10:23 PM PDT   A   1   12345
9442845 Jun 15, 2015 10:23 PM PDT   C   2   34567
9442840 Jun 15, 2015 10:23 PM PDT   C   3   12345
9442839 Jun 15, 2015 10:23 PM PDT   C   1   34567
9442838 Jun 15, 2015 10:23 PM PDT   C   2   12345
9442907 Jun 15, 2015 10:24 PM PDT   C   3   34567
9442886 Jun 15, 2015 10:24 PM PDT   C   1   12345
9442949 Jun 15, 2015 10:25 PM PDT   C   2   34567
9442934 Jun 15, 2015 10:25 PM PDT   C   3   12345

For each cluster found, I want to return a set of (id_1, id_2, id_3, [list of event_ids], min_timestamp_of_cluster, max_timestamp_of_cluster). Additionally, if there's a cluster with (e.g.) 6 events, I'd only want to return a single result with all events, not one for each grouping of 3 events.


问:
How to specify applet libraries in JNLP file
I'm trying to deploy an applet using JNLP. The file structure is thus:

```<code>/
  dbstats.html
  dbstats.jnlp
  dbstats.jar
  lib/
    substance.jar
    trident.jar
    guava-0.7.jar
</code>```

Here's my HTML:

```<code><html>
    <head>
        <title>Dreambearstatistieken</title>

        <script src="http://www.java.com/js/deployJava.js"></script>
        <script type="text/javascript">

            var attributes = {
                code:'dreambear.stats.viewer.DBStatsViewer',
                width:900, height:600
            };
            var parameters = {jnlp_href: "dbstats.jnlp"};
            var version = "1.6";

        </script>

    </head>
    <body>

    <script type="text/javascript">
        deployJava.runApplet(attributes, parameters, version);
    </script>

    </body>
</html>
</code>```

And the JNLP file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="" href="">
    <information>
        <title>Dreambearstatistieken</title>
        <vendor>Weber</vendor>
    </information>
    <resources>
        <j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se" />
        <jar href="lib/trident.jar" />
        <jar href="lib/substance.jar" />
        <jar href="lib/guava-r07.jar" />
        <jar href="dbstats.jar" main="true" />
    </resources>
    <applet-desc
         name="Dreambearstatistieken"
         main-class="dreambear.stats.viewer.DBStatsViewer"
         width="900"
         height="600">
     </applet-desc>
     <update check="background" />
</jnlp>
</code>```

As far as I can see, everything should be ok, but it's not. I get a ClassNotFoundException on org.pushingpixels.substance.api.skin.SubstanceNebulaLookAndFeel, which is in substance.jar. What am I doing wrong?

And wider, is there a good tutorial or book about using applets and JNLP in the 2010s?

答:
First your codebase is empty. As far as I remember it should contain the absolute path to your application. Probably I am wrong but start from this. If it helps but you wish to reuse the jnlp file try codebase="." (although I am not sure it is legal.)

Next, try to download one of the jars under lib directory using browser. It is needed to be sure that this directory is accessible.

Good luck!

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to deploy an applet using JNLP. The file structure is thus:

/
  dbstats.html
  dbstats.jnlp
  dbstats.jar
  lib/
    substance.jar
    trident.jar
    guava-0.7.jar

Here's my HTML:

        <title>Dreambearstatistieken</title>

And the JNLP file:

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="" href="">
    <information>
        <title>Dreambearstatistieken</title>
        <vendor>Weber</vendor>
    </information>
    <resources>
        <j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se" />
        <jar href="lib/trident.jar" />
        <jar href="lib/substance.jar" />
        <jar href="lib/guava-r07.jar" />
        <jar href="dbstats.jar" main="true" />
    </resources>
    <applet-desc
         name="Dreambearstatistieken"
         main-class="dreambear.stats.viewer.DBStatsViewer"
         width="900"
         height="600">
     </applet-desc>
     <update check="background" />
</jnlp>

As far as I can see, everything should be ok, but it's not. I get a ClassNotFoundException on org.pushingpixels.substance.api.skin.SubstanceNebulaLookAndFeel, which is in substance.jar. What am I doing wrong?

And wider, is there a good tutorial or book about using applets and JNLP in the 2010s?


问:
Jackson mapper expands LocalDate
We have a DTO defined with a LocalDate:

```<code>@JsonProperty("dob")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate dob;
</code>```

We have code with an ObjectMapper defined as follows:

```<code>private static final ObjectMapper makeMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ParameterNamesModule());
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    return mapper;
}
</code>```

We have all the jackson-datababindm core, jsr310 in our pom.xml file:

```<code>    <!-- Jackson JSON Mapping -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-parameter-names</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jdk8</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>2.8.8</version>
    </dependency>
</code>```

So, when I convert my object to a JSON string:

```<code>    String json = makeMapper().writeValueAsString(myobject);
</code>```

The dob writes to the JSON string as:

"dob":{
      "year": 1964,
      "month": "FEBRUARY",
      "chronology": {
          "calendarType": "iso8601",
          "id": "ISO"
      },
      "monthValue": 2,
      "dayOfMonth": 13,
      "dayOfWeek": "THURSDAY",
      "era": "CE",
       "dayOfYear": 44,
       "leapYear": true}

instead of:   "dob":"1964-02-13"   which is correct.

So, I am not sure how I made this happen?

I'd like to make sure the date gets written out correct, so I can re-parse back to a LocalDate.   Or, is there a way I can take the existing JSON (expanded) and parse that back to a LocalDate?

Thanks!

答:
Turns out this was a ClassLoader issue.  In the smallest case, the code works and the LocalDate is turned into JSON accordingly.  When you emebed one project into another into another, then what happens is that the ObjectMapper was defined elsewhere without the JavaTimeModule.

I took the code:

```<code>private static final ObjectMapper makeMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ParameterNamesModule());
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    return mapper;
}
</code>```

and brought it right into my class where I needed it, and that worked.   Reaching out to a utility from a different project didn't work for me.

Hope this helps someone else.

Title: Jackson mapper expands LocalDate

Body:
We have a DTO defined with a LocalDate:

@JsonProperty("dob")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate dob;

We have code with an ObjectMapper defined as follows:

private static final ObjectMapper makeMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ParameterNamesModule());
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    return mapper;
}

We have all the jackson-datababindm core, jsr310 in our pom.xml file:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-parameter-names</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jdk8</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>2.8.8</version>
    </dependency>

So, when I convert my object to a JSON string:

    String json = makeMapper().writeValueAsString(myobject);

The dob writes to the JSON string as:

"dob":{
      "year": 1964,
      "month": "FEBRUARY",
      "chronology": {
          "calendarType": "iso8601",
          "id": "ISO"
      },
      "monthValue": 2,
      "dayOfMonth": 13,
      "dayOfWeek": "THURSDAY",
      "era": "CE",
       "dayOfYear": 44,
       "leapYear": true}

instead of:   "dob":"1964-02-13"   which is correct.

So, I am not sure how I made this happen?

I'd like to make sure the date gets written out correct, so I can re-parse back to a LocalDate.   Or, is there a way I can take the existing JSON (expanded) and parse that back to a LocalDate?

Thanks!

Body:
Turns out this was a ClassLoader issue.  In the smallest case, the code works and the LocalDate is turned into JSON accordingly.  When you emebed one project into another into another, then what happens is that the ObjectMapper was defined elsewhere without the JavaTimeModule.

I took the code:

private static final ObjectMapper makeMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ParameterNamesModule());
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    return mapper;
}

and brought it right into my class where I needed it, and that worked.   Reaching out to a utility from a different project didn't work for me.

Hope this helps someone else.


问:
Badly registered generic type with Autofac
I have service

```<code>public class CircleProfileService : CircleService<ICircleProfileInput, ICircleProfileOutput, ICircleProfile>, ICircleProfileService
{
        public CircleProfileService(ICircleProfileQueryBuilder queryBuilder,
                                             ICircleQueryProcessor queryProcessor,
                                             ICircleParser<ICircleProfile> parser)
            : base(queryBuilder, queryProcessor, parser)
        {
        }
        ... other methods
}
</code>```

As you can see I try to inject generic type of my parser.

```<code>public interface ICircleParser<out TOutput> where TOutput : ICircleParsedOutput
{
        IEnumerable<TOutput> Parse(string json);
}

public class CircleParser<TOutput> : ICircleParser<TOutput> where TOutput: ICircleParsedOutput, new()
//new() is only one option to make project buildable as jsonParser want non-abstract type...
    {
        private readonly IJsonParser jsonParser;

        public CircleParser(IJsonParser jsonParser)
        {
            this.jsonParser = jsonParser;
        }

        public IEnumerable<TOutput> Parse(string json)
        {
            return jsonParser.Parse<TOutput>(json);
        }
    }
</code>```

And here is how I register my generic types (everything like in Autofac documentation)

```<code> builder.RegisterGeneric(typeof(CircleParser<>)).As(typeof(ICircleParser<>));
</code>```

But this always throws exception that cannot inject parser...

What am I doing wrong?

Error :

Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyProj.Services.DataServices.Circle.CircleProfileService' can be invoked with the available services and parameters:
  Cannot resolve parameter 'MyProj.Services.DataServices.Circle.Parsers.Interfaces.ICircleParser1[MyProj.Services.DataServices.Circle.Outputs.Interfaces.ICircleProfile] parser' of constructor 'Void .ctor(MyProj.Services.DataServices.Circle.QueryBuilders.Interfaces.ICircleProfileQueryBuilder, MyProj.Services.DataServices.Circle.QueryProcessors.Interfaces.ICircleQueryProcessor, MyProj.Services.DataServices.Circle.Parsers.Interfaces.ICircleParser1[MyProj.Services.DataServices.Circle.Outputs.Interfaces.ICircleProfile])'.

答:
Unable to comment do to rep, so I am forced to make a post.

Do you have a binding for IJsonParser? If not, you need to add one so that autofac can inject an implementation of it into CircleParser

Body:
I have service

public class CircleProfileService : CircleService<ICircleProfileInput, ICircleProfileOutput, ICircleProfile>, ICircleProfileService
{
        public CircleProfileService(ICircleProfileQueryBuilder queryBuilder,
                                             ICircleQueryProcessor queryProcessor,
                                             ICircleParser<ICircleProfile> parser)
            : base(queryBuilder, queryProcessor, parser)
        {
        }
        ... other methods
}

As you can see I try to inject generic type of my parser.

public interface ICircleParser<out TOutput> where TOutput : ICircleParsedOutput
{
        IEnumerable<TOutput> Parse(string json);
}

public class CircleParser<TOutput> : ICircleParser<TOutput> where TOutput: ICircleParsedOutput, new()
//new() is only one option to make project buildable as jsonParser want non-abstract type...
    {
        private readonly IJsonParser jsonParser;

        public CircleParser(IJsonParser jsonParser)
        {
            this.jsonParser = jsonParser;
        }

        public IEnumerable<TOutput> Parse(string json)
        {
            return jsonParser.Parse<TOutput>(json);
        }
    }

And here is how I register my generic types (everything like in Autofac documentation)

 builder.RegisterGeneric(typeof(CircleParser<>)).As(typeof(ICircleParser<>));

But this always throws exception that cannot inject parser...

What am I doing wrong?

Error :

Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyProj.Services.DataServices.Circle.CircleProfileService' can be invoked with the available services and parameters:
  Cannot resolve parameter 'MyProj.Services.DataServices.Circle.Parsers.Interfaces.ICircleParser1[MyProj.Services.DataServices.Circle.Outputs.Interfaces.ICircleProfile] parser' of constructor 'Void .ctor(MyProj.Services.DataServices.Circle.QueryBuilders.Interfaces.ICircleProfileQueryBuilder, MyProj.Services.DataServices.Circle.QueryProcessors.Interfaces.ICircleQueryProcessor, MyProj.Services.DataServices.Circle.Parsers.Interfaces.ICircleParser1[MyProj.Services.DataServices.Circle.Outputs.Interfaces.ICircleProfile])'.


问:
PeopleSoft ExceltoCI - not saving zeros
I am trying to load some data into a custom table PeopleSoft using the delivered ExceltoCI utilty.  I have a record with a single key -EMPLID; we are expecting only one row per employee, not effective dated or anything like that.  In addition to EMPLID, I have about 9 numeric fields.  The upload process appears to work - the status for each row of data is the green OK, but with certain rows of data, when I check online or in my SQL tool, the data is not there.  This occurs when all of the 9 numeric fields in the data entry tab of the spreadsheet are set to 0.  All other rows load ok.  I am able to enter the data containig all zeros online.  I have noticed that if I set the default value of one of the numeric fields to 1, everything loads (but not if I set it to 0) through the utility.

Thanks in advance!

答: Put ,0 in the exceltoci field.  it will load and save.  it is the excel spreadsheet and the vba code behind the scenes that causes this.</p>

Title: PeopleSoft ExceltoCI - not saving zeros


问:
Access For Loop Hide Objects
I'm trying to hide/unhide around 30 objects on my form when the user selects certain values from a dropdown menu. I tried the loop below, however I receive the following error: 'Object doesn't support this property or method.' I have this code running on the 'AfterUpdate' of the dropdown menu object. </p>

```<code>Dim VisibleVisitFields() As String
Dim VisibleVisitFieldlist As String
Dim varVisibleVisit As Variant
VisibleVisitFieldlist = "VisitDate_Event,VisitTime_Event,VisitSite_Event,VisitStaff_Event,VisitMeet_Event"
VisibleVisitFields = Split(VisibleVisitFieldlist, ",")

If (EventType = 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = True
    Exit For
Next
Else
If (EventType <> 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = False
    Exit For
Next
End If
End If
</code>```

答:
Which line triggers the error? Suspect it is reference to the subform that is flawed. Never seen code like that to loop through an array. Suggest naming subform container different from the object it holds, such as ctrEvent. What is EventType - a textbox/field on the form? Consider code:

```<code>Dim aryFields As Variant
Dim x As Integer
aryFields = Split("VisitDate_Event,VisitTime_Event,VisitSite_Event,VisitStaff_Event,VisitMeet_Event", ",")
For x = 0 To UBound(aryFields)
    Me.ctrEvent.Form.Controls(aryFields(x)).Visible = Me.EventType = 3
Next
</code>```

Alternative methods not using array:

Set control Tag property then code loops through all controls on form and sets visibility for those that have particular value in Tag.

```<code>Dim ctrl As Control
For Each ctrl in Me.ctrEvent.Form.Controls
    If ctrl.Tag = "something" Then ctrl.Visibility = Me.EventType = 3
Next
</code>```

Another is to give controls similar names, like: Visit1, Visit2, etc. Then code:

```<code>Dim x As Integer
For x = 1 to 30
    Me.ctrEvent.Form.Controls("Visit" & x).Visible = Me.EventType = 3
Next
</code>```

Advise no spaces or punctuation/special characters (underscore only exception) in naming convention.

Title: Access For Loop Hide Objects

Body:
I'm trying to hide/unhide around 30 objects on my form when the user selects certain values from a dropdown menu. I tried the loop below, however I receive the following error: 'Object doesn't support this property or method.' I have this code running on the 'AfterUpdate' of the dropdown menu object.

Dim VisibleVisitFields() As String
Dim VisibleVisitFieldlist As String
Dim varVisibleVisit As Variant
VisibleVisitFieldlist = "VisitDate_Event,VisitTime_Event,VisitSite_Event,VisitStaff_Event,VisitMeet_Event"
VisibleVisitFields = Split(VisibleVisitFieldlist, ",")

If (EventType = 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = True
    Exit For
Next
Else
If (EventType <> 3) Then
    For Each varVisibleVisit In VisibleVisitFields
    [Forms]![subFRM_TBL_Event-All in One].Controls(varVisibleVisit).visible = False
    Exit For
Next
End If
End If

Body:
Which line triggers the error? Suspect it is reference to the subform that is flawed. Never seen code like that to loop through an array. Suggest naming subform container different from the object it holds, such as ctrEvent. What is EventType - a textbox/field on the form? Consider code:

Dim aryFields As Variant
Dim x As Integer
aryFields = Split("VisitDate_Event,VisitTime_Event,VisitSite_Event,VisitStaff_Event,VisitMeet_Event", ",")
For x = 0 To UBound(aryFields)
    Me.ctrEvent.Form.Controls(aryFields(x)).Visible = Me.EventType = 3
Next

Alternative methods not using array:

Set control Tag property then code loops through all controls on form and sets visibility for those that have particular value in Tag.

Dim ctrl As Control
For Each ctrl in Me.ctrEvent.Form.Controls
    If ctrl.Tag = "something" Then ctrl.Visibility = Me.EventType = 3
Next

Another is to give controls similar names, like: Visit1, Visit2, etc. Then code:

Dim x As Integer
For x = 1 to 30
    Me.ctrEvent.Form.Controls("Visit" & x).Visible = Me.EventType = 3
Next

Advise no spaces or punctuation/special characters (underscore only exception) in naming convention.


问:
How to use jquery plugins (like Owl Carousel 2) with angular 4 in typescript class?
I am trying to use jQuery plugins with angular 4 typescript class but unfortunately i am not successful to attain my objective.

I tried in many ways but angular 4 html component view didn't allow jQuery ready/other events so how can i use them?

I have currently created a component typescript class and tried to use jquery function in it but couldn't get success.

please see my code below :

```<code> import { Component, Input, ElementRef, HostBinding } from '@angular/core';
import * as $ from 'jquery';
import 'owl-carousel';

@Component({
  selector: 'owl-carousel',
  template: `<ng-content></ng-content>`
})
export class OwlCarouselComponent {
    @HostBinding('class') defaultClass = 'owl-carousel';
    @Input() options: Object;

  $owlElement: any;

  defaultOptions: any = {};

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    // use default - empty
    // for (var key in this.options) {
    //   this.defaultOptions[key] = this.options[key];
    // }
    this.$owlElement = $(this.el.nativeElement).owlCarousel(this.defaultOptions);
  }

  ngOnDestroy() {
    this.$owlElement.data('owlCarousel').destroy();
    this.$owlElement = null;
  }
}
</code>```

Visual Studio compiler display the red error on this line.

this.$owlElement = $(this.el.nativeElement).owlCarousel(this.defaultOptions);

and error messages are :

Severity    Code    Description Project File    Line    Suppression State
Error   TS2339  Build:Property 'owlCarousel' does not exist on type 'JQuery'.   On.Store.UI L:\ESaleStore\On.Store.UI\src\On.Store.UI\wwwroot\app\shared\OwlCarousel.component.ts   24

Error   TS2339  Property 'owlCarousel' does not exist on type 'JQuery'. On.Store.UI (tsconfig project)  L:\ESaleStore\On.Store.UI\src\On.Store.UI\wwwroot\app\shared\OwlCarousel.component.ts   24  Active

this is my tsconfig.json

```<code>  {
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules"
  ]
}
</code>```

and this is my systemjs.config.js file

```<code>`/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
            jquery: 'npm:@angular/jquery/dist/jquery.min.js',
            'owl-carousel': 'npm:@angular/owl.carousel/dist/owl.carousel.min.js'
        },
        meta: {
            'owl-carousel': {
                deps: ['jquery']
            },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);
</code>```

`

Kindly guide me . thank you

答:
I'm wondering whether your OwlCarousel is being correctly included.
There is a prebuilt module for OwlCarousel on npm (here), try that and see if it works for you.

Also, this post is about Angular 4, and so you should change your tag to angular instead of angularjs.

Body:
I am trying to use jQuery plugins with angular 4 typescript class but unfortunately i am not successful to attain my objective.

I tried in many ways but angular 4 html component view didn't allow jQuery ready/other events so how can i use them?

I have currently created a component typescript class and tried to use jquery function in it but couldn't get success.

please see my code below :

 import { Component, Input, ElementRef, HostBinding } from '@angular/core';
import * as $ from 'jquery';
import 'owl-carousel';

@Component({
  selector: 'owl-carousel',
  template: `<ng-content></ng-content>`
})
export class OwlCarouselComponent {
    @HostBinding('class') defaultClass = 'owl-carousel';
    @Input() options: Object;

  $owlElement: any;

  defaultOptions: any = {};

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    // use default - empty
    // for (var key in this.options) {
    //   this.defaultOptions[key] = this.options[key];
    // }
    this.$owlElement = $(this.el.nativeElement).owlCarousel(this.defaultOptions);
  }

  ngOnDestroy() {
    this.$owlElement.data('owlCarousel').destroy();
    this.$owlElement = null;
  }
}

Visual Studio compiler display the red error on this line.

this.$owlElement = $(this.el.nativeElement).owlCarousel(this.defaultOptions);

and error messages are :

Severity    Code    Description Project File    Line    Suppression State
Error   TS2339  Build:Property 'owlCarousel' does not exist on type 'JQuery'.   On.Store.UI L:\ESaleStore\On.Store.UI\src\On.Store.UI\wwwroot\app\shared\OwlCarousel.component.ts   24

Error   TS2339  Property 'owlCarousel' does not exist on type 'JQuery'. On.Store.UI (tsconfig project)  L:\ESaleStore\On.Store.UI\src\On.Store.UI\wwwroot\app\shared\OwlCarousel.component.ts   24  Active

this is my tsconfig.json

  {
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules"
  ]
}

and this is my systemjs.config.js file

`/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
            jquery: 'npm:@angular/jquery/dist/jquery.min.js',
            'owl-carousel': 'npm:@angular/owl.carousel/dist/owl.carousel.min.js'
        },
        meta: {
            'owl-carousel': {
                deps: ['jquery']
            },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);

`

Kindly guide me . thank you


问:
How to make Pandas unpack JSON data into proper DataFrame instead of list of dicts
I'm trying to parse the data at http://dev.hsl.fi/tmp/citybikes/stations_20170503T071501Z into a Pandas DataFrame. Using read_json gives me a list of dicts instead of a proper DataFrame with the variable names as columns:

```<code>In [1]:

data = pd.read_json("http://dev.hsl.fi/tmp/citybikes/stations_20170503T071501Z")
print(data)

Out[1]:

                                                result
0    {'name': '001 Kaivopuisto', 'coordinates': '60...
1    {'name': '002 Laivasillankatu', 'coordinates':...
..                                                 ...
149  {'name': '160 Nokkala', 'coordinates': '60.147...
150  {'name': '997 Workshop Helsinki', 'coordinates...

[151 rows x 1 columns]
</code>```

This happens with all orient option. I've tried json_normalize() to no avail as well and a few other things I found here. How could I make this into a sensible DataFrame? Thanks!

答:
Option 1

Use pd.DataFrame on the list of dictionaries

```<code>pd.DataFrame(data['result'].values.tolist())

   avl_bikes          coordinates  free_slots                    name  operative style  total_slots
0         12  60.155411,24.950391          18         001 Kaivopuisto       True    CB           30
1          3  60.159715,24.955212           9     002 Laivasillankatu       True                 12
2          0  60.158172,24.944808          16  003 Kapteeninpuistikko       True                 16
3          0  60.160944,24.941859          14           004 Viiskulma       True                 14
4         16  60.157935,24.936083          16           005 Sepänkatu       True                 32
</code>```

Option 2

Use apply

```<code>data.result.apply(pd.Series)

   avl_bikes          coordinates  free_slots                    name  operative style  total_slots
0         12  60.155411,24.950391          18         001 Kaivopuisto       True    CB           30
1          3  60.159715,24.955212           9     002 Laivasillankatu       True                 12
2          0  60.158172,24.944808          16  003 Kapteeninpuistikko       True                 16
3          0  60.160944,24.941859          14           004 Viiskulma       True                 14
4         16  60.157935,24.936083          16           005 Sepänkatu       True                 32
</code>```

Option 3

Or you could fetch the json yourself and strip out the results

```<code>import urllib, json
url = "http://dev.hsl.fi/tmp/citybikes/stations_20170503T071501Z"
response = urllib.request.urlopen(url)
data = json.loads(response.read())

df = pd.DataFrame(data['result'])
df

   avl_bikes          coordinates  free_slots                    name  operative style  total_slots
0         12  60.155411,24.950391          18         001 Kaivopuisto       True    CB           30
1          3  60.159715,24.955212           9     002 Laivasillankatu       True                 12
2          0  60.158172,24.944808          16  003 Kapteeninpuistikko       True                 16
3          0  60.160944,24.941859          14           004 Viiskulma       True                 14
4         16  60.157935,24.936083          16           005 Sepänkatu       True                 32
</code>```

Body:
I'm trying to parse the data at http://dev.hsl.fi/tmp/citybikes/stations_20170503T071501Z into a Pandas DataFrame. Using read_json gives me a list of dicts instead of a proper DataFrame with the variable names as columns:

In [1]:

data = pd.read_json("http://dev.hsl.fi/tmp/citybikes/stations_20170503T071501Z")
print(data)

Out[1]:

                                                result
0    {'name': '001 Kaivopuisto', 'coordinates': '60...
1    {'name': '002 Laivasillankatu', 'coordinates':...
..                                                 ...
149  {'name': '160 Nokkala', 'coordinates': '60.147...
150  {'name': '997 Workshop Helsinki', 'coordinates...

[151 rows x 1 columns]

This happens with all orient option. I've tried json_normalize() to no avail as well and a few other things I found here. How could I make this into a sensible DataFrame? Thanks!

Body:
Option 1

Use pd.DataFrame on the list of dictionaries

pd.DataFrame(data['result'].values.tolist())

   avl_bikes          coordinates  free_slots                    name  operative style  total_slots
0         12  60.155411,24.950391          18         001 Kaivopuisto       True    CB           30
1          3  60.159715,24.955212           9     002 Laivasillankatu       True                 12
2          0  60.158172,24.944808          16  003 Kapteeninpuistikko       True                 16
3          0  60.160944,24.941859          14           004 Viiskulma       True                 14
4         16  60.157935,24.936083          16           005 Sepänkatu       True                 32

Option 2

Use apply

data.result.apply(pd.Series)

   avl_bikes          coordinates  free_slots                    name  operative style  total_slots
0         12  60.155411,24.950391          18         001 Kaivopuisto       True    CB           30
1          3  60.159715,24.955212           9     002 Laivasillankatu       True                 12
2          0  60.158172,24.944808          16  003 Kapteeninpuistikko       True                 16
3          0  60.160944,24.941859          14           004 Viiskulma       True                 14
4         16  60.157935,24.936083          16           005 Sepänkatu       True                 32

Option 3

Or you could fetch the json yourself and strip out the results

import urllib, json
url = "http://dev.hsl.fi/tmp/citybikes/stations_20170503T071501Z"
response = urllib.request.urlopen(url)
data = json.loads(response.read())

df = pd.DataFrame(data['result'])
df

   avl_bikes          coordinates  free_slots                    name  operative style  total_slots
0         12  60.155411,24.950391          18         001 Kaivopuisto       True    CB           30
1          3  60.159715,24.955212           9     002 Laivasillankatu       True                 12
2          0  60.158172,24.944808          16  003 Kapteeninpuistikko       True                 16
3          0  60.160944,24.941859          14           004 Viiskulma       True                 14
4         16  60.157935,24.936083          16           005 Sepänkatu       True                 32


问:
MVC ViewModel HttpPost return value has null values
I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.

View model UserRightViewModel

```<code>public class UserRightViewModel
{
    public string SelectedItemId { get; set; }

    public SelectList Users;

    public List<RightViewModel> Rights { get; set; }
}
</code>```

View model RightsViewModel

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

    public string Name{ get; set; }

    public bool isSelected { get; set; }
}
</code>```

Controller Post

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
   UserRightsViewModel viewModel = _viewModel;
   /*value _viewModel = null for Users and Rights
   /* code stuff */
   return View(viewModel);
}
</code>```

View

```<code>@model Web.ViewModels.UserRightsViewModel
     @using (Html.BeginForm())
     {
         @Html.AntiForgeryToken()

    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <h1>
                @ViewBag.Title
            </h1>
            @*<ol class="breadcrumb">
                    <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
                    <li><a href="#">Examples</a></li>
                    <li class="active">Blank page</li>
                </ol>*@
        </section>

        <!-- Main content -->
        <section class="content">

            <!-- Default box -->
            <div class="box">
                <div class="box-header with-border">

                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
                            <i class="fa fa-minus"></i>
                        </button>
                        <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>

        <br />
                <div class="form-group">
                    @Html.LabelFor(model => model.SelectedItemId, "User", new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.SelectedItemId)
                    </div>
                </div>
                <br />

          <div class="box-body">

                    @for (int i = 0; i < Model.Rights.Count(); i += 2)
                    {
                        <div class="row form-group">
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="col-md-6">

                                        </div>
                                        <div class="col-md-6">
                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                    <div class="col-md-8">

                                        @Model.Rights.ElementAt(i).Denumire
                                    </div>
                                </div>

                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="col-md-6">

                                        </div>
                                        <div class="col-md-6">
                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                    <div class="col-md-8">
                                        @Model.Rights.ElementAt(i + 1).Name
                                    </div>
                                </div>
                            </div>
                        </div>

                    }
                    <br />
                    <br />
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="col-md-9">

                                </div>
                                <div class="col-md-3">
                                    <input type="submit" value="Save" class="btn btn-primary" />
                                </div>
                            </div>
                            <div class="col-md-6">
                                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-danger" })
                            </div>
                        </div>
                    </div>
                </div>
               </div>
        </section>
    </div>
}
</code>```

I have no idea why some values are null. Why some of values are sent and some not?

答:
Hi here is answer for your doubt, some values are posting and some values are not.

Actually you are getting the correct result and everything works perfectly

I said this because, if you bind selectedid and selectlistitem to the dropdownlistfor helper, then you will get only selectedid which was assigned as a name for the dropdownlist control. so when post, browser has sent name value pair.

This is same reason for checkbox also , which property has binded to the name that only you will get it in the post.

Hope above information was helpful

Thanks

Karthik

ContentLicense: CC BY-SA 4.0

Body:
I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.

View model UserRightViewModel

public class UserRightViewModel
{
    public string SelectedItemId { get; set; }

    public SelectList Users;

    public List<RightViewModel> Rights { get; set; }
}

View model RightsViewModel

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

    public string Name{ get; set; }

    public bool isSelected { get; set; }
}

Controller Post

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
   UserRightsViewModel viewModel = _viewModel;
   /*value _viewModel = null for Users and Rights
   /* code stuff */
   return View(viewModel);
}

View

@model Web.ViewModels.UserRightsViewModel
     @using (Html.BeginForm())
     {
         @Html.AntiForgeryToken()

                @ViewBag.Title

            @*

 Home

Examples

Blank page

*@

                        <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">

                        </button>
                        <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">

                        </button>

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

                        @Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.SelectedItemId)

                    @for (int i = 0; i < Model.Rights.Count(); i += 2)
                    {

                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { @class = "text-danger" })

                                        @Model.Rights.ElementAt(i).Denumire

                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { @class = "text-danger" })

                                        @Model.Rights.ElementAt(i + 1).Name

                    }

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

                                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-danger" })

}

I have no idea why some values are null. Why some of values are sent and some not?


问:
How to get immediate parent node with scrapy in python?
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

```<code>dom style1:
<div class="user-info">
    <p class="user-name">
        something in p tag
    </p>
    text data I want
</div>

dom style2:
<div class="user-info">
    <div>
        <p class="user-img">
            something in p tag
        </p>
        something in div tag
    </div>
    <div>
        <p class="user-name">
            something in p tag
        </p>
        text data I want
    </div>
</div>
</code>```

I want to get the data text data I want, now I can use css or xpath selector to get it by check it exists. But I want to know some better ways.
For example, I can get css p.user-name first, and then I get it's parent, and then I get it's div/text(), and always the data I want is the text() of the p.user-name's immediate parent div, but the question is, how can I get the immediate parent p.user-name?

答:
With xpath you can traverse the xml tree in every direction(parent, sibling, child etc.) where css doesn't support this.

For your case you can get node's parent with xpath .. parent notation:

```<code>//p[@class='user-name']/../text()
</code>```

Explanation:

//p[@class='user-name'] - find
 nodes with class value user-name.

/.. - select node's parent.

/text() - select text of the current node.

This xpath should work in both of your described cases.

Body:
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

dom style1:

        something in p tag

    text data I want

dom style2:

            something in p tag

        something in div tag

            something in p tag

        text data I want

I want to get the data text data I want, now I can use css or xpath selector to get it by check it exists. But I want to know some better ways.
For example, I can get css p.user-name first, and then I get it's parent, and then I get it's div/text(), and always the data I want is the text() of the p.user-name's immediate parent div, but the question is, how can I get the immediate parent p.user-name?

Body:
With xpath you can traverse the xml tree in every direction(parent, sibling, child etc.) where css doesn't support this.

For your case you can get node's parent with xpath .. parent notation:

//p[@class='user-name']/../text()

Explanation:

//p[@class='user-name'] - find <p> nodes with class value user-name.

/.. - select node's parent.

/text() - select text of the current node.

This xpath should work in both of your described cases.


问:
com.finder.desktopservices asks for admin password when copying files
I am trying to copy files from my mac to a network drive. When copying the files, an empty file is created at the destination and I get a prompt saying I might have to enter an administrator password to change the file named "whatever my file name is". When I press continue, the password dialog shows it is com.apple.desktopservices which is asking for the password.

From what I see happening, an empty file is first created and then I am prompted for a password. Once I enter the password, the empty file is removed and another file is created. It is to this file that the contents are written.

Any ideas why this should happen?

Thanks.

P.S. The file has full read-write permissions

答: Is the file actually created, or is Finder just displaying an icon for it? What kind of machine is the network drive (another Mac, a Windows machine, a NAS?), and what protocol are you using to connect to it? (SMB, CIFS)?</p>

OwnerDisplayName: lostInTransit

LastEditorDisplayName: Peter Hosey

OwnerDisplayName: Mo


问:
implementing an abstract base class function in another template base class
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

```<code>class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}
</code>```

Unfortunately, this yields the compiler error:

```<code>1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'
</code>```

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH

答: Since Foo extends Base, before instantiating Foo (Foo c;), you need to implement all virtual methods of Base. In your example, you need to implement virtual void Base_Do( Buzz* ).

Body:
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}

Unfortunately, this yields the compiler error:

1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH