问:
Error with practicalmeteor:mocha & Meteor 1.6
I'm getting the following error on terminal when tried to run practicalmeteor:mocha with Meteor 1.6</p>

```<code>Uncaught TypeError: MochaRunner.runEverywhere is not a function
</code>```

答:
After few trials I managed to fix the problem by doing the following updates to my project

```<code>coffeescript           upgraded from 1.0.17 to 1.12.7_3
coffeescript-compiler  added, version 1.12.7_3
</code>```

To update one or more of these packages to their latest
compatible versions, pass their names to meteor update,

Body:
I'm getting the following error on terminal when tried to run practicalmeteor:mocha with Meteor 1.6

Uncaught TypeError: MochaRunner.runEverywhere is not a function

Body:
After few trials I managed to fix the problem by doing the following updates to my project

coffeescript           upgraded from 1.0.17 to 1.12.7_3
coffeescript-compiler  added, version 1.12.7_3

To update one or more of these packages to their latest
compatible versions, pass their names to meteor update,


来源: stackexchange

问:
Gradle build error styles attributes not found
I was try to upgrade android studio 2.3 to 3.0 but the gradle can't build and shows this message:
Probably one of your libraries is expecting that style to be available and it's not finding it

please help me to fix this error.

screenshot of the error message

this is the build.gradle of the project

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

repositories {
    maven {
        url 'https://repo1.maven.org/maven2/'
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.skills.inuk"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "0.3.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true //important
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }

    packagingOptions {
        exclude 'LICENSE.txt'
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    // compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.1'
    compile 'com.jakewharton:butterknife:8.6.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.twitter.sdk.android:twitter:3+'
    compile 'com.google.android.gms:play-services:11.4.2'
    compile 'com.makeramen:roundedimageview:2.3.0'
    compile 'com.github.curioustechizen.android-ago:library:1.3.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.google.code.gson:gson:2.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:support-v4:26.0.1'
    compile 'com.android.support:support-vector-drawable:26.0.1'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.android.support:multidex:1.0.1'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Thx for your reponses guys, i founded the probleme , this happening because :

Consider if you incorrectly include the symbol when accessing a resource from the android namespace, as shown below:

```<code><!-- When referencing resources from the 'android' namespace, omit the '@' symbol. -->
<item name="@android:windowEnterAnimation"/>
</code>```

答:
Go to your gradle.properties write the below code and Sync your project

```<code>android.enableAapt2=false
</code>```

And remove @ symbol because from Android Studio 3.0

When referencing resources from the 'android' namespace, omit the '@' symbol.

ContentLicense: CC BY-SA 3.0

Body:
I was try to upgrade android studio 2.3 to 3.0 but the gradle can't build and shows this message:
Probably one of your libraries is expecting that style to be available and it's not finding it

please help me to fix this error.

screenshot of the error message

this is the build.gradle of the project

apply plugin: 'com.android.application'

repositories {
    maven {
        url 'https://repo1.maven.org/maven2/'
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.skills.inuk"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "0.3.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true //important
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }

    packagingOptions {
        exclude 'LICENSE.txt'
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    // compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.1'
    compile 'com.jakewharton:butterknife:8.6.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.twitter.sdk.android:twitter:3+'
    compile 'com.google.android.gms:play-services:11.4.2'
    compile 'com.makeramen:roundedimageview:2.3.0'
    compile 'com.github.curioustechizen.android-ago:library:1.3.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.google.code.gson:gson:2.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:support-v4:26.0.1'
    compile 'com.android.support:support-vector-drawable:26.0.1'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.android.support:multidex:1.0.1'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
apply plugin: 'com.google.gms.google-services'

Thx for your reponses guys, i founded the probleme , this happening because :

Consider if you incorrectly include the symbol when accessing a resource from the android namespace, as shown below:

<item name="@android:windowEnterAnimation"/>

Body:
Go to your gradle.properties write the below code and Sync your project

android.enableAapt2=false

And remove @ symbol because from Android Studio 3.0

When referencing resources from the 'android' namespace, omit the '@' symbol.


答:
you can try this :</p>

```<code>if($("svg")[0]){
    console.log("present");
} else {
    console.log("absent");
}
</code>```

Title: How to check if a div has an svg in it using JavaScript?

Body:
I have a div like the following with a question mark in it...

?

In my code, when someone tries to submit a form, I do a check to see if that field has a question mark in it, like this:

const fieldText = $('#mydiv').text();
return fieldText.indexOf('?') !== -1;

That works fine, but now, instead of a question mark in that div, I have an SVG of a question mark (rather than just a text question mark), like this.

  <svg version='1.1' id='Layer_1' class='q-mark-svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 50 50' style='enable-background:new 0 0 50 50;' xml:space='preserve'>

    <g>
      <g>
        <path class='q-mark' d='M18.3,17.2c0,0.4-0.1,0.7-0.2,1c-0.1,0.3-0.3,0.6-0.5,0.8c-0.2,0.2-0.5,0.4-0.8,0.5c-0.3,0.1-0.6,0.2-1,0.2 c-0.7,0-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8c0-1.6,0.3-3.2,0.9-4.6c0.6-1.4,1.5-2.7,2.6-3.8s2.3-1.9,3.8-2.5 c1.4-0.6,3-0.9,4.6-0.9s3.1,0.3,4.6,1c1.4,0.6,2.7,1.5,3.8,2.6s1.9,2.3,2.6,3.8c0.6,1.4,0.9,2.9,0.9,4.5c0,3.2-1.2,6-3.5,8.4 l-3.8,3.5c-1.3,1.3-2,2.7-2,4.3c0,0.7-0.2,1.3-0.7,1.8c-0.5,0.5-1.1,0.7-1.8,0.7s-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8 c0-2.9,1.2-5.6,3.5-7.9l3.8-3.6c1.3-1.4,2-2.9,2-4.8c0-0.9-0.2-1.8-0.5-2.6c-0.4-0.8-0.8-1.5-1.5-2.1c-0.6-0.6-1.3-1.1-2.1-1.5 c-0.8-0.4-1.7-0.5-2.6-0.5c-0.9,0-1.8,0.2-2.6,0.5c-0.8,0.4-1.5,0.8-2.1,1.4c-0.6,0.6-1.1,1.3-1.4,2.1 C18.5,15.3,18.3,16.2,18.3,17.2z M28.5,40.9c0,1-0.3,1.8-1,2.5c-0.7,0.7-1.5,1-2.5,1c-1,0-1.8-0.3-2.5-1c-0.7-0.7-1-1.5-1-2.5 c0-1,0.3-1.8,1-2.5c0.7-0.7,1.5-1,2.5-1c1,0,1.8,0.3,2.5,1C28.2,39.1,28.5,40,28.5,40.9z'/>
      </g>
    </g>
  </svg>

I still want to run a check on that div, but now I have to check to see if it has an SVG in it, rather than just "?".  How can I use JS to check if a div has an svg element in it?

FYI, I tried the following since I thought it would still look for the text, but to no avail...

const fieldText = $('#mydiv').text();
return fieldText.indexOf('svg') !== -1;

Body:
you can try this :

if($("svg")[0]){
    console.log("present");
} else {
    console.log("absent");
}


问:
Task "default" is not in your gulpfile
I run gulp in my console I got this error:

Task 'default' is not in your gulpfile

My gulpfile looks just fine:

```<code>var gulp = require('gulp'),
    LiveServer = require('gulp-live-server'),
    browserSync = require('browser-sync');

gulp.task('live-server', function () {
    var server = new LiveServer('server/main.js');
    server.start();
});

gulp.task('serve', ['live-server'], function () {
    browserSync.init(null, {
        proxy: "http://localhost:3000",
        port: 9001
    });
});
</code>```

答:
I had a similar issue, and this is my gulp file

Instead of having a 'default' task, what i do is directly calling the 'serve' task.

In cmd -> gulp serve

By directly calling the serve, it would call the browser-sync task for me.

Hope this would be helpful for someone :)

Title: Task "default" is not in your gulpfile

Body:
I run gulp in my console I got this error:

Task 'default' is not in your gulpfile

My gulpfile looks just fine:

var gulp = require('gulp'),
    LiveServer = require('gulp-live-server'),
    browserSync = require('browser-sync');

gulp.task('live-server', function () {
    var server = new LiveServer('server/main.js');
    server.start();
});

gulp.task('serve', ['live-server'], function () {
    browserSync.init(null, {
        proxy: "http://localhost:3000",
        port: 9001
    });
});


问:
Unit test ASP.NET, Open a file in web api
I have a Web api with a function like this:

```<code>    [HttpPost]
    public IHttpActionResult PostData([FromBody] JObject new_data)
    {
        //Some code here
        var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/data.txt");

        System.IO.File.WriteAllText(fullPath, new_data.ToString());

        return Ok();
    }
</code>```

Then I am testing this api like this:

```<code>    [TestMethod]
    public void TestPostData()
    {
        // Arrange
        JObject data = getSampleData();
        var controller = new MyController();
        //Act
        IHttpActionResult result = controller.PostData(data);

        //Assert
        Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<JObject>));
    }
</code>```

Here I get error at the line below:

```<code>    System.IO.File.WriteAllText(fullPath, new_data.ToString());
</code>```

And the error says:
Message: Test method NetWorth.Tests.UnitTest1.TestPostData threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: path

Can someone help please? I'm very new to ASP and c# and unit testing! Any suggestions would help a lot.

I should say that the api works perfect when I run it and this problem is just at the time of testing.

答:
for the test, use the full path to the file instead of var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/data.txt");
for example, let the method take a file path that, if not passed, will be equal to your constant

Body:
I have a Web api with a function like this:

    [HttpPost]
    public IHttpActionResult PostData([FromBody] JObject new_data)
    {
        //Some code here
        var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/data.txt");

        System.IO.File.WriteAllText(fullPath, new_data.ToString());

        return Ok();
    }

Then I am testing this api like this:

    [TestMethod]
    public void TestPostData()
    {
        // Arrange
        JObject data = getSampleData();
        var controller = new MyController();
        //Act
        IHttpActionResult result = controller.PostData(data);

        //Assert
        Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<JObject>));
    }

Here I get error at the line below:

    System.IO.File.WriteAllText(fullPath, new_data.ToString());

And the error says:
Message: Test method NetWorth.Tests.UnitTest1.TestPostData threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: path

Can someone help please? I'm very new to ASP and c# and unit testing! Any suggestions would help a lot.

I should say that the api works perfect when I run it and this problem is just at the time of testing.


问:
How to extend XSD scheme for supporting SVG?
I try to extend ISOSTS XSD scheme for supporting SVG images tags.
I found XSD scheme for SVG and has put it near ISOSTS.xsd.
Now I try to extend ISOSTS.xsd:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:mml="http://www.w3.org/1998/Math/MathML"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tbx="urn:iso:std:iso:30042:ed-1"
        xmlns:xlink="http://www.w3.org/1999/xlink"

<!-- my line -->
        xmlns:svg="http://www.w3.org/2000/svg"

        elementFormDefault="qualified">
      <xs:import namespace="http://www.w3.org/1998/Math/MathML"
                 schemaLocation="ncbi-mathml2/mathml2.xsd"/>
      <xs:import namespace="http://www.w3.org/1999/xlink"
                 schemaLocation="xlink.xsd"/>
      <!-- XSD import of namespace http://www.w3.org/2001/XMLSchema-instance suppressed (not necessary) -->
      <xs:import namespace="http://www.w3.org/XML/1998/namespace"
                 schemaLocation="xml.xsd"/>
      <xs:import namespace="urn:iso:std:iso:30042:ed-1"
                 schemaLocation="tbx.xsd"/>

<!-- my line -->
      <xs:import namespace="http://www.w3.org/2000/svg"
                 schemaLocation="SVG.xsd"/>

....
<xs:element name="p">
  <xs:complexType mixed="true">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
<!-- my line -->   <xs:element ref="svg:svg"/>
                   <xs:element ref="email"/>
....
</code>```

But I have error when try to load scheme:

```<code>    from lxml.etree import parse, XMLSchema

    schema_file = open(self._schema_filename)

    schema_doc = parse(schema_file)
    schema_file.close()

    self._xmlschema = XMLSchema(schema_doc)  # Error
</code>```

Error message:

File "src/lxml/xmlschema.pxi", line 87, in lxml.etree.XMLSchema.init (src/lxml/lxml.etree.c:197819)

lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': References from this schema to components in the namespace 'http://www.w3.org/2000/svg' are not allowed, since not indicated by an import statement., line 4664

What is wrong?

答: Problem solved using next XSD schema for SVG: https://github.com/dumistoklus/svg-xsd-schema</p>

Body:
I try to extend ISOSTS XSD scheme for supporting SVG images tags.
I found XSD scheme for SVG and has put it near ISOSTS.xsd.
Now I try to extend ISOSTS.xsd:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:mml="http://www.w3.org/1998/Math/MathML"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:tbx="urn:iso:std:iso:30042:ed-1"
        xmlns:xlink="http://www.w3.org/1999/xlink"

        xmlns:svg="http://www.w3.org/2000/svg"

        elementFormDefault="qualified">
      <xs:import namespace="http://www.w3.org/1998/Math/MathML"
                 schemaLocation="ncbi-mathml2/mathml2.xsd"/>
      <xs:import namespace="http://www.w3.org/1999/xlink"
                 schemaLocation="xlink.xsd"/>

      <xs:import namespace="http://www.w3.org/XML/1998/namespace"
                 schemaLocation="xml.xsd"/>
      <xs:import namespace="urn:iso:std:iso:30042:ed-1"
                 schemaLocation="tbx.xsd"/>

      <xs:import namespace="http://www.w3.org/2000/svg"
                 schemaLocation="SVG.xsd"/>

....
<xs:element name="p">
  <xs:complexType mixed="true">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
   <xs:element ref="svg:svg"/>
                   <xs:element ref="email"/>
....

But I have error when try to load scheme:

    from lxml.etree import parse, XMLSchema

    schema_file = open(self._schema_filename)

    schema_doc = parse(schema_file)
    schema_file.close()

    self._xmlschema = XMLSchema(schema_doc)  # Error

Error message:

File "src/lxml/xmlschema.pxi", line 87, in lxml.etree.XMLSchema.init (src/lxml/lxml.etree.c:197819)

lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': References from this schema to components in the namespace 'http://www.w3.org/2000/svg' are not allowed, since not indicated by an import statement., line 4664

What is wrong?


问:
How to pass the fetch data from table from one function to another function in php
I have a table named as tab2 in mysql. It contains name and phone fields.

I have created a function named as gettabledata():

```<code>function gettabledata()
{
    $data = array();

    $query = mysql_query("SELECT * FROM tab2");
    $row = mysql_fetch_assoc($query);
     //Here I am unable to get that how can I pass the fetched data in row
    //  variable to anywhere this function called.
 //  After update:
     return $row;
}
if(isset($_POST['action']))
{
       $gettab = createtable();//calling the function gettabledata

       //Here I want to get the all data from that table
     // After doing Update:
      foreach($gettab as $row){
        echo $row['name'];
        echo $row['phone'];
     }

}
</code>```

After Update I am getting warning like:

```<code>`
Warning: Illegal string offset 'name' in E:\xampp\htdocs\practive\csvtest.php on line 29

Notice: Uninitialized string offset: 0 in E:\xampp\htdocs\practive\csvtest.php on line 29

Warning: Illegal string offset 'phone' in E:\xampp\htdocs\practive\csvtest.php on line 30

Notice: Uninitialized string offset: 0 in E:\xampp\htdocs\practive\csvtest.php on line 30

Warning: Illegal string offset 'name' in E:\xampp\htdocs\practive\csvtest.php on line 29
0
Warning: Illegal string offset 'phone' in E:\xampp\htdocs\practive\csvtest.php on line 30 `
</code>```

Also on doing print_r($gettab), I got:

```<code>Array ( [name] => [phone] => 0 )
</code>```

Its just first record from table.

Help me with this.Thanks in anticipation.

答:
You just need to add a return statement at the end of the

gettabledata()

Modify the function with return statement as follows.

```<code>    function gettabledata()
    {
        $query = mysql_query("SELECT * FROM tab2");
        $row = mysql_fetch_assoc($query);

        return $row;
    }

    if(isset($_POST['action']))
    {
         $row_arr = gettabledata();//calling the function gettabledata

         foreach($row_arr as $row){
            echo $row['id'];
         }

     }
</code>```

Body:
I have a table named as tab2 in mysql. It contains name and phone fields.

I have created a function named as gettabledata():

function gettabledata()
{
    $data = array();

    $query = mysql_query("SELECT * FROM tab2");
    $row = mysql_fetch_assoc($query);
     //Here I am unable to get that how can I pass the fetched data in row
    //  variable to anywhere this function called.
 //  After update:
     return $row;
}
if(isset($_POST['action']))
{
       $gettab = createtable();//calling the function gettabledata

       //Here I want to get the all data from that table
     // After doing Update:
      foreach($gettab as $row){
        echo $row['name'];
        echo $row['phone'];
     }

}

After Update I am getting warning like:

`
Warning: Illegal string offset 'name' in E:\xampp\htdocs\practive\csvtest.php on line 29

Notice: Uninitialized string offset: 0 in E:\xampp\htdocs\practive\csvtest.php on line 29

Warning: Illegal string offset 'phone' in E:\xampp\htdocs\practive\csvtest.php on line 30

Notice: Uninitialized string offset: 0 in E:\xampp\htdocs\practive\csvtest.php on line 30

Warning: Illegal string offset 'name' in E:\xampp\htdocs\practive\csvtest.php on line 29
0
Warning: Illegal string offset 'phone' in E:\xampp\htdocs\practive\csvtest.php on line 30 `

Also on doing print_r($gettab), I got:

Array ( [name] => [phone] => 0 )

Its just first record from table.

Help me with this.Thanks in anticipation.

Body:
You just need to add a return statement at the end of the

gettabledata()

Modify the function with return statement as follows.

    function gettabledata()
    {
        $query = mysql_query("SELECT * FROM tab2");
        $row = mysql_fetch_assoc($query);

        return $row;
    }

    if(isset($_POST['action']))
    {
         $row_arr = gettabledata();//calling the function gettabledata

         foreach($row_arr as $row){
            echo $row['id'];
         }

     }


问:
Argument `$color` of `opacity($color)` must be a color
I am trying to create Angular 2 theme, I follow the tutorial as mentioned on the site. This is my theme file.

```<code>@import '~@angular/material/theming';

@include mat-core();
$primary: mat-palette($mat-deep-purple);
$accent:  mat-palette($mat-amber, A200);
$theme: mat-light-theme($primary, $accent);

@include angular-material-theme($theme);

.m2app-dark {
  $dark-primary: mat-palette($mat-blue, A800);
  $dark-accent:  mat-palette($mat-light-blue, A8008);
  $dark-warn:    mat-palette($mat-orange, A200);
  $dark-theme: mat-dark-theme($dark-primary, $dark-accent, $dark-warn);
  @include angular-material-theme($dark-theme);
}
</code>```

While building I am getting following exeception

```<code>ERROR in ./node_modules/css-loader?{"sourceMap":false,"importLoaders":1}!./node_modules/postcss-loader?{"ident":"postcss"}!./node_modules/sass-loader/lib/loader.js?{"sourceMap":false,"precision":8,"includePaths":[]}!./src/app-theme.scss
Module build failed:
undefined
                                ^
      Argument `$color` of `opacity($color)` must be a color

Backtrace:
        node_modules/@angular/material/_theming.scss:1119, in function `opacity`
        node_modules/@angular/material/_theming.scss:1119, in function `if`
        node_modules/@angular/material/_theming.scss:1119, in function `mat-color`
        node_modules/@angular/material/_theming.scss:1508, in mixin `mat-option-theme`
        node_modules/@angular/material/_theming.scss:3798, in mixin `mat-core-theme`
        node_modules/@angular/material/_theming.scss:3848, in mixin `angular-material-theme`
        stdin:15
      in C:\my-data\code\xenia\xenia-ui\node_modules\@angular\material\_theming.scss (line 1119, column 34)
Error:
undefined
                                ^
      Argument `$color` of `opacity($color)` must be a color

Backtrace:
        node_modules/@angular/material/_theming.scss:1119, in function `opacity`
        node_modules/@angular/material/_theming.scss:1119, in function `if`
        node_modules/@angular/material/_theming.scss:1119, in function `mat-color`
        node_modules/@angular/material/_theming.scss:1508, in mixin `mat-option-theme`
        node_modules/@angular/material/_theming.scss:3798, in mixin `mat-core-theme`
        node_modules/@angular/material/_theming.scss:3848, in mixin `angular-material-theme`
        stdin:15
      in C:\my-data\code\xenia\xenia-ui\node_modules\@angular\material\_theming.scss (line 1119, column 34)
    at options.error (C:\my-data\code\xenia\xenia-ui\node_modules\node-sass\lib\index.js:291:26)
 @ ./src/app-theme.scss 4:14-190
 @ multi ./src/styles.css ./src/app-theme.scss
</code>```

Please let me know what am I doing wrong. Thanks

答:
I think the issue is with this line

```<code>$primary: mat-palette($mat-deep-purple);
</code>```

Replace it with below line :

```<code>$primary: mat-palette($mat-deep-purple,A100);
</code>```

Body:
I am trying to create Angular 2 theme, I follow the tutorial as mentioned on the site. This is my theme file.

@import '~@angular/material/theming';

@include mat-core();
$primary: mat-palette($mat-deep-purple);
$accent:  mat-palette($mat-amber, A200);
$theme: mat-light-theme($primary, $accent);

@include angular-material-theme($theme);

.m2app-dark {
  $dark-primary: mat-palette($mat-blue, A800);
  $dark-accent:  mat-palette($mat-light-blue, A8008);
  $dark-warn:    mat-palette($mat-orange, A200);
  $dark-theme: mat-dark-theme($dark-primary, $dark-accent, $dark-warn);
  @include angular-material-theme($dark-theme);
}

While building I am getting following exeception

ERROR in ./node_modules/css-loader?{"sourceMap":false,"importLoaders":1}!./node_modules/postcss-loader?{"ident":"postcss"}!./node_modules/sass-loader/lib/loader.js?{"sourceMap":false,"precision":8,"includePaths":[]}!./src/app-theme.scss
Module build failed:
undefined
                                ^
      Argument `$color` of `opacity($color)` must be a color

Backtrace:
        node_modules/@angular/material/_theming.scss:1119, in function `opacity`
        node_modules/@angular/material/_theming.scss:1119, in function `if`
        node_modules/@angular/material/_theming.scss:1119, in function `mat-color`
        node_modules/@angular/material/_theming.scss:1508, in mixin `mat-option-theme`
        node_modules/@angular/material/_theming.scss:3798, in mixin `mat-core-theme`
        node_modules/@angular/material/_theming.scss:3848, in mixin `angular-material-theme`
        stdin:15
      in C:\my-data\code\xenia\xenia-ui\node_modules\@angular\material\_theming.scss (line 1119, column 34)
Error:
undefined
                                ^
      Argument `$color` of `opacity($color)` must be a color

Backtrace:
        node_modules/@angular/material/_theming.scss:1119, in function `opacity`
        node_modules/@angular/material/_theming.scss:1119, in function `if`
        node_modules/@angular/material/_theming.scss:1119, in function `mat-color`
        node_modules/@angular/material/_theming.scss:1508, in mixin `mat-option-theme`
        node_modules/@angular/material/_theming.scss:3798, in mixin `mat-core-theme`
        node_modules/@angular/material/_theming.scss:3848, in mixin `angular-material-theme`
        stdin:15
      in C:\my-data\code\xenia\xenia-ui\node_modules\@angular\material\_theming.scss (line 1119, column 34)
    at options.error (C:\my-data\code\xenia\xenia-ui\node_modules\node-sass\lib\index.js:291:26)
 @ ./src/app-theme.scss 4:14-190
 @ multi ./src/styles.css ./src/app-theme.scss

Please let me know what am I doing wrong. Thanks

Body:
I think the issue is with this line

$primary: mat-palette($mat-deep-purple);

Replace it with below line :

$primary: mat-palette($mat-deep-purple,A100);


问:
Given a string, how to iterate through many regexes to find a match?
Given a string, and a mapping of regexes to integers, I want to find out which integer the string maps to (assume the string will match exactly one of those regexes)

Is it inefficient to just iterate through the hash of regexes, trying each regex against the string, then outputting the value? Certainly I cannot explicitly enumerate all possible string => integer mappings, but it seems bad to try matching each regex in bunch of regexes.

答:
RegexpTrie, which wasn't around when I last looked for something like it, helps with this sort of problem:

```<code>require 'regexp_trie'

sentence = 'life on the mississippi'
words_ary = %w[the sip life]

words_regex = /\b(?:#{RegexpTrie.union(words_ary, option: Regexp::IGNORECASE).source})\b/i
# => /\b(?:(?:the|sip|life))\b/i

words_to_ints = words_ary.each_with_index.to_h
# => {"the"=>0, "sip"=>1, "life"=>2}

sentence_words = sentence.split
# => ["life", "on", "the", "mississippi"]

word_hits = sentence_words.map { |w| w[words_regex] }
# => ["life", nil, "the", nil]
</code>```

nil means there was no match of that word in the regular expression.

```<code>words_to_ints.values_at(*word_hits)
# => [2, nil, 0, nil]
</code>```

Again, nil means there was no match. nil values could be ignored using:

```<code>word_hits = sentence_words.map { |w| w[words_regex] }.compact
# => ["life", "the"]

words_to_ints.values_at(*word_hits)
# => [2, 0]
</code>```

Similarly, if you want to scan a sentence for word matches instead of individual words:

```<code>require 'regexp_trie'

sentence = 'life on the mississippi'
words = %w[the sip life]

words_regex = /\b(?:#{RegexpTrie.union(words, option: Regexp::IGNORECASE).source})\b/i
# => /\b(?:(?:the|sip|life))\b/i

words_to_ints = words.each_with_index.to_h
# => {"the"=>0, "sip"=>1, "life"=>2}

word_hits = sentence.scan(words_regex)
# => ["life", "the"]

words_to_ints.values_at(*word_hits)
# => [2, 0]
</code>```

Perl has a really useful module for this sort of thing called Regexp::Assemble, which lets you combine regexes into one big one, then search a string, returning the hits. You can ask it to tell which pattern was used if you want to know.

Ruby doesn't have such a module, but this gets kinda close:

```<code>patterns = {
  /(foo)/ => 1,
  /(bar)/ => 2
}

pattern_union = Regexp.union(patterns.keys)

pattern_union # => /(?-mix:(foo))|(?-mix:(bar))/

str = 'foo some text'

if (pattern_union =~ str)

  # these show what are being processed...
  pattern_union.match(str).captures # => ["foo", nil]
  pattern_union.match(str).captures.zip(patterns.keys).find_all{ |c| c[0] }.map{ |c| c[1] } # => [/(foo)/]

  # process it...
  matched_pattern_values = patterns.values_at(*pattern_union.match(str).captures.zip(patterns.keys).find_all{ |c| c[0] }.map{ |c| c[1] })

  # here's what we got
  matched_pattern_values # => [1]

end
</code>```

There's probably a way to do it in one line, but this works.

I think its important to avoid having to iterate over patterns to look for hits in strings if at all possible, because they can slow down badly as the size of the text or number of patterns increase.

See "Is there an efficient way to perform hundreds of text substitutions in Ruby?" for more about using Regexp::Assemble from Ruby.

Body:
RegexpTrie, which wasn't around when I last looked for something like it, helps with this sort of problem:

require 'regexp_trie'

sentence = 'life on the mississippi'
words_ary = %w[the sip life]

words_regex = /\b(?:#{RegexpTrie.union(words_ary, option: Regexp::IGNORECASE).source})\b/i
# => /\b(?:(?:the|sip|life))\b/i

words_to_ints = words_ary.each_with_index.to_h
# => {"the"=>0, "sip"=>1, "life"=>2}

sentence_words = sentence.split
# => ["life", "on", "the", "mississippi"]

word_hits = sentence_words.map { |w| w[words_regex] }
# => ["life", nil, "the", nil]

nil means there was no match of that word in the regular expression.

words_to_ints.values_at(*word_hits)
# => [2, nil, 0, nil]

Again, nil means there was no match. nil values could be ignored using:

word_hits = sentence_words.map { |w| w[words_regex] }.compact
# => ["life", "the"]

words_to_ints.values_at(*word_hits)
# => [2, 0]

Similarly, if you want to scan a sentence for word matches instead of individual words:

require 'regexp_trie'

sentence = 'life on the mississippi'
words = %w[the sip life]

words_regex = /\b(?:#{RegexpTrie.union(words, option: Regexp::IGNORECASE).source})\b/i
# => /\b(?:(?:the|sip|life))\b/i

words_to_ints = words.each_with_index.to_h
# => {"the"=>0, "sip"=>1, "life"=>2}

word_hits = sentence.scan(words_regex)
# => ["life", "the"]

words_to_ints.values_at(*word_hits)
# => [2, 0]

Perl has a really useful module for this sort of thing called Regexp::Assemble, which lets you combine regexes into one big one, then search a string, returning the hits. You can ask it to tell which pattern was used if you want to know.

Ruby doesn't have such a module, but this gets kinda close:

patterns = {
  /(foo)/ => 1,
  /(bar)/ => 2
}

pattern_union = Regexp.union(patterns.keys)

pattern_union # => /(?-mix:(foo))|(?-mix:(bar))/

str = 'foo some text'

if (pattern_union =~ str)

  # these show what are being processed...
  pattern_union.match(str).captures # => ["foo", nil]
  pattern_union.match(str).captures.zip(patterns.keys).find_all{ |c| c[0] }.map{ |c| c[1] } # => [/(foo)/]

  # process it...
  matched_pattern_values = patterns.values_at(*pattern_union.match(str).captures.zip(patterns.keys).find_all{ |c| c[0] }.map{ |c| c[1] })

  # here's what we got
  matched_pattern_values # => [1]

end

There's probably a way to do it in one line, but this works.

I think its important to avoid having to iterate over patterns to look for hits in strings if at all possible, because they can slow down badly as the size of the text or number of patterns increase.

See "Is there an efficient way to perform hundreds of text substitutions in Ruby?" for more about using Regexp::Assemble from Ruby.


问:
Codeigniter PHP submit post
i have a simple form using codeigniter and there is a submit button:

```<code><?php echo form_open('myController/add'); ?>
<input type="text" class="form-control" name="myInput" value='abc'>
<button type="submit" name="Submit">Save</button>
<?php echo form_close(); ?>
</code>```

but it doesn't contain Submit when i run this code:

```<code>function add(){
  print_r($_POST);
}
</code>```

here is the result:

```<code>Array ( [myInput] => abc )
</code>```

i think the result should be like this:

```<code>Array ( [myInput] => abc [Submit] =>)
</code>```

please help.. thank you.

答:
try this

use

```<code><input type="submit" name="Submit" value="Save">
</code>```

instead of

```<code><button type="submit" name="Submit">Save</button>
</code>```

because $_post get value of input

but you can also get its value using its name

like

```<code>$formSubmit = $this->input->post('Submit');
echo $formSubmit;
</code>```

Title: Codeigniter PHP submit post

Body:
i have a simple form using codeigniter and there is a submit button:

<?php echo form_open('myController/add'); ?>
<input type="text" class="form-control" name="myInput" value='abc'>
<button type="submit" name="Submit">Save</button>
<?php echo form_close(); ?>

but it doesn't contain Submit when i run this code:

function add(){
  print_r($_POST);
}

here is the result:

Array ( [myInput] => abc )

i think the result should be like this:

Array ( [myInput] => abc [Submit] =>)

please help.. thank you.

Body:
try this

use

<input type="submit" name="Submit" value="Save">

instead of

<button type="submit" name="Submit">Save</button>

because $_post get value of input

but you can also get its value using its name

like

$formSubmit = $this->input->post('Submit');
echo $formSubmit;


问:
Django View & Form Inheritance
I am trying to change the password change form for my custom user auth django project.  I am running into a bit of a problem.  Perhaps I am too tired, perhaps I am wrong or misunderstanding things, which is why I am seeking help.  I know it seems like a lot of work for such a small thing but I am trying to create a 'canned' auth app.  My goal with this particular problem is simply to apply style to the PasswordChangeForm(SetPasswordForm) class without the aid\dependency of non-native packages.  Am I wrong in my thought process here?  urls calls a view that inherits from the auth view which points to a form that inherits from auth form with changed field values.  Thanks in advance.

urls.py

```<code>from .views import ChangePasswordView
from django.contrib.auth.views import (
    PasswordChangeDoneView,
)

urlpatterns = [
    path('change_password/',
        ChangePasswordView,
        name='password_change'),
]
</code>```

views.py

```<code>    from django.contrib.auth.decorators import login_required
    from django.contrib.auth.views import PasswordChangeView
    from .forms import ChangePasswordForm

    @login_required
    class ChangePasswordView(PasswordChangeView):
        template_name='account/change_password_form.html'
        form_class = ChangePasswordForm
</code>```

forms.py

```<code>from django import forms
from django.utils.translation import gettext, gettext_lazy as _
from django.contrib.auth.forms import (
    PasswordChangeForm,
    SetPasswordForm,
)

class ChangePasswordForm(PasswordChangeForm):
    template_name='account/change_password_form.html'
    old_password = forms.CharField(
        label=_("Old password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'autofocus': True, 'placeholder': 'Password',
                               'class': 'form-control', 'required': 'true'}),
    )

    new_password1 = forms.CharField(
        label=_("New Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'placeholder': 'Password',
                               'class': 'form-control', 'required': 'true'}),
    )

    new_password2 = forms.CharField(
        label=_("Confirm Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'placeholder': 'Password',
                               'class': 'form-control', 'required': 'true'}),
</code>```

the error

TypeError at /account/change_password/
  init() takes 1 positional argument but 2 were given

答:
It's always the little things...

```<code>urlpatterns = [
    path('change_password/',
        ChangePasswordView,
        name='password_change'),
]
</code>```

should be

```<code>urlpatterns = [
    path('change_password/',
        ChangePasswordView.as_view(),
        name='password_change'),
]
</code>```

It's late! You're tired! Get it working, then get some sleep. :-)

Title: Django View & Form Inheritance

Body:
I am trying to change the password change form for my custom user auth django project.  I am running into a bit of a problem.  Perhaps I am too tired, perhaps I am wrong or misunderstanding things, which is why I am seeking help.  I know it seems like a lot of work for such a small thing but I am trying to create a 'canned' auth app.  My goal with this particular problem is simply to apply style to the PasswordChangeForm(SetPasswordForm) class without the aid\dependency of non-native packages.  Am I wrong in my thought process here?  urls calls a view that inherits from the auth view which points to a form that inherits from auth form with changed field values.  Thanks in advance.

urls.py

from .views import ChangePasswordView
from django.contrib.auth.views import (
    PasswordChangeDoneView,
)

urlpatterns = [
    path('change_password/',
        ChangePasswordView,
        name='password_change'),
]

views.py

    from django.contrib.auth.decorators import login_required
    from django.contrib.auth.views import PasswordChangeView
    from .forms import ChangePasswordForm

    @login_required
    class ChangePasswordView(PasswordChangeView):
        template_name='account/change_password_form.html'
        form_class = ChangePasswordForm

forms.py

from django import forms
from django.utils.translation import gettext, gettext_lazy as _
from django.contrib.auth.forms import (
    PasswordChangeForm,
    SetPasswordForm,
)

class ChangePasswordForm(PasswordChangeForm):
    template_name='account/change_password_form.html'
    old_password = forms.CharField(
        label=_("Old password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'autofocus': True, 'placeholder': 'Password',
                               'class': 'form-control', 'required': 'true'}),
    )

    new_password1 = forms.CharField(
        label=_("New Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'placeholder': 'Password',
                               'class': 'form-control', 'required': 'true'}),
    )

    new_password2 = forms.CharField(
        label=_("Confirm Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'placeholder': 'Password',
                               'class': 'form-control', 'required': 'true'}),

the error

TypeError at /account/change_password/
  init() takes 1 positional argument but 2 were given

Body:
It's always the little things...

urlpatterns = [
    path('change_password/',
        ChangePasswordView,
        name='password_change'),
]

should be

urlpatterns = [
    path('change_password/',
        ChangePasswordView.as_view(),
        name='password_change'),
]

It's late! You're tired! Get it working, then get some sleep. :-)


问:
How to validate number is greater than 0 in python?
I tried to validate the returned number from input form in python. The input value must be a number and greater than 0.

My script is like this:

hello.py

```<code># -*- coding: utf-8 -*-
from flask import *

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def checNumber():
    if request.method=='POST':

        number = request.form['Number']

        try:
            if int(number) < 0:
                raise 'Number should be greater than 0'
        except:
                raise 'Please enter number only'

    return render_template('hello.html')

if __name__ == '__main__':

    app.run(debug=True)
</code>```

hello.html

```<code><form class="form-horizontal" action='' method='POST'>
      <div class="form-group">
        <label for="KhmerName" class="col-sm-2 control-label">Number:</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="Number" name="Number" placeholder="Please enter number only">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default">Submit</button>
        </div>
      </div>
    </form>
</code>```

After I click on submit form, if the inputted value is not a number (alphabet or something else) it will raise 'Please enter number only'. However, if number is negative, it never raise 'Number should be greater than 0', yet the python regards it as not a number and raise 'Please enter number only'.

I think a negative value is also a number.

How can I fix this? Thanks.

答:
Instead of:

```<code>    try:
        if int(number) < 0:
            raise 'Number should be greater than 0'
    except:
            raise 'Please enter number only'
</code>```

Go with:

```<code>   try:
       if float(request.form['Number']) <= 0:
          raise 'Number should be greater than 0'
   finally:
       raise 'Please enter number only'
</code>```

And if that does not help, let the exception from "int(number) < 0" raise through and see what caused the exception.

Body:
I tried to validate the returned number from input form in python. The input value must be a number and greater than 0.

My script is like this:

hello.py

# -*- coding: utf-8 -*-
from flask import *

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def checNumber():
    if request.method=='POST':

        number = request.form['Number']

        try:
            if int(number) < 0:
                raise 'Number should be greater than 0'
        except:
                raise 'Please enter number only'

    return render_template('hello.html')

if __name__ == '__main__':

    app.run(debug=True)

hello.html

<form class="form-horizontal" action='' method='POST'>

        Number:

          <input type="text" class="form-control" id="Number" name="Number" placeholder="Please enter number only">

          <button type="submit" class="btn btn-default">Submit</button>

    </form>

After I click on submit form, if the inputted value is not a number (alphabet or something else) it will raise 'Please enter number only'. However, if number is negative, it never raise 'Number should be greater than 0', yet the python regards it as not a number and raise 'Please enter number only'.

I think a negative value is also a number.

How can I fix this? Thanks.

Body:
Instead of:

    try:
        if int(number) < 0:
            raise 'Number should be greater than 0'
    except:
            raise 'Please enter number only'

Go with:

   try:
       if float(request.form['Number']) <= 0:
          raise 'Number should be greater than 0'
   finally:
       raise 'Please enter number only'

And if that does not help, let the exception from "int(number) < 0" raise through and see what caused the exception.


问:
Can I make springfox be package-aware?
Let's say I have following classes

```<code>.../RabbitController
.../test/SomeController
</code>```

springfox, without any swagger annotations, works fine.

```<code>rabbit-controller
some-controller
</code>```

When I add another class

```<code>.../RabbitController
.../test/SomeController
.../test/RabbitController
</code>```

An error comes out,

```<code>Annotation-specified bean name 'rabbitController'
for bean class [...RabbitController]
conflicts with existing,
non-compatible bean definition of same name and class
[.....test.RabbitController]
</code>```

Is there any way to make springfox be aware of the hierarchy of the class so that I get something like

```<code>rabbit-controller
test-some-controller
test-rabbit-controller
</code>```

?

答:
Spring

Spring will complain if you have two controllers of the same name. Spring names an autodetected component such as a bean marked with @RestController as an uncapitalized non-qualified class name in the absence of a name value.

You can avoid the following error by naming the second RabbitController as @RestController("test-rabbit-controller"). You can find more information here.

Annotation-specified bean name 'rabbitController'
for bean class [...RabbitController]
conflicts with existing,
non-compatible bean definition of same name and class
[.....test.RabbitController]

Springfox

From the perspective of Springfox, you can make both the controllers distinct by having distinct description value in the @Api annotation.

Here are the changes you need to make:

Controller 1

```<code>@RestController
@Slf4j
@Api(description = "rabbit-controller",
        produces = "application/json", tags = {"1"})
public class RabbitController {
    ...
}
</code>```

Controller 2

```<code>@RestController("test-rabbit-controller")
@Slf4j
@Api(description = "test-rabbit-controller",
        produces = "application/json", tags = {"2"})
public class RabbitController {
    ...
}
</code>```

Title: Can I make springfox be package-aware?

Body:
Let's say I have following classes

.../RabbitController
.../test/SomeController

springfox, without any swagger annotations, works fine.

rabbit-controller
some-controller

When I add another class

.../RabbitController
.../test/SomeController
.../test/RabbitController

An error comes out,

Annotation-specified bean name 'rabbitController'
for bean class [...RabbitController]
conflicts with existing,
non-compatible bean definition of same name and class
[.....test.RabbitController]

Is there any way to make springfox be aware of the hierarchy of the class so that I get something like

rabbit-controller
test-some-controller
test-rabbit-controller

?

Body:
Spring

Spring will complain if you have two controllers of the same name. Spring names an autodetected component such as a bean marked with @RestController as an uncapitalized non-qualified class name in the absence of a name value.

You can avoid the following error by naming the second RabbitController as @RestController("test-rabbit-controller"). You can find more information here.

Annotation-specified bean name 'rabbitController'
for bean class [...RabbitController]
conflicts with existing,
non-compatible bean definition of same name and class
[.....test.RabbitController]

Springfox

From the perspective of Springfox, you can make both the controllers distinct by having distinct description value in the @Api annotation.

Here are the changes you need to make:

Controller 1

@RestController
@Slf4j
@Api(description = "rabbit-controller",
        produces = "application/json", tags = {"1"})
public class RabbitController {
    ...
}

Controller 2

@RestController("test-rabbit-controller")
@Slf4j
@Api(description = "test-rabbit-controller",
        produces = "application/json", tags = {"2"})
public class RabbitController {
    ...
}


问:
Regular expressions to select text from string in Python
I have formatted lines of the text, i.e.

```<code>[[item1 *,* {_item2*} *;{item3*}* ;{item4*}*]]
</code>```

where * means any text between the words and brackets.
Is it possible to collect text from * to variables?

```<code>item1, after1, before2, item2, after2, item3, after3, item4, after4, afterall = re. ???
</code>```

答:
You should be able to do it with regular expressions.

http://docs.python.org/library/re.html

You can put parenthesis around parts of the expression you want to pull out later.

Are you trying to grab the * parts or the item parts? If you trying to grab the * parts it shouldn't be too hard.

```<code>import re

reg = r'\[\[item1 (.*),(.*) {_item2(.*)} (.*);{item3(.*)}(.*) ;{item4(.*)}(.*)\]\]'
match = re.match(reg, text)
# You grab items by index. Starting from 1, 0 is the entire match
item1 = match.group(1)
item2 = match.group(2)
</code>```

You will probably have to play with it a bit to get it to match what you want.

Body:
I have formatted lines of the text, i.e.

[[item1 *,* {_item2*} *;{item3*}* ;{item4*}*]]

where * means any text between the words and brackets.
Is it possible to collect text from * to variables?

item1, after1, before2, item2, after2, item3, after3, item4, after4, afterall = re. ???

Body:
You should be able to do it with regular expressions.

http://docs.python.org/library/re.html

You can put parenthesis around parts of the expression you want to pull out later.

Are you trying to grab the * parts or the item parts? If you trying to grab the * parts it shouldn't be too hard.

import re

reg = r'\[\[item1 (.*),(.*) {_item2(.*)} (.*);{item3(.*)}(.*) ;{item4(.*)}(.*)\]\]'
match = re.match(reg, text)
# You grab items by index. Starting from 1, 0 is the entire match
item1 = match.group(1)
item2 = match.group(2)

You will probably have to play with it a bit to get it to match what you want.

ContentLicense: CC BY-SA 2.5


问:
Nothing to repeat at position 0 when replacing string in pandas dataframe
In my MySQL database, phone in a VARCHAR. Then, I import this to a pandas dataframe. Here's my data:

```<code>data5

id   phone
1     +62634783472
2       0834838483
3              +62
</code>```

What I want is convert +62 to 0, expected output would be like this

```<code>id   phone
1       0634783472
2       0834838483
3                0
</code>```

I already try two thing, there are

```<code>data5['phone'] = data5['phone'].str.replace('+62', '0')

data5['phone'] = data5['phone'].replace(to_replace='+62', value='0', regex=True)
</code>```

And the result is:

```<code>error: nothing to repeat at position 0
</code>```

What is I miss?

Body:
In my MySQL database, phone in a VARCHAR. Then, I import this to a pandas dataframe. Here's my data:

data5

id   phone
1     +62634783472
2       0834838483
3              +62

What I want is convert +62 to 0, expected output would be like this

id   phone
1       0634783472
2       0834838483
3                0

I already try two thing, there are

data5['phone'] = data5['phone'].str.replace('+62', '0')

data5['phone'] = data5['phone'].replace(to_replace='+62', value='0', regex=True)

And the result is:

error: nothing to repeat at position 0

What is I miss?

Body:
replace and regex=True

data5.replace({'\+62':'0'},regex=True)
Out[76]:
   id       phone
0   1  0634783472
1   2  0834838483
2   3           0


问:
jQuery datepicker - End Date should not be less than Start Date & Date difference
I referred to the following two pages to combine two features:
- End date should not be less than satart date
- The date difference
(Reference pages:
http://www.jquerybyexample.net/2012/01/end-date-should-not-be-greater-than.html
and
jquery datepicker + date diff calculation )

The code I created using two sources above:

$(document).ready(function(){
 var select=function(dateStr) {
      var d1 = $('#datepicker3').datepicker('getDate');
      var d2 = $('#datepicker4').datepicker('getDate');
      var diff = 0;
      if (d1 && d2) {
            diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
      }
      $('#calculated').val(diff);
}

    $("#datepicker3").datepicker({
             showMonthAfterYear: true,

        numberOfMonths: 2,
             minDate: 0,
         onSelect: function(selected) {
          $("#datepicker4").datepicker("option","minDate", selected)
        }
    });
    $("#datepicker4").datepicker({
     showMonthAfterYear: true,
         numberOfMonths: 2,
         onSelect: select,
         function(selected) {
           $("#datepicker3").datepicker("option","maxDate", selected)
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>

<input type="text" id="datepicker3" placeholder="Start Date"> - <input type="text" id="datepicker4" placeholder="End Date"><br>
<input type="text" id="calculated"></code>```

The code above works in Chrome but not in Internet Explorer. I think there is something wrong with my code. Could you please check it?

Thank you very much.

答:
start date and greater than end date</p>

```<code>$(document).on('change', '#startdate', function () {
    var startdate = $(this).val();
    var endDate = $('#endDate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        endDate: '+0d',
        autoclose: true
    });
    endDate.datepicker("setStartDate", startdate);
});
</code>```

Body:
I referred to the following two pages to combine two features:
- End date should not be less than satart date
- The date difference
(Reference pages:
http://www.jquerybyexample.net/2012/01/end-date-should-not-be-greater-than.html
and
jquery datepicker + date diff calculation )

The code I created using two sources above:

$(document).ready(function(){
 var select=function(dateStr) {
      var d1 = $('#datepicker3').datepicker('getDate');
      var d2 = $('#datepicker4').datepicker('getDate');
      var diff = 0;
      if (d1 && d2) {
            diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
      }
      $('#calculated').val(diff);
}

    $("#datepicker3").datepicker({
             showMonthAfterYear: true,

        numberOfMonths: 2,
             minDate: 0,
         onSelect: function(selected) {
          $("#datepicker4").datepicker("option","minDate", selected)
        }
    });
    $("#datepicker4").datepicker({
     showMonthAfterYear: true,
         numberOfMonths: 2,
         onSelect: select,
         function(selected) {
           $("#datepicker3").datepicker("option","maxDate", selected)
        }
    });
});

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/redmond/jquery-ui.css">

<input type="text" id="datepicker3" placeholder="Start Date"> - <input type="text" id="datepicker4" placeholder="End Date">

<input type="text" id="calculated">

The code above works in Chrome but not in Internet Explorer. I think there is something wrong with my code. Could you please check it?

Thank you very much.

Body:
start date and greater than end date

$(document).on('change', '#startdate', function () {
    var startdate = $(this).val();
    var endDate = $('#endDate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        endDate: '+0d',
        autoclose: true
    });
    endDate.datepicker("setStartDate", startdate);
});


问:
Qt how to open a file in current dir ? or what's wrong with this?
I'm trying to open an xml file in the current location of the executable

```<code>        QString path = QDir::currentPath();
        path.append("/acc.xml");
        QFile file(path);

        if(!file.open(QIODevice::ReadOnly))
        {
            insertItem("IO ERR");
        }
</code>```

When I run it from Qt creator, everything works. currentPath() returns the path to the executable's folder

When I go to project-build-desktop/ folder and try to run it manually currentPath() returns /home/user/Documents

EDIT

also tried with same results:

```<code>Qt::current().path();
Qt::current().absolutePath();
</code>```

答:
To open a file in the current directory, you simply call QFile constructor

I tested this on my Linux machine and it works

```<code>#include <QtCore>

int main(int argc, char** argv){
    QFile some_file("test.xml");
    if(!some_file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << "Unable to open file";
    } else {
        qDebug() << "File open successfully";
    }
    exit(-1);
}
</code>```

I run ./TestQFile and if there is a test.xml in the current directory, it works.

UPDATE: I notice that the wording of your question says that you want the file in the same directory as the executable, this can be done as follow:

```<code>// Getting directory of the executable
QFileInfo exec_fileinfo(argv[0]);
qDebug() << "Executable is in" << exec_fileinfo.absolutePath();
</code>```

UPDATE 2: Under the project panel of QtCreator, there is a field for Working Directory. This is the directory that is returned by QDir::currentPath() if you are running it via QtCreator.

Body:
I'm trying to open an xml file in the current location of the executable

        QString path = QDir::currentPath();
        path.append("/acc.xml");
        QFile file(path);

        if(!file.open(QIODevice::ReadOnly))
        {
            insertItem("IO ERR");
        }

When I run it from Qt creator, everything works. currentPath() returns the path to the executable's folder

When I go to project-build-desktop/ folder and try to run it manually currentPath() returns /home/user/Documents

EDIT

also tried with same results:

Qt::current().path();
Qt::current().absolutePath();

Body:
To open a file in the current directory, you simply call QFile constructor

I tested this on my Linux machine and it works

#include <QtCore>

int main(int argc, char** argv){
    QFile some_file("test.xml");
    if(!some_file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << "Unable to open file";
    } else {
        qDebug() << "File open successfully";
    }
    exit(-1);
}

I run ./TestQFile and if there is a test.xml in the current directory, it works.

UPDATE: I notice that the wording of your question says that you want the file in the same directory as the executable, this can be done as follow:

// Getting directory of the executable
QFileInfo exec_fileinfo(argv[0]);
qDebug() << "Executable is in" << exec_fileinfo.absolutePath();

UPDATE 2: Under the project panel of QtCreator, there is a field for Working Directory. This is the directory that is returned by QDir::currentPath() if you are running it via QtCreator.


问:
Combining Multiple row values in a single line SSRS expression
There are three rows in my SQL output which I would like to view them in a single line when I want to view them while running the SSRS report.

Source Data

These two columns are part of my DataSet1 in the SSRS report.

Output I am expecting in the SSRS report (Expression): Semester 1 2017, Semester 2 2017, Semester 3 2017

Can someone please help?

答:
Check this
https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql</p>

```<code>SELECT STUFF(
             (SELECT ',' + Semesters
              FROM table t1
              FOR XML PATH (''))
             , 1, 1, '') AS Semesters from table t2
</code>```

Body:
Check this
https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql

SELECT STUFF(
             (SELECT ',' + Semesters
              FROM table t1
              FOR XML PATH (''))
             , 1, 1, '') AS Semesters from table t2


问:
Firebase Create and Login?
Can I use firebase with python to do user account creation and logging in and out?

or any other recommendations? I've read but seems like it only uses nodejs

答:
There is an Admin SDK for Python for certain Firebase products, including Firebase Authentication.

The Admin SDK for Firebase is meant to run on servers and in other trusted environments. This means that a process using the Admin SDK has administrative access to all Firebase services. This for example allows you to easily create a new user account with the Python SDK.

But that also means that the Python SDK cannot be used to sign in with Firebase Authentication: after all, the process already runs with administrative privileges.

If you want to use the Python SDK to verify users, you should have the users sign in on the client with one of the regular Firebase Authentication SDKs. Then send the ID token from the client to your server, and use the Python SDK to verify that token.

Title: Firebase Create and Login?


问:
Python Ordered Pairs
I am new to python, and I am trying to generate ordered pairs, and then evaluate the Domain and Range of the set relation. My issue with my current code is that it sets up the list just fine, but rather than giving me the actual ordered pair, it gives me (what I am assuming is) the address of the ordered pair.</p>

```<code>    relation = [[] for i in range(numOrderPairs)]
    for x in range(numOrderPairs):
       inputOrderPair = input("\nPlease enter an ordered pair, i.e (x, y).")
       orderPair = (int(t.strip("(),")) for t in inputOrderPair.split())
       relation[x] = orderPair
    print(relation)

    >>>[<generator object <genexpr> at 0x7f4242a0ab48>, <generator object
       <genexpr> at 0x7f4242a0aba0>, <generator object <genexpr> at
       0x7f4242a0abf8>]
</code>```

答:
The following code returns a generator.

```<code>(int(t.strip("(),")) for t in inputOrderPair.split())
</code>```

I think you possibly expected it to create a tuple, in which case you would have to do something like this;

```<code>tuple(int(t.strip("(),")) for t in inputOrderPair.split())
</code>```

Or you could just use a list instead

```<code>[int(t.strip("(),")) for t in inputOrderPair.split()]
</code>```

Title: Python Ordered Pairs

Body:
I am new to python, and I am trying to generate ordered pairs, and then evaluate the Domain and Range of the set relation. My issue with my current code is that it sets up the list just fine, but rather than giving me the actual ordered pair, it gives me (what I am assuming is) the address of the ordered pair.

    relation = [[] for i in range(numOrderPairs)]
    for x in range(numOrderPairs):
       inputOrderPair = input("\nPlease enter an ordered pair, i.e (x, y).")
       orderPair = (int(t.strip("(),")) for t in inputOrderPair.split())
       relation[x] = orderPair
    print(relation)

    >>>[<generator object <genexpr> at 0x7f4242a0ab48>, <generator object
       <genexpr> at 0x7f4242a0aba0>, <generator object <genexpr> at
       0x7f4242a0abf8>]

Body:
The following code returns a generator.

(int(t.strip("(),")) for t in inputOrderPair.split())

I think you possibly expected it to create a tuple, in which case you would have to do something like this;

tuple(int(t.strip("(),")) for t in inputOrderPair.split())

Or you could just use a list instead

[int(t.strip("(),")) for t in inputOrderPair.split()]


答:
Yes you could use STUFF() function with xml path method for that

```<code>SELECT DISTINCT
       Semester = STUFF(
                       (
                           SELECT ','+CONCAT(Semester, ' ', [year])
                           FROM <table> FOR XML PATH('')
                       ), 1, 1, '')
FROM <table>;
</code>```

Update : You could use CONCAT() function for combining the year & Semester

Result :

```<code>Semester
Semester 1 2017,Semester 2 2017,Semester 3 2017
</code>```

Title: Combining Multiple row values in a single line SSRS expression

Body:
There are three rows in my SQL output which I would like to view them in a single line when I want to view them while running the SSRS report.

Source Data

These two columns are part of my DataSet1 in the SSRS report.

Output I am expecting in the SSRS report (Expression): Semester 1 2017, Semester 2 2017, Semester 3 2017

Can someone please help?

Body:
Yes you could use STUFF() function with xml path method for that

SELECT DISTINCT
       Semester = STUFF(
                       (
                           SELECT ','+CONCAT(Semester, ' ', [year])
                           FROM <table> FOR XML PATH('')
                       ), 1, 1, '')
FROM <table>;

Update : You could use CONCAT() function for combining the year & Semester

Result :

Semester
Semester 1 2017,Semester 2 2017,Semester 3 2017


问:
Detect user change clock time after Force Stop app
I can detect change clock time when app in foreground, background, or kill from Recent App by using android.intent.action.TIME_SET follow here.

However, if I Force Stop app in Setting->Apps I can not receive this broadcast anymore.

Currently, I want to detect user change clock time come back to my app after ForceStop so I do

```<code>long deltaTimeBeetweenCurrentTimeAndTimeSinceReboot = System.currentTimeMillis() - SystemClock.elapsedRealtime();
long oldDelta = mSharedPreference.getDeltaTimeBeetweenCurrentTimeAndTimeSinceReboot();
if(deltaTimeBeetweenCurrentTimeAndRebootTime - oldDelta > 5000){
    // clock time change
}
</code>```

Idea is I saved a delta between currently time (System.currentTimeMillis()) and time since reboot (SystemClock.elapsedRealtime()). Every time I open app, I will compare oldDelta and newDelta (except the first time install). It work well in case: User Fore Stop app->Change time->come back to app.

However, there is still have 1 case that is: User Fore Stop app -> Change the clock time -> Reboot device -> Open my app. At this time I can not use the above method to check the clock time have changed because after reboot the SystemClock.elapsedRealtime() will reset. How can I detect clock time have changed in that case?

Any help or suggestion would be great appreciate.

答:
It would be hard to implement without external etalon (backend is the best option). You may save time a user force to stop the app and when the app alive again compare with some predefined delta (time window). If you get a "big" difference consider the user is cheating. </p>

<p>You may also play with timestamps of the filesystem to define some inconsistency.  </p>

Body:
I can detect change clock time when app in foreground, background, or kill from Recent App by using android.intent.action.TIME_SET follow here.

However, if I Force Stop app in Setting->Apps I can not receive this broadcast anymore.

Currently, I want to detect user change clock time come back to my app after ForceStop so I do

long deltaTimeBeetweenCurrentTimeAndTimeSinceReboot = System.currentTimeMillis() - SystemClock.elapsedRealtime();
long oldDelta = mSharedPreference.getDeltaTimeBeetweenCurrentTimeAndTimeSinceReboot();
if(deltaTimeBeetweenCurrentTimeAndRebootTime - oldDelta > 5000){
    // clock time change
}

Idea is I saved a delta between currently time (System.currentTimeMillis()) and time since reboot (SystemClock.elapsedRealtime()). Every time I open app, I will compare oldDelta and newDelta (except the first time install). It work well in case: User Fore Stop app->Change time->come back to app.

However, there is still have 1 case that is: User Fore Stop app -> Change the clock time -> Reboot device -> Open my app. At this time I can not use the above method to check the clock time have changed because after reboot the SystemClock.elapsedRealtime() will reset. How can I detect clock time have changed in that case?

Any help or suggestion would be great appreciate.

Body:
It would be hard to implement without external etalon (backend is the best option). You may save time a user force to stop the app and when the app alive again compare with some predefined delta (time window). If you get a "big" difference consider the user is cheating.

You may also play with timestamps of the filesystem to define some inconsistency.


问:
Need for a JasperReports null parameter value to show all
I've been through this problem for a while and I hope you can help me.

I have a report made on iReport, and I'd like the report to be filled even if some parameters are null.

Here's what I have

```<code>SELECT
    evento."titulo" AS evento_titulo,
    evento."data_inicio_realizacao" AS evento_data_inicio_realizacao,
    evento."data_fim_realizacao" AS evento_data_fim_realizacao,
    evento."id" AS evento_id
FROM
    "public"."evento" evento
WHERE
    evento."id" = $P{eventoid} OR
    evento."data_inicio_realizacao" BETWEEN $P{data1} AND $P{data2}
</code>```

I'd like the WHERE clause to be optional, i.e., if I leave these parameters null (or 0-valued on id's case), I want to get all values instead of a blank report.

Is it possible? I found some people making a $P{WHERE_CLAUSE} and passing the whole where clause as its value, but it didn't work for me.

答:
Well I tried a bit harder and figured out how to make it work by passing the whole WHERE clause inside a $P{} param.

I simply deleted the whole WHERE clause and put this:

```<code>$P!{whereClause}
</code>```

I put a single parameter in there and deleted the three parameters $P{eventoid}, $P{data1} and $P{data2} from the report.

I'm working on Spring MVC and inside my class Controller, under the POST request mapping for that page, I added a String variable called whereClause, and set its value to "WHERE 1=1" (or true if you prefer):

```<code>String whereClause = "WHERE 1=1";

if (relIndice.getEventoId() != 0) {
    whereClause += " AND evento.id = " + relIndice.getEventoId().toString();
}

if (relIndice.getData1() != null) {
    whereClause += " AND evento.data_inicio_realizacao >= '" + relIndice.getData1().toString() + "'";
}

if (relIndice.getData2() != null) {
whereClause += " AND evento.data_inicio_realizacao <= '" + relIndice.getData2().toString() + "'";
}

whereClause += " ORDER BY evento.data_inicio_realizacao";
</code>```

After setting the initial value for the whereClause variable, I made 3 IF statements, each for one of the fields I want to include in the WHERE statement, in the SQL.

Since "WHERE 1=1 will run anyway, a blankspace is needed before the AND, in order to make a clean and working syntax.

And in the end I added an ORDER BY clause that will run anyway too.
And that's it, the values of your parameters will be the values you'll get from the getters you want to use.

In my case I can leave any values null or zero(on eventoId's case since it's an int), and I'll have all the records from that table since the SELECT statement won't see the WHERE clause... Coz it doesn't exist!

Thank you guys!

Body:
I've been through this problem for a while and I hope you can help me.

I have a report made on iReport, and I'd like the report to be filled even if some parameters are null.

Here's what I have

SELECT
    evento."titulo" AS evento_titulo,
    evento."data_inicio_realizacao" AS evento_data_inicio_realizacao,
    evento."data_fim_realizacao" AS evento_data_fim_realizacao,
    evento."id" AS evento_id
FROM
    "public"."evento" evento
WHERE
    evento."id" = $P{eventoid} OR
    evento."data_inicio_realizacao" BETWEEN $P{data1} AND $P{data2}

I'd like the WHERE clause to be optional, i.e., if I leave these parameters null (or 0-valued on id's case), I want to get all values instead of a blank report.

Is it possible? I found some people making a $P{WHERE_CLAUSE} and passing the whole where clause as its value, but it didn't work for me.

Body:
Well I tried a bit harder and figured out how to make it work by passing the whole WHERE clause inside a $P{} param.

I simply deleted the whole WHERE clause and put this:

$P!{whereClause}

I put a single parameter in there and deleted the three parameters $P{eventoid}, $P{data1} and $P{data2} from the report.

I'm working on Spring MVC and inside my class Controller, under the POST request mapping for that page, I added a String variable called whereClause, and set its value to "WHERE 1=1" (or true if you prefer):

String whereClause = "WHERE 1=1";

if (relIndice.getEventoId() != 0) {
    whereClause += " AND evento.id = " + relIndice.getEventoId().toString();
}

if (relIndice.getData1() != null) {
    whereClause += " AND evento.data_inicio_realizacao >= '" + relIndice.getData1().toString() + "'";
}

if (relIndice.getData2() != null) {
whereClause += " AND evento.data_inicio_realizacao <= '" + relIndice.getData2().toString() + "'";
}

whereClause += " ORDER BY evento.data_inicio_realizacao";

After setting the initial value for the whereClause variable, I made 3 IF statements, each for one of the fields I want to include in the WHERE statement, in the SQL.

Since "WHERE 1=1 will run anyway, a blankspace is needed before the AND, in order to make a clean and working syntax.

And in the end I added an ORDER BY clause that will run anyway too.
And that's it, the values of your parameters will be the values you'll get from the getters you want to use.

In my case I can leave any values null or zero(on eventoId's case since it's an int), and I'll have all the records from that table since the SELECT statement won't see the WHERE clause... Coz it doesn't exist!

Thank you guys!


问:
UMBRACO: How to add image on template
So, I'm currently new to Umbraco and I'm following some tutorial videos on umbraco.tv. I have created my template and is currently using it to setup the Home Page for my website. I have all the front end working and its displaying properly.

My problem is on the images. I'm using a lot of images for my website and I'm trying to link it to content so the images can be easily changed(not sure if I'm making sense).

Navigation bar image

If you click the link above, that's how my current navigation bar look like. I want to be able to change the LOGO using Umbraco's media picker. However, everytime I do so, it either gives me the alt name or a runtime error.

This is the code for the image on the template.

```<code><img src="@Umbraco.Field("navigationLogo")" height="100" width="50" alt="Logo">
</code>```

I'd appreciate it if you can help me. I'm not sure if I've explained it properly so feel free to ask in detail. Thanks!

Edit -----

I am only coding on browser since it doesn't allow me to login to pull the codes locally (only on trial version since I'm just testing out if its a good CMS).

Not sure if I'm doing it correctly so I apologize. I wrote my code like this

```<code>@{
   var navigationLogo = @Umbraco.AssignedContent.Site().GetPropertyValue("navigationLogo");
   var navigationLogoMediaItem = @Umbraco.TypedMedia(navigationLogo);

   <img src="@navigationLogoMediaItem.Url" height="100" width="50" alt="Logo" />
 }
</code>```

It's giving me the following error so far.

Compiler Error Message: CS1061: 'Umbraco.Web.UmbracoHelper' does not contain a definition for 'AssignedContent' and no extension method 'AssignedContent' accepting a first argument of type 'Umbraco.Web.UmbracoHelper' could be found (are you missing a using directive or an assembly reference?

答:
```<code>@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = "WebBase.cshtml";
    string navigationLogoMediaItem = "";
    if (Model.Content.HasValue("navigationLogo"))
    {
     navigationLogoMediaItem = Model.Content.GetPropertyValue<IPublishedContent>("navigationLogo").Url;

    }
}

<img src="@navigationLogoMediaItem" height="100" width="50" alt="Logo" />
</code>```

you can try this

Title: UMBRACO: How to add image on template

Body:
So, I'm currently new to Umbraco and I'm following some tutorial videos on umbraco.tv. I have created my template and is currently using it to setup the Home Page for my website. I have all the front end working and its displaying properly.

My problem is on the images. I'm using a lot of images for my website and I'm trying to link it to content so the images can be easily changed(not sure if I'm making sense).

Navigation bar image

If you click the link above, that's how my current navigation bar look like. I want to be able to change the LOGO using Umbraco's media picker. However, everytime I do so, it either gives me the alt name or a runtime error.

This is the code for the image on the template.

I'd appreciate it if you can help me. I'm not sure if I've explained it properly so feel free to ask in detail. Thanks!

Edit -----

I am only coding on browser since it doesn't allow me to login to pull the codes locally (only on trial version since I'm just testing out if its a good CMS).

Not sure if I'm doing it correctly so I apologize. I wrote my code like this

@{
   var navigationLogo = @Umbraco.AssignedContent.Site().GetPropertyValue("navigationLogo");
   var navigationLogoMediaItem = @Umbraco.TypedMedia(navigationLogo);

 }

It's giving me the following error so far.

Compiler Error Message: CS1061: 'Umbraco.Web.UmbracoHelper' does not contain a definition for 'AssignedContent' and no extension method 'AssignedContent' accepting a first argument of type 'Umbraco.Web.UmbracoHelper' could be found (are you missing a using directive or an assembly reference?

Body:
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = "WebBase.cshtml";
    string navigationLogoMediaItem = "";
    if (Model.Content.HasValue("navigationLogo"))
    {
     navigationLogoMediaItem = Model.Content.GetPropertyValue<IPublishedContent>("navigationLogo").Url;

    }
}

<img src="@navigationLogoMediaItem" height="100" width="50" alt="Logo" />

you can try this


问:
POSTGRES: How to do loop & How to join inside the loops?
SQL Newbie here.

I have two tables like these

Table: Order

```<code>CREATE TABLE orders (
 ID serial NOT NULL PRIMARY KEY,
 data json NOT NULL
);

INSERT INTO orders (data)
VALUES
 (
 '{"customer":"John Doe","items":[{"1234":{"attributes":{"name":"parent"}},"id":"1234","isPhone":true,"items":[{"5678":{"attributes":{"name":"child"}},"id":"5678","isPhone":false}]},{"9012":{"attributes":{"name":"parent"}},"id":"9012","isPhone":true,"items":[{"3456":{"attributes":{"name":"child"}},"id":"3456","isPhone":false}]}]}'
 );

 INSERT INTO orders (data)
VALUES
 (
 '{"customer":"John Doe","items":[{"7890":{"attributes":{"name":"parent"}},"id":"7890","isPhone":true,"items":[{"0987":{"attributes":{"name":"child"}},"id":"0987","isPhone":false}]},{"6543":{"attributes":{"name":"parent"}},"id":"6543","isPhone":true,"items":[{"2109":{"attributes":{"name":"child"}},"id":"2109","isPhone":false}]}]}'
 );
</code>```

Table: Backlog

```<code>CREATE TABLE backlog (
 ID serial NOT NULL PRIMARY KEY,
 data json NOT NULL
);

  INSERT INTO backlog (data)
VALUES
 ('{"id":"5678","isAvailable":true,"order_id":1}'),
 ('{"id":"9012","isAvailable":true,"order_id":1}'),
 ('{"id":"3456","isAvailable":false,"order_id":1}'),
 ('{"id":"7890","isAvailable":false,"order_id":2}'),
 ('{"id":"0987","isAvailable":false,"order_id":2}'),
 ('{"id":"6543","isAvailable":false,"order_id":2}'),
 ('{"id":"2109","isAvailable":false,"order_id":2}'),
 ('{"id":"1234","isAvailable":true,"order_id":1}')
</code>```

Now i need to loop inside the each order.data.items array recursively to get both parent & child item id and do a join to Backlog table based on the Backlog.data.id

Final output like to be

If i didnt explain correctly my needs, please comment i will try to make more verbose as possible.

Thanks in advance.

答:
You can do this with a subquery (or CTE) and generate_series().

```<code>select baz from ( select o.data->'items'->generate_series( 0, json_array_length( o.data->'items' ) - 1 )->>'id' as foo, b.data->>'id' as bar, b.data as baz from orders as o, backlog as b ) as t where foo = bar;
</code>```

This returns

```<code>                         baz
-----------------------------------------------------
 {"id": "9012", "order_id": 1, "isAvailable": true}
 {"id": "7890", "order_id": 2, "isAvailable": false}
 {"id": "6543", "order_id": 2, "isAvailable": false}
 {"id": "1234", "order_id": 1, "isAvailable": true}
(4 rows)
</code>```

Deconstructing and understanding my query is left as an exercise.

And read the docs:
https://www.postgresql.org/docs/current/static/functions-json.html

Body:
SQL Newbie here.

I have two tables like these

Table: Order

CREATE TABLE orders (
 ID serial NOT NULL PRIMARY KEY,
 data json NOT NULL
);

INSERT INTO orders (data)
VALUES
 (
 '{"customer":"John Doe","items":[{"1234":{"attributes":{"name":"parent"}},"id":"1234","isPhone":true,"items":[{"5678":{"attributes":{"name":"child"}},"id":"5678","isPhone":false}]},{"9012":{"attributes":{"name":"parent"}},"id":"9012","isPhone":true,"items":[{"3456":{"attributes":{"name":"child"}},"id":"3456","isPhone":false}]}]}'
 );

 INSERT INTO orders (data)
VALUES
 (
 '{"customer":"John Doe","items":[{"7890":{"attributes":{"name":"parent"}},"id":"7890","isPhone":true,"items":[{"0987":{"attributes":{"name":"child"}},"id":"0987","isPhone":false}]},{"6543":{"attributes":{"name":"parent"}},"id":"6543","isPhone":true,"items":[{"2109":{"attributes":{"name":"child"}},"id":"2109","isPhone":false}]}]}'
 );

Table: Backlog

CREATE TABLE backlog (
 ID serial NOT NULL PRIMARY KEY,
 data json NOT NULL
);

  INSERT INTO backlog (data)
VALUES
 ('{"id":"5678","isAvailable":true,"order_id":1}'),
 ('{"id":"9012","isAvailable":true,"order_id":1}'),
 ('{"id":"3456","isAvailable":false,"order_id":1}'),
 ('{"id":"7890","isAvailable":false,"order_id":2}'),
 ('{"id":"0987","isAvailable":false,"order_id":2}'),
 ('{"id":"6543","isAvailable":false,"order_id":2}'),
 ('{"id":"2109","isAvailable":false,"order_id":2}'),
 ('{"id":"1234","isAvailable":true,"order_id":1}')

Now i need to loop inside the each order.data.items array recursively to get both parent & child item id and do a join to Backlog table based on the Backlog.data.id

Final output like to be

If i didnt explain correctly my needs, please comment i will try to make more verbose as possible.

Thanks in advance.

Body:
You can do this with a subquery (or CTE) and generate_series().

select baz from ( select o.data->'items'->generate_series( 0, json_array_length( o.data->'items' ) - 1 )->>'id' as foo, b.data->>'id' as bar, b.data as baz from orders as o, backlog as b ) as t where foo = bar;

This returns

                         baz
-----------------------------------------------------
 {"id": "9012", "order_id": 1, "isAvailable": true}
 {"id": "7890", "order_id": 2, "isAvailable": false}
 {"id": "6543", "order_id": 2, "isAvailable": false}
 {"id": "1234", "order_id": 1, "isAvailable": true}
(4 rows)

Deconstructing and understanding my query is left as an exercise.

And read the docs:
https://www.postgresql.org/docs/current/static/functions-json.html


问:
Jquery / Javascript error: Object doesn't support this property or method
I am getting the error "Object doesn't support this property or method" in javascript.

I took some original code by, Paul Da Silva, and modified it. I am changing from a datePicker into a timePicker.  I have renamed some fields and functions, and am still debugging it. But I did something wrong / broke something in the process.  I ran it thru jLint and fixed some of the minor issues.  I am stumped, can someone help?

The error occurs on the following line

```<code>this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime");
</code>```

but the functions: "bindMethodsToObj", "show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime" all exist?

Line 534:

```<code>bindMethodsToObj: function () {
    var i = 0;
    for (i = 0; i < arguments.length; i++) {
        this[arguments[i]] = this.bindToObj(this[arguments[i]]);
    }
},
</code>```

The test html page is at: http://www.gleneck.com/tv/_vhslibr14/jtpicker/jtpicker_test.htm

the javascript is at: www.gleneck.com/tv/_vhslibr14/jtpicker/jquery.jtpicker.js

I am stumped, can someone help?

答:
In your JavaScript file, I think that line 88:

```<code>jtPicker.R_o_w_type = {
</code>```

... should probably look like:

```<code>jtPicker.prototype = {
</code>```

so that it actually adds the methods to the function.

It looks like there's some other stuff to figure out, but that should correct your issue.

Body:
I am getting the error "Object doesn't support this property or method" in javascript.

I took some original code by, Paul Da Silva, and modified it. I am changing from a datePicker into a timePicker.  I have renamed some fields and functions, and am still debugging it. But I did something wrong / broke something in the process.  I ran it thru jLint and fixed some of the minor issues.  I am stumped, can someone help?

The error occurs on the following line

this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime");

but the functions: "bindMethodsToObj", "show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime" all exist?

Line 534:

bindMethodsToObj: function () {
    var i = 0;
    for (i = 0; i < arguments.length; i++) {
        this[arguments[i]] = this.bindToObj(this[arguments[i]]);
    }
},

The test html page is at: http://www.gleneck.com/tv/_vhslibr14/jtpicker/jtpicker_test.htm

the javascript is at: www.gleneck.com/tv/_vhslibr14/jtpicker/jquery.jtpicker.js

I am stumped, can someone help?

Body:
In your JavaScript file, I think that line 88:

jtPicker.R_o_w_type = {

... should probably look like:

jtPicker.prototype = {

so that it actually adds the methods to the function.

It looks like there's some other stuff to figure out, but that should correct your issue.


问:
How to prevent random queries from being matched to an action annotated with [Route('')]?
I currently have this controller

```<code>[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}
</code>```

I want only the following 3 urls to be matched:

api/Home (Both id and AnotherId are null)

api/Home?id=1 (Only Anotherid is null)

api/Home?AnotherId=1 (Only Id is null)

Other urls should return unregistered routes or error. Currently, api/Home?asdfanyquery also returns a match which is not what I desired.

How do I rewrite the controller so that the routes only matches to the 3 urls above?

答:
I ended up creating an ActionFilterAttribute as suggested in the comments and applying it like so:

```<code>public class InvalidQueryStringRejector : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var arguments = actionContext.ActionArguments.Keys;

        var queryString = actionContext.Request.GetQueryNameValuePairs()
            .Select(q => q.Key);

        var invalidParams = queryString.Where(k => !arguments.Contains(k));

        if (invalidParams.Any())
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, new
            {
                message = "Invalid query string parameters",
                parameters = invalidParams
            });
        }
    }
}

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{
     [InvalidQueryStringRejector] //The custom created ActionFilterAttribute
     [HttpGet]
     [Route("")]
     public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null)
     {
         if (!ModelState.IsValid) //From ApiController.ModelState
         {
              return BadRequest(ModelState);
         }
     }
}
</code>```

Body:
I currently have this controller

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}

I want only the following 3 urls to be matched:

api/Home (Both id and AnotherId are null)

api/Home?id=1 (Only Anotherid is null)

api/Home?AnotherId=1 (Only Id is null)

Other urls should return unregistered routes or error. Currently, api/Home?asdfanyquery also returns a match which is not what I desired.

How do I rewrite the controller so that the routes only matches to the 3 urls above?

Body:
I ended up creating an ActionFilterAttribute as suggested in the comments and applying it like so:

public class InvalidQueryStringRejector : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var arguments = actionContext.ActionArguments.Keys;

        var queryString = actionContext.Request.GetQueryNameValuePairs()
            .Select(q => q.Key);

        var invalidParams = queryString.Where(k => !arguments.Contains(k));

        if (invalidParams.Any())
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, new
            {
                message = "Invalid query string parameters",
                parameters = invalidParams
            });
        }
    }
}

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{
     [InvalidQueryStringRejector] //The custom created ActionFilterAttribute
     [HttpGet]
     [Route("")]
     public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null)
     {
         if (!ModelState.IsValid) //From ApiController.ModelState
         {
              return BadRequest(ModelState);
         }
     }
}


问:
Python re.sub specific syntax
I am writing a script in python that replaces specific lines in files Linux.  Say i have a file called hi in the /home directory that contains:

```<code>hi 873840
</code>```

Here is my script:

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

import re

fp = open("/home/hi","w")
re.sub(r"hi+", "hi 90", fp)
</code>```

My desired outcome is:

```<code>hi 90
</code>```

however, when i run it i get this error and the hi file ends up being balnk:

```<code>Traceback (most recent call last):
  File "./script.py", line 6, in <module>
    re.sub(r"hi+", "hi 90", fp)
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
 TypeError: expected string or buffer
</code>```

Is there something wrong with my syntax?
Thanks

答:
use "r" more to read file, "w" mode will create empty file for writing. .readline() will get and pass the string to the re.sub(). r" .*" will return a string you want to replace after the 'space' character. i assume 'hi 873840' is the only text in your file and your desired output is only 'hi 90'

```<code>echo "hi 873840" > hi.txt

python3.6

import re
fp = open("hi.txt", "r")
print(re.sub(r" .*", " 90", fp.readline()))
</code>```

Title: Python re.sub specific syntax

Body:
I am writing a script in python that replaces specific lines in files Linux.  Say i have a file called hi in the /home directory that contains:

hi 873840

Here is my script:

#! /usr/bin/env python

import re

fp = open("/home/hi","w")
re.sub(r"hi+", "hi 90", fp)

My desired outcome is:

hi 90

however, when i run it i get this error and the hi file ends up being balnk:

Traceback (most recent call last):
  File "./script.py", line 6, in <module>
    re.sub(r"hi+", "hi 90", fp)
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
 TypeError: expected string or buffer

Is there something wrong with my syntax?
Thanks

Body:
use "r" more to read file, "w" mode will create empty file for writing. .readline() will get and pass the string to the re.sub(). r" .*" will return a string you want to replace after the 'space' character. i assume 'hi 873840' is the only text in your file and your desired output is only 'hi 90'

echo "hi 873840" > hi.txt

python3.6

import re
fp = open("hi.txt", "r")
print(re.sub(r" .*", " 90", fp.readline()))


问:
get value of [object HTMLDivElement]
I am trying to make my son a spelling quiz.
I want to enter his weekly words in mysql with id, word, and weekNo fields
I am using a js text to speech to say the word, and he types it into a textbox. After he submits it there is a function to check if it is correct, then the next word in the mysql row is spoken.
I am getting the next row with...

```<code>     $.ajax({
       type: "POST",
       url: "getNext.php",
       data: "count=" + $number,
       success: function(results){
         $('#results').append(results);
       }
     });
</code>```

getNext.php

```<code>    $result = mysql_query("SELECT * FROM spelling LIMIT
    {$_POST['count']},1");
    while($row = mysql_fetch_array($result))
    {
    echo "<div class='result'>".$row['word'] ."</div>";
    }
</code>```

On the index.php I can display $row['word'] one by one on submit with

```<code>    <div id='results'></div>
</code>```

My problem is I don't know how to get the value from the ajax call into the TTS, everything I try it says "object HTMLDivElement"

Here is the line where I need to get the ajax value...

```<code>    var message = new SpeechSynthesisUtterance(AJAX.VALUE.HERE);
</code>```

答:
I would suggest to output the exact word from Next.php

```<code>echo $row['word'];
</code>```

Do the decoration in javascript when you get the response.

```<code>success: function(result){
     var word = $.trim(result); // You can use this in your speech engine.
     var wordHtml = "<div class='result'>"+ word + "</div>"; // adding div decoration in JS
     $('#results').append(wordHtml);
   }
</code>```

Title: get value of [object HTMLDivElement]

Body:
I am trying to make my son a spelling quiz.
I want to enter his weekly words in mysql with id, word, and weekNo fields
I am using a js text to speech to say the word, and he types it into a textbox. After he submits it there is a function to check if it is correct, then the next word in the mysql row is spoken.
I am getting the next row with...

     $.ajax({
       type: "POST",
       url: "getNext.php",
       data: "count=" + $number,
       success: function(results){
         $('#results').append(results);
       }
     });

getNext.php

    $result = mysql_query("SELECT * FROM spelling LIMIT
    {$_POST['count']},1");
    while($row = mysql_fetch_array($result))
    {
    echo "
".$row['word'] ."
";
    }

On the index.php I can display $row['word'] one by one on submit with

My problem is I don't know how to get the value from the ajax call into the TTS, everything I try it says "object HTMLDivElement"

Here is the line where I need to get the ajax value...

    var message = new SpeechSynthesisUtterance(AJAX.VALUE.HERE);

Body:
I would suggest to output the exact word from Next.php

echo $row['word'];

Do the decoration in javascript when you get the response.

success: function(result){
     var word = $.trim(result); // You can use this in your speech engine.
     var wordHtml = "<div class='result'>"+ word + "</div>"; // adding div decoration in JS
     $('#results').append(wordHtml);
   }


答:
Seems like a bug in pandas.

Try this:

```<code>a[a!=0].rolling(window=100, center=False, min_periods=1).median()
</code>```

Title: median of a rolling window, excluding zeros

Body:
when i try to find the rolling median of the following series, i get a list of NaNs.

I used:

b = a[a!=0].rolling(100).median()

a = actual data series (dataframe).  Has a bunch of zeros in it that i want to exclude when finding the median

b = rolling median

a[a!=0] gives me the following series.

2017-10-05       NaN
2017-10-06 -0.001074
2017-10-09 -0.001804
2017-10-10       NaN
2017-10-11       NaN
2017-10-12 -0.001687
2017-10-13       NaN
2017-10-16       NaN
2017-10-17       NaN
2017-10-18       NaN
2017-10-19       NaN
2017-10-20       NaN
2017-10-23 -0.003972
2017-10-24       NaN
2017-10-25 -0.004663
2017-10-26       NaN
2017-10-27       NaN
2017-10-30 -0.003192
2017-10-31       NaN
2017-11-01       NaN
2017-11-02       NaN
2017-11-03       NaN
t2017-11-06       NaN
2017-11-07 -0.000189
2017-11-08       NaN
2017-11-09 -0.003762
2017-11-10 -0.000898
2017-11-13       NaN
2017-11-14 -0.002310

the output is just a list of NaNs.

what am i doing wrong?
thank you!

Body:
Seems like a bug in pandas.

Try this:

a[a!=0].rolling(window=100, center=False, min_periods=1).median()


问:
How would you create an ASP.NET MVC EditorTemplate that disables field if data is present?
I don't have a lot of experience writing EditorTemplates, the one I've written was to apply a css class to a textarea (I find it odd that the EditorFor method doesn't have an overload for applying HTML attributes).

I'm trying to create a form, that has several fields that - if there is already data present (in the viewdata model) - that those fields would remain in the form, but be disabled so visitors cannot change them... leaving the open fields active to change.

I wish to use the HTML.EditorFor(model => model.property) syntax, is it possible to create an EditorTemplate that does what I described?

答:
Here is an example that should get you started.  Inside the editor template you would check if the value of the model is empty or null and if so pass in a custom dictionary of HtmlAttributes to the TextBox or area template.</p>

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%
    IDictionary<string, object> htmlAttributes = new Dictionary<string, object>();
    if(!String.IsNullOrWhiteSpace(Model))
    {
        htmlAttributes.Add("disabled", "disabled");
    }
%>
<%: Html.TextBox("Name", Model, htmlAttributes)%>
</code>```

Body:
Here is an example that should get you started.  Inside the editor template you would check if the value of the model is empty or null and if so pass in a custom dictionary of HtmlAttributes to the TextBox or area template.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%
    IDictionary<string, object> htmlAttributes = new Dictionary<string, object>();
    if(!String.IsNullOrWhiteSpace(Model))
    {
        htmlAttributes.Add("disabled", "disabled");
    }
%>
<%: Html.TextBox("Name", Model, htmlAttributes)%>