问:
Accessing filename from file queue in Tensor Flow
I have a directory of images, and a separate file matching image filenames to labels. So the directory of images has files like 'train/001.jpg' and the labeling file looks like:

```<code>train/001.jpg 1
train/002.jpg 2
...
</code>```

I can easily load images from the image directory in Tensor Flow by creating a filequeue from the filenames:

```<code>filequeue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
img = reader.read(filequeue)
</code>```

But I'm at a loss for how to couple these files with the labels from the labeling file. It seems I need access to the filenames inside the queue at each step. Is there a way to get them? Furthermore, once I have the filename, I need to be able to look up the label keyed by the filename. It seems like a standard Python dictionary wouldn't work because these computations need to happen at each step in the graph.

答:
I used this:</p>

```<code> filename = filename.strip().decode('ascii')
</code>```

Body:
I have a directory of images, and a separate file matching image filenames to labels. So the directory of images has files like 'train/001.jpg' and the labeling file looks like:

train/001.jpg 1
train/002.jpg 2
...

I can easily load images from the image directory in Tensor Flow by creating a filequeue from the filenames:

filequeue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
img = reader.read(filequeue)

But I'm at a loss for how to couple these files with the labels from the labeling file. It seems I need access to the filenames inside the queue at each step. Is there a way to get them? Furthermore, once I have the filename, I need to be able to look up the label keyed by the filename. It seems like a standard Python dictionary wouldn't work because these computations need to happen at each step in the graph.

Body:
I used this:

 filename = filename.strip().decode('ascii')


来源: stackexchange

问:
Parallel and sequencial script execution
Need to run the following: if script-a ok, run script -b and script-c in parallel.

Tried the following code, but it runs script-a && script-b and script-c in parallel.

```<code>script-a && script-b & script-c & wait
</code>```

Is there a way to group script-b and script-c?

答:
Use braces:</p>

```<code>script-a && { script-b & script-c & wait; }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Need to run the following: if script-a ok, run script -b and script-c in parallel.

Tried the following code, but it runs script-a && script-b and script-c in parallel.

script-a && script-b & script-c & wait

Is there a way to group script-b and script-c?

Body:
Use braces:

script-a && { script-b & script-c & wait; }


问:
How to convert Varchar to Int in sql server 2008?
How to convert Varchar to Int in sql server 2008.

i have following code when i tried to run it wont allowed me to convert Varchar to Int.

```<code>Select Cast([Column1] as INT)
</code>```

Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int.
actually i am trying to insert Column1 into another table having Field as INT.
can someone please help me to convert this ?

答:
Try the following code. In most case, it is caused by the comma issue.</p>

```<code>cast(replace([FIELD NAME],',','') as float)
</code>```

Body:
How to convert Varchar to Int in sql server 2008.

i have following code when i tried to run it wont allowed me to convert Varchar to Int.

Select Cast([Column1] as INT)

Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int.
actually i am trying to insert Column1 into another table having Field as INT.
can someone please help me to convert this ?

Body:
Try the following code. In most case, it is caused by the comma issue.

cast(replace([FIELD NAME],',','') as float)


问:
Ignore failing test in jacoco test coverage
I'm using robolectric for unit tests and instrumentation tests for testing an android application. I've enabled jacoco test coverage plugin for providing coverage report, but it doesn't create when there is at least one failed test. How can failures be ignored in jacoco?

Here is my gradle.build

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

    android {
        jacoco {
            version = '0.7.3.201502191951'
        }

        testOptions {
            unitTests.returnDefaultValues = true
        }

        compileSdkVersion 22
        buildToolsVersion '22.0.1'

        defaultConfig {
            applicationId "com.nitralabs.m1_mm"
            minSdkVersion 12
            targetSdkVersion 18
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
            debug {
                testCoverageEnabled = true
            }
        }

    ...
    }

    dependencies {
        testCompile 'org.robolectric:robolectric:3.0'
        testCompile 'junit:junit:4.12'
        ...
    }

    task jacocoReport << {
        ant {
            taskdef(name: 'jacocoreport',
                    classname: 'org.jacoco.ant.ReportTask',
                    classpath: configurations.jacocoReport.asPath,
                    ignoreFailures: true, i)

            mkdir dir: "${buildDir}/test-coverage-report"
            mkdir dir: "${buildDir}/reports/jacoco/test/"

            jacocoreport {
                executiondata {
                    fileset dir: "${buildDir}/jacoco"
                }

                structure(name: "${rootProject.name}") {
                    classfiles {
                        fileset(dir: "${buildDir}/intermediates/classes/debug") {
                            exclude(name: '**/R.class')
                            exclude(name: '**/R$*.class')
                        }
                    }

                    sourcefiles {
                        fileset dir: "src/main/java"
                        fileset dir: 'build/generated/source/buildConfig/debug'
                    }
                }

                xml destfile: "${buildDir}/reports/jacoco/test/jacocoTestReport.xml"
                html destdir: "${buildDir}/test-coverage-report/"
            }
        }
    }

    project.afterEvaluate {
        def append = "append=true"
        def destFile = "destfile=$buildDir/outputs/code-coverage/connected/coverage.ec"
        testDebug.jvmArgs "-javaagent:$buildDir/intermediates/jacoco/jacocoagent.jar=$append,$destFile"
        createDebugCoverageReport.dependsOn testDebug
    }
</code>```

答:
This is my relevant config to ignore failing unit tests</p>

```<code>android {

 testOptions {
    unitTests.all {
        setIgnoreFailures(true)
    }
}

buildTypes {
    debug {
        testCoverageEnabled true
        }
    }
}
</code>```

Body:
I'm using robolectric for unit tests and instrumentation tests for testing an android application. I've enabled jacoco test coverage plugin for providing coverage report, but it doesn't create when there is at least one failed test. How can failures be ignored in jacoco?

Here is my gradle.build

apply plugin: 'com.android.application'

    android {
        jacoco {
            version = '0.7.3.201502191951'
        }

        testOptions {
            unitTests.returnDefaultValues = true
        }

        compileSdkVersion 22
        buildToolsVersion '22.0.1'

        defaultConfig {
            applicationId "com.nitralabs.m1_mm"
            minSdkVersion 12
            targetSdkVersion 18
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
            debug {
                testCoverageEnabled = true
            }
        }

    ...
    }

    dependencies {
        testCompile 'org.robolectric:robolectric:3.0'
        testCompile 'junit:junit:4.12'
        ...
    }

    task jacocoReport << {
        ant {
            taskdef(name: 'jacocoreport',
                    classname: 'org.jacoco.ant.ReportTask',
                    classpath: configurations.jacocoReport.asPath,
                    ignoreFailures: true, i)

            mkdir dir: "${buildDir}/test-coverage-report"
            mkdir dir: "${buildDir}/reports/jacoco/test/"

            jacocoreport {
                executiondata {
                    fileset dir: "${buildDir}/jacoco"
                }

                structure(name: "${rootProject.name}") {
                    classfiles {
                        fileset(dir: "${buildDir}/intermediates/classes/debug") {
                            exclude(name: '**/R.class')
                            exclude(name: '**/R$*.class')
                        }
                    }

                    sourcefiles {
                        fileset dir: "src/main/java"
                        fileset dir: 'build/generated/source/buildConfig/debug'
                    }
                }

                xml destfile: "${buildDir}/reports/jacoco/test/jacocoTestReport.xml"
                html destdir: "${buildDir}/test-coverage-report/"
            }
        }
    }

    project.afterEvaluate {
        def append = "append=true"
        def destFile = "destfile=$buildDir/outputs/code-coverage/connected/coverage.ec"
        testDebug.jvmArgs "-javaagent:$buildDir/intermediates/jacoco/jacocoagent.jar=$append,$destFile"
        createDebugCoverageReport.dependsOn testDebug
    }

Body:
This is my relevant config to ignore failing unit tests

android {

 testOptions {
    unitTests.all {
        setIgnoreFailures(true)
    }
}

buildTypes {
    debug {
        testCoverageEnabled true
        }
    }
}


问:
Trouble Using an If Statement
I am trying to create a table that will generate numbers to round to a specified place value.  The table (in HTML code) is shown below.

```<code>        <table border = "1">

            <col width = "25">
            <col width = "150">
            <col width = "100">
            <col width = "100">
            <col width = "50">

            <tr><td>  </td><td>Place Vaue</td><td>Value</td><td></td></tr>
            <tr><td>a.</td><td><span id = "roundingQuestion1"></span></td><td><span id = "placeValue1"></span></td><td></td></tr>
            <tr><td>b.</td><td><span id = "roundingQuestion2"></span></td><td><span id = "placeValue2"></span></td><td></td></tr>
            <tr><td>c.</td><td><span id = "roundingQuestion3"></span></td><td><span id = "placeValue3"></span></td><td></td></tr>
            <tr><td>d.</td><td><span id = "roundingQuestion4"></span></td><td><span id = "placeValue4"></span></td><td></td></tr>
            <tr><td>d.</td><td><span id = "roundingQuestion5"></span></td><td><span id = "placeValue5"></span></td><td></td></tr>
            <tr><td>e.</td><td><span id = "roundingQuestion6"></span></td><td><span id = "placeValue6"></span></td><td></td></tr>
            <tr><td>f.</td><td><span id = "roundingQuestion7"></span></td><td><span id = "placeValue7"></span></td><td></td></tr>
            <tr><td>g.</td><td><span id = "roundingQuestion8"></span></td><td><span id = "placeValue8"></span></td><td></td></tr>
            <tr><td>h.</td><td><span id = "roundingQuestion9"></span></td><td><span id = "placeValue9"></span></td><td></td></tr>
            <tr><td>i.</td><td><span id = "roundingQuestion10"></span></td><td><span id = "placeValue10"></span></td><td></td></tr>

        </table>

        <br />
        <br />

        <button onclick="createRoundingQuestions()">Create Questions</button>
</code>```

The javascript file that I am using to do this is:

```<code>var placeValueName = ["Thousandth", "Hundredth", "Tenth", "Ones", "tens", "Hundreds", "Thousands", "Ten Thousands", "Hundred Thousands"];

function getRndInteger(min, max){
    return Math.floor(Math.random() * (max - min) ) + min;
}

function createRoundingQuestions(){
    var j;
    var x;
    var numberDecimals;
    var lowValue;
    var highValue;

    for (j = 1; j <= 10; j++){
        x = getRndInteger(0, placeValueName.length, 0);

        document.getElementById("roundingQuestion"+j).innerHTML = placeValueName[x];
        document.getElementById("number"+j).innerHTML = x;

        if (x >= 5){
            lowValue = Math.pow(10, x - 3);
            highValue = Math.pow(10, x - 2);
            numberDecimals = getRndInteger(0, 6);
        } else if (x >= 3) && (x < 5){
            lowValue = 1;
            highValue = 1000;
            numberDecimals = getRndInteger(1, 3);
        } else {
            lowValue = 1;
            highValue = 1000;
            numberDecimals = getRndInteger(2, 6);
        }

        document.getElementById("placeValue"+j).innerHTML = (Math.random() * (highValue - lowValue) ) + lowValue).tofixed(numberDecimals);
    }
}
</code>```

The first part of the javascript file works.  It will add the place value (thousands, hundreds, tens, etc.) to each row of the table.  However, when I include the If Statement to detemine the number and the proper number of decimal places, the output is a blank table that will not populate.  I would appreciate if anyone could point out what I am doing wrong and suggest how to fix it.

答:
here it is, you got a lot of missing code / typos...

var placeValueName = ["Thousandth", "Hundredth", "Tenth", "Ones", "tens", "Hundreds", "Thousands", "Ten Thousands", "Hundred Thousands"];

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function createRoundingQuestions() {
  var j;
  var x;
  var numberDecimals;
  var lowValue;
  var highValue;

  for (j = 1; j <= 10; j++) {
    x = getRndInteger(0, placeValueName.length, 0);

    document.getElementById("roundingQuestion" + j).innerHTML = placeValueName[x];
    document.getElementById("number" + j).innerHTML = x;

    if (x >= 5) {
      lowValue = Math.pow(10, x - 3);
      highValue = Math.pow(10, x - 2);
      numberDecimals = getRndInteger(0, 6);
    } else if ((x >= 3) && (x < 5)){
      lowValue = 1;
      highValue = 1000;
      numberDecimals = getRndInteger(1, 3);
    } else {
      lowValue = 1;
      highValue = 1000;
      numberDecimals = getRndInteger(2, 6);
    }

    document.getElementById("placeValue" + j).innerHTML = (Math.random() * (highValue - lowValue)) + (lowValue).toFixed(numberDecimals);
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">

  <col width="25">
  <col width="150">
  <col width="100">
  <col width="100">
  <col width="50">

  <tr>
    <td> </td>
    <td>Place Vaue</td>
    <td>Value</td>
    <td></td>
  </tr>
  <tr>
    <td>a.</td>
    <td><span id="roundingQuestion1"></span></td>
    <td><span id="placeValue1"></span></td>
    <td><span id="number1"></span></td>
  </tr>
  <tr>
    <td>b.</td>
    <td><span id="roundingQuestion2"></span></td>
    <td><span id="placeValue2"></span></td>
    <td><span id="number2"></span></td>
  </tr>
  <tr>
    <td>c.</td>
    <td><span id="roundingQuestion3"></span></td>
    <td><span id="placeValue3"></span></td>
    <td><span id="number3"></span></td>
  </tr>
  <tr>
    <td>d.</td>
    <td><span id="roundingQuestion4"></span></td>
    <td><span id="placeValue4"></span></td>
    <td><span id="number4"></span></td>
  </tr>
  <tr>
    <td>d.</td>
    <td><span id="roundingQuestion5"></span></td>
    <td><span id="placeValue5"></span></td>
    <td><span id="number5"></span></td>
  </tr>
  <tr>
    <td>e.</td>
    <td><span id="roundingQuestion6"></span></td>
    <td><span id="placeValue6"></span></td>
    <td><span id="number6"></span></td>
  </tr>
  <tr>
    <td>f.</td>
    <td><span id="roundingQuestion7"></span></td>
    <td><span id="placeValue7"></span></td>
    <td><span id="number7"></span></td>
  </tr>
  <tr>
    <td>g.</td>
    <td><span id="roundingQuestion8"></span></td>
    <td><span id="placeValue8"></span></td>
    <td><span id="number8"></span></td>
  </tr>
  <tr>
    <td>h.</td>
    <td><span id="roundingQuestion9"></span></td>
    <td><span id="placeValue9"></span></td>
    <td><span id="number9"></span></td>
  </tr>
  <tr>
    <td>i.</td>
    <td><span id="roundingQuestion10"></span></td>
    <td><span id="placeValue10"></span></td>
    <td><span id="number10"></span></td>
  </tr>

</table>

<br />
<br />

<button onclick="createRoundingQuestions()">Create Questions</button></code>```

Title: Trouble Using an If Statement

Body:
I am trying to create a table that will generate numbers to round to a specified place value.  The table (in HTML code) is shown below.

            <col width = "25">
            <col width = "150">
            <col width = "100">
            <col width = "100">
            <col width = "50">

  	Place Vaue	Value

a.

b.

c.

d.

d.

e.

f.

g.

h.

i.

        <button onclick="createRoundingQuestions()">Create Questions</button>

The javascript file that I am using to do this is:

var placeValueName = ["Thousandth", "Hundredth", "Tenth", "Ones", "tens", "Hundreds", "Thousands", "Ten Thousands", "Hundred Thousands"];

function getRndInteger(min, max){
    return Math.floor(Math.random() * (max - min) ) + min;
}

function createRoundingQuestions(){
    var j;
    var x;
    var numberDecimals;
    var lowValue;
    var highValue;

    for (j = 1; j <= 10; j++){
        x = getRndInteger(0, placeValueName.length, 0);

        document.getElementById("roundingQuestion"+j).innerHTML = placeValueName[x];
        document.getElementById("number"+j).innerHTML = x;

        if (x >= 5){
            lowValue = Math.pow(10, x - 3);
            highValue = Math.pow(10, x - 2);
            numberDecimals = getRndInteger(0, 6);
        } else if (x >= 3) && (x < 5){
            lowValue = 1;
            highValue = 1000;
            numberDecimals = getRndInteger(1, 3);
        } else {
            lowValue = 1;
            highValue = 1000;
            numberDecimals = getRndInteger(2, 6);
        }

        document.getElementById("placeValue"+j).innerHTML = (Math.random() * (highValue - lowValue) ) + lowValue).tofixed(numberDecimals);
    }
}

The first part of the javascript file works.  It will add the place value (thousands, hundreds, tens, etc.) to each row of the table.  However, when I include the If Statement to detemine the number and the proper number of decimal places, the output is a blank table that will not populate.  I would appreciate if anyone could point out what I am doing wrong and suggest how to fix it.

Body:
here it is, you got a lot of missing code / typos...

var placeValueName = ["Thousandth", "Hundredth", "Tenth", "Ones", "tens", "Hundreds", "Thousands", "Ten Thousands", "Hundred Thousands"];

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function createRoundingQuestions() {
  var j;
  var x;
  var numberDecimals;
  var lowValue;
  var highValue;

  for (j = 1; j <= 10; j++) {
    x = getRndInteger(0, placeValueName.length, 0);

    document.getElementById("roundingQuestion" + j).innerHTML = placeValueName[x];
    document.getElementById("number" + j).innerHTML = x;

    if (x >= 5) {
      lowValue = Math.pow(10, x - 3);
      highValue = Math.pow(10, x - 2);
      numberDecimals = getRndInteger(0, 6);
    } else if ((x >= 3) && (x < 5)){
      lowValue = 1;
      highValue = 1000;
      numberDecimals = getRndInteger(1, 3);
    } else {
      lowValue = 1;
      highValue = 1000;
      numberDecimals = getRndInteger(2, 6);
    }

    document.getElementById("placeValue" + j).innerHTML = (Math.random() * (highValue - lowValue)) + (lowValue).toFixed(numberDecimals);
}
}

<table border="1">

  <col width="25">
  <col width="150">
  <col width="100">
  <col width="100">
  <col width="50">

  <tr>
    <td> </td>
    <td>Place Vaue</td>
    <td>Value</td>
    <td></td>
  </tr>
  <tr>
    <td>a.</td>
    <td><span id="roundingQuestion1"></span></td>
    <td><span id="placeValue1"></span></td>
    <td><span id="number1"></span></td>
  </tr>
  <tr>
    <td>b.</td>
    <td><span id="roundingQuestion2"></span></td>
    <td><span id="placeValue2"></span></td>
    <td><span id="number2"></span></td>
  </tr>
  <tr>
    <td>c.</td>
    <td><span id="roundingQuestion3"></span></td>
    <td><span id="placeValue3"></span></td>
    <td><span id="number3"></span></td>
  </tr>
  <tr>
    <td>d.</td>
    <td><span id="roundingQuestion4"></span></td>
    <td><span id="placeValue4"></span></td>
    <td><span id="number4"></span></td>
  </tr>
  <tr>
    <td>d.</td>
    <td><span id="roundingQuestion5"></span></td>
    <td><span id="placeValue5"></span></td>
    <td><span id="number5"></span></td>
  </tr>
  <tr>
    <td>e.</td>
    <td><span id="roundingQuestion6"></span></td>
    <td><span id="placeValue6"></span></td>
    <td><span id="number6"></span></td>
  </tr>
  <tr>
    <td>f.</td>
    <td><span id="roundingQuestion7"></span></td>
    <td><span id="placeValue7"></span></td>
    <td><span id="number7"></span></td>
  </tr>
  <tr>
    <td>g.</td>
    <td><span id="roundingQuestion8"></span></td>
    <td><span id="placeValue8"></span></td>
    <td><span id="number8"></span></td>
  </tr>
  <tr>
    <td>h.</td>
    <td><span id="roundingQuestion9"></span></td>
    <td><span id="placeValue9"></span></td>
    <td><span id="number9"></span></td>
  </tr>
  <tr>
    <td>i.</td>
    <td><span id="roundingQuestion10"></span></td>
    <td><span id="placeValue10"></span></td>
    <td><span id="number10"></span></td>
  </tr>

</table>

<br />
<br />

<button onclick="createRoundingQuestions()">Create Questions</button>


问:
How to create Dask DataFrame from a list of urls?
I have a list of the URLs, and I'd love to read them to the dask data frame
at once, but it looks like read_csv can't use an asterisk for http. Is there any way to achieve that?

Here is an example:

```<code>link = 'http://web.mta.info/developers/'

data = [     'data/nyct/turnstile/turnstile_170128.txt',
                        'data/nyct/turnstile/turnstile_170121.txt',
                        'data/nyct/turnstile/turnstile_170114.txt',
                        'data/nyct/turnstile/turnstile_170107.txt'
        ]
</code>```

and what I want is

df = dd.read_csv('XXXX*X')

答:
Try using dask.delayed to turn each of your urls into a lazy pandas dataframe and then use dask.dataframe.from_delayed  to turn those lazy values into a full dask dataframe

```<code>import pandas as pd
import dask
import dask.dataframe as dd

dfs = [dask.delayed(pd.read_csv)(url) for url in urls]

df = dd.from_delayed(dfs)
</code>```

This will read one of your links immediately in order to figure out metadata (column, dtypes).  If you know these dtypes and links ahead of time then you can avoid this by passing a sample empty dataframe to dd.from_delayed(..., meta=sample_df)

See also: http://dask.pydata.org/en/latest/delayed-collections.html

Body:
I have a list of the URLs, and I'd love to read them to the dask data frame
at once, but it looks like read_csv can't use an asterisk for http. Is there any way to achieve that?

Here is an example:

link = 'http://web.mta.info/developers/'

data = [     'data/nyct/turnstile/turnstile_170128.txt',
                        'data/nyct/turnstile/turnstile_170121.txt',
                        'data/nyct/turnstile/turnstile_170114.txt',
                        'data/nyct/turnstile/turnstile_170107.txt'
        ]

and what I want is

df = dd.read_csv('XXXX*X')

Body:
Try using dask.delayed to turn each of your urls into a lazy pandas dataframe and then use dask.dataframe.from_delayed  to turn those lazy values into a full dask dataframe

import pandas as pd
import dask
import dask.dataframe as dd

dfs = [dask.delayed(pd.read_csv)(url) for url in urls]

df = dd.from_delayed(dfs)

This will read one of your links immediately in order to figure out metadata (column, dtypes).  If you know these dtypes and links ahead of time then you can avoid this by passing a sample empty dataframe to dd.from_delayed(..., meta=sample_df)

See also: http://dask.pydata.org/en/latest/delayed-collections.html


问:
newbie: idled python def
I'm feeling a rabbit posting this question, but I don't continue because this:
What's is wrong with this stretch of my code:

When I put something after the "if" I receive:

IndentationError: unindent does not match any outer indentation level

For example, if I put "cont =3" after the "if" and before "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      post = form2.save(commit=False)
                                    ^ IndentationError: unindent does not match any outer indentation level

If I put the same expression but before of "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      cont = 3
             ^ TabError: inconsistent use of tabs and spaces in indentation

the code:

```<code>def evaluation(request):
    # form2 initialization
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    cont = 0

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid() == True:
            cont = 3
            post = form2.save(commit=False)
            post.save()
            return redirect('canditate_list')
    else:
        form2 = EvalForm()
    return render(request, 'app/evaluation.html', {'criterions': form2,})
</code>```

[EDIT]:
Guys, I don't indented wrong because I just press "Enter" before I type "True:",There's no way I could have mistaken it if the editor did this automatically

[EDIT2]:
I NEVER use space to indent my codes precisely avoid this problems, I ALWAYS use "tab" and just "tab"

答:
Normally, this happens because sometimes tabs != spaces. This also depends on type of editor a person is using.

A tab could be a different number of columns depending on your environment, but a space is always one column.

Spaces are the actual lowest-common denominator in punctuation.Many decent text editor has a "replace tabs with spaces" and this makes easier for programmers to just hit TAB key and get the desired indentation.

If you ever face such an error, try using spaces, because you can't go wrong with spaces, you might go wrong with tabs.

Latest editors like PyCharm follows PEP-8 and according to PEP-8, it's recommended to use spaces only for indentation in Python programs.

Title: newbie: idled python def

Body:
I'm feeling a rabbit posting this question, but I don't continue because this:
What's is wrong with this stretch of my code:

When I put something after the "if" I receive:

IndentationError: unindent does not match any outer indentation level

For example, if I put "cont =3" after the "if" and before "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      post = form2.save(commit=False)
                                    ^ IndentationError: unindent does not match any outer indentation level

If I put the same expression but before of "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      cont = 3
             ^ TabError: inconsistent use of tabs and spaces in indentation

the code:

def evaluation(request):
    # form2 initialization
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    cont = 0

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid() == True:
            cont = 3
            post = form2.save(commit=False)
            post.save()
            return redirect('canditate_list')
    else:
        form2 = EvalForm()
    return render(request, 'app/evaluation.html', {'criterions': form2,})

[EDIT]:
Guys, I don't indented wrong because I just press "Enter" before I type "True:",There's no way I could have mistaken it if the editor did this automatically

[EDIT2]:
I NEVER use space to indent my codes precisely avoid this problems, I ALWAYS use "tab" and just "tab"


问:
Unable to make div cover the entire screen and entire content
I am trying to make a a div overlap all the other contents of the web page even the fixed navbar i.e. when i click a button then a div appears that covers the entire page and covers the entire content.But with the code i have written,it is unable to cover the navbar and also the other contents shift down

The image that appears in the background,i want it to cover the entire page even the fixed navbar.Here is my code:

```<code>  <body  style=" background-color: black"  onload="countview()" >
        <div class="main" style="height:100vh;display: none;text-align: center;background-image: url(hmk1.jpg);" id="main">
            <h1>Livie</h1>
            <a href="#" class=" glyphicon glyphicon-tag">WHAT WE DO</a>
            <a href="#" class=" glyphicon glyphicon-tag">SIGNUP FOR NEWSLETTER</a>
            <a href="#" class=" glyphicon glyphicon-tag">PRIVACY POLICY</a>
            <a href="#" class=" glyphicon glyphicon-tag">TERMS AND CONDITIONS</a>
            <a href="#" class=" glyphicon glyphicon-tag">FAQS</a>
            <a href="#" class=" glyphicon glyphicon-tag">CONTACT US</a>
            <a href="#" class=" glyphicon glyphicon-remove" onclick="document.getElementById('main').style.display='none'"></a>
          </div>
         <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" style="height:120px">
         <div style="clear: both;">
         <h1  style="cursor:pointer"><a href="#" class=" glyphicon glyphicon-link" onclick="v();"></a> Welcome to Livie</h1>
   </nav>
</code>```

In the third last line i have given the link which on click will display the background that covers entire screen

答:
If you want a div that will cover EVERYTHING...

#COVER_EVERYTHING{
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: rgba(0,0,0,0.1);
z-index: 9999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="COVER_EVERYTHING"></div>
<p>Some text</p>
<h1>Some more text</h1>
<span>LOL</span></code>```

#COVER_EVERYTHING{
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: rgba(0,0,0,0.1);
z-index: 9999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--<div id="COVER_EVERYTHING"></div>
and without....
-->
<p>Some text</p>
<h1>Some more text</h1>
<span>LOL</span></code>```

Notice, it's easier to highlight without the DIV. The z-index on a position absolute property determines what it will be "higher" than if you will.

Body:
I am trying to make a a div overlap all the other contents of the web page even the fixed navbar i.e. when i click a button then a div appears that covers the entire page and covers the entire content.But with the code i have written,it is unable to cover the navbar and also the other contents shift down

The image that appears in the background,i want it to cover the entire page even the fixed navbar.Here is my code:

Livie

            WHAT WE DO
            SIGNUP FOR NEWSLETTER
            PRIVACY POLICY
            TERMS AND CONDITIONS
            FAQS
            CONTACT US

 Welcome to Livie

In the third last line i have given the link which on click will display the background that covers entire screen

Body:
If you want a div that will cover EVERYTHING...

#COVER_EVERYTHING{
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: rgba(0,0,0,0.1);
z-index: 9999;
}

<div id="COVER_EVERYTHING"></div>
<p>Some text</p>
<h1>Some more text</h1>
<span>LOL</span>

#COVER_EVERYTHING{
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: rgba(0,0,0,0.1);
z-index: 9999;
}

<!--<div id="COVER_EVERYTHING"></div>
and without....
-->
<p>Some text</p>
<h1>Some more text</h1>
<span>LOL</span>

Notice, it's easier to highlight without the DIV. The z-index on a position absolute property determines what it will be "higher" than if you will.


问:
Alternative of NOT EXISTS in MySQL as query is taking time to execute with NOT EXISTS
Dummy table:

```<code>id   FileName    DateLastSaved
1    Marium.doc    2015-01-01
2    Amna.doc      2016-01-01
3    Marium.doc    2016-01-01
</code>```

I want the query to return such rows where FileName is unique in the whole table. Rows should be returned for particular date range.
Suppose date ranges are of 2016 only, so third row should not be returned as FileName is not unique.

The query that I have created is:

```<code>$presentquery="SELECT * FROM InitialLog i WHERE MDid='$MDid' AND
(DateLastSaved>='$firstdate' AND DateLastSaved<='$presentdate') AND NOT
 EXISTS (SELECT id FROM InitialLog i2  WHERE i2.id<i.id AND i.FileName=i2.FileName )";
</code>```

(Where $firstdate and $presentdate are 2 dates for date ranges)

The query is returning the accurate results but it's taking time to execute. Is there any other way that I can rewrite this query??

(I have table with many rows)

答:
You can get the same logic using a LEFT JOIN and looking for nulls, that is,

```<code>$presentquery = "SELECT DISTINCT i.* FROM InitialLog i
LEFT JOIN InitialLog i2 ON i2.id<i.id AND i.FileName=i2.FileName
WHERE i.MDid='$MDid'
AND i.DateLastSaved>='$firstdate'
AND i.DateLastSaved<='$presentdate'
AND i2.id IS NULL";
</code>```

This way you are doing a single join rather than subquerying against each value in i.

Body:
Dummy table:

id   FileName    DateLastSaved
1    Marium.doc    2015-01-01
2    Amna.doc      2016-01-01
3    Marium.doc    2016-01-01

I want the query to return such rows where FileName is unique in the whole table. Rows should be returned for particular date range.
Suppose date ranges are of 2016 only, so third row should not be returned as FileName is not unique.

The query that I have created is:

$presentquery="SELECT * FROM InitialLog i WHERE MDid='$MDid' AND
(DateLastSaved>='$firstdate' AND DateLastSaved<='$presentdate') AND NOT
 EXISTS (SELECT id FROM InitialLog i2  WHERE i2.id<i.id AND i.FileName=i2.FileName )";

(Where $firstdate and $presentdate are 2 dates for date ranges)

The query is returning the accurate results but it's taking time to execute. Is there any other way that I can rewrite this query??

(I have table with many rows)

Body:
You can get the same logic using a LEFT JOIN and looking for nulls, that is,

$presentquery = "SELECT DISTINCT i.* FROM InitialLog i
LEFT JOIN InitialLog i2 ON i2.id<i.id AND i.FileName=i2.FileName
WHERE i.MDid='$MDid'
AND i.DateLastSaved>='$firstdate'
AND i.DateLastSaved<='$presentdate'
AND i2.id IS NULL";

This way you are doing a single join rather than subquerying against each value in i.


问:
How to skip specific properties when deserializing with newtonsoft json?
I have an API that returns a JSON array with 6000 objects. Each object has around 40 properties, but I only need to use around 20. How do ignore certain properties?
Here is my current code:</p>

```<code>string json = await client.GetStringAsync(string.Format(url));
List<ListModelClass> ListOfStuff = JsonConvert.DeserializeObject<List<ListModelClass>>(JArray.Parse(json).ToString());

public class ListModelClass {
    public string firstProperty { get; set; }
    public string secondProperty { get; set; }
    public string thirdProperty { get; set; }
    ... about 40 more
}
</code>```

答:
Properties in the JSON object match if and only if there is a property in the model class with the same name or you can use [JsonProperty(PropertyName = "your_property_name")]

So you can only include the properties which you want to use in your model class.

Body:
I have an API that returns a JSON array with 6000 objects. Each object has around 40 properties, but I only need to use around 20. How do ignore certain properties?
Here is my current code:

string json = await client.GetStringAsync(string.Format(url));
List<ListModelClass> ListOfStuff = JsonConvert.DeserializeObject<List<ListModelClass>>(JArray.Parse(json).ToString());

public class ListModelClass {
    public string firstProperty { get; set; }
    public string secondProperty { get; set; }
    public string thirdProperty { get; set; }
    ... about 40 more
}


问:
in db2 , how to delete records from multiple tables
i've been trying many of the solutions found by googling, but none work with this seemingly simple task.

in db2, i want to delete PO and PO lines, based on PO vendor and PO date.

PO and PO lines are linked by PO number. (below don't work)

```<code>DELETE FROM po, po_lines
  WHERE po_lines.po_num = po.po_num
  AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE
</code>```

TIA!

答:
The Delete statement only supports deleting rows from a single table. You can accomplish the same in 2 statements:</p>

```<code>DELETE FROM po_lines WHERE po_num IN
(
   SELECT po.po_num FROM po_lines
   JOIN po ON po_lines.po_num=po.po_num
   WHERE po.vendor = 'AAA' AND po.order_date = CURRENT DATE
);

DELETE FROM po WHERE po.vendor = 'AAA' AND po.order_date = CURRENT DATE
</code>```

Body:
i've been trying many of the solutions found by googling, but none work with this seemingly simple task.

in db2, i want to delete PO and PO lines, based on PO vendor and PO date.

PO and PO lines are linked by PO number. (below don't work)

DELETE FROM po, po_lines
  WHERE po_lines.po_num = po.po_num
  AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE

TIA!

Body:
The Delete statement only supports deleting rows from a single table. You can accomplish the same in 2 statements:

DELETE FROM po_lines WHERE po_num IN
(
   SELECT po.po_num FROM po_lines
   JOIN po ON po_lines.po_num=po.po_num
   WHERE po.vendor = 'AAA' AND po.order_date = CURRENT DATE
);

DELETE FROM po WHERE po.vendor = 'AAA' AND po.order_date = CURRENT DATE


问:
Upload image and store locally, save file name in db, show in view MVC 5
Spent a lot of time going through similar articles in search for an answer to this question, here are some of them:

1Link, (Unable to show more than 2 links, but i have a bunch of them)

And most relevant
8 Link but that project is not working

But after going through this examples i still unable to sort it out. At the moment my project works without images, im able to CRUD new articles to page and remove it. But now i need to add image.
First of all, i need an image to be as part of a class (i'm creating a new article with some title, short description, text body and image) here is model i came up with, this is non working code. As i want to store link to file to db so i guess i need to create new variable ImagePath

```<code>namespace PhClub.Models
{
    public class Media
    {
        public int Id { get; set; }

        public string title { get; set; }
        public string description { get; set; }
        [Required, StringLength(2048), DataType(DataType.MultilineText)]
        public string body { get; set; }
        public string ImagePath { get; set; }
    }
}
</code>```

Next i need to add create form to get a filename to upload it.  Here is Create view code snippet

```<code>@using (Html.BeginForm("Create", "Medias", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.title, "Title", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.title)
                @Html.ValidationMessageFor(model => model.title)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.description, "Description",new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.description)
                @Html.ValidationMessageFor(model => model.description)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.body,  "Media",new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.body)
                @Html.ValidationMessageFor(model => model.body)
            </div>
        </div>
        **<div class="form-group">
            File name
            <div class="uploadfile">
                @Html.TextBoxFor(model => model.file, new { type = "file" })
                @Html.ValidationMessageFor(model => model.file)
                <input type="submit" value="Submit" />
            </div>
        </div>**

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Создать" class="btn btn-default" />
            </div>
        </div>
    </div>
}
</code>```

However here i have two uncertainties:
1. I already have a Create method in in Controller, it was generated by EF for me:

```<code>[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,title,description,body")] Media media)
        {
            if (ModelState.IsValid)
            {
                db.Medias.Add(media);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(media);
        }
</code>```

But i need to integrate it somehow with this method somehow (i took this one from one of the examples)

```<code>   [HttpPost]
    public ActionResult FileUpload(Media mRegister)
    {
        //Check server side validation using data annotation
        if (ModelState.IsValid)
        {
            //TO:DO
            var fileName = Path.GetFileName(mRegister.file.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
            mRegister.file.SaveAs(path);
            ViewBag.Message = "File has been uploaded successfully";
            ModelState.Clear();
        }
        return View();
    }
</code>```

I cannot have two methods with the same name - CREATE doing different things on one hand and on other I cannot give different name to it as i don't need other View for it, it needs to be shown on Create view if im understanding what is going on here.
2. Secondary  - do i need to have two buttons for this? one for upload image and one for creating object?

And finally i need to show image as part of the article somehow in my Media view. At the moment it looks like that

```<code>    <h2>@Model.title</h2>
    <br>

    <div class="media">
        <p>
            <strong>@Html.Raw(Model.title)</strong>
        </p>
        <p>
            @Html.Raw(Model.description)
        </p>
        <p>
            @Html.Raw(Model.body)
        </p>
    </div>
   <div style ="float:right margin: 0px; 0px; 15px; 15px;">
          @Html.Raw(Model.file)
   </div>
</code>```

From here I'm lost. I need to place that image in certain place, but don't know how.In other examples people creating bunch of other classes for file. Do i need it? What the easiest way of doing it? I know I'm not the first who came up with this question, but i could really use your help guys.

答:
Your code is a little confusing to me. In your second example, you are using file property. But your class does not have that!!!

One suggestion : Try to use PascalCasing when writing C# classes and be consistent

Ideally you should create a view model for your view

```<code>public class MediaVm
{
   public string Title { get; set; }
   public string Body { get; set; }
   public HttpPostedFileBase Image { set; get; }
}
</code>```

Now have your view strongly typed to this view model

```<code>@model MediaVm
@using (Html.BeginForm("Create", "Medias", FormMethod.Post,
                                                new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(false)
    @Html.TextBoxFor(s=>s.Title)
    @Html.TextBoxFor(s=>s.Body)
    @Html.TextBoxFor(model => model.Image, new { type = "file" })
    <input type="submit" />
}
</code>```

Now, in your httppost action method, use the same view model as parameter, read the Image property value, save to disk with a unique name and save that unique file name in your table. We will move the code which saves the file to disk to another method which can be used from other methods as needed.

```<code>[HttpPost]
public ActionResult Create(MediaVm model)
{
  if (ModelState.IsValid)
  {
      var fileName = SaveAndReturnFileName(model.Img);
      var m = new Media { title = model.Title, body, model.Body};
      m.ImagePath = fileName;
      db.Medias.Add(m);
      db.SaveChanges();
      return RedirectToAction("Index");
  }
  return View(model);
}
public string SaveAndReturnFileName(HttpPostedFileBase file)
{
    if (file == null)
        return null;

    var fileName = Path.GetFileName(file.FileName);
    string randomFileName = Path.GetFileNameWithoutExtension(fileName) +
                        "_" +
                        Guid.NewGuid().ToString().Substring(0, 4)
                            + Path.GetExtension(fileName);
    var path = Path.Combine(Server.MapPath("~/Content/Upload/"), randomFileName);
    file.SaveAs(path);
    return randomFileName;
}
</code>```

You should be able to access the image like the below url

```<code>yourSiteName/Content/Upload/theRandomImageNameWeSavedInTable
</code>```

Body:
Spent a lot of time going through similar articles in search for an answer to this question, here are some of them:

1Link, (Unable to show more than 2 links, but i have a bunch of them)

And most relevant
8 Link but that project is not working

But after going through this examples i still unable to sort it out. At the moment my project works without images, im able to CRUD new articles to page and remove it. But now i need to add image.
First of all, i need an image to be as part of a class (i'm creating a new article with some title, short description, text body and image) here is model i came up with, this is non working code. As i want to store link to file to db so i guess i need to create new variable ImagePath

namespace PhClub.Models
{
    public class Media
    {
        public int Id { get; set; }

        public string title { get; set; }
        public string description { get; set; }
        [Required, StringLength(2048), DataType(DataType.MultilineText)]
        public string body { get; set; }
        public string ImagePath { get; set; }
    }
}

Next i need to add create form to get a filename to upload it.  Here is Create view code snippet

@using (Html.BeginForm("Create", "Medias", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true)

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

                @Html.EditorFor(model => model.title)
                @Html.ValidationMessageFor(model => model.title)

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

                @Html.EditorFor(model => model.description)
                @Html.ValidationMessageFor(model => model.description)

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

                @Html.EditorFor(model => model.body)
                @Html.ValidationMessageFor(model => model.body)

        **

            File name

                @Html.TextBoxFor(model => model.file, new { type = "file" })
                @Html.ValidationMessageFor(model => model.file)
                <input type="submit" value="Submit" />

**

                <input type="submit" value="Создать" class="btn btn-default" />

}

However here i have two uncertainties:
1. I already have a Create method in in Controller, it was generated by EF for me:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,title,description,body")] Media media)
        {
            if (ModelState.IsValid)
            {
                db.Medias.Add(media);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(media);
        }

But i need to integrate it somehow with this method somehow (i took this one from one of the examples)

   [HttpPost]
    public ActionResult FileUpload(Media mRegister)
    {
        //Check server side validation using data annotation
        if (ModelState.IsValid)
        {
            //TO:DO
            var fileName = Path.GetFileName(mRegister.file.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
            mRegister.file.SaveAs(path);
            ViewBag.Message = "File has been uploaded successfully";
            ModelState.Clear();
        }
        return View();
    }

I cannot have two methods with the same name - CREATE doing different things on one hand and on other I cannot give different name to it as i don't need other View for it, it needs to be shown on Create view if im understanding what is going on here.
2. Secondary  - do i need to have two buttons for this? one for upload image and one for creating object?

And finally i need to show image as part of the article somehow in my Media view. At the moment it looks like that

@Model.title

            @Html.Raw(Model.title)

            @Html.Raw(Model.description)

            @Html.Raw(Model.body)

          @Html.Raw(Model.file)

From here I'm lost. I need to place that image in certain place, but don't know how.In other examples people creating bunch of other classes for file. Do i need it? What the easiest way of doing it? I know I'm not the first who came up with this question, but i could really use your help guys.

Body:
Your code is a little confusing to me. In your second example, you are using file property. But your class does not have that!!!

One suggestion : Try to use PascalCasing when writing C# classes and be consistent

Ideally you should create a view model for your view

public class MediaVm
{
   public string Title { get; set; }
   public string Body { get; set; }
   public HttpPostedFileBase Image { set; get; }
}

Now have your view strongly typed to this view model

@model MediaVm
@using (Html.BeginForm("Create", "Medias", FormMethod.Post,
                                                new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(false)
    @Html.TextBoxFor(s=>s.Title)
    @Html.TextBoxFor(s=>s.Body)
    @Html.TextBoxFor(model => model.Image, new { type = "file" })
    <input type="submit" />
}

Now, in your httppost action method, use the same view model as parameter, read the Image property value, save to disk with a unique name and save that unique file name in your table. We will move the code which saves the file to disk to another method which can be used from other methods as needed.

[HttpPost]
public ActionResult Create(MediaVm model)
{
  if (ModelState.IsValid)
  {
      var fileName = SaveAndReturnFileName(model.Img);
      var m = new Media { title = model.Title, body, model.Body};
      m.ImagePath = fileName;
      db.Medias.Add(m);
      db.SaveChanges();
      return RedirectToAction("Index");
  }
  return View(model);
}
public string SaveAndReturnFileName(HttpPostedFileBase file)
{
    if (file == null)
        return null;

    var fileName = Path.GetFileName(file.FileName);
    string randomFileName = Path.GetFileNameWithoutExtension(fileName) +
                        "_" +
                        Guid.NewGuid().ToString().Substring(0, 4)
                            + Path.GetExtension(fileName);
    var path = Path.Combine(Server.MapPath("~/Content/Upload/"), randomFileName);
    file.SaveAs(path);
    return randomFileName;
}

You should be able to access the image like the below url

yourSiteName/Content/Upload/theRandomImageNameWeSavedInTable


答:
I put this query together and it returns the results very quickly.

```<code>Select *
FROM foo
Where (`datelastsaved` > '2015-12-31' && `datelastsaved` < '2017-01-01')
    AND `filename` NOT IN (
         Select `filename`
         FROM foo
         GROUP BY `filename`
         HAVING COUNT(*) > 1);
</code>```

The first part is your normal select statement with the where clauses to filter on the dates.

The second part is the NOT IN where the select statement finds all of the ones with duplicate filenames.

```<code>Select `filename`  FROM foo GROUP BY `filename` HAVING COUNT(*) > 1)
</code>```

Title: Alternative of NOT EXISTS in MySQL as query is taking time to execute with NOT EXISTS

Body:
I put this query together and it returns the results very quickly.

Select *
FROM foo
Where (`datelastsaved` > '2015-12-31' && `datelastsaved` < '2017-01-01')
    AND `filename` NOT IN (
         Select `filename`
         FROM foo
         GROUP BY `filename`
         HAVING COUNT(*) > 1);

The first part is your normal select statement with the where clauses to filter on the dates.

The second part is the NOT IN where the select statement finds all of the ones with duplicate filenames.

Select `filename`  FROM foo GROUP BY `filename` HAVING COUNT(*) > 1)


问:
Does Scott Meyers's advice to prefer non-member non-friend methods apply to object construction?
Let's say I have a class:

```<code>class C{
  int x_;
  int y_;
public:
  C(int x, int y): x_(x), y_(y){}
};
</code>```

Then I want to add construction from a string, which would just parse x and y. Before reading Meyers's book I would usually make it another constructor in class C. However, it's also possible to make it non-member non-friend:

```<code>C CFromString(const std::string& s){
  int x, y;
  //...parse them somehow, throw exception if needed...
  return C(x,y);
}
</code>```

To me this is standard situation for many "value classes", when there is a "main" constructor which sets private members to provided values (probably checking there correctness). Other constructors for such classes are often just calculate these values from some other arguments.

Are there any drawbacks in making such constructors non-member non-friends like in my example?

Upd. I understand the Meyers's advice, and what are the advantages of NMNF functions. There is just no examples of NMNF object construction in his book, so I want to ensure that his advice applies to construction as well.

答:
If you start adding constructors for every possible way a class can be serialized, you are tightly coupling that class with those serialization methods.

It is preferred that you separate the class and the serializer in order to separate concerns. Let the class focus on what the class does and the serializer on what it does (read json or whatever)

You have to consider that your class might be serialized from a file, from a socket, from json, from xml, from a database...from any number of things.

That's why in modern programming we use interfaces.
We also make use of the Factory pattern.

Body:
Let's say I have a class:

class C{
  int x_;
  int y_;
public:
  C(int x, int y): x_(x), y_(y){}
};

Then I want to add construction from a string, which would just parse x and y. Before reading Meyers's book I would usually make it another constructor in class C. However, it's also possible to make it non-member non-friend:

C CFromString(const std::string& s){
  int x, y;
  //...parse them somehow, throw exception if needed...
  return C(x,y);
}

To me this is standard situation for many "value classes", when there is a "main" constructor which sets private members to provided values (probably checking there correctness). Other constructors for such classes are often just calculate these values from some other arguments.

Are there any drawbacks in making such constructors non-member non-friends like in my example?

Upd. I understand the Meyers's advice, and what are the advantages of NMNF functions. There is just no examples of NMNF object construction in his book, so I want to ensure that his advice applies to construction as well.


问:
Guide to Kubernetes Manifests: Good Resources/Docker Run options
I was wondering if there was a centralized document on options that are available for use in Kubernetes manifest files;

I know there's a bunch on general YAML files but since theres an overlap of docker run commands and kubectl commands, I wanted to know which ones are actually useable for Kubernetes.

i.e. specifically docker run options include --net=host, --pid=host, --privileged

I know --privileged is for securityContext in the kubernetes manifest
https://kubernetes.io/docs/user-guide/security-context/

```<code>containers:
...
  -name:
   ...
   securityContext:
     privileged: true
</code>```

but as for the other two I can't find good resources to verify if those options are available.

答:
All options and fields are documented within the resource references which you can find in the Kubernetes reference section.

E.g. for the definition of a Pod you can check the related docs, you'll find that everything within the "spec" block relates to PodSpec objects and these contain among others Container definitions. Within the Container reference you'll find all required and optional fields.

I assume that's the centralized document you were looking for.

Besides that you might want to check the Container Command and Arguments reference guide.

Body:
I was wondering if there was a centralized document on options that are available for use in Kubernetes manifest files;

I know there's a bunch on general YAML files but since theres an overlap of docker run commands and kubectl commands, I wanted to know which ones are actually useable for Kubernetes.

i.e. specifically docker run options include --net=host, --pid=host, --privileged

I know --privileged is for securityContext in the kubernetes manifest
https://kubernetes.io/docs/user-guide/security-context/

containers:
...
  -name:
   ...
   securityContext:
     privileged: true

but as for the other two I can't find good resources to verify if those options are available.


问:
Typescript underscore case translation
I am using my domain class like this:

```<code>export class Contact {

  private _name: string;
  private _phone: string;

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
  }

  get phone(): string {
    return this._phone;
  }

  set phone(value: string) {
    this._phone = value;
  }

}
</code>```

My problem is when I send data to backend through angular http.post, the properties that are sent are the those with underscore and my backend is prepared only for camelCase (Change backend might not be an option here). Is there any other known option besides translate JSON before send?
Thanks in advance.

答:
You have two ways to do that:

1) Defining a toJSON() function on your Contact class:

```<code>public toJSON() {
    return {
        name: this._name,
        phone: this._phone,
    };
}
</code>```

2) By using JSON.stringify(...), replacing the 2nd argument:

```<code>let serialized = JSON.stringify(contact, Object.keys(contact.constructor.prototype))
</code>```

To know more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Title: Typescript underscore case translation

Body:
I am using my domain class like this:

export class Contact {

  private _name: string;
  private _phone: string;

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
  }

  get phone(): string {
    return this._phone;
  }

  set phone(value: string) {
    this._phone = value;
  }

}

My problem is when I send data to backend through angular http.post, the properties that are sent are the those with underscore and my backend is prepared only for camelCase (Change backend might not be an option here). Is there any other known option besides translate JSON before send?
Thanks in advance.

Body:
You have two ways to do that:

1) Defining a toJSON() function on your Contact class:

public toJSON() {
    return {
        name: this._name,
        phone: this._phone,
    };
}

2) By using JSON.stringify(...), replacing the 2nd argument:

let serialized = JSON.stringify(contact, Object.keys(contact.constructor.prototype))

To know more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify


答:
Use explode

Here's the full example (mostly getting the data):

```<code>import pyspark.sql.functions as sql
import pandas as pd
#sc = SparkContext()
sqlContext = SQLContext(sc)

s = "28-12-2001T12:02:01.143 | Class_A | SubClass_B |some-info| {'key1': 'value1', 'key2':'value2', 'keyN':'valueN'}"
data = s.split('|')
data = data[:-1]+[eval(data[-1])]
p_df = pd.DataFrame(data).T
s_df = sqlContext.createDataFrame(p_df,schema=  ['created','class','sub_class','meta','intrests'])

s_df.select(s_df.columns[:-1]+[sql.explode(s_df.intrests).alias("key", "value")]).show()
</code>```

Title: Data modification in pyspark

Body:
I am using spark 2.0.1 and python-2.7 to modify and flattening some nested JSON data.

Raw data (json format)

{
 "created" : '28-12-2001T12:02:01.143',
 "class" : 'Class_A',
 "sub_class": "SubClass_B",
 "properties": {
    meta : 'some-info',
    ...,
    interests : {"key1": "value1", "key2":"value2, ..., "keyN":"valueN"}
  }
}

using withColumn and udf function I was able to flatten raw_data in to dataframe which looks like follows

---------------------------------------------------------------------
| created                | class   | sub_class  | meta       | interests                                                 |
---------------------------------------------------------------------
|28-12-2001T12:02:01.143 | Class_A | SubClass_B |'some-info' | "{key1: 'value1', 'key2':'value2', ..., 'keyN':'valueN'}" |
---------------------------------------------------------------------

Now I want to convert/split this 1 row into multiple rows based on interest column. How Can I do the same?

Desired Output

---------------------------------------------------------------------
| created                 | class   | sub_class  | meta        | key  | value  |
---------------------------------------------------------------------
| 28-12-2001T12:02:01.143 | Class_A | SubClass_B | 'some-info' | key1 | value1 |
---------------------------------------------------------------------
| 28-12-2001T12:02:01.143 | Class_A | SubClass_B | 'some-info' | key2 | value2 |
---------------------------------------------------------------------
| 28-12-2001T12:02:01.143 | Class_A | SubClass_B | 'some-info' | keyN | valueN |
---------------------------------------------------------------------

Thank you

Body:
Use explode

Here's the full example (mostly getting the data):

import pyspark.sql.functions as sql
import pandas as pd
#sc = SparkContext()
sqlContext = SQLContext(sc)

s = "28-12-2001T12:02:01.143 | Class_A | SubClass_B |some-info| {'key1': 'value1', 'key2':'value2', 'keyN':'valueN'}"
data = s.split('|')
data = data[:-1]+[eval(data[-1])]
p_df = pd.DataFrame(data).T
s_df = sqlContext.createDataFrame(p_df,schema=  ['created','class','sub_class','meta','intrests'])

s_df.select(s_df.columns[:-1]+[sql.explode(s_df.intrests).alias("key", "value")]).show()


问:
UITextfield text is moving on edit
When my UITextField becomes first responder(on edit) the text is moving down very slightly and the spacing between the characters is increased very slightly. Upon resign first responder(keyboard goes away), the characters move back to the original positioning. At first I thought this was a font issue, as I am using a custom font, but the same thing happens when I use the system font or other custom fonts.

Please check the images below. The first one is with the keyboard down and the second is with the keyboard up. It may be difficult to see, as the variance is small, but the keyboard up state shows the characters moved down and apart slightly.

答: Setting the Min Font Size property equal to the font size in Interface Builder worked for me

Title: UITextfield text is moving on edit


问:
IIS rewrites and handlers conflict
I'm trying to set up a Django/Angular application under IIS.

When I set a similar application under nginx, I pass all URLs starting with /api (my backend) or /admin (the Django admin interface) to Django. I also set two locations: / and /static - both are aliases to the folder with all the static resources.

I need to alias /static, too, because Django's admin application references resources at /static/admin/...

I can't get IIS to work the same way. I'm using wfastcgi to interface with Django, and a rewrite rule to map /static back to /. This is the relevant portion of my Web.config:

```<code><rewrite>
    <rules>
        <rule name="Static Perfix" stopProcessing="true" >
            <match url="^static/(.+)" />
            <action type="Rewrite" url="{R:1}" />
        </rule>
    </rules>
</rewrite>
<handlers>
    <add name="Admin"
         path="/admin"
         verb="*"
         modules="FastCgiModule"
         scriptProcessor="..."
         resourceType="Unspecified" />
</handlers>
</code>```

This doesn't work. When I access /admin the handler catches it and forwards the request to Django, as it should. Django return an html page with resources located at /static/admin/base.css (for example).

When the browser tries to load such a resource the rewrite rule catches it, rewrites it to /admin/base.css, and then the handler catches it and forwards it to Django, which doesn't know what /admin/base.css is and returns a 404.

I tried making /static a Virtual Directory pointing to the same physical directory as the root directory. This caused all sorts of conflicts because my root Web.config was read twice, causing all sorts of duplicate key violations (for all the keys I have defined, more or less).

I would appreciate any help on getting out of this situation.

答:
I ended up avoiding the problem altogether, by restructuring my static resources folder and adding an actual static subfolder that contains the Admin static files.

I will no longer be able to use manage.py collectstatic for front-end deployment, though, I will need to create an additional script. Oh well.

Title: IIS rewrites and handlers conflict

Body:
I'm trying to set up a Django/Angular application under IIS.

When I set a similar application under nginx, I pass all URLs starting with /api (my backend) or /admin (the Django admin interface) to Django. I also set two locations: / and /static - both are aliases to the folder with all the static resources.

I need to alias /static, too, because Django's admin application references resources at /static/admin/...

I can't get IIS to work the same way. I'm using wfastcgi to interface with Django, and a rewrite rule to map /static back to /. This is the relevant portion of my Web.config:

<rewrite>
    <rules>
        <rule name="Static Perfix" stopProcessing="true" >
            <match url="^static/(.+)" />
            <action type="Rewrite" url="{R:1}" />
        </rule>
    </rules>
</rewrite>
<handlers>
    <add name="Admin"
         path="/admin"
         verb="*"
         modules="FastCgiModule"
         scriptProcessor="..."
         resourceType="Unspecified" />
</handlers>

This doesn't work. When I access /admin the handler catches it and forwards the request to Django, as it should. Django return an html page with resources located at /static/admin/base.css (for example).

When the browser tries to load such a resource the rewrite rule catches it, rewrites it to /admin/base.css, and then the handler catches it and forwards it to Django, which doesn't know what /admin/base.css is and returns a 404.

I tried making /static a Virtual Directory pointing to the same physical directory as the root directory. This caused all sorts of conflicts because my root Web.config was read twice, causing all sorts of duplicate key violations (for all the keys I have defined, more or less).

I would appreciate any help on getting out of this situation.


问:
Problem with printing values
As Similar to previous issue I am unable to print value on the screen. I have tested the prime mark loop and It does produce correct figures but print statements are not printing value so I can not verify the code. The code is attached below. Few Reputed people guided me to use BigInteger but I have few issue in it so I will look into that as well.

Thanks in advance for all your help and assistance.

```<code>package javaapplication1;

import java.util.Random;
import java.math.*;

public class DH {

    public static void main(String[] arg) {

        int q;
        int z = 10000;
        Random generator = new Random(0);
        q = generator.nextInt(50000);

        double sk1 = generator.nextDouble();
        double sk2 = generator.nextDouble();

        for (int p = generator.nextInt(z); p < 50000; p++) {
            int j;
            for (j = 2; j < p; j++) {
                int n = p % j;
                if (n == 0) {
                    break;
                }
            }

            if (p == j) {
                double a = Math.pow(q, sk1);
                double pk1 = a % p;

                double b = Math.pow(q, sk2);
                double pk2 = b % p;

                if (pk1 == pk2) {
                    System.out.println("true");
                    System.out.println(p);
                    System.out.println(q);
                    System.out.println(sk1);
                    System.out.println(sk2);
                    System.out.println(pk1);
                    System.out.println(pk2);
                    System.out.print("  " + i);
                }
            }
        }

    }
}
</code>```

答: Since sk1 and sk2 have different values (because they are random), pk1 and pk2 have different values too. Only case when you can have output happening is when they are equal (and that is nearly impossible). By the way, what was that "i" variable in the last output statement?</p>

ContentLicense: CC BY-SA 2.5

Title: Problem with printing values

Body:
As Similar to previous issue I am unable to print value on the screen. I have tested the prime mark loop and It does produce correct figures but print statements are not printing value so I can not verify the code. The code is attached below. Few Reputed people guided me to use BigInteger but I have few issue in it so I will look into that as well.

Thanks in advance for all your help and assistance.

package javaapplication1;

import java.util.Random;
import java.math.*;

public class DH {

    public static void main(String[] arg) {

        int q;
        int z = 10000;
        Random generator = new Random(0);
        q = generator.nextInt(50000);

        double sk1 = generator.nextDouble();
        double sk2 = generator.nextDouble();

        for (int p = generator.nextInt(z); p < 50000; p++) {
            int j;
            for (j = 2; j < p; j++) {
                int n = p % j;
                if (n == 0) {
                    break;
                }
            }

            if (p == j) {
                double a = Math.pow(q, sk1);
                double pk1 = a % p;

                double b = Math.pow(q, sk2);
                double pk2 = b % p;

                if (pk1 == pk2) {
                    System.out.println("true");
                    System.out.println(p);
                    System.out.println(q);
                    System.out.println(sk1);
                    System.out.println(sk2);
                    System.out.println(pk1);
                    System.out.println(pk2);
                    System.out.print("  " + i);
                }
            }
        }

    }
}


问:
How to Calculate the Area of a Triangle with HTML
I am trying to create a table with two boxes in which you type the height and the base of a triangle and then you can get the resulting area at the bottom this is what I got so far as for the other shapes. But I can not figure it out for a triangle. I am new so sorry in advance. </p>

```<code>    <h3>Calculo de Areas</h3>
        <p>Ingrese la Informacion requerida para sacar el Area de las siguientes Figuras.</p>
        <p>Nota:Los Resultados estan dados en la misma unidad que se introduce.</p>
            <table>
        <tr>
            <th>
<p>
  <label>Radio de un Circulo</label>
  <input id="inputradio" type="number" placeholder="Radio" oninput="LengthConverter9(this.value)" onchange="LengthConverter9(this.value)">
</p>
<p>Area: <span id="outputArea"></span></p>

<script>
function LengthConverter9(valNum9) {
  document.getElementById("outputArea").innerHTML=(valNum9*valNum9)*3.14159265359;
}
                </script>
            </th><th>
<p>
  <label>Lado de un Cuadrado</label>
  <input id="inputLado" type="number" placeholder="Largo" oninput="LengthConverter10(this.value)" onchange="LengthConverter10(this.value)">
</p>
<p>Area: <span id="outputArea1"></span></p>

<script>
function LengthConverter10(valNum10) {
  document.getElementById("outputArea1").innerHTML=(valNum10*valNum10);
}
</script>

    <tr><th>
        <p>
  <label>Base de un Triangulo Rectangulo</label>
  <input id="inputBase" type="number" placeholder="Ancho" oninput="LengthConverter11(this.value)" onchange="LengthConverter11(this.value)">
</p>
        <p>
  <label>Altura de dicho Triangulo</label>
  <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter12(this.value)" onchange="LengthConverter12(this.value)">
</p>
<p>Area: <span id="outputArea4"></span></p>
<script>
function LengthConverter11(valNum11){
  document.getElementById("outputMetros4").innerHTML=(LengthConverter11*LengthConverter12)/2;
}
                </script>

        </th></tr>
    </table>
</code>```

<p>The only one that i cant get to work is the triangle one, Thanks in advance. </p>

答:
In your function LengthConverter11() you are calling LengthConverter11 and LengthConverter12, these are functions, not variables. What you Need to do is a function to retrieve both values, and then you perform the operation.
example:

```<code><input id="inputBase" type="number" placeholder="Ancho" name="triangleBase">
<input id="inputAltura" type="number" placeholder="Largo" name="triangleAltura" onchange="areaCalculator(this.value)">
<script>
  function areaCalculator(){
    var base = document.getElementById('inputBase').value;
    var altura = document.getElementById('inputAltura').value ;
    document.getElementById("outputMetros4").innerHTML= (base*altura)/2;
  }
<script>
</code>```

Something like that, I haven't tested it so, I don't know if its accurate, but basicly is what you need to do.

Body:
I am trying to create a table with two boxes in which you type the height and the base of a triangle and then you can get the resulting area at the bottom this is what I got so far as for the other shapes. But I can not figure it out for a triangle. I am new so sorry in advance.

Calculo de Areas

Ingrese la Informacion requerida para sacar el Area de las siguientes Figuras.

Nota:Los Resultados estan dados en la misma unidad que se introduce.

  Radio de un Circulo
  <input id="inputradio" type="number" placeholder="Radio" oninput="LengthConverter9(this.value)" onchange="LengthConverter9(this.value)">

Area:

  Lado de un Cuadrado
  <input id="inputLado" type="number" placeholder="Largo" oninput="LengthConverter10(this.value)" onchange="LengthConverter10(this.value)">

Area:

  Base de un Triangulo Rectangulo
  <input id="inputBase" type="number" placeholder="Ancho" oninput="LengthConverter11(this.value)" onchange="LengthConverter11(this.value)">

  Altura de dicho Triangulo
  <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter12(this.value)" onchange="LengthConverter12(this.value)">

Area:

The only one that i cant get to work is the triangle one, Thanks in advance.

Body:
In your function LengthConverter11() you are calling LengthConverter11 and LengthConverter12, these are functions, not variables. What you Need to do is a function to retrieve both values, and then you perform the operation.
example:

<input id="inputBase" type="number" placeholder="Ancho" name="triangleBase">
<input id="inputAltura" type="number" placeholder="Largo" name="triangleAltura" onchange="areaCalculator(this.value)">
<script>
  function areaCalculator(){
    var base = document.getElementById('inputBase').value;
    var altura = document.getElementById('inputAltura').value ;
    document.getElementById("outputMetros4").innerHTML= (base*altura)/2;
  }
<script>

Something like that, I haven't tested it so, I don't know if its accurate, but basicly is what you need to do.


问:
Regex - Find Name With No Middle Initial
I'm doing a query on an SQL database and need to write a regular expression to find names with no middle initial.

For example.

Michael J. Fox - Should fail

Michael J Fox - Should fail

Michael Fox - Should pass

Full names in the database are stored in a single string for reference.

答:
```<code>drop table if exists t;
create table t (name text);
insert into t values ('Michael J Fox');
insert into t values ('Michael J. Fox');
insert into t values ('Michael Fox');
insert into t values ('  Michael     Fox  ');
</code>```

Allowing for leading and trailing spaces, and multiple spaces in between, but only two sets of non-space characters:

```<code>select name, name REGEXP '^ *[^ ]+ +[^ ]+ *$'
from t;
</code>```

rextester demo: http://rextester.com/CFID40649

```<code>+---------------------+----------------------------------+
|        name         | name REGEXP '^ *[^ ]+ +[^ ]+ *$' |
+---------------------+----------------------------------+
| Michael J Fox       |                                0 |
| Michael J. Fox      |                                0 |
| Michael Fox         |                                1 |
|   Michael     Fox   |                                1 |
+---------------------+----------------------------------+
</code>```

Body:
drop table if exists t;
create table t (name text);
insert into t values ('Michael J Fox');
insert into t values ('Michael J. Fox');
insert into t values ('Michael Fox');
insert into t values ('  Michael     Fox  ');

Allowing for leading and trailing spaces, and multiple spaces in between, but only two sets of non-space characters:

select name, name REGEXP '^ *[^ ]+ +[^ ]+ *$'
from t;

rextester demo: http://rextester.com/CFID40649

+---------------------+----------------------------------+
|        name         | name REGEXP '^ *[^ ]+ +[^ ]+ *$' |
+---------------------+----------------------------------+
| Michael J Fox       |                                0 |
| Michael J. Fox      |                                0 |
| Michael Fox         |                                1 |
|   Michael     Fox   |                                1 |
+---------------------+----------------------------------+


问:
How to use an interface with methods that has in input or return type the reference of the interface?
I have an interface like that:

```<code>public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}
</code>```

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

```<code>public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);
</code>```

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

```<code>public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}
</code>```

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

答:
If you're allowed to modify the interface declaration then you can change it as following:

```<code>public interface IntTree<T extends IntTree<T>> {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (T t);
    public void addChild (T child);
    public T followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}
</code>```

Then you should declare your class as:

```<code>public class MyTree implements IntTree<MyTree>
</code>```

Now your methods will look like:

```<code>public void addChild (MyTree child);
public MyTree followPath(int[] path);
public boolean equals (MyTree t);
</code>```

So you'll be able to work with them in the way you want.

Body:
I have an interface like that:

public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

Body:
If you're allowed to modify the interface declaration then you can change it as following:

public interface IntTree<T extends IntTree<T>> {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (T t);
    public void addChild (T child);
    public T followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}

Then you should declare your class as:

public class MyTree implements IntTree<MyTree>

Now your methods will look like:

public void addChild (MyTree child);
public MyTree followPath(int[] path);
public boolean equals (MyTree t);

So you'll be able to work with them in the way you want.


问:
How would I create a DCG to parse queries about a database?
I'm just playing around with learning Prolog and am trying to build a database of information and then use natural English to query about relationships.  How would I go about doing this?

Example:

```<code>%facts

male(bob).
female(sarah).
male(timmy).
female(mandy).

parent(bob, timmy).
parent(bob, mandy).
parent(sarah, timmy).
parent(sarah, mandy).

spouse(bob, sarah).
spouse(sarah, bob).

%some basic rules

married(X,Y) :- spouse(X,Y).
married(X,Y) :- spouse(Y,X).

child(C,X) :- parent(X,C).
</code>```

Now, I want to ask some "who" questions, i.e., "who is the parent of timmy".

I read something about DCGs, but, can anyone point me to some good resources or get me going in the right direction?

Thank you!

答:
First, I would also like to ask a "who" question: In a fact like

```<code>parent(X, Y).
</code>```

WHO is actually the parent? Is it X or is it Y?

To make this clearer, I strongly recommend you use a naming convention that makes clear what each argument means. For example:

```<code>parent_child(X, Y).
</code>```

Now, to translate "informal" questions to Prolog goals that reason over your data, consider for example the following DCG:

```
question(Query, Person) --> [who,is], question_(Query, Person).

question_(parent_child(Parent,Child), Parent) --> [the,parent,of,Child].
question_(parent_child(Parent,Child), Child)  --> [the,child,of,Parent].
question_(married(Person0,Person), Person)    --> [married,to,Person0].
question_(spouse(Person0,Person), Person)     --> [the,spouse,of,Person0].
```

Here, I am assuming you have already converted given sentences to tokens, which I represent as Prolog atoms.

In order to conveniently work with DCGs, I strongly recommend the following declaration:

```
<b>:- set_prolog_flag(double_quotes, chars).</b>
```

This lets you write for example:

```
?- Xs = "abc".
<b>Xs = [a, b, c].</b>
```

Thus, it becomes very convenient to work with such programs. I leave converting such lists of characters to tokens as an exercise for you.

Once you have such tokens, you can use the DCG to relate lists of such tokens to Prolog queries over your program.

For example:

```
?- phrase(question(Query, Person), <b>[who,is,the,parent,of,timmy]</b>).
<b>Query = parent_child(Person, timmy) .</b>
```

Another example:

```
?- phrase(question(Query, Person), <b>[who,is,the,spouse,of,sarah]</b>).
<b>Query = spouse(sarah, Person).</b>
```

To actually run such queries, simply post them as goals. For example:

```
?- phrase(question(Query, Person), [who,is,married,to,bob]),
   <b>Query</b>.
Query = married(bob, sarah),
<b>Person = sarah .</b>
```

This shows that such a conversion is quite straight-forward in Prolog.

As @GuyCoder already mentioned in the comments, make sure to check out dcg for more information about DCG notation!

Body:
I'm just playing around with learning Prolog and am trying to build a database of information and then use natural English to query about relationships.  How would I go about doing this?

Example:

%facts

male(bob).
female(sarah).
male(timmy).
female(mandy).

parent(bob, timmy).
parent(bob, mandy).
parent(sarah, timmy).
parent(sarah, mandy).

spouse(bob, sarah).
spouse(sarah, bob).

%some basic rules

married(X,Y) :- spouse(X,Y).
married(X,Y) :- spouse(Y,X).

child(C,X) :- parent(X,C).

Now, I want to ask some "who" questions, i.e., "who is the parent of timmy".

I read something about DCGs, but, can anyone point me to some good resources or get me going in the right direction?

Thank you!

Body:
First, I would also like to ask a "who" question: In a fact like

parent(X, Y).

WHO is actually the parent? Is it X or is it Y?

To make this clearer, I strongly recommend you use a naming convention that makes clear what each argument means. For example:

parent_child(X, Y).

Now, to translate "informal" questions to Prolog goals that reason over your data, consider for example the following DCG:

question(Query, Person) --> [who,is], question_(Query, Person).

question_(parent_child(Parent,Child), Parent) --> [the,parent,of,Child].
question_(parent_child(Parent,Child), Child)  --> [the,child,of,Parent].
question_(married(Person0,Person), Person)    --> [married,to,Person0].
question_(spouse(Person0,Person), Person)     --> [the,spouse,of,Person0].

Here, I am assuming you have already converted given sentences to tokens, which I represent as Prolog atoms.

In order to conveniently work with DCGs, I strongly recommend the following declaration:

:- set_prolog_flag(double_quotes, chars).

This lets you write for example:

?- Xs = "abc".
Xs = [a, b, c].

Thus, it becomes very convenient to work with such programs. I leave converting such lists of characters to tokens as an exercise for you.

Once you have such tokens, you can use the DCG to relate lists of such tokens to Prolog queries over your program.

For example:

?- phrase(question(Query, Person), [who,is,the,parent,of,timmy]).
Query = parent_child(Person, timmy) .

Another example:

?- phrase(question(Query, Person), [who,is,the,spouse,of,sarah]).
Query = spouse(sarah, Person).

To actually run such queries, simply post them as goals. For example:

?- phrase(question(Query, Person), [who,is,married,to,bob]),
   Query.
Query = married(bob, sarah),
Person = sarah .

This shows that such a conversion is quite straight-forward in Prolog.

As @GuyCoder already mentioned in the comments, make sure to check out dcg for more information about DCG notation!


问:
Enterpise Architect - is it possibhle to import SCXML file? How?
Is it possible to import SCXML file into Enterpise Architect as a "State Machine" or other diagram?

If so then how?

答: It looks to not be possible directly in EA, but it does seem that a conversion script from XMI (what EA can export) to SCXML exists.</p>