问:
How can I use Jar produced by mvn package in another Jenkins declarative pipeline stage?
I'm trying to build CI/CD pipeline with Jenkins for Maven project. I can't seem to find any decent examples on how to use .jar file produced by mvn package in another Jenkins declarative pipeline stage. I need the jar file to make an docker-image before uploading it to docker-registry. Here's my relevant parts of jenkinsfile:

```<code>pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}
</code>```

Dockerfile:

```<code>#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]
</code>```

EDIT 1----------------------------------------------------------------------:

Laszlos answer did the trick, as I noticed that my .jar file was under different name than dockerfile assumed.
Here is my working final jenkinsfile:

```<code>pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                unstash 'targetfiles'
                sh 'ls -l -R'
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}
</code>```

And modified dockerfile:

```<code>#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
#ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
ADD target/AdWordsProducer-1.0-SNAPSHOT.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]
</code>```

答:
You are stashing the jar files under the name 'targetfiles'. This is good.

What I think is missing is to pop from the stash, try adding the unstash line as shown bellow. The files will be in the exact same location as when you stashed them. Under "target/" in your case.

```<code>stage('Deploy') {
  steps {
        script{
            unstash 'targetfiles'
            sh 'docker build image-name:test'
        }
  }
}
</code>```

Body:
I'm trying to build CI/CD pipeline with Jenkins for Maven project. I can't seem to find any decent examples on how to use .jar file produced by mvn package in another Jenkins declarative pipeline stage. I need the jar file to make an docker-image before uploading it to docker-registry. Here's my relevant parts of jenkinsfile:

pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}

Dockerfile:

#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]

EDIT 1----------------------------------------------------------------------:

Laszlos answer did the trick, as I noticed that my .jar file was under different name than dockerfile assumed.
Here is my working final jenkinsfile:

pipeline {
  agent none
  stages{
    stage('Build Jar'){
        agent {
          docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
          }
        }
        steps {
            sh 'mvn package'
            stash includes: 'target/*.jar', name: 'targetfiles'
        }
    }
    stage('Deploy') {
        agent {
            node {
                label 'DockerDefault'
            }
         }

      steps {
            script{
                unstash 'targetfiles'
                sh 'ls -l -R'
                def image = docker.build("image-name:test", ' .')
            }
      }
    }
  }
}

And modified dockerfile:

#install OS
FROM centos
#install java
RUN yum install -y java
#make directory structure to store temporary files
RUN mkdir -p /store
#put jar into container
#ADD target/AdWordsProducer-1.0-SNAPSHOT-shaded.jar adwordsproducer.jar
ADD target/AdWordsProducer-1.0-SNAPSHOT.jar adwordsproducer.jar
#run jar
ENTRYPOINT ["java", "-jar", "/adwordsproducer.jar"]

Body:
You are stashing the jar files under the name 'targetfiles'. This is good.

What I think is missing is to pop from the stash, try adding the unstash line as shown bellow. The files will be in the exact same location as when you stashed them. Under "target/" in your case.

stage('Deploy') {
  steps {
        script{
            unstash 'targetfiles'
            sh 'docker build image-name:test'
        }
  }
}


来源: stackexchange

问:
Python asyncio http request module
Here is how I'm making a request:

```<code>    from aiohttp import request
    def make_request(self, request_payload, request_headers, request_method, request_url_path):
        url = self.config["HOST_URL"] + "/" + request_url_path
        response = yield from request(request_method, url=url, params=request_payload, headers=request_headers, allow_redirects=False)
        return response
</code>```

The expected response in case of successful request here is response status 302 and a Location header in response, which will contain the url on which redirect needs to be done.

The issue is, I'm getting response status as 200, which is response from the final url. How can I achieve what I want?

"allow_redirects=False" should have worked, but it doesn't. I'm not sure how can I get it to work as I need.

答: Request supports an optional allow_redirects parameter, that you can set to False.</p>

ContentLicense: CC BY-SA 3.0

Title: Python asyncio http request module

Body:
Here is how I'm making a request:

    from aiohttp import request
    def make_request(self, request_payload, request_headers, request_method, request_url_path):
        url = self.config["HOST_URL"] + "/" + request_url_path
        response = yield from request(request_method, url=url, params=request_payload, headers=request_headers, allow_redirects=False)
        return response

The expected response in case of successful request here is response status 302 and a Location header in response, which will contain the url on which redirect needs to be done.

The issue is, I'm getting response status as 200, which is response from the final url. How can I achieve what I want?

"allow_redirects=False" should have worked, but it doesn't. I'm not sure how can I get it to work as I need.


问:
How to insert data of sql server database table columns into excel using vba
I am trying to insert all data from sql server database table into excel macros by the help of vba coding

here is my code-

```<code>Private Sub CommandButton1_Click()

    Dim myConn As ADODB.Connection
    Dim myCommand As ADODB.Command
    Dim DB_CONNECT_STRING As String
    Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=P3A-B1YH882\SQLOPER;Initial Catalog=master;Integrated Security=SSPI"
    Set myConn = CreateObject("ADODB.Connection")
    Set myCommand = CreateObject("ADODB.Command")
    myConn.Open DB_CONNECT_STRING
    Set myCommand.ActiveConnection = myConn
    myCommand.CommandText = "SELECT *FROM Table_1"
    myCommand.Execute
    myConn.Close

End Sub
</code>```

my code is not running successfully, it is showing me some compile error user-defined type not defined .

plus i also don't know what to write in code to assign the macros value .
i am not sure what to do any help is appreciated

答:
You have an issue with what is called "early binding" vs "late binding". There are advantages for both methods.

If you want to use "early binding", you have to tell the VBA compiler what things like ADODB.Connection are by adding a reference: In the VBA-Editor, choose Tools->References and set a checkmark on one of the listed Active X DataObject libraries. Probably you are missing this reference, causing the compiler error.

I give an example for both ways that should work for you - read about binding and decide which fits you better.

Note that the Connection and Command object needs to be created by you (thus the new in the var declaration resp the CreateObject), while the RecordSet object is created by the Execute method.

To get the data from the recordSet into your worksheet, the easiest way is the Range.CopyFromRecordSet method. As an alternative, you can loop over the recordset and do the writing manually - you can find enough examples on the internet.

```<code>Sub EarlyBinding()
    Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=P3A-B1YH882\SQLOPER;Initial Catalog=master;Integrated Security=SSPI"

    Dim myConn As New ADODB.Connection
    Dim myCommand As New ADODB.Command
    Dim myRs As ADODB.Recordset

    myConn.Open DB_CONNECT_STRING
    Set myCommand.ActiveConnection = myConn
    myCommand.CommandText = "SELECT * FROM Table_1"
    Set myRs = myCommand.Execute

    ThisWorkbook.Worksheets("Sheet1").Range("A1").CopyFromRecordset myRs

    myConn.Close
End Sub

Sub LateBinding()
    Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=P3A-B1YH882\SQLOPER;Initial Catalog=master;Integrated Security=SSPI"

    Dim myConn As Object
    Dim myCommand As Object
    Dim myRs As Object

    Set myConn = CreateObject("ADODB.Connection")
    myConn.Open DB_CONNECT_STRING
    Set myCommand = CreateObject("ADODB.Command")
    Set myCommand.ActiveConnection = myConn

    myCommand.CommandText = "SELECT * FROM Table_1"
    Set myRs = myCommand.Execute

    ThisWorkbook.Worksheets("Sheet1").Range("A1").CopyFromRecordset myRs

    myConn.Close
End Sub
</code>```

Body:
I am trying to insert all data from sql server database table into excel macros by the help of vba coding

here is my code-

Private Sub CommandButton1_Click()

    Dim myConn As ADODB.Connection
    Dim myCommand As ADODB.Command
    Dim DB_CONNECT_STRING As String
    Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=P3A-B1YH882\SQLOPER;Initial Catalog=master;Integrated Security=SSPI"
    Set myConn = CreateObject("ADODB.Connection")
    Set myCommand = CreateObject("ADODB.Command")
    myConn.Open DB_CONNECT_STRING
    Set myCommand.ActiveConnection = myConn
    myCommand.CommandText = "SELECT *FROM Table_1"
    myCommand.Execute
    myConn.Close

End Sub

my code is not running successfully, it is showing me some compile error user-defined type not defined .

plus i also don't know what to write in code to assign the macros value .
i am not sure what to do any help is appreciated

Body:
You have an issue with what is called "early binding" vs "late binding". There are advantages for both methods.

If you want to use "early binding", you have to tell the VBA compiler what things like ADODB.Connection are by adding a reference: In the VBA-Editor, choose Tools->References and set a checkmark on one of the listed Active X DataObject libraries. Probably you are missing this reference, causing the compiler error.

I give an example for both ways that should work for you - read about binding and decide which fits you better.

Note that the Connection and Command object needs to be created by you (thus the new in the var declaration resp the CreateObject), while the RecordSet object is created by the Execute method.

To get the data from the recordSet into your worksheet, the easiest way is the Range.CopyFromRecordSet method. As an alternative, you can loop over the recordset and do the writing manually - you can find enough examples on the internet.

Sub EarlyBinding()
    Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=P3A-B1YH882\SQLOPER;Initial Catalog=master;Integrated Security=SSPI"

    Dim myConn As New ADODB.Connection
    Dim myCommand As New ADODB.Command
    Dim myRs As ADODB.Recordset

    myConn.Open DB_CONNECT_STRING
    Set myCommand.ActiveConnection = myConn
    myCommand.CommandText = "SELECT * FROM Table_1"
    Set myRs = myCommand.Execute

    ThisWorkbook.Worksheets("Sheet1").Range("A1").CopyFromRecordset myRs

    myConn.Close
End Sub

Sub LateBinding()
    Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=P3A-B1YH882\SQLOPER;Initial Catalog=master;Integrated Security=SSPI"

    Dim myConn As Object
    Dim myCommand As Object
    Dim myRs As Object

    Set myConn = CreateObject("ADODB.Connection")
    myConn.Open DB_CONNECT_STRING
    Set myCommand = CreateObject("ADODB.Command")
    Set myCommand.ActiveConnection = myConn

    myCommand.CommandText = "SELECT * FROM Table_1"
    Set myRs = myCommand.Execute

    ThisWorkbook.Worksheets("Sheet1").Range("A1").CopyFromRecordset myRs

    myConn.Close
End Sub


问:
How do I group in memory lists?
I have a list of Foo. Foo has properties Bar and Lum. Some Foos have identical values for Bar. How can I use lambda/linq to group my Foos by Bar so I can iterate over each grouping's Lums?

答:
Deeno,

Enjoy:

```<code>var foos = new List<Foo> {
   new Foo{Bar = 1,Lum = 1},
   new Foo{Bar = 1,Lum = 2},
   new Foo{Bar = 2,Lum = 3},
};

// Using language integrated queries:

var q = from foo in foos
        group foo by foo.Bar into groupedFoos
        let lums = from fooGroup in groupedFoos
                   select fooGroup.Lum
        select new { Bar = groupedFoos.Key, Lums = lums };

// Using lambdas

var q = foos.GroupBy(x => x.Bar).
            Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)});

foreach (var group in q)
{
    Console.WriteLine("Lums for Bar#" + group.Bar);
    foreach (var lum in group.Lums)
    {
        Console.WriteLine(lum);
    }
}
</code>```

To learn more about LINQ read 101 LINQ Samples

OwnerDisplayName: Deeno

Title: How do I group in memory lists?

Body:
Deeno,

Enjoy:

var foos = new List<Foo> {
   new Foo{Bar = 1,Lum = 1},
   new Foo{Bar = 1,Lum = 2},
   new Foo{Bar = 2,Lum = 3},
};

// Using language integrated queries:

var q = from foo in foos
        group foo by foo.Bar into groupedFoos
        let lums = from fooGroup in groupedFoos
                   select fooGroup.Lum
        select new { Bar = groupedFoos.Key, Lums = lums };

// Using lambdas

var q = foos.GroupBy(x => x.Bar).
            Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)});

foreach (var group in q)
{
    Console.WriteLine("Lums for Bar#" + group.Bar);
    foreach (var lum in group.Lums)
    {
        Console.WriteLine(lum);
    }
}

To learn more about LINQ read 101 LINQ Samples

OwnerDisplayName: aku

ContentLicense: CC BY-SA 2.5


问:
regex to count english words as single char inside char count of asian words
need some help from a regex jedi master:

If I have a string of mb chars (specifically, Japanese, Korean or Chinese) with English words sprinkled throughout, I would like to count:

asian characters as 1 per single char

english "words" (no dictionary check needed - just a string of consecutive english letters) as a single char.

English only is fine - don't worry about special spanish, swedish, etc. chars.

I am searching for a regex pattern I can use to count these strings, that will function in php and js.

Example:

これは猫です、けどKittyも大丈夫。

should count as 13 chars.

thanks for your help!

jeff

答:
What ever you are trying to achieve, this will help you:

To count only Hiragana+Katakana+Kanji (Japanese) Chars (excluding punctuation marks):

```<code>var x = "これは猫です、けどKittyも大丈夫。";
x.match(/[ぁ-ゖァ-ヺー一-龯々]/g).length; //Result: 12 : これは猫ですけども大丈夫
</code>```

Updated:

To count only words in Alphabet:

```<code>x.match(/\w+/g).length; //Result: 1 : "Kitty"
</code>```

All in one line (as function):

```<code>function myCount(str) {
   return str.match(/[ぁ-ゖァ-ヺー一-龯々]|\w+/g).length;
}
alert(myCount("これは猫です、けどKittyも大丈夫。")); //13
alert(myCount("これは犬です。DogとPuppyもOKですね！")); //14
</code>```

These are the arrays resulted of match:

```<code>["こ", "れ", "は", "猫", "で", "す", "け", "ど", "Kitty", "も", "大", "丈", "夫"]
["こ", "れ", "は", "犬", "で", "す", "Dog", "と", "Puppy", "も", "OK", "で", "す", "ね"]
</code>```

Updated (JAP, KOR, CH):

```<code>function myCount(str) {
   return str.match(/[ぁ-ㆌㇰ-䶵一-鿃々가-힣-豈ｦ-ﾝ]|\w+/g).length;
}
</code>```

These will cover around 99% of the Japanese, Chinese and Korean. You may need to manually add extra characters that are not included such as "〶".

A very good reference is:

http://www.tamasoft.co.jp/en/general-info/unicode.html

This should solve your question.

Body:
What ever you are trying to achieve, this will help you:

To count only Hiragana+Katakana+Kanji (Japanese) Chars (excluding punctuation marks):

var x = "これは猫です、けどKittyも大丈夫。";
x.match(/[ぁ-ゖァ-ヺー一-龯々]/g).length; //Result: 12 : これは猫ですけども大丈夫

Updated:

To count only words in Alphabet:

x.match(/\w+/g).length; //Result: 1 : "Kitty"

All in one line (as function):

function myCount(str) {
   return str.match(/[ぁ-ゖァ-ヺー一-龯々]|\w+/g).length;
}
alert(myCount("これは猫です、けどKittyも大丈夫。")); //13
alert(myCount("これは犬です。DogとPuppyもOKですね！")); //14

These are the arrays resulted of match:

["こ", "れ", "は", "猫", "で", "す", "け", "ど", "Kitty", "も", "大", "丈", "夫"]
["こ", "れ", "は", "犬", "で", "す", "Dog", "と", "Puppy", "も", "OK", "で", "す", "ね"]

Updated (JAP, KOR, CH):

function myCount(str) {
   return str.match(/[ぁ-ㆌㇰ-䶵一-鿃々가-힣-豈ｦ-ﾝ]|\w+/g).length;
}

These will cover around 99% of the Japanese, Chinese and Korean. You may need to manually add extra characters that are not included such as "〶".

A very good reference is:

http://www.tamasoft.co.jp/en/general-info/unicode.html

This should solve your question.


问:
Method in child class doesn't get called by virtual function in parent class
In my application, I have several readers which read data out of .csv files. I want to structure them now by creating a parent class for those readers which have in common that they own the method getData(std::string filename). I wanted to do it by implementing a virtual method in the base class. The filename should be passed by the constructor.

main

```<code>int main()
{
    std::string filename = "file.csv";
    ChildReader1 reader = new ChildReader1(filename);
}
</code>```

ChildReader1.h

```<code>class ChildReader1: public ParentReader
    {
    public:
        ChildReader1(std::string filename)
            : ParentReader(filename)
        {

        };
        void getData(std::string filename)
        {
             //get the data here
        }
    };
</code>```

ParentReader.h

```<code>class ParentReader
    {
    public:
        ParentReader() {};
        ParentReader(std::string filename)
        {
            getData(filename);
        };
        ~ParentReader() {};

        virtual void getData(std::string filename) {};
    };
</code>```

At the moment, filename is passed to ParentReader but the getData(filename) opens the virtual method in ParentReader instead of the actual method in ChildReader 1. How can I solve that?

答:
The virtual methods are not called during construction of the base (parent) class. Because the the derived is not ready yet.

12.7 Construction and destruction [class.cdtor] #4 ISO/IEC N3797

Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class’s non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class. If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the behavior is undefined.

Body:
In my application, I have several readers which read data out of .csv files. I want to structure them now by creating a parent class for those readers which have in common that they own the method getData(std::string filename). I wanted to do it by implementing a virtual method in the base class. The filename should be passed by the constructor.

main

int main()
{
    std::string filename = "file.csv";
    ChildReader1 reader = new ChildReader1(filename);
}

ChildReader1.h

class ChildReader1: public ParentReader
    {
    public:
        ChildReader1(std::string filename)
            : ParentReader(filename)
        {

        };
        void getData(std::string filename)
        {
             //get the data here
        }
    };

ParentReader.h

class ParentReader
    {
    public:
        ParentReader() {};
        ParentReader(std::string filename)
        {
            getData(filename);
        };
        ~ParentReader() {};

        virtual void getData(std::string filename) {};
    };

At the moment, filename is passed to ParentReader but the getData(filename) opens the virtual method in ParentReader instead of the actual method in ChildReader 1. How can I solve that?


问:
How can I omit certain fields of IdentityUser object

IdentityUser Fields

public virtual bool PhoneNumberConfirmed { get; set; }
public virtual bool TwoFactorEnabled { get; set; }
public virtual string SecurityStamp { get; set; }
public virtual DateTime? LockoutEndDateUtc { get; set; }

答:
Ignoring desired fields from IdentityUser</p>

```<code>   modelBuilder.Entity<IdentityUser>().Ignore(c => c.PhoneNumberConfirmed )
                                           .Ignore(c=> c.TwoFactorEnabled )
                                           .Ignore(c=>c.SecurityStamp )
                                           .Ignore(c=>c.LockoutEndDateUtc
</code>```

Body:
Ignoring desired fields from IdentityUser

   modelBuilder.Entity<IdentityUser>().Ignore(c => c.PhoneNumberConfirmed )
                                           .Ignore(c=> c.TwoFactorEnabled )
                                           .Ignore(c=>c.SecurityStamp )
                                           .Ignore(c=>c.LockoutEndDateUtc


问:
How to install Zendframework-2 in wampserver?
i already install git, and composer.exe now i try to install zendframework-2 but it not work please provide rightway for installing zend framework-2.
please provide me right tutorial or video for install proper.

答:
It is possible to install ZF2 as a library but that's not what I recommend. I think it's best to install ZF2 in every project from composer.phar. This makes it easier to master the updates of applications in production.

For ZF2, install the skeleton application that allows you to set up your project. This installation sets up ZF2 complete.

Make sure your Windows path contains php.exe and composer.bat
paths ;

Run in console : php "path\to\composer.phar" create-project -sdev --repository-url="https://packages.zendframework.com" zendframework/skeleton-application "directory/of/your/project"

For ZF3, follow : https://framework.zend.com/downloads


问:
import c++ dll to windows phone project
I'm new on windows phone developement and i have one problem that i don't know how to resolve....

the problem is....

i have a c++ project that i had complided with visual c++ 2010 and this create one dll with code compiled...

so i know that C# import dll libraries but when i add refrences it's make this error "Unable to retrieve assembly fullname ""Parameter name: AssemblyPath" and i dont kown what it means...

I searched on google and i found one method to import c++ dll manualy with DllImport and calling a external method... that causes one error because it's dont find the dll location... it's happens because wp7 don't suport C++???

thanks for help me

答: Neither P/Invoke nor C++/CLI is supported, only managed user code. See social.msdn.</p>

Title: import c++ dll to windows phone project


问:
Structured Data (schema.org) - openingHours for EducationalOrganization
I'm just about to expand my templates with schema.org attributes and have the following question. With which property can I specify the opening hours for the type EducationalOrganization? Unfortunately, the openingHours property is not available here. In addition, there is no type similar to the EducationalOrganization type.

Here is the current state of my code:

```<code><div itemscope itemtype="http://schema.org/EducationalOrganization" class="ce_text address block">
    <div class="text_container">
        <p>
            <span>
                <strong itemprop="name"><?php echo $this->field('company')->value(); ?></strong><br>
            </span>
        <p itemscope itemtype="http://schema.org/PostalAddress" itemprop="address">
            <span itemprop="streetAddress">
                <?php echo $this->field('street')->value(); ?><br>
            </span>
            <span itemprop="postalCode">
                <?php echo $this->field('zipcode')->value(); ?>
            </span>
            <span itemprop="addressLocality">
                <?php echo $this->field('place')->value(); ?>
            </span>
        </p>
        <p>
            Aus dem Ausland: <span itemprop="telephone"><?php echo $this->field('phone_foreign')->value(); ?></span><br>
            Fax: <span itemprop="telephone"><?php echo $this->field('fax')->value(); ?></span>
        </p>
        <p itemscope itemtype="??????"> <!-- What type can I use here? -->
            <strong>Öffnungszeiten:</strong><br>
            Montag bis Donnerstag: <meta itemprop="openingHours" content="Mo-Th 08:00-18:00"><?php echo $this->field('mothu')->value(); ?><br>
            Freitag: <meta itemprop="openingHours" content="Fr 08:00-15:00"><?php echo $this->field('fri')->value(); ?>
        </p> <!-- Öffnungszeiten Ende -->
    </div>
</div>
</code>```

What type can I use in this case to use the itemprop="openingHours" property or is there another workarount, if this is not possible?

UPDATE:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

```<code>    <div itemscope itemtype="http://schema.org/Service">
        <strong>Öffnungszeiten:</strong><br>
        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?><br>
        Freitag: <?php echo $this->field('fri')->value(); ?>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>
        </div>
    </div>
</code>```

答:
UPDATE/SOLUTION:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

```<code>    <div itemscope itemtype="http://schema.org/Service">
        <strong>Öffnungszeiten:</strong><br>
        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?><br>
        Freitag: <?php echo $this->field('fri')->value(); ?>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>
        </div>
    </div>
</code>```

Body:
I'm just about to expand my templates with schema.org attributes and have the following question. With which property can I specify the opening hours for the type EducationalOrganization? Unfortunately, the openingHours property is not available here. In addition, there is no type similar to the EducationalOrganization type.

Here is the current state of my code:

                <?php echo $this->field('company')->value(); ?>

                <?php echo $this->field('street')->value(); ?>

                <?php echo $this->field('zipcode')->value(); ?>

                <?php echo $this->field('place')->value(); ?>

            Aus dem Ausland: <?php echo $this->field('phone_foreign')->value(); ?>

            Fax: <?php echo $this->field('fax')->value(); ?>

            Öffnungszeiten:

            Montag bis Donnerstag: <meta itemprop="openingHours" content="Mo-Th 08:00-18:00"><?php echo $this->field('mothu')->value(); ?>

            Freitag: <meta itemprop="openingHours" content="Fr 08:00-15:00"><?php echo $this->field('fri')->value(); ?>

What type can I use in this case to use the itemprop="openingHours" property or is there another workarount, if this is not possible?

UPDATE:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

        Öffnungszeiten:

        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?>

        Freitag: <?php echo $this->field('fri')->value(); ?>

            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>

Body:
UPDATE/SOLUTION:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

    <div itemscope itemtype="http://schema.org/Service">
        <strong>Öffnungszeiten:</strong><br>
        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?><br>
        Freitag: <?php echo $this->field('fri')->value(); ?>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>
        </div>
    </div>


问:
Last set of form element is missing
I am currently making a form page. However, it seems like my last set of form element is missing. However, my other form elements are present, except for the "Less than/Equal" one which is not appearing. I will add a picture at the end how it is looking right now.

```<code><form>
    <div class="ui-grid-a">
        <div class="ui-block-title title-a">From</div>
        <div class="ui-block-title title-b"> To</div>
        <div class="ui-block-a"><input type="text" name="From" id="From" required /></div>
        <div class="ui-block-b"><input type="text" name="To" id="To" required /></div>
    </div>

    Conversion Rate
    <input type="text" name="conversionrate" id="conversionrate" required />

    <div class="ui-grid-a">
        <div class="ui-block-title title-a">Greater/Equal</div>
        <div class="ui-block-title title-b"> Comment</div>
        <div class="ui-block-a"><input type="text" name="greaterequal" id="greaterequal" required /></div>
        <div class="ui-block-b"><input type="text" name="greaterequalcomment" id="greaterequalcomment" required /></div>
    </div>

    <div class="ui-grid-e">
        <div class="ui-block-title title-a">Between</div>
        <div class="ui-block-title title-b">Comment</div>
        <div class=ui-block-a><input type="text" name="between1" id="between1" required /></div>
        <div class=ui-block-b><input type="text" name="between2" id="between2" required /></div>
        <div class=ui-block-c><input type="text" name="betweencomment" id="betweencomment" required /></div>
    </div>

    <div class="ui-grid-a">
        <div class="ui-block-title title-a">Less than/Equal</div>
        <div class="ui-block-title title-b"> Comment</div>
        <div class="ui-block-a"><input type="text" name="lessthanequal" id="lessthanequal" required /></div>
        <div class="ui-block-b"><input type="text" name="lessthanequal" id="lessthanequalcomment" required /></div>
    </div>

    <input type="button" id="btnCalculate" value="Calculate" />
</form>
</code>```

Edit - I have added in the CSS as requested:

```<code>.ui-grid-a,
.ui-grid-b,
.ui-grid-c,
.ui-grid-d,
.ui-grid-solo {
overflow: hidden;
}

.ui-block-a,
.ui-block-b,
.ui-block-c,
.ui-block-d,
.ui-block-e {
margin: 0;
padding: 0;
border: 0;
float: left;
min-height: 1px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

/* force new row */
.ui-block-a {
clear: left;
}

ul.ui-grid-a,
ul.ui-grid-b,
ul.ui-grid-c,
ul.ui-grid-d,
ul.ui-grid-solo,
li.ui-block-a,
li.ui-block-b,
li.ui-block-c,
li.ui-block-d,
li.ui-block-e {
margin-left: 0;
margin-right: 0;
padding: 0;
list-style: none;
}

/* No margin in grids for 100% width button elements until we can use max-width: fill-available; */
[class*="ui-block-"] > button.ui-btn {
margin-right: 0;
margin-left: 0;
}

[class*="ui-block-"] > .ui-btn,
[class*="ui-block-"] > .ui-select,
[class*="ui-block-"] > .ui-checkbox,
[class*="ui-block-"] > .ui-radio,
[class*="ui-block-"] > button.ui-btn-inline,
[class*="ui-block-"] > button.ui-btn-icon-notext,
.ui-header [class*="ui-block-"] > button.ui-btn,
.ui-footer [class*="ui-block-"] > button.ui-btn {
margin-right: .3125em;
margin-left: .3125em;
}

.ui-grid-a > .ui-block-a,
.ui-grid-a > .ui-block-b {
/* width: 49.95%; IE7 */
/* margin-right: -.5px; BB5 */
width: 50%;
}

.ui-grid-b > .ui-block-a,
.ui-grid-b > .ui-block-b,
.ui-grid-b > .ui-block-c {
/* width: 33.25%; IE7 */
/* margin-right: -.5px; BB5 */
width: 33.333%;
}

.ui-grid-c > .ui-block-a,
.ui-grid-c > .ui-block-b,
.ui-grid-c > .ui-block-c,
.ui-grid-c > .ui-block-d {
/* width: 24.925%; IE7 */
/* margin-right: -.5px; BB5 */
width: 25%;
}

.ui-grid-d > .ui-block-a,
.ui-grid-d > .ui-block-b,
.ui-grid-d > .ui-block-c,
.ui-grid-d > .ui-block-d,
.ui-grid-d > .ui-block-e {
/* width: 19.925%; IE7 */
width: 20%;
}

.ui-grid-solo > .ui-block-a {
width: 100%;
float: none;
}

.ui-grid-e {
position: relative;
width: 400px;
}

.ui-block-a,
.ui-block-b,
.ui-block-c {
box-sizing: border-box;
padding: 0 5px;
}

.ui-block-a {
padding-left: 0;
}

.title-c {
padding-left: 5px;
}

.ui-block-title {
box-sizing: border-box;
float: left;
width: 50%;
}

.ui-block-a,
.ui-block-b {
width: 22.5%;
}

.ui-block-c {
width: 50%;
}
</code>```

https://imgur.com/a/YawlE

答:
Please use below HTML code:

```<code><form>
<div class="ui-grid-a">
    <div class="ui-block-title title-a">From</div>
    <div class="ui-block-title title-b"> To</div>
    <div class="ui-block-a"><input type="text" name="From" id="From"
required /></div>
    <div class="ui-block-b"><input type="text" name="To" id="To" required />
</div>
</div>

Conversion Rate
<input type="text" name="conversionrate" id="conversionrate" required />

<div class="ui-grid-a">
    <div class="ui-block-title title-a">Greater/Equal</div>
    <div class="ui-block-title title-b"> Comment</div>
    <div class="ui-block-a"><input type="text" name="greaterequal"
id="greaterequal" required /></div>
    <div class="ui-block-b"><input type="text" name="greaterequalcomment"
id="greaterequalcomment" required /></div>
</div>

<div class="ui-grid-e">
    <div class="ui-block-title title-a">Between</div>
    <div class="ui-block-title title-b">Comment</div>
    <div class=ui-block-a><input type="text" name="between1" id="between1"
required /></div>
    <div class=ui-block-b><input type="text" name="between2" id="between2"
required /></div>
    <div class=ui-block-c><input type="text" name="betweencomment"
id="betweencomment" required /></div>
</div>

<div class="ui-block-a">
    <div class="ui-block-title title-a">Less than/Equal</div>
    <div class="ui-block-title title-b"> Comment</div>
    <div class="ui-block-a"><input type="text" name="lessthanequal"
id="lessthanequal" required /></div>
    <div class="ui-block-b"><input type="text" name="lessthanequal"
id="lessthanequalcomment" required /></div>
</div>

<div class="ui-block-a">
    <div><input type="button" id="btnCalculate" value="Calculate" /></div>
</div>
</form>
</code>```

You can also check at https://jsfiddle.net/nzw91xw0/4/

Hope it works!

Title: Last set of form element is missing

Body:
I am currently making a form page. However, it seems like my last set of form element is missing. However, my other form elements are present, except for the "Less than/Equal" one which is not appearing. I will add a picture at the end how it is looking right now.

<form>

From

 To

<input type="text" name="From" id="From" required />

<input type="text" name="To" id="To" required />

    Conversion Rate
    <input type="text" name="conversionrate" id="conversionrate" required />

Greater/Equal

 Comment

<input type="text" name="greaterequal" id="greaterequal" required />

<input type="text" name="greaterequalcomment" id="greaterequalcomment" required />

Between

Comment

<input type="text" name="between1" id="between1" required />

<input type="text" name="between2" id="between2" required />

<input type="text" name="betweencomment" id="betweencomment" required />

Less than/Equal

 Comment

<input type="text" name="lessthanequal" id="lessthanequal" required />

<input type="text" name="lessthanequal" id="lessthanequalcomment" required />

    <input type="button" id="btnCalculate" value="Calculate" />
</form>

Edit - I have added in the CSS as requested:

.ui-grid-a,
.ui-grid-b,
.ui-grid-c,
.ui-grid-d,
.ui-grid-solo {
overflow: hidden;
}

.ui-block-a,
.ui-block-b,
.ui-block-c,
.ui-block-d,
.ui-block-e {
margin: 0;
padding: 0;
border: 0;
float: left;
min-height: 1px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

/* force new row */
.ui-block-a {
clear: left;
}

ul.ui-grid-a,
ul.ui-grid-b,
ul.ui-grid-c,
ul.ui-grid-d,
ul.ui-grid-solo,
li.ui-block-a,
li.ui-block-b,
li.ui-block-c,
li.ui-block-d,
li.ui-block-e {
margin-left: 0;
margin-right: 0;
padding: 0;
list-style: none;
}

/* No margin in grids for 100% width button elements until we can use max-width: fill-available; */
[class*="ui-block-"] > button.ui-btn {
margin-right: 0;
margin-left: 0;
}

[class*="ui-block-"] > .ui-btn,
[class*="ui-block-"] > .ui-select,
[class*="ui-block-"] > .ui-checkbox,
[class*="ui-block-"] > .ui-radio,
[class*="ui-block-"] > button.ui-btn-inline,
[class*="ui-block-"] > button.ui-btn-icon-notext,
.ui-header [class*="ui-block-"] > button.ui-btn,
.ui-footer [class*="ui-block-"] > button.ui-btn {
margin-right: .3125em;
margin-left: .3125em;
}

.ui-grid-a > .ui-block-a,
.ui-grid-a > .ui-block-b {
/* width: 49.95%; IE7 */
/* margin-right: -.5px; BB5 */
width: 50%;
}

.ui-grid-b > .ui-block-a,
.ui-grid-b > .ui-block-b,
.ui-grid-b > .ui-block-c {
/* width: 33.25%; IE7 */
/* margin-right: -.5px; BB5 */
width: 33.333%;
}

.ui-grid-c > .ui-block-a,
.ui-grid-c > .ui-block-b,
.ui-grid-c > .ui-block-c,
.ui-grid-c > .ui-block-d {
/* width: 24.925%; IE7 */
/* margin-right: -.5px; BB5 */
width: 25%;
}

.ui-grid-d > .ui-block-a,
.ui-grid-d > .ui-block-b,
.ui-grid-d > .ui-block-c,
.ui-grid-d > .ui-block-d,
.ui-grid-d > .ui-block-e {
/* width: 19.925%; IE7 */
width: 20%;
}

.ui-grid-solo > .ui-block-a {
width: 100%;
float: none;
}

.ui-grid-e {
position: relative;
width: 400px;
}

.ui-block-a,
.ui-block-b,
.ui-block-c {
box-sizing: border-box;
padding: 0 5px;
}

.ui-block-a {
padding-left: 0;
}

.title-c {
padding-left: 5px;
}

.ui-block-title {
box-sizing: border-box;
float: left;
width: 50%;
}

.ui-block-a,
.ui-block-b {
width: 22.5%;
}

.ui-block-c {
width: 50%;
}

https://imgur.com/a/YawlE

Body:
Please use below HTML code:

<form>
<div class="ui-grid-a">
    <div class="ui-block-title title-a">From</div>
    <div class="ui-block-title title-b"> To</div>
    <div class="ui-block-a"><input type="text" name="From" id="From"
required /></div>
    <div class="ui-block-b"><input type="text" name="To" id="To" required />
</div>
</div>

Conversion Rate
<input type="text" name="conversionrate" id="conversionrate" required />

<div class="ui-grid-a">
    <div class="ui-block-title title-a">Greater/Equal</div>
    <div class="ui-block-title title-b"> Comment</div>
    <div class="ui-block-a"><input type="text" name="greaterequal"
id="greaterequal" required /></div>
    <div class="ui-block-b"><input type="text" name="greaterequalcomment"
id="greaterequalcomment" required /></div>
</div>

<div class="ui-grid-e">
    <div class="ui-block-title title-a">Between</div>
    <div class="ui-block-title title-b">Comment</div>
    <div class=ui-block-a><input type="text" name="between1" id="between1"
required /></div>
    <div class=ui-block-b><input type="text" name="between2" id="between2"
required /></div>
    <div class=ui-block-c><input type="text" name="betweencomment"
id="betweencomment" required /></div>
</div>

<div class="ui-block-a">
    <div class="ui-block-title title-a">Less than/Equal</div>
    <div class="ui-block-title title-b"> Comment</div>
    <div class="ui-block-a"><input type="text" name="lessthanequal"
id="lessthanequal" required /></div>
    <div class="ui-block-b"><input type="text" name="lessthanequal"
id="lessthanequalcomment" required /></div>
</div>

<div class="ui-block-a">
    <div><input type="button" id="btnCalculate" value="Calculate" /></div>
</div>
</form>

You can also check at https://jsfiddle.net/nzw91xw0/4/

Hope it works!


问:
Knockout bind multiple checkedValue to input
I have custom dropdown (made with using divs and list)

```<code><div class="primary-tags-wrapper">
    <div id="primaryTag" class="primary-tags-dropdown ui-dropdown fl">
        <div class="fl">
            <div class="primary-tag-selected-value" data-bind="text: showPrimaryTag"></div>
        </div>
        <div class="fr" data-primary="tag">
            <div class="fa fa-caret-down"></div>
            <ul class="primary-tags-list">
                <li class="primary-tags-item">
                    <input class="primary-tags-item-radio" type="radio" name="primary-tag" id="primary-tag-default" data-bind="checkedValue: null, checked: primaryTag"/>
                    <label class="primary-tags-item-label" for="primary-tag-default">Set Primary Tag</label>
                </li>
                <!-- ko foreach: tags -->
                <li class="primary-tags-item">
                    <input class="primary-tags-item-radio" type="radio" name="primary-tag" data-bind="attr: { 'id': 'primary-tag-' + $index() }, checkedValue: $data, checked: $parent.primaryTag"/>
                    <label class="primary-tags-item-label" data-bind="attr: { 'for': 'primary-tag-' + $index() }, text: $data"></label>
                </li>
                <!-- /ko -->
                <li class="primary-tags-item">
                    <input type="button" class="btn green-btn" data-bind="click: savePrimaryTag" value="Save"/>
                </li>
            </ul>
        </div>
    </div>
</div>
</code>```

To it I have binded knockout ViewModel

```<code>var TagsViewModel = function (inputModel) {
            var vm = this;

            vm.tags = ko.observableArray(inputModel.tags);
            vm.allTags = ko.observableArray(inputModel.allTags);
            vm.primaryTag = ko.observable(inputModel.primaryTag);

            vm.refreshTags = function () {
                var data = vm.tags().slice(0);
                vm.tags([]);
                vm.tags(data);
            };

            vm.savePrimaryTag = function() {
                var data = {
                    locationId: inputModel.locationId,
                    reviewId: inputModel.reviewId,
                    tag: vm.primaryTag()
                };

                initializeAjaxLoader();

                $.post('/data/reviews/primaryTag',
                    data,
                    function(response) {
                        if (!response.status) {
                            vm.primaryTag('');
                        } else {
                            vm.primaryTag(response.tag);
                        }

                        removeAjaxLoader();
                    });
            }

            vm.showPrimaryTag = ko.pureComputed(function() {
                    var primaryTagVal = vm.primaryTag();
                    if (primaryTagVal) {
                        return 'Primary Tag: ' + primaryTagVal;
                    }
                    return DEFAULT_PRIMARY_TAG;
                },
                vm);

            vm.noPrimaryTagSelected = ko.pureComputed(function() {
                    var primaryTagVal = vm.primaryTag();
                    if (primaryTagVal) {
                        return false;
                    }
                    return true;
                },
                vm);
        }
</code>```

In dropdown I have default option : "Set Primary Tag" which should be selected when primaryTag is null or string.Empty. Currently it is what I can't achive.

So is it possible to set multiple checkedValue to radio button, or there are another way to support this "feature"

答:
When knockout handles the checked binding, it compares primitives using ===. This means, as you've noticed, that a checked value of null doesn't work with "", false, undefined or 0.

If you somehow can't prevent your selected value to be initialized as an empty string, you could bind to a computed layer that "sanitizes" the output.

All of the radio inputs write their value to a computed observable.

The computed observable has a private backing field to store raw input

The read method makes sure all falsey values are returned as null

var VM = function() {
  // Notice this can be initialized as any falsey value
  // and the checkedValue=null binding will work.
  const _selectedTag = ko.observable("");

  this.selectedTag = ko.computed({
    read: function() {
      // Explicitly "cast" all falsey values
      // to `null` so it can be handled by
      // knockout's `checked` binding:
      return _selectedTag() || null;
    },
    write: _selectedTag
  });

  this.tags = [
    { label: "one" },
    { label: "two" },
    { label: "three" },
    { label: "four" },
  ]
};

ko.applyBindings(new VM());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label { display: block }</code>```

    <input type="radio" data-bind="checked: selectedTag, checkedValue: null">
    Don't use a tag

      <input type="radio" data-bind="checked: $parent.selectedTag, checkedValue: $data">

```

Body:
I have custom dropdown (made with using divs and list)

                    <input class="primary-tags-item-radio" type="radio" name="primary-tag" id="primary-tag-default" data-bind="checkedValue: null, checked: primaryTag"/>
                    Set Primary Tag

                    <input class="primary-tags-item-radio" type="radio" name="primary-tag" data-bind="attr: { 'id': 'primary-tag-' + $index() }, checkedValue: $data, checked: $parent.primaryTag"/>

                    <input type="button" class="btn green-btn" data-bind="click: savePrimaryTag" value="Save"/>

To it I have binded knockout ViewModel

var TagsViewModel = function (inputModel) {
            var vm = this;

            vm.tags = ko.observableArray(inputModel.tags);
            vm.allTags = ko.observableArray(inputModel.allTags);
            vm.primaryTag = ko.observable(inputModel.primaryTag);

            vm.refreshTags = function () {
                var data = vm.tags().slice(0);
                vm.tags([]);
                vm.tags(data);
            };

            vm.savePrimaryTag = function() {
                var data = {
                    locationId: inputModel.locationId,
                    reviewId: inputModel.reviewId,
                    tag: vm.primaryTag()
                };

                initializeAjaxLoader();

                $.post('/data/reviews/primaryTag',
                    data,
                    function(response) {
                        if (!response.status) {
                            vm.primaryTag('');
                        } else {
                            vm.primaryTag(response.tag);
                        }

                        removeAjaxLoader();
                    });
            }

            vm.showPrimaryTag = ko.pureComputed(function() {
                    var primaryTagVal = vm.primaryTag();
                    if (primaryTagVal) {
                        return 'Primary Tag: ' + primaryTagVal;
                    }
                    return DEFAULT_PRIMARY_TAG;
                },
                vm);

            vm.noPrimaryTagSelected = ko.pureComputed(function() {
                    var primaryTagVal = vm.primaryTag();
                    if (primaryTagVal) {
                        return false;
                    }
                    return true;
                },
                vm);
        }

In dropdown I have default option : "Set Primary Tag" which should be selected when primaryTag is null or string.Empty. Currently it is what I can't achive.

So is it possible to set multiple checkedValue to radio button, or there are another way to support this "feature"

Body:
When knockout handles the checked binding, it compares primitives using ===. This means, as you've noticed, that a checked value of null doesn't work with "", false, undefined or 0.

If you somehow can't prevent your selected value to be initialized as an empty string, you could bind to a computed layer that "sanitizes" the output.

All of the radio inputs write their value to a computed observable.

The computed observable has a private backing field to store raw input

The read method makes sure all falsey values are returned as null

var VM = function() {
  // Notice this can be initialized as any falsey value
  // and the checkedValue=null binding will work.
  const _selectedTag = ko.observable("");

  this.selectedTag = ko.computed({
    read: function() {
      // Explicitly "cast" all falsey values
      // to `null` so it can be handled by
      // knockout's `checked` binding:
      return _selectedTag() || null;
    },
    write: _selectedTag
  });

  this.tags = [
    { label: "one" },
    { label: "two" },
    { label: "three" },
    { label: "four" },
  ]
};

ko.applyBindings(new VM());

label { display: block }

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div>
  <label>
    <input type="radio" data-bind="checked: selectedTag, checkedValue: null">
    Don't use a tag
  </label>

  <!-- ko foreach: tags -->
    <label>
      <input type="radio" data-bind="checked: $parent.selectedTag, checkedValue: $data">
      <span data-bind="text: label"></span>
    </label>
  <!-- /ko -->

</div>


问:
CircularReferenceError when serializing an ActiveRecord instance (fetched by using ThinkingSphinx) to JSON
I try to serialize an instance of my ActiveRecord model to JSON (using "render :json => @entities" or "@entities.to_json"), but I always get an CircularReferenceError ("ActiveSupport::JSON::Encoding::CircularReferenceError (object references itself)").
This only happens when the ActiveRecord instances are queried by using ThinkingSphinx. The to_xml serialization works fine. Is that a known problem? I am using the latest Rails 3 and ThinkingSphinx.</p>

答:
Thinking Sphinx & Rails 3 & JSON didn't work on my system until I used the following: </p>

```<code>@entities = Entity.find(:all)
render :js => @entities.as_json
</code>```

Body:
Thinking Sphinx & Rails 3 & JSON didn't work on my system until I used the following:

@entities = Entity.find(:all)
render :js => @entities.as_json


问:
Service worker with workbox and Gulp, how to add my own rules?
I just started to work with workbox and I am using Gulp to generate my service worker with the following code in the example: https://developers.google.com/web/tools/workbox/get-started/gulp

It generates the service-worker file properly, but the thing I do not understand is how can I add my own code to the file? Lets say I want to add the following route:

workboxSW.router.registerRoute(
  'https://pixabay.com/get/(.*)',
  cacheOneWeekStrategy
);```

Now if I run the gulp task again it overwrites my own route. How can I add my own code? I also want to add some event listeners etc.

Update: so far I have found out that I can use injectManifest() which will inject routes to the file inside workboxSW.precache([]); But I still need to copy the actual service worker script somehow.

答:
I could not figure out any other way. This is my solution. I copy workbox from node_modules and then I write my code to sw.js and then I use inject-manifest to inject the routes to my own code.

gulp.task('copy-workbox', () => {
  return gulp.src(['node_modules/workbox-sw/build/importScripts/workbox-sw.prod*.js'])
    .pipe(rename('workbox.js'))
    .pipe(gulp.dest('app'));
});

gulp.task('inject-manifest', () => {
  return wbBuild.injectManifest({
    swSrc: './app/sw.js',
    swDest: './app/service-worker.js',
    globDirectory: './app/',
    globPatterns: ['**\/*.{html,js,css,png}'],
    globIgnores: ['admin.html']
  })
  .then(() => {
    console.log('Service worker generated.');
  });
});```

UPDATE: after some reading I figured out it is not a good idea to rename the workbox. However I couldn't find a way to do this otherwise.

Body:
I just started to work with workbox and I am using Gulp to generate my service worker with the following code in the example: https://developers.google.com/web/tools/workbox/get-started/gulp

It generates the service-worker file properly, but the thing I do not understand is how can I add my own code to the file? Lets say I want to add the following route:

workboxSW.router.registerRoute(
  'https://pixabay.com/get/(.*)',
  cacheOneWeekStrategy
);

Now if I run the gulp task again it overwrites my own route. How can I add my own code? I also want to add some event listeners etc.

Update: so far I have found out that I can use injectManifest() which will inject routes to the file inside workboxSW.precache([]); But I still need to copy the actual service worker script somehow.

Body:
I could not figure out any other way. This is my solution. I copy workbox from node_modules and then I write my code to sw.js and then I use inject-manifest to inject the routes to my own code.

gulp.task('copy-workbox', () => {
  return gulp.src(['node_modules/workbox-sw/build/importScripts/workbox-sw.prod*.js'])
    .pipe(rename('workbox.js'))
    .pipe(gulp.dest('app'));
});

gulp.task('inject-manifest', () => {
  return wbBuild.injectManifest({
    swSrc: './app/sw.js',
    swDest: './app/service-worker.js',
    globDirectory: './app/',
    globPatterns: ['**\/*.{html,js,css,png}'],
    globIgnores: ['admin.html']
  })
  .then(() => {
    console.log('Service worker generated.');
  });
});

UPDATE: after some reading I figured out it is not a good idea to rename the workbox. However I couldn't find a way to do this otherwise.


问:
test server for upload files - android
I am using retrofit library in my android app. I read multiple tutorial about upload and download files and working with json data. most of these tutorial have worked with image for simplicity and there is some API for working with that like imagur, but I want to work with audio files in my app and I don not know any server or API  for testing upload and download mp3 files. can anybody introduce me some of that?

update :
How can I make my own computer for testing? is this possible?

答:
There are so many Linux servers and which are free. Try https://www.hostinger.in/
for free domains and 1gb disk size.

Furthermore, if you want to test on your own computer try wamp,xampp or IIS (for .NET) and publish your code over there.

Title: test server for upload files - android


问:
How to send two files from node?
I have two html files.

mynewFile1.html

mynewFile2.html

How to send it to the Angular 4 client from nodejs?
How to get the files in angular 4 which is rendered from back end?

答:
It is pretty simple actually. Just serve the files using static function of express.

```<code>var app = express();
app.use(express.static('Files'));//assuming you have the files within the folder Files
</code>```

Now, you can access your files via angular with the path of the server/filename. For example, if your nodejs api is hosted on http://localhost:4200. Access it in angular using:

```<code> http://localhost:4200/mynewFile1.html
</code>```

Title: How to send two files from node?

Body:
It is pretty simple actually. Just serve the files using static function of express.

var app = express();
app.use(express.static('Files'));//assuming you have the files within the folder Files

Now, you can access your files via angular with the path of the server/filename. For example, if your nodejs api is hosted on http://localhost:4200. Access it in angular using:

 http://localhost:4200/mynewFile1.html


问:
Port finding race condition
I have a master.js and a slave.js

Whenever the master.js needs more slaves to handle data, it will .fork them.

In slave.js (truncated)

```<code>portscanner.findAPortNotInUse(config.wss.start_port, config.wss.end_port)
.then((port) => {
    httpsServer.listen(port);
    process.send('Connected and listening on : ' + port);
})
</code>```

Start Port is 11001 and End Port is 11100.

Now sometimes slave4 and slave5 both think that 11004 is free, both bind to that port and throw EADDRINUSE.

master.js

```<code>function CreateSlave(mode, amount) {
    return new Promise((res) => {

        var c = connected_slaves;
        for (var i = 0; i < amount; i++) {

            var id = uuid.v4().split("-")[0];

            slaves[c] = fork('/opt/nodeapps/ass/slave/server.js',
            [serverKeyForSession, mode]);
            slaves[c].id = id;
            slaves[c].mode = mode;

            AttachHandlerToSlave(c).then((res) => {
                if (res) return;
            });
            c++;
        }
    });
}

function AttachHandlerToSlave(c) {
    return new Promise((res, rej) => {
        slaves[c].on('message', (msg) => {
            console.log('\x1b[33m['+ slaves[c].id +'] | \x1b[0m'+msg);
        });
        res(true);
    });
}
</code>```

How can I prevent such behavior?

答:
You can make your master process to transmit the port number to the slaves.

When forking you automatically open a channel of communication between the master and the slave. Use it.

Here is a good tutorial about child processes.

I quote :

parent.js

```<code>const { fork } = require('child_process');

const forked = fork('child.js');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });
</code>```

slave.js

```<code>process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

let counter = 0;

setInterval(() => {
  process.send({ counter: counter++ });
}, 1000);
</code>```

Title: Port finding race condition

Body:
I have a master.js and a slave.js

Whenever the master.js needs more slaves to handle data, it will .fork them.

In slave.js (truncated)

portscanner.findAPortNotInUse(config.wss.start_port, config.wss.end_port)
.then((port) => {
    httpsServer.listen(port);
    process.send('Connected and listening on : ' + port);
})

Start Port is 11001 and End Port is 11100.

Now sometimes slave4 and slave5 both think that 11004 is free, both bind to that port and throw EADDRINUSE.

master.js

function CreateSlave(mode, amount) {
    return new Promise((res) => {

        var c = connected_slaves;
        for (var i = 0; i < amount; i++) {

            var id = uuid.v4().split("-")[0];

            slaves[c] = fork('/opt/nodeapps/ass/slave/server.js',
            [serverKeyForSession, mode]);
            slaves[c].id = id;
            slaves[c].mode = mode;

            AttachHandlerToSlave(c).then((res) => {
                if (res) return;
            });
            c++;
        }
    });
}

function AttachHandlerToSlave(c) {
    return new Promise((res, rej) => {
        slaves[c].on('message', (msg) => {
            console.log('\x1b[33m['+ slaves[c].id +'] | \x1b[0m'+msg);
        });
        res(true);
    });
}

How can I prevent such behavior?

Body:
You can make your master process to transmit the port number to the slaves.

When forking you automatically open a channel of communication between the master and the slave. Use it.

Here is a good tutorial about child processes.

I quote :

parent.js

const { fork } = require('child_process');

const forked = fork('child.js');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

slave.js

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

let counter = 0;

setInterval(() => {
  process.send({ counter: counter++ });
}, 1000);


问:
How to avoid segfault after calling deleteLater on pointer?
I have a GraphicsScene:public QGraphicsScene inherited class with a single QGraphicsView looking at it and QTimer, ticking to call function

```<code>void GraphicsScene::adv()
{
if (actor)
    views().at(0)->ensureVisible(actor,200,100);
advance();
}
</code>```

advance() is an overriden method which is send to all QGraphicsItem objects on scene. The point of this function - I want to make sure actor is always visible.
actor is a unit:public QGraphicsPixmapItem object on GraphicsScene.

At some point in actor method I call deleteLater().

The next timer tick I receive SEGFAULT at views().at(0)->ensureVisible(actor,200,100); line

I wonder, why if (actor) passes as true after deleteLater() and what is the correct condition should I use?

答:
If you call deleteLater() from inside your actor, the container GraphicsScene still has its pointer on it - the object itself doesn't reset all external pointers to it.

You have to reset this pointer - the member actor of your GraphicsScene to get your if-statement in adv() working.

Body:
I have a GraphicsScene:public QGraphicsScene inherited class with a single QGraphicsView looking at it and QTimer, ticking to call function

void GraphicsScene::adv()
{
if (actor)
    views().at(0)->ensureVisible(actor,200,100);
advance();
}

advance() is an overriden method which is send to all QGraphicsItem objects on scene. The point of this function - I want to make sure actor is always visible.
actor is a unit:public QGraphicsPixmapItem object on GraphicsScene.

At some point in actor method I call deleteLater().

The next timer tick I receive SEGFAULT at views().at(0)->ensureVisible(actor,200,100); line

I wonder, why if (actor) passes as true after deleteLater() and what is the correct condition should I use?


问:
regular expression using oracle REGEXP_INSTR
I want to use REGEXP_INSTR function in a query to search for any match for user input but I don't know how to write the regular expression that for example will match any value that includes the word car followed by unspecified numbers of letters/numbers/spaces and then the word Paterson. can any one please help me with writing this regEx? </p>

答:
Ok, so let's break this down.

"any value that includes the word car"

I surmise from this that the word car doesn't need to be at the start of the string, therefore i would start the format string with...

```<code>'^.*'
</code>```

Here the '^' character means the start of the string, the '.' means any character and '*' means 0 or more of the preceding character. So zero or more of any character after the start of the string.

Then the word 'car', so...

```<code>'^.*car'
</code>```

Next up...

"followed by unspecified numbers of letters/numbers/spaces"

I'm guessing that unspecified means zero or more. This is very similar to what we did to identify any characters that might come before 'car'. Where the '.' means any character

```<code>'^.*car.*'
</code>```

However, if unspecified means one or more, then you can use '+' in place of '*'

"then the word Paterson"

I'm going to assume that as this is the end of the description, there are no more characters after 'Paterson'.

```<code>'^.*car.*Paterson$'
</code>```

The '$' symbol means that the 'n' of 'Paterson' must be at the end of the string.

Code example:

```<code>select
    REGEXP_INSTR('123456car1234ABCDPaterson', '^.*car.*Paterson$') as rgx
from dual
</code>```

Output

```<code>       RGX
----------
         1
</code>```

Body:
Ok, so let's break this down.

"any value that includes the word car"

I surmise from this that the word car doesn't need to be at the start of the string, therefore i would start the format string with...

'^.*'

Here the '^' character means the start of the string, the '.' means any character and '*' means 0 or more of the preceding character. So zero or more of any character after the start of the string.

Then the word 'car', so...

'^.*car'

Next up...

"followed by unspecified numbers of letters/numbers/spaces"

I'm guessing that unspecified means zero or more. This is very similar to what we did to identify any characters that might come before 'car'. Where the '.' means any character

'^.*car.*'

However, if unspecified means one or more, then you can use '+' in place of '*'

"then the word Paterson"

I'm going to assume that as this is the end of the description, there are no more characters after 'Paterson'.

'^.*car.*Paterson$'

The '$' symbol means that the 'n' of 'Paterson' must be at the end of the string.

Code example:

select
    REGEXP_INSTR('123456car1234ABCDPaterson', '^.*car.*Paterson$') as rgx
from dual

Output

       RGX
----------
         1


问:
raw SQL to laravel query
Can anybody please help me to write a DB query version of the SQL statement below.
I need a little help around the select statement and the partitioned joins.

I have managed to do this so far.

```<code>$query = DB::table(raw('SapakInAdminOrder a'))
->select(raw('a.*'))
->leftJoin(raw('currency cu'), 'a.currency', '=', 'cu.id')
->leftJoin(raw('moodboards m'), 'a.orderMoodboardID', '=', 'm.id')
 ->join(raw('clients b'), 'a.clientID', '=', 'b.id')
 ->leftJoin(raw('moodboards mc'), 'b.moodboardID', 'mc.id')
 ->join(raw('sapakim c'), 'b.sapakID', '=', 'c.id')
 ->leftJoin(raw('sapakim sm'), 'c.managerid', '=', 'sm.id')
 ->leftJoin(raw('products p'), 'a.productKey', '=', 'p.id')
 ->where(function ($query) {
     $query->whereNull('a.isDeleted');
     $query->orWhere('a.isDeleted', '!=', 1);
 });
</code>```

But I need to achieve this.

```<code>select * from (select ROW_NUMBER() OVER(ORDER BY case when (indesign.status=4 or indesign.statusdate is null) then getdate()+2 else indesign.statusdate end ASC) AS RowNum,a.*
FROM sapakInAdminOrder a
left join currency cu on cu.id=a.currency
left join moodboards m on m.id=a.orderMoodboardID
inner join Clients b on a.clientID=b.id
left join moodboards mc on mc.id=b.moodboardID
inner join Sapakim c on b.sapakID=c.id
left join Sapakim sm on sm.id=c.managerid
left join products p on p.id=a.productKey
left join (select * from (select ROW_NUMBER() over(PARTITION BY orderID ORDER BY id DESC) r, * from orderCommunication ) f where r=1) chat on chat.orderId = a.id
left join (select id,[status],orderid,approveSMSDate,coverImage,statusDate from (SELECT  id,[status],statusDate,approveSMSDate,coverImage,orderid,ROW_NUMBER() OVER(PARTITION BY orderid ORDER BY id DESC) AS r  FROM  SapakimInAdminDesigns) f where  r=1) indesign on a.id=indesign.orderid
where (a.isDeleted is null or a.isDeleted != 1) and
      c.inAdminManagerID=(select id from sapakim where sapakguid='test')  and
      c.sapakguid='test' and
      a.isFreeDesign=0 and
      a.transactionID = -1 and
      (a.designerPaid is null or a.designerPaid=0) and
      (chat.sentToPrinter is null and chat.sentToManager is null and chat.sentToDesigner is null)
) bb where RowNum>=1 and RowNum<31
ORDER BY  RowNum asc
</code>```

I can do the simple ones but couldn't quite really wrap my head around the partitioned joins and the select statement.

I would really appreciate a help on this.

Thanks in advance.

答:
I am also stuck with this type of problem but I got a solution and its working fine for me!

use DB::unprepared() for this type of query :

```<code>$path = base_path() . "/storage/agency.sql";
$sql = file_get_contents($path);
DB::unprepared(DB::raw($sql));
</code>```

All SQL commands in Laravel are prepared by default, but sometimes you need to execute a command in an unprepared mode, because some commands in some database cannot be ran in prepared mode.

Title: raw SQL to laravel query

Body:
Can anybody please help me to write a DB query version of the SQL statement below.
I need a little help around the select statement and the partitioned joins.

I have managed to do this so far.

$query = DB::table(raw('SapakInAdminOrder a'))
->select(raw('a.*'))
->leftJoin(raw('currency cu'), 'a.currency', '=', 'cu.id')
->leftJoin(raw('moodboards m'), 'a.orderMoodboardID', '=', 'm.id')
 ->join(raw('clients b'), 'a.clientID', '=', 'b.id')
 ->leftJoin(raw('moodboards mc'), 'b.moodboardID', 'mc.id')
 ->join(raw('sapakim c'), 'b.sapakID', '=', 'c.id')
 ->leftJoin(raw('sapakim sm'), 'c.managerid', '=', 'sm.id')
 ->leftJoin(raw('products p'), 'a.productKey', '=', 'p.id')
 ->where(function ($query) {
     $query->whereNull('a.isDeleted');
     $query->orWhere('a.isDeleted', '!=', 1);
 });

But I need to achieve this.

select * from (select ROW_NUMBER() OVER(ORDER BY case when (indesign.status=4 or indesign.statusdate is null) then getdate()+2 else indesign.statusdate end ASC) AS RowNum,a.*
FROM sapakInAdminOrder a
left join currency cu on cu.id=a.currency
left join moodboards m on m.id=a.orderMoodboardID
inner join Clients b on a.clientID=b.id
left join moodboards mc on mc.id=b.moodboardID
inner join Sapakim c on b.sapakID=c.id
left join Sapakim sm on sm.id=c.managerid
left join products p on p.id=a.productKey
left join (select * from (select ROW_NUMBER() over(PARTITION BY orderID ORDER BY id DESC) r, * from orderCommunication ) f where r=1) chat on chat.orderId = a.id
left join (select id,[status],orderid,approveSMSDate,coverImage,statusDate from (SELECT  id,[status],statusDate,approveSMSDate,coverImage,orderid,ROW_NUMBER() OVER(PARTITION BY orderid ORDER BY id DESC) AS r  FROM  SapakimInAdminDesigns) f where  r=1) indesign on a.id=indesign.orderid
where (a.isDeleted is null or a.isDeleted != 1) and
      c.inAdminManagerID=(select id from sapakim where sapakguid='test')  and
      c.sapakguid='test' and
      a.isFreeDesign=0 and
      a.transactionID = -1 and
      (a.designerPaid is null or a.designerPaid=0) and
      (chat.sentToPrinter is null and chat.sentToManager is null and chat.sentToDesigner is null)
) bb where RowNum>=1 and RowNum<31
ORDER BY  RowNum asc

I can do the simple ones but couldn't quite really wrap my head around the partitioned joins and the select statement.

I would really appreciate a help on this.

Thanks in advance.

Body:
I am also stuck with this type of problem but I got a solution and its working fine for me!

use DB::unprepared() for this type of query :

$path = base_path() . "/storage/agency.sql";
$sql = file_get_contents($path);
DB::unprepared(DB::raw($sql));

All SQL commands in Laravel are prepared by default, but sometimes you need to execute a command in an unprepared mode, because some commands in some database cannot be ran in prepared mode.


问:
Resuming a thread by using notifyAll
Take the Pausing a Thread example. If I use notifyAll instead of notify, is there any side effect, and is it necessary?

答:
In that example, it will not make any difference, because there's only 1 thread waiting.

The difference between notify and notifyAll is that the latter wakes all waiters, instead of just one.

Title: Resuming a thread by using notifyAll


问:
Why does this EF insert with IDENTITY_INSERT not work?
This is the query:

```<code>using (var db = new AppDbContext())
{
    var item = new IdentityItem {Id = 418, Name = "Abrahadabra" };
    db.IdentityItems.Add(item);
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Test.Items ON;");
    db.SaveChanges();
}
</code>```

When executed, the Id of the inserted record, on a new table, is still 1.

NEW: When I use either the transaction, or TGlatzer's answer, I get the exception:

Explicit value must be specified for identity column in table 'Items'
  either when IDENTITY_INSERT is set to ON or when a replication user is
  inserting into a NOT FOR REPLICATION identity column.

答:
I had a very similar problem.

The solution was something like:

```<code>db.Database.ExecuteSqlCommand("disable trigger all on  myTable ;")
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT myTable  ON;");
db.SaveChanges();
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT myTable  OFF");
db.Database.ExecuteSqlCommand("enable trigger all on  myTable ;")
</code>```

In my case, the message Explicit value must be specified for identity... was because on insert a trigger called and would insert something else.

```<code>ALTER TABLE myTable NOCHECK CONSTRAINT all
</code>```

Can also be usefull

Body:
This is the query:

using (var db = new AppDbContext())
{
    var item = new IdentityItem {Id = 418, Name = "Abrahadabra" };
    db.IdentityItems.Add(item);
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Test.Items ON;");
    db.SaveChanges();
}

When executed, the Id of the inserted record, on a new table, is still 1.

NEW: When I use either the transaction, or TGlatzer's answer, I get the exception:

Explicit value must be specified for identity column in table 'Items'
  either when IDENTITY_INSERT is set to ON or when a replication user is
  inserting into a NOT FOR REPLICATION identity column.

Body:
I had a very similar problem.

The solution was something like:

db.Database.ExecuteSqlCommand("disable trigger all on  myTable ;")
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT myTable  ON;");
db.SaveChanges();
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT myTable  OFF");
db.Database.ExecuteSqlCommand("enable trigger all on  myTable ;")

In my case, the message Explicit value must be specified for identity... was because on insert a trigger called and would insert something else.

ALTER TABLE myTable NOCHECK CONSTRAINT all

Can also be usefull


问:
Adobe Flash frame scripting versus seprate file scripting
in my game , I have created separated action script classes and files for enemies, players and other objects of the game. this is pretty good , because this makes me to use dry ( don't repeat yourself) design principle . but in my menu screen there is a script like this at start of frame 100:

```<code>import flash.events.Event;
import flash.display.MovieClip;

var clouds: Array = [cloud1, cloud2, cloud3, cloud4];
var initCloudsX: Array = [cloud1.x, cloud2.x, cloud3.x, cloud4.x];
var nclouds = clouds.length;
var scrollSpeed: Number = 1;

if (this.hasEventListener(Event.ENTER_FRAME)) {
    this.removeEventListener(Event.ENTER_FRAME, scroll);

}

this.addEventListener(Event.ENTER_FRAME, scroll);
function garbageFrame(): void {
    sndBgChannel.stop();
    if (this.hasEventListener(Event.ENTER_FRAME)) {
        this.removeEventListener(Event.ENTER_FRAME, scroll);

    }
}
function scroll(e: Event): void {
    ground1.x -= scrollSpeed;
    ground2.x -= scrollSpeed;

    mountains1.x -= scrollSpeed;
    mountains2.x -= scrollSpeed;
    if (ground1.x < -ground1.width) {

        ground1.x = ground2.x + ground2.width - 5;
    }

    if (ground2.x < -ground2.width) {
        ground2.x = ground1.x + ground1.width - 10;
    }

    if (mountains1.x < -mountains1.width) {

        mountains1.x = mountains2.x + mountains2.width - 2;
    }
    if (mountains2.x < -mountains2.width) {

        mountains2.x = mountains1.x + mountains1.width - 2;
    }

    for (var i: Number = 0; i < nclouds; i++) {
        clouds[i].x -= scrollSpeed;
        if (clouds[i].x < -clouds[i].width) {
            clouds[i].x = initCloudsX[i];
        }
    }
}
</code>```

So far , I think it is a good approach and after leaving the frame 101, by calling garbageFrame which has been defined above , I can simply leave the frame without any hassles or bothering.
But the question raises here is , for example suppose that in frame 300 , there is a movie clip with instance name of clouds. the compiler will throw me an error that you have defined a clouds of type of array before in frame 101.so:

1 ) it shows me that if I define a variable, frame 1 , it is not destroying in any other frames.

2 ) I think in the background  , the flash compiler makes a class which puts every actions of frames onto it , so it doesn't allow me to redefine a variable or function twice the times.

Now what's your idea for mixed approach of using action script programming , I mean using both frame scripting and separated file classes ( and linkage). Does it make any sense? what is the pron and cons of frame scripting?

Thanks in advance..

答:
Maybe someone have treated that the post is not exciting and voted down the post, but I will answer this question myself. after reading ,searching and also thinking to the other comments , even though , maybe other users would think that there is no answer for that ,  the final answer is :

Before I go any further, I should go ahead and state for the
record that coding on the timeline should be avoided at all costs.
There is basically nothing that you can’t do with classes to control your DisplayObjects at this point, and forcing your code into
classes imposes better architecture and less sloppy shortcuts that
will later come back to bite you.
Now , I say “ basically ” because until AS3 (Flash CS3, specifically) you still had to put a stop() action on the last frame of any
MovieClip you didn’t want to loop. Since switching to all-class
scripting architecture, I found it very frustrating to not be able to
easily remove this last bit of straggling timeline code from my FLA
once and for all. Then I discovered an undocumented method
of MovieClips. It’s called addFrameScript, and it is a complete
mystery to me why Adobe hasn’t documented it or encouraged
its use, because it is a fantastic piece of code. Basically, it allows
you to tell a particular function to run when a certain frame of
a MovieClip is hit. Unlike all the other MovieClip functions, it is
zero based, rather than one based, so you must subtract one from
the desired frame number to use it correctly. Here is its syntax in
the context of a MovieClip class:

```<code>public function MyMovieClip() {
  addFrameScript(totalFrames-1, stop);
}
</code>```

Now when the clip reaches the last frame, it will call its stop()
method and not loop. Obviously this has further reaching implications and uses than simply stopping a MovieClip from playing.
In fact, I have come up with a way to use this method to make
up for what I see as a defi ciency in ActionScript with regard to
MovieClips and frame labels. Since early versions of Flash, you
could put string labels on any frame in the timeline and use them
as reference points for navigation. Starting in AS3, Adobe finally
introduced the ability to see what label you’re currently on in
a clip (with the currentLabel property) as well as a list of all the
labels in a clip (the currentLabels property). I’ve long thought that
Flash should dispatch an event whenever a frame label is hit so
you could trigger actions based on label markers.

Body:
in my game , I have created separated action script classes and files for enemies, players and other objects of the game. this is pretty good , because this makes me to use dry ( don't repeat yourself) design principle . but in my menu screen there is a script like this at start of frame 100:

import flash.events.Event;
import flash.display.MovieClip;

var clouds: Array = [cloud1, cloud2, cloud3, cloud4];
var initCloudsX: Array = [cloud1.x, cloud2.x, cloud3.x, cloud4.x];
var nclouds = clouds.length;
var scrollSpeed: Number = 1;

if (this.hasEventListener(Event.ENTER_FRAME)) {
    this.removeEventListener(Event.ENTER_FRAME, scroll);

}

this.addEventListener(Event.ENTER_FRAME, scroll);
function garbageFrame(): void {
    sndBgChannel.stop();
    if (this.hasEventListener(Event.ENTER_FRAME)) {
        this.removeEventListener(Event.ENTER_FRAME, scroll);

    }
}
function scroll(e: Event): void {
    ground1.x -= scrollSpeed;
    ground2.x -= scrollSpeed;

    mountains1.x -= scrollSpeed;
    mountains2.x -= scrollSpeed;
    if (ground1.x < -ground1.width) {

        ground1.x = ground2.x + ground2.width - 5;
    }

    if (ground2.x < -ground2.width) {
        ground2.x = ground1.x + ground1.width - 10;
    }

    if (mountains1.x < -mountains1.width) {

        mountains1.x = mountains2.x + mountains2.width - 2;
    }
    if (mountains2.x < -mountains2.width) {

        mountains2.x = mountains1.x + mountains1.width - 2;
    }

    for (var i: Number = 0; i < nclouds; i++) {
        clouds[i].x -= scrollSpeed;
        if (clouds[i].x < -clouds[i].width) {
            clouds[i].x = initCloudsX[i];
        }
    }
}

So far , I think it is a good approach and after leaving the frame 101, by calling garbageFrame which has been defined above , I can simply leave the frame without any hassles or bothering.
But the question raises here is , for example suppose that in frame 300 , there is a movie clip with instance name of clouds. the compiler will throw me an error that you have defined a clouds of type of array before in frame 101.so:

1 ) it shows me that if I define a variable, frame 1 , it is not destroying in any other frames.

2 ) I think in the background  , the flash compiler makes a class which puts every actions of frames onto it , so it doesn't allow me to redefine a variable or function twice the times.

Now what's your idea for mixed approach of using action script programming , I mean using both frame scripting and separated file classes ( and linkage). Does it make any sense? what is the pron and cons of frame scripting?

Thanks in advance..

Body:
Maybe someone have treated that the post is not exciting and voted down the post, but I will answer this question myself. after reading ,searching and also thinking to the other comments , even though , maybe other users would think that there is no answer for that ,  the final answer is :

Before I go any further, I should go ahead and state for the
record that coding on the timeline should be avoided at all costs.
There is basically nothing that you can’t do with classes to control your DisplayObjects at this point, and forcing your code into
classes imposes better architecture and less sloppy shortcuts that
will later come back to bite you.
Now , I say “ basically ” because until AS3 (Flash CS3, specifically) you still had to put a stop() action on the last frame of any
MovieClip you didn’t want to loop. Since switching to all-class
scripting architecture, I found it very frustrating to not be able to
easily remove this last bit of straggling timeline code from my FLA
once and for all. Then I discovered an undocumented method
of MovieClips. It’s called addFrameScript, and it is a complete
mystery to me why Adobe hasn’t documented it or encouraged
its use, because it is a fantastic piece of code. Basically, it allows
you to tell a particular function to run when a certain frame of
a MovieClip is hit. Unlike all the other MovieClip functions, it is
zero based, rather than one based, so you must subtract one from
the desired frame number to use it correctly. Here is its syntax in
the context of a MovieClip class:

public function MyMovieClip() {
  addFrameScript(totalFrames-1, stop);
}

Now when the clip reaches the last frame, it will call its stop()
method and not loop. Obviously this has further reaching implications and uses than simply stopping a MovieClip from playing.
In fact, I have come up with a way to use this method to make
up for what I see as a defi ciency in ActionScript with regard to
MovieClips and frame labels. Since early versions of Flash, you
could put string labels on any frame in the timeline and use them
as reference points for navigation. Starting in AS3, Adobe finally
introduced the ability to see what label you’re currently on in
a clip (with the currentLabel property) as well as a list of all the
labels in a clip (the currentLabels property). I’ve long thought that
Flash should dispatch an event whenever a frame label is hit so
you could trigger actions based on label markers.


问:
Yargs - How to provide custom error msg for omitted positional argument
I can't find a way to properly configure positional arguments. I have this code:

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

const create = (argv) => {
  console.log('create component with name:', argv.name)
}

const createBuilder = (yargs) => {
  yargs.positional('name', {
    desc: 'Name of the new component',
  })
}

/* eslint-disable no-unused-expressions */
require('yargs')
  .command({
    command: 'create <name>',
    desc: 'Create a new component',
    builder: createBuilder,
    handler: create,
  })
  .demandCommand(1, 'A command is required')
  .help()
  .argv
</code>```

and I would like to provide a custom error message in case the user doesn't specify a name after the create command.

It's not clear to me from the documentation how to do that, and while going through github issues I came across this comment (#928):

I recommend instead using demandCommand and demandOption (each of
  which are documented).

These allow you to configure positional arguments and flag arguments
  separately

I've tried all kinds of combinations with

```<code>.demandCommand(1, 'You need to provide name for the new component')
</code>```

or

```<code>.demandOption('name', 'You need to provide name for the new component')
</code>```

but without luck. Does anybody know how to do this?

答:
The command option of yargs can take two types of arguments.

The first being Obligatory: <varName>. If for some reason, the user type the command without entering a varName, then it will run the help page.

The second being Optional: [varName]. If the user enters the command, even with a missing varName, the command will run.

Extra: if you want infinite varName variables, then you can provide a spread operator for the wanted option. Being <...varNames> or [...varNames]

That being said, if you want to provide a custom error message, there are several ways of going about it. The first is this one:

```<code>const program = require('yargs')
    .command('create [fileName]', 'your description', () => {}, argv => {
        if(argv.fileName === undefined) {
            console.error('You need to provide name for the new component')
            return;
        }
        console.log(`success, a component called ${argv.fileName} got created.`)
    })
</code>```

Lodash also provides a function _.isUndefined which would also work.

The second is this one:

```<code>const program = require('yargs')
    .command('create <fileName>', 'A description', () => {}, argv => {

    }).fail((msg, err, yargs) => {
        console.log('Sorry, no component name was given.')
    })

program.argv
</code>```

For more information, here is the fail documentation on yargs api.

Body:
I can't find a way to properly configure positional arguments. I have this code:

#!/usr/bin/env node

const create = (argv) => {
  console.log('create component with name:', argv.name)
}

const createBuilder = (yargs) => {
  yargs.positional('name', {
    desc: 'Name of the new component',
  })
}

/* eslint-disable no-unused-expressions */
require('yargs')
  .command({
    command: 'create <name>',
    desc: 'Create a new component',
    builder: createBuilder,
    handler: create,
  })
  .demandCommand(1, 'A command is required')
  .help()
  .argv

and I would like to provide a custom error message in case the user doesn't specify a name after the create command.

It's not clear to me from the documentation how to do that, and while going through github issues I came across this comment (#928):

I recommend instead using demandCommand and demandOption (each of
  which are documented).

These allow you to configure positional arguments and flag arguments
  separately

I've tried all kinds of combinations with

.demandCommand(1, 'You need to provide name for the new component')

or

.demandOption('name', 'You need to provide name for the new component')

but without luck. Does anybody know how to do this?

Body:
The command option of yargs can take two types of arguments.

The first being Obligatory: <varName>. If for some reason, the user type the command without entering a varName, then it will run the help page.

The second being Optional: [varName]. If the user enters the command, even with a missing varName, the command will run.

Extra: if you want infinite varName variables, then you can provide a spread operator for the wanted option. Being <...varNames> or [...varNames]

That being said, if you want to provide a custom error message, there are several ways of going about it. The first is this one:

const program = require('yargs')
    .command('create [fileName]', 'your description', () => {}, argv => {
        if(argv.fileName === undefined) {
            console.error('You need to provide name for the new component')
            return;
        }
        console.log(`success, a component called ${argv.fileName} got created.`)
    })

Lodash also provides a function _.isUndefined which would also work.

The second is this one:

const program = require('yargs')
    .command('create <fileName>', 'A description', () => {}, argv => {

    }).fail((msg, err, yargs) => {
        console.log('Sorry, no component name was given.')
    })

program.argv

For more information, here is the fail documentation on yargs api.


问:
Excel add its number by 10 if column has number

I would like to add its number by 10 for example in the screenshot, I'm trying to add '1480 on row A490' because the previous number was messed up, and would like excel to add its number by 10 from its previous number so, it has to be 1490, 1500, 1510 and so on, is it possible? Also I would like to leave those empty column if no number has been detected. That would be very very helpful for my future project.

答:
Yes, its possible.

Just write the values 1480, 1490, 1500, 1510.

Then, select all your values.

Drag the highlighted box from your right-bottom corner.

Move the selection as long as you need.

Hope it helps.