问:
Save Return Error in Sitecore Page Editor
I get an error when save a page in page editor.. Somehow when I edited the page from presentation > detail and display it in page editor it works fine.. The error logs is in below here..

```<code>ERROR After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 38, position 85.  Exception: Newtonsoft.Json.JsonReaderException
Message: After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 38, position 85.  Source: Newtonsoft.Json
    at Newtonsoft.Json.JsonTextReader.ParsePostValue()
    at Newtonsoft.Json.JsonTextReader.ReadInternal()
    at Newtonsoft.Json.JsonTextReader.Read()
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
    at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
    at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
    at Sitecore.ExperienceEditor.Speak.Server.Requests.PipelineProcessorRequest`1.Process(RequestArgs requestArgs)
</code>```

Any kind of thought or solution may help

Thanks

答:
This post fixed for me. Note I'm using Sitecore 8.2 Update 2

My error:

After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 1, position 2246.

http://jockstothecore.com/experience-editor-error/

In the event that the above link does work, the instructions are to:

Edit the file, [Website]/sitecore/shell/client/Sitecore/ExperienceEditor/ExperienceEditor.js and to replace the code for postServerRequest function with this updated version.

```<code>postServerRequest: function (requestType, commandContext, handler, async) {

    function normalizeDeviceProp(d) {
        if (typeof(d) !== "object")
            throw new Error("Unexpected presentation details XML: cannot find device property");

        if (d instanceof Array)
            return d;

        var normalized = [];
        normalized.push(d);
        return normalized;
    }

    var token = $('input[name="__RequestVerificationToken"]').val();

    // Custom Brainjocks code to fix Experience Editor error.
    var ajaxData = unescape(JSON.stringify(commandContext));
    if (commandContext && commandContext.scLayout) {
        var obj = JSON.parse(commandContext.scLayout);
      if (obj && obj.r) {
          normalizeDeviceProp(obj.r.d).forEach(function (d) {
              if (d.r instanceof Array) {
                  d.r.forEach(function (r) {
                      var val = r["@par"];
                        if (val && val.length > 0) {
                            ajaxData = ajaxData.replace(unescape(val), val);
                        }
                  });
              }

            });
        }
    }

    jQuery.ajax({
        url: "/-/speak/request/v1/expeditor/" + requestType,
        data: {
            __RequestVerificationToken: token,
            data: ajaxData
        },
        success: handler,
        type: "POST",
        async: async != undefined ? async : false
    });
}
</code>```

Body:
I get an error when save a page in page editor.. Somehow when I edited the page from presentation > detail and display it in page editor it works fine.. The error logs is in below here..

ERROR After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 38, position 85.  Exception: Newtonsoft.Json.JsonReaderException
Message: After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 38, position 85.  Source: Newtonsoft.Json
    at Newtonsoft.Json.JsonTextReader.ParsePostValue()
    at Newtonsoft.Json.JsonTextReader.ReadInternal()
    at Newtonsoft.Json.JsonTextReader.Read()
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
    at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
    at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
    at Sitecore.ExperienceEditor.Speak.Server.Requests.PipelineProcessorRequest`1.Process(RequestArgs requestArgs)

Any kind of thought or solution may help

Thanks

Body:
This post fixed for me. Note I'm using Sitecore 8.2 Update 2

My error:

After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 1, position 2246.

http://jockstothecore.com/experience-editor-error/

In the event that the above link does work, the instructions are to:

Edit the file, [Website]/sitecore/shell/client/Sitecore/ExperienceEditor/ExperienceEditor.js and to replace the code for postServerRequest function with this updated version.

postServerRequest: function (requestType, commandContext, handler, async) {

    function normalizeDeviceProp(d) {
        if (typeof(d) !== "object")
            throw new Error("Unexpected presentation details XML: cannot find device property");

        if (d instanceof Array)
            return d;

        var normalized = [];
        normalized.push(d);
        return normalized;
    }

    var token = $('input[name="__RequestVerificationToken"]').val();

    // Custom Brainjocks code to fix Experience Editor error.
    var ajaxData = unescape(JSON.stringify(commandContext));
    if (commandContext && commandContext.scLayout) {
        var obj = JSON.parse(commandContext.scLayout);
      if (obj && obj.r) {
          normalizeDeviceProp(obj.r.d).forEach(function (d) {
              if (d.r instanceof Array) {
                  d.r.forEach(function (r) {
                      var val = r["@par"];
                        if (val && val.length > 0) {
                            ajaxData = ajaxData.replace(unescape(val), val);
                        }
                  });
              }

            });
        }
    }

    jQuery.ajax({
        url: "/-/speak/request/v1/expeditor/" + requestType,
        data: {
            __RequestVerificationToken: token,
            data: ajaxData
        },
        success: handler,
        type: "POST",
        async: async != undefined ? async : false
    });
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
How to get Deploy.cmd to fill in replacement fields from Parameters.xml
I have a web application which we are deploying with msdeploy.

I've defined the following parameters.xml file in the project:

```<code><parameters>

    <parameter
        name="Database Server"
        description="Location of your database server."
        defaultValue="localhost"
        tags="DBServer, SQL">
    </parameter>

    <parameter
        name="Database Name"
        description="Name of the database for your application."
        defaultValue="MyDatabase" tags="DBName, SQL">
    </parameter>

    <parameter
        name="Database Username"
        description="User name to access your application database."
        defaultValue="myusername"
        tags="SQL, DbUsername">
    </parameter>

    <parameter
       name="Database Password"
       description="Password for the Database Username."
       defaultValue="mypassword"
       tags="SQL, DbUserPassword">
    </parameter>

    <parameter
        name="RTPOne-Web.config Connection String"
        description="Connection string to enter into config"
        defaultValue="Data Source={Database Server};Initial Catalog={Database Name};User Id={Database Username};Password={Database Password};Connection TimeOut=30;Pooling=false;Max Pool Size=500;"
        tags="Hidden, SQL">
        <parameterEntry kind="XmlFile" scope="\\web\.config$" match="//*[local-name()='connectionStrings']/*[local-name()='add'][@name='RTPOne']/@connectionString" tags="Sql, SqlConnectionString, Hidden" />
        <parameterEntry kind="XmlFile" scope="\\web\.config$" match="//*[local-name()='appSettings']/*[local-name()='add'][@key='DBConnStr']/@value" tags="" />
    </parameter>
</parameters>
</code>```

The last parameter uses the following replacement fields:

```<code>{Database Server}
{Database Name}
{Database Username}
{Database Password}
</code>```

When I use the "Import Application" option from within IIS 7.5, these replacement fields are filled in correctly using the values that were supplied by the other parameters.

However, when I use the Application.Deploy.cmd file to deploy the application via command line, none of these values are replaced correctly and I end up with a connection string that looks like this:

```<code>Data Source={Database Server};Initial Catalog={Database Name};User Id={Database Username};Password={Database Password};Connection TimeOut=30;Pooling=false;Max Pool Size=500;
</code>```

The Application.SetParameters.xml file that is generated with the deployment package contains the correct default values.  I'm expecting that the Deploy.cmd batch file should be able to use the default values from it:

```<code><?xml version="1.0" encoding="utf-8"?>
<parameters>
  <setParameter name="IIS Web Application Name" value="Default Web Site/MyApplication" />
  <setParameter name="Database Server" value="localhost" />
  <setParameter name="Database Name" value="MyDatabase" />
  <setParameter name="Database Username" value="MyUsername" />
  <setParameter name="Database Password" value="MyPassword" />
  <setParameter name="Web.config Connection String" value="Data Source={Database Server};Initial Catalog={Database Name};User Id={Database Username};Password={Database Password};Connection TimeOut=30;Pooling=false;Max Pool Size=500;" />
</parameters>
</code>```

Is there anything I can do to get the Deploy.cmd batch file to correctly substitute these values?

答:
One peculiarity you may not be aware of...

If the Application.SetParameters.xml file contains a setParameter element for the connection string, that value will be used as is by WebDeploy. I.e. no attempt will be made to perform any substitution at all.

If that setParameter reference is removed from the SetParameters.xml file WebDeploy will recognize that the defined default value should be used instead, and calculate it, as expected, based on the value(s) of the other parameters.

ContentLicense: CC BY-SA 3.0

Body:
I have a web application which we are deploying with msdeploy.

I've defined the following parameters.xml file in the project:

<parameters>

    <parameter
        name="Database Server"
        description="Location of your database server."
        defaultValue="localhost"
        tags="DBServer, SQL">
    </parameter>

    <parameter
        name="Database Name"
        description="Name of the database for your application."
        defaultValue="MyDatabase" tags="DBName, SQL">
    </parameter>

    <parameter
        name="Database Username"
        description="User name to access your application database."
        defaultValue="myusername"
        tags="SQL, DbUsername">
    </parameter>

    <parameter
       name="Database Password"
       description="Password for the Database Username."
       defaultValue="mypassword"
       tags="SQL, DbUserPassword">
    </parameter>

    <parameter
        name="RTPOne-Web.config Connection String"
        description="Connection string to enter into config"
        defaultValue="Data Source={Database Server};Initial Catalog={Database Name};User Id={Database Username};Password={Database Password};Connection TimeOut=30;Pooling=false;Max Pool Size=500;"
        tags="Hidden, SQL">
        <parameterEntry kind="XmlFile" scope="\\web\.config$" match="//*[local-name()='connectionStrings']/*[local-name()='add'][@name='RTPOne']/@connectionString" tags="Sql, SqlConnectionString, Hidden" />
        <parameterEntry kind="XmlFile" scope="\\web\.config$" match="//*[local-name()='appSettings']/*[local-name()='add'][@key='DBConnStr']/@value" tags="" />
    </parameter>
</parameters>

The last parameter uses the following replacement fields:

{Database Server}
{Database Name}
{Database Username}
{Database Password}

When I use the "Import Application" option from within IIS 7.5, these replacement fields are filled in correctly using the values that were supplied by the other parameters.

However, when I use the Application.Deploy.cmd file to deploy the application via command line, none of these values are replaced correctly and I end up with a connection string that looks like this:

Data Source={Database Server};Initial Catalog={Database Name};User Id={Database Username};Password={Database Password};Connection TimeOut=30;Pooling=false;Max Pool Size=500;

The Application.SetParameters.xml file that is generated with the deployment package contains the correct default values.  I'm expecting that the Deploy.cmd batch file should be able to use the default values from it:

<?xml version="1.0" encoding="utf-8"?>
<parameters>
  <setParameter name="IIS Web Application Name" value="Default Web Site/MyApplication" />
  <setParameter name="Database Server" value="localhost" />
  <setParameter name="Database Name" value="MyDatabase" />
  <setParameter name="Database Username" value="MyUsername" />
  <setParameter name="Database Password" value="MyPassword" />
  <setParameter name="Web.config Connection String" value="Data Source={Database Server};Initial Catalog={Database Name};User Id={Database Username};Password={Database Password};Connection TimeOut=30;Pooling=false;Max Pool Size=500;" />
</parameters>

Is there anything I can do to get the Deploy.cmd batch file to correctly substitute these values?


问:
Circe cannot find implicit encoder
I am trying to encode a few classes into json strings, however no matter what I try, my classes do not seem to be able to find an implicit encoder for the case classes I am using.

Here's the smallest example I was able to pare it down to.

```<code>import io.circe._
import io.circe.generic.semiauto._
import io.circe.generic.auto._
import io.circe.syntax._

case class OneCol(value: String)

object testObject {
  def main(args: Array[String]): Unit = {
    val testVal = OneCol("someVal")
    println(testVal.asJson)
  }
}
</code>```

Which gives the following compile error

Error:(30, 21) could not find implicit value for parameter encoder:
  io.circe.Encoder[OneCol]
      println(testVal.asJson)

I have tried the same thing with semi-auto encoder creation

```<code>def main(args: Array[String]): Unit = {
  implicit val enc : Encoder[OneCol] = deriveEncoder
  val testVal = OneCol("someVal")
  println(testVal.asJson)
}
</code>```

Which gives the following errors

Error:(25, 42) could not find Lazy implicit value of type
  io.circe.generic.encoding.DerivedObjectEncoder[A]
      implicit val enc : Encoder[OneCol] = deriveEncoder

Error:(25, 42) not enough arguments for method deriveEncoder:
  (implicit encode:
  shapeless.Lazy[io.circe.generic.encoding.DerivedObjectEncoder[A]])io.circe.ObjectEncoder[A].
  Unspecified value parameter encode.
      implicit val enc : Encoder[OneCol] = deriveEncoder

I am fairly sure that the entire purpose of auto and semi-auto encoder generation is to handle situations like these, so I am at a bit of a loss as to what I am doing wrong.

I am using scala 2.10.4, and circe 0.7.0 (circe-core_2.10, circe-generic_2.10 artifacts) if version information is relevant, with maven as the package manager.

Does anyone know why this is failing, and how to get it properly compiling?

Edit:

Here's the section of my POM with the macros plugin. Have tried both compiler plugins listed (both commented and non-commented), and both still give the same error.

```<code>        <plugin>
            <groupId>net.alchim31.maven</groupId>
            <artifactId>scala-maven-plugin</artifactId>
            <configuration>
                <args>
                    <!-- work-around for https://issues.scala-lang.org/browse/SI-8358 -->
                    <arg>-nobootcp</arg>
                </args>
                <recompileMode>incremental</recompileMode>
                <compilerPlugins>
                    <compilerPlugin>
                        <groupId>org.scalamacros</groupId>
                        <artifactId>paradise_2.10.4</artifactId>
                        <version>2.1.0</version>
                    </compilerPlugin>
                    <!--<compilerPlugin>-->
                        <!--<groupId>org.scala-lang.plugins</groupId>-->
                        <!--<artifactId>macro-paradise_2.10.2</artifactId>-->
                        <!--<version>2.0.0-SNAPSHOT</version>-->
                    <!--</compilerPlugin>-->
                </compilerPlugins>
            </configuration>
            <executions>
                <execution>
                    <id>scala-compile-first</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
                <execution>
                    <id>scala-test-compile-first</id>
                    <phase>process-test-resources</phase>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

答: It turns out that circe-core_2.10 has a dependency on scala version 2.10.6, meaning that my version of scala (2.10.4) was incompatible with the library, causing the issues. Upgrading to the proper version of scala fixed this. </p>

Title: Circe cannot find implicit encoder

Body:
I am trying to encode a few classes into json strings, however no matter what I try, my classes do not seem to be able to find an implicit encoder for the case classes I am using.

Here's the smallest example I was able to pare it down to.

import io.circe._
import io.circe.generic.semiauto._
import io.circe.generic.auto._
import io.circe.syntax._

case class OneCol(value: String)

object testObject {
  def main(args: Array[String]): Unit = {
    val testVal = OneCol("someVal")
    println(testVal.asJson)
  }
}

Which gives the following compile error

Error:(30, 21) could not find implicit value for parameter encoder:
  io.circe.Encoder[OneCol]
      println(testVal.asJson)

I have tried the same thing with semi-auto encoder creation

def main(args: Array[String]): Unit = {
  implicit val enc : Encoder[OneCol] = deriveEncoder
  val testVal = OneCol("someVal")
  println(testVal.asJson)
}

Which gives the following errors

Error:(25, 42) could not find Lazy implicit value of type
  io.circe.generic.encoding.DerivedObjectEncoder[A]
      implicit val enc : Encoder[OneCol] = deriveEncoder

Error:(25, 42) not enough arguments for method deriveEncoder:
  (implicit encode:
  shapeless.Lazy[io.circe.generic.encoding.DerivedObjectEncoder[A]])io.circe.ObjectEncoder[A].
  Unspecified value parameter encode.
      implicit val enc : Encoder[OneCol] = deriveEncoder

I am fairly sure that the entire purpose of auto and semi-auto encoder generation is to handle situations like these, so I am at a bit of a loss as to what I am doing wrong.

I am using scala 2.10.4, and circe 0.7.0 (circe-core_2.10, circe-generic_2.10 artifacts) if version information is relevant, with maven as the package manager.

Does anyone know why this is failing, and how to get it properly compiling?

Edit:

Here's the section of my POM with the macros plugin. Have tried both compiler plugins listed (both commented and non-commented), and both still give the same error.

        <plugin>
            <groupId>net.alchim31.maven</groupId>
            <artifactId>scala-maven-plugin</artifactId>
            <configuration>
                <args>

                    <arg>-nobootcp</arg>
                </args>
                <recompileMode>incremental</recompileMode>
                <compilerPlugins>
                    <compilerPlugin>
                        <groupId>org.scalamacros</groupId>
                        <artifactId>paradise_2.10.4</artifactId>
                        <version>2.1.0</version>
                    </compilerPlugin>

                </compilerPlugins>
            </configuration>
            <executions>
                <execution>
                    <id>scala-compile-first</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
                <execution>
                    <id>scala-test-compile-first</id>
                    <phase>process-test-resources</phase>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>


问:
Ruby - Continuously reading from the end of a file
I have made a Ruby program that should read the end of a Linux log file, as well any additional information that is added to the end of the file during the execution of the script. A regular expression is then used to match specific lines, such as can be seen below.

Mar 31 13:28:05 dns.ns1.local dnsmasq[82093]: query[A] ns1.localdomain
  from 192.168.10.2

The program should then mail the whole line to a local user (which can be done manually), doing so indefinitely, while applying the same procedure to any additional information that is added to the log file. The idea is that the program should never exit.

I can run my program without any errors, using ruby name_of_program.rb /var/log/messages, providing tsystemhe path to the log file as an argument. The issue lies in the fact that the program does not fulfill any of the tasks that can otherwise be carried out manually.

My Ruby program:

```<code>open(ARGV.first) do |file|
    file.seek(0, IO::SEEK_END)
    loop do
        changes = file.read
        unless changes.empty?
            if changes =~ /query.*ns1.localdomain/
                cmd "echo Q%DNS_QUERY_TO_WWW -> #{file}Q% | /usr/sbin/sendmail berit"
            end
        end
    end
end
</code>```

Any input as to what I'm missing would be appreciated.

答:
The issue seemed to stem from the system output, which I solved with the following fix.</p>

```<code>open(ARGV.first) do |file|
    file.seek(0, IO::SEEK_END)
    loop do
        changes = file.read
        unless changes.empty?
            if changes =~ /query.*ns1.localdomain/
                system "echo '#{changes}' | /usr/sbin/sendmail berit\n"
            end
        end
    end
end
</code>```

Body:
I have made a Ruby program that should read the end of a Linux log file, as well any additional information that is added to the end of the file during the execution of the script. A regular expression is then used to match specific lines, such as can be seen below.

Mar 31 13:28:05 dns.ns1.local dnsmasq[82093]: query[A] ns1.localdomain
  from 192.168.10.2

The program should then mail the whole line to a local user (which can be done manually), doing so indefinitely, while applying the same procedure to any additional information that is added to the log file. The idea is that the program should never exit.

I can run my program without any errors, using ruby name_of_program.rb /var/log/messages, providing tsystemhe path to the log file as an argument. The issue lies in the fact that the program does not fulfill any of the tasks that can otherwise be carried out manually.

My Ruby program:

open(ARGV.first) do |file|
    file.seek(0, IO::SEEK_END)
    loop do
        changes = file.read
        unless changes.empty?
            if changes =~ /query.*ns1.localdomain/
                cmd "echo Q%DNS_QUERY_TO_WWW -> #{file}Q% | /usr/sbin/sendmail berit"
            end
        end
    end
end

Any input as to what I'm missing would be appreciated.

Body:
The issue seemed to stem from the system output, which I solved with the following fix.

open(ARGV.first) do |file|
    file.seek(0, IO::SEEK_END)
    loop do
        changes = file.read
        unless changes.empty?
            if changes =~ /query.*ns1.localdomain/
                system "echo '#{changes}' | /usr/sbin/sendmail berit\n"
            end
        end
    end
end


问:
How to get the azure account tenant Id?
My question is: Is it possible to get the azure active directory tenant id without using powershell command?

I found this two blogs and with this help, I'm already able to get the tenant ID and subscriptions ID from powershell.  Is it the only way to retrieve the tenant?

Get Windows Azure Active Directory Tenant ID in Windows PowerShell

Windows Azure AD authentication support for PowerShell

Thanks

答:
In PowerShell:</p>

```<code>Add-AzureRmAccount #if not already logged in
Get-AzureRmSubscription -SubscriptionName <SubscriptionName> | Select-Object -Property TenantId
</code>```

Title: How to get the azure account tenant Id?

Body:
In PowerShell:

Add-AzureRmAccount #if not already logged in
Get-AzureRmSubscription -SubscriptionName <SubscriptionName> | Select-Object -Property TenantId


问:
Row or 'Tablename' object in 'Databasename' type * FILE being used
Before a RPG program that update a table (an specific record) this problem appear, How can I fix this for make a regular update in DB2 AS400, because the error message (in the title) delay the update to finally show the message and didn't let me complete the update.</p>

答:
Find out what's locking the table and/or record...

Work with Object Locks (WRKOBJLCK) command


问:
How to build a website?
I have a really really big question which is how to write a social networking website like facebook? I want to know which language should I use and why. And also the relationship of them or the whole structure of website. Only a general idea of blue print will be all right. However I don't mind if u can tell me things in detail. Thanks in advance. </p>

答:
Simply put: You can't realistically without a huge team of experts and lots of money. If you're a full-stack developer I'm sure you can pull off a website that has user profiles and a commenting system just with HTML, CSS, javascript, AJAX, and something like PHP/MySQL on the backend (lots of options here). Facebook is obviously a lot more complicated than that though, especially with all the asynchronous features going on such as the chat system.

Extended answer: https://www.forbes.com/sites/quora/2013/05/20/how-is-a-facebook-like-site-actually-created-from-scratch/#71ee985bdd2d

Title: How to build a website?


问:
Error: Could not find or load main class version
I have downloaded Java on mac mavericks system. But when I type on terminal to see the Java version using  command:

```<code>java version
</code>```

I get the following error

Could not find or load main class version

I went to oracle website and tried a check to see if Java is installed on my system,which confirmed the Java7 is installed on the system. But why can I not see version in terminal?

答:
java -version is the command  to check java version

Download latest Java SE from Oracle site and install it. Then reopen cmd and check java version using java -version.

Set the Java path to bin and check it's version also. Both java and javac should be on same version.

In my case:

C:\Users\darshan>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

C:\Users\darshan>javac -version
javac 1.8.0_121

Body:
I have downloaded Java on mac mavericks system. But when I type on terminal to see the Java version using  command:

java version

I get the following error

Could not find or load main class version

I went to oracle website and tried a check to see if Java is installed on my system,which confirmed the Java7 is installed on the system. But why can I not see version in terminal?


问:
Mysql - Change collation to UFC-8 general-ci (for tables and columns)
By default all my tables and columns are in some weird collation (latin1_swedish_ci). I would like to change them to "utf8_unicode_ci" but as I have 100 tables and many columns I would like to do this with one command. Does anyone know how to do it?</p>

答:
You can run this in PHP:

```<code>$con = mysql_connect('server_name','user_name','password');
mysql_select_db('database_name');
$result = mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
        foreach ($tables as $key => $table_name) {
          mysql_query('alter table $table_name convert to character set utf8 collate utf8_general_ci');
}}
</code>```

Body:
You can run this in PHP:

$con = mysql_connect('server_name','user_name','password');
mysql_select_db('database_name');
$result = mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
        foreach ($tables as $key => $table_name) {
          mysql_query('alter table $table_name convert to character set utf8 collate utf8_general_ci');
}}


问:
Django - jQuery - change() function on DateField()
I have 2 date fields (from_date, to_date) in django admin site for a model.  Whenever the value of 'from_date' changed, I need to add from_date + 10 more days to the to_date field. I have used change() event  of the from_date text box. The problem is that When I choose the date from Date Widget, this change() is not getting called. Any suggestions to deduct this change?

答:
The reason the change event is not fired is because the value is changed programmatically instead of by the user, after which the input field recieves focus. Upon losing focus, the input field detects no changes, as the value is not changed during the time the widget was focussed.

I would suggest using the onBlur() event listener of the TextInput to change the to_date field, which is fired as soon as a input widget loses focus:

```<code>$('.dateinput').blur(function() {
    // Calculate to_date here
})
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The reason the change event is not fired is because the value is changed programmatically instead of by the user, after which the input field recieves focus. Upon losing focus, the input field detects no changes, as the value is not changed during the time the widget was focussed.

I would suggest using the onBlur() event listener of the TextInput to change the to_date field, which is fired as soon as a input widget loses focus:

$('.dateinput').blur(function() {
    // Calculate to_date here
})


问:
Passing table name to a function and returning a table
I need to run the same query on many tables of a DB (PostgreSQL 9.3.5) and passing the table name as an argument to a function seems a logic thing to do. Reading at examples in the docs and numerous S.O. postings, I still cannot nail it down.

Using this minimal example:

```<code>CREATE TABLE films (
code        char(5),
kind        varchar(10)
);
INSERT INTO films VALUES
('UA502', 'Comedy');
</code>```

And this function:

```<code>CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS void AS  -- I know, void is not what I am after
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;
</code>```

The following query catches something:

```<code>mydb=> SELECT foo('films');
 foo
-----
(1 row)
</code>```

However because I want to retrieve a table I edit the second line and re-create the function like so:

```<code>CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS TABLE(count integer) AS
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;
</code>```

However the same query does not catch anything:

```<code>mydb=> SELECT foo('films');
foo
-----
(0 rows)
</code>```

Could someone let me know what I am missing here and how to proceed? Any hints greatly appreciated!

答:
You need dynamic SQL with EXECUTE and you need to escape identifiers properly. You already got that right.

You had problems with how to return values and @klin provides solutions for that.

To pass a table name I suggest to use a regclass parameter. And, for simplicity, an OUT parameter for the result:

```<code>CREATE OR REPLACE FUNCTION f_count_rows(_tbl regclass, OUT _ct bigint)
  RETURNS bigint AS
$func$
BEGIN
   EXECUTE 'SELECT count(*) FROM ' ||  _tbl INTO _ct;
END
$func$  LANGUAGE plpgsql;
</code>```

This way ...

You don't need to escape the table name manually because that's built into the type cast.

Most importantly, you can pass schema-qualified table names like myschema.mytable which would fail if you pass that as text and escape it in the function body with quote_ident(_tbl) or format('... %I' _tbl). Would be interpreted as table name "myschema.mytable". You would have to pass schema and table name separately to make it work.

The OUT parameter is handy because it replaces a variable declaration plus a RETURN command. Otherwise equivalent. When the function reaches end of control the current state of OUT parameters is returned automatically.

Related:

Table name as a PostgreSQL function parameter

To be clear: a RETURN command is only one way of several to return a scalar value from a function. There are others like the one I demonstrate above, and more:

Can I make a plpgsql function return an integer without using a variable?

Body:
I need to run the same query on many tables of a DB (PostgreSQL 9.3.5) and passing the table name as an argument to a function seems a logic thing to do. Reading at examples in the docs and numerous S.O. postings, I still cannot nail it down.

Using this minimal example:

CREATE TABLE films (
code        char(5),
kind        varchar(10)
);
INSERT INTO films VALUES
('UA502', 'Comedy');

And this function:

CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS void AS  -- I know, void is not what I am after
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;

The following query catches something:

mydb=> SELECT foo('films');
 foo
-----
(1 row)

However because I want to retrieve a table I edit the second line and re-create the function like so:

CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS TABLE(count integer) AS
$func$
BEGIN
   EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$  LANGUAGE plpgsql;

However the same query does not catch anything:

mydb=> SELECT foo('films');
foo
-----
(0 rows)

Could someone let me know what I am missing here and how to proceed? Any hints greatly appreciated!

Body:
You need dynamic SQL with EXECUTE and you need to escape identifiers properly. You already got that right.

You had problems with how to return values and @klin provides solutions for that.

To pass a table name I suggest to use a regclass parameter. And, for simplicity, an OUT parameter for the result:

CREATE OR REPLACE FUNCTION f_count_rows(_tbl regclass, OUT _ct bigint)
  RETURNS bigint AS
$func$
BEGIN
   EXECUTE 'SELECT count(*) FROM ' ||  _tbl INTO _ct;
END
$func$  LANGUAGE plpgsql;

This way ...

You don't need to escape the table name manually because that's built into the type cast.

Most importantly, you can pass schema-qualified table names like myschema.mytable which would fail if you pass that as text and escape it in the function body with quote_ident(_tbl) or format('... %I' _tbl). Would be interpreted as table name "myschema.mytable". You would have to pass schema and table name separately to make it work.

The OUT parameter is handy because it replaces a variable declaration plus a RETURN command. Otherwise equivalent. When the function reaches end of control the current state of OUT parameters is returned automatically.

Related:

Table name as a PostgreSQL function parameter

To be clear: a RETURN command is only one way of several to return a scalar value from a function. There are others like the one I demonstrate above, and more:

Can I make a plpgsql function return an integer without using a variable?


问:
2 consiquenced presign post urls to S3 with boto3
I`m trying to generate 2 consequence pressing post urls for posting to S3 using boto3. This urls I return to user to post 2 semantically connected files that have different format.

```<code>full_ecs_xsd_key = 'txn/jackalope/edispec/TPD/local/opikovets/my_test_file_3'

fields = {
    "x-amz-meta-identity-id": user_id,
    "x-amz-server-side-encryption": "AES256"
}
conditions = [
    {"x-amz-meta-identity-id": user_id},
    {"x-amz-server-side-encryption": "AES256"}
]

xsd_key = full_ecs_xsd_key + '.xsd'
pre_signed_xsd_post_url = copy.deepcopy(s3_client.generate_presigned_post(
    bucket_name, xsd_key,
    Fields=fields,
    Conditions=conditions
))

ecs_key = full_ecs_xsd_key + '.ecs'
pre_signed_ecs_post_url = copy.deepcopy(s3_client.generate_presigned_post(
    bucket_name, ecs_key,
    Fields=fields,
    Conditions=conditions
))
</code>```

as a result, I get 2 urls which seems to be working, but I`m not able to post data to the second url (pre_signed_ecs_post_url). Getting an error

```<code><?xml version="1.0" encoding="UTF-8"?>
<Error>
    <Code>AccessDenied</Code>
    <Message>Invalid according to Policy: Policy Condition failed: ["eq", "$key", "txn/jackalope/edispec/TPD/local/opikovets/my_test_file_3.xsd"]</Message>
    <RequestId>1343F7E406E82C1A</RequestId>
    <HostId>wm0U14OouoMkbm0bWIqkYDtP7fgR2A+0Q/Mvhvo9sJ7paaXDiMWfqnjCMR4mc5euPcXCyP3u2/w=</HostId>
</Error>
</code>```

What is confusing here is that key, displayed in the error is actually a key for the first url, not the second one. So, I think that when I call generate_presigned_post for the first time it creates an instance of a class that is also used for creating second url...

But that`s only a guess, and I have no idea how to solve this particular problem

答:
Per @Michael-sqlbot comments, fields and conditions are changing during the generate_presigned_post() execution, so I`ve changed the call to:

```<code>ecs_key = full_ecs_xsd_key + '.ecs'
pre_signed_ecs_post_url = s3_client.generate_presigned_post(
    bucket_name, ecs_key,
    Fields=copy.deepcopy(fields),
    Conditions=copy.deepcopy(conditions)
)

xsd_key = full_ecs_xsd_key + '.xsd'
pre_signed_xsd_post_url = s3_client.generate_presigned_post(
    bucket_name, xsd_key,
    Fields=copy.deepcopy(fields),
    Conditions=copy.deepcopy(conditions)
)
</code>```

and everything worked just fine

Body:
I`m trying to generate 2 consequence pressing post urls for posting to S3 using boto3. This urls I return to user to post 2 semantically connected files that have different format.

full_ecs_xsd_key = 'txn/jackalope/edispec/TPD/local/opikovets/my_test_file_3'

fields = {
    "x-amz-meta-identity-id": user_id,
    "x-amz-server-side-encryption": "AES256"
}
conditions = [
    {"x-amz-meta-identity-id": user_id},
    {"x-amz-server-side-encryption": "AES256"}
]

xsd_key = full_ecs_xsd_key + '.xsd'
pre_signed_xsd_post_url = copy.deepcopy(s3_client.generate_presigned_post(
    bucket_name, xsd_key,
    Fields=fields,
    Conditions=conditions
))

ecs_key = full_ecs_xsd_key + '.ecs'
pre_signed_ecs_post_url = copy.deepcopy(s3_client.generate_presigned_post(
    bucket_name, ecs_key,
    Fields=fields,
    Conditions=conditions
))

as a result, I get 2 urls which seems to be working, but I`m not able to post data to the second url (pre_signed_ecs_post_url). Getting an error

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    AccessDenied
    <Message>Invalid according to Policy: Policy Condition failed: ["eq", "$key", "txn/jackalope/edispec/TPD/local/opikovets/my_test_file_3.xsd"]</Message>
    <RequestId>1343F7E406E82C1A</RequestId>
    <HostId>wm0U14OouoMkbm0bWIqkYDtP7fgR2A+0Q/Mvhvo9sJ7paaXDiMWfqnjCMR4mc5euPcXCyP3u2/w=</HostId>
</Error>

What is confusing here is that key, displayed in the error is actually a key for the first url, not the second one. So, I think that when I call generate_presigned_post for the first time it creates an instance of a class that is also used for creating second url...

But that`s only a guess, and I have no idea how to solve this particular problem

Body:
Per @Michael-sqlbot comments, fields and conditions are changing during the generate_presigned_post() execution, so I`ve changed the call to:

ecs_key = full_ecs_xsd_key + '.ecs'
pre_signed_ecs_post_url = s3_client.generate_presigned_post(
    bucket_name, ecs_key,
    Fields=copy.deepcopy(fields),
    Conditions=copy.deepcopy(conditions)
)

xsd_key = full_ecs_xsd_key + '.xsd'
pre_signed_xsd_post_url = s3_client.generate_presigned_post(
    bucket_name, xsd_key,
    Fields=copy.deepcopy(fields),
    Conditions=copy.deepcopy(conditions)
)

and everything worked just fine


问:
How to create a form at the front end and save data in entities
I created a module in path app/code/Smartshore/Subscription

I want to create a route that displays a form and save data in it. I have the code but I don't know what is missing: Please see the below code:

Smartshore/Subscription/etc/frontend/routes.xml

```<code><?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="subscription" frontName="subscription">
            <module name="Smartshore_Subscription" />
        </route>
    </router>
</config>
</code>```

Smartshore/Subscription/Controller/Index/Index.php

```<code><?php

namespace Smartshore\Subscription\Controller\Index;

use \Magento\Framework\App\Action\Action;

class Index extends Action
{
    /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     */
    public function __construct(\Magento\Framework\App\Action\Context $context,
                                \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Subscription Index, shows a list of subscriptions
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }
}
</code>```

Smartshore/Subscription/Controller/Index/Add.php

```<code><?php

namespace Smartshore\Subscription\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Add extends Action
{
    protected $resultPageFactory;

    public function __construct(Context $context, PageFactory $pageFactory)
    {
        $this->resultPageFactory = $pageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();

        return $resultPage;
    }
}
</code>```

Smartshore/Subscription/Controller/Index/Result.php

```<code><?php

namespace Smartshore\Subscription\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Element\Messages;
use Magento\Framework\View\Result\PageFactory;

class Result extends Action
{
    /** @var PageFactory $resultPageFactory */
    protected $resultPageFactory;

    /**
     * Result constructor.
     * @param Context $context
     * @param PageFactory $pageFactory
     */
    public function __construct(Context $context, PageFactory $pageFactory)
    {
        $this->resultPageFactory = $pageFactory;
        parent::__construct($context);
    }

    /**
     * The controller action
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $number = $this->getRequest()->getParam('number');

        $resultPage = $this->resultPageFactory->create();

        /** @var Messages $messageBlock */
        $messageBlock = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Messages',
            'answer'
        );
        if (is_numeric($number)) {
            $messageBlock->addSuccess($number . ' times 2 is ' . ($number * 2));
        }else{
            $messageBlock->addError('You didn\'t enter a number!');
        }

        $resultPage->getLayout()->setChild(
            'content',
            $messageBlock->getNameInLayout(),
            'answer_alias'
        );

        return $resultPage;
    }
}
</code>```

Smartshore/Subscription/view/frontend/layout/subscription_index_add.xml

```<code><?xml version="1.0"?>
<page layout="2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>New Subscription</title>
    </head>
    <body>
        <referenceBlock name="navigation.sections" remove="true" />
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="subscriptionform.add" template="Smartshore_Subscription::form.phtml"/>
        </referenceContainer>
    </body>
</page>
</code>```

Smartshore/Subscription/view/frontend/layout/subscription_index_result.xml

```<code><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>Result</title>
    </head>
</page>
</code>```

I have other files as well. But I have shown here files respect to my form and its submission.

When I enter /subscription/index/add I get No route found.

What is the problem?

答: Check namespaces in Add and Result files/classes. It should be namespace Smartshore\Subscription\Controller\Index

Body:
I created a module in path app/code/Smartshore/Subscription

I want to create a route that displays a form and save data in it. I have the code but I don't know what is missing: Please see the below code:

Smartshore/Subscription/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="subscription" frontName="subscription">
            <module name="Smartshore_Subscription" />
        </route>
    </router>
</config>

Smartshore/Subscription/Controller/Index/Index.php

<?php

namespace Smartshore\Subscription\Controller\Index;

use \Magento\Framework\App\Action\Action;

class Index extends Action
{
    /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     */
    public function __construct(\Magento\Framework\App\Action\Context $context,
                                \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Subscription Index, shows a list of subscriptions
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
        return $this->resultPageFactory->create();
    }
}

Smartshore/Subscription/Controller/Index/Add.php

<?php

namespace Smartshore\Subscription\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Add extends Action
{
    protected $resultPageFactory;

    public function __construct(Context $context, PageFactory $pageFactory)
    {
        $this->resultPageFactory = $pageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();

        return $resultPage;
    }
}

Smartshore/Subscription/Controller/Index/Result.php

<?php

namespace Smartshore\Subscription\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Element\Messages;
use Magento\Framework\View\Result\PageFactory;

class Result extends Action
{
    /** @var PageFactory $resultPageFactory */
    protected $resultPageFactory;

    /**
     * Result constructor.
     * @param Context $context
     * @param PageFactory $pageFactory
     */
    public function __construct(Context $context, PageFactory $pageFactory)
    {
        $this->resultPageFactory = $pageFactory;
        parent::__construct($context);
    }

    /**
     * The controller action
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $number = $this->getRequest()->getParam('number');

        $resultPage = $this->resultPageFactory->create();

        /** @var Messages $messageBlock */
        $messageBlock = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Messages',
            'answer'
        );
        if (is_numeric($number)) {
            $messageBlock->addSuccess($number . ' times 2 is ' . ($number * 2));
        }else{
            $messageBlock->addError('You didn\'t enter a number!');
        }

        $resultPage->getLayout()->setChild(
            'content',
            $messageBlock->getNameInLayout(),
            'answer_alias'
        );

        return $resultPage;
    }
}

Smartshore/Subscription/view/frontend/layout/subscription_index_add.xml

<?xml version="1.0"?>
<page layout="2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <title>New Subscription</title>

        <referenceBlock name="navigation.sections" remove="true" />
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="subscriptionform.add" template="Smartshore_Subscription::form.phtml"/>
        </referenceContainer>

</page>

Smartshore/Subscription/view/frontend/layout/subscription_index_result.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <title>Result</title>

</page>

I have other files as well. But I have shown here files respect to my form and its submission.

When I enter /subscription/index/add I get No route found.

What is the problem?


问:
how to only sub the last space with dash in R
how to only sub the last space with dash in R? In some cases, there are multi spaces (such as aa), but I'd like to only sub the last space with dash (such as bb). Code is as below:

```<code>aa <- c("Rapamycin 20nM", "Tributyltin chloride 100nM")
bb <- c("Rapamycin_20nM", "Tributyltin chloride_100nM")
</code>```

Thanks.

答:
```<code>sub("(.*) ", "\\1_", aa)
[1] "Rapamycin_20nM"             "Tributyltin chloride_100nM"
</code>```

Some details on the Regular Expression

. matches any character.  .* matches zero or more copies of any character. Putting the .* in parentheses saves the matching material for later use.
Now the whole thing.  (.*) matches any number of characters followed by a blank. Because the matching is "greedy", it goes until the last blank. The string before the blank is saved so that when we write out the replacement,  we just duplicate the stuff before the blank and replace the blank with underscore.

Body:
how to only sub the last space with dash in R? In some cases, there are multi spaces (such as aa), but I'd like to only sub the last space with dash (such as bb). Code is as below:

aa <- c("Rapamycin 20nM", "Tributyltin chloride 100nM")
bb <- c("Rapamycin_20nM", "Tributyltin chloride_100nM")

Thanks.

Body:
sub("(.*) ", "\\1_", aa)
[1] "Rapamycin_20nM"             "Tributyltin chloride_100nM"

Some details on the Regular Expression

. matches any character.  .* matches zero or more copies of any character. Putting the .* in parentheses saves the matching material for later use.
Now the whole thing.  (.*) matches any number of characters followed by a blank. Because the matching is "greedy", it goes until the last blank. The string before the blank is saved so that when we write out the replacement,  we just duplicate the stuff before the blank and replace the blank with underscore.


问:
python sphinx documentation
Can any one tell me how can this  project be used for documentation purpose  http://sphinx.pocoo.org

I have successfully installed it on my CentOS machine .After installation The Readme file says to run sphinx-quickstart and root for documentation is /home/tom/Docs

Where to from here how can i use the commands in /home/tom/Docs i have files
  __build
  conf.py
  index.rst
  make.bat
  Makefile
  _static
  _templates

What next?how to generate reports for my django project which resides in /usr/my-site

答:
Well, you're going to have to do some reading up yourself. However, as a basic overview:

You would usually run sphinx-quickstart in a subfolder of your project for documentation (e.g. /usr/my-site/docs).

You write Sphinx documentation in reStructuredText (rst) format. Start by editing the index.rst file, and you can add more files later.

When you're done, use make html (or make.bat html on Windows) to build the HTML files from your RST.

Title: python sphinx documentation


问:
Is it possible to change the text of selected item in a drop down?
I have a dropdown in which I am displaying items as below:

1             Apple

2              Banana

3              Mango

4              Orange

Now when I select any option, I just want the Number to be displayed not the entire item text. i.e when I select "1    Apple", I just want "1" to be displayed. How do I achieve this?

I've tried changing the text using

```<code> $("#ddlFruits option:selected").text($("#ddlFruits option:selected").text().split(' ')[0])
</code>```

but this also changes the item in dropdown.

答:
First you need to know that the select's value has changed, and in that case, you will have the information of which option has been selected.

Then two things must happen: first you need to make sure that all options return to its original state (where they display the full label), this is because you are going to modify those labels. Secondly, you will go ahead and update the selected option's label simply by selecting the first portion of its value (I choose value just for convenience, but it can very well be the text of the option or an external source).

note that in order to properly split the value of the option, I have to pass in a white space as a parameter to the split function.

$(function() {
  $("#ddlFruits").on('change', function() {
    var $selected = $('option:selected', this);
        $notSelected = $('option:not(:selected)', this);

        $notSelected.each(function(i, option) {
          $(option).text( $(option).val() );
        });
        $selected.text( $selected.val().split(' ')[0] );

  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="ddlFruits" id="ddlFruits">
  <option value="1 Apple">1 Apple</option>
  <option value="2 Banana">2 Banana</option>
  <option value="3 Mango">3 Mango</option>
</select></code>```

Body:
I have a dropdown in which I am displaying items as below:

1             Apple

2              Banana

3              Mango

4              Orange

Now when I select any option, I just want the Number to be displayed not the entire item text. i.e when I select "1    Apple", I just want "1" to be displayed. How do I achieve this?

I've tried changing the text using

 $("#ddlFruits option:selected").text($("#ddlFruits option:selected").text().split(' ')[0])

but this also changes the item in dropdown.

Body:
First you need to know that the select's value has changed, and in that case, you will have the information of which option has been selected.

Then two things must happen: first you need to make sure that all options return to its original state (where they display the full label), this is because you are going to modify those labels. Secondly, you will go ahead and update the selected option's label simply by selecting the first portion of its value (I choose value just for convenience, but it can very well be the text of the option or an external source).

note that in order to properly split the value of the option, I have to pass in a white space as a parameter to the split function.

$(function() {
  $("#ddlFruits").on('change', function() {
    var $selected = $('option:selected', this);
        $notSelected = $('option:not(:selected)', this);

        $notSelected.each(function(i, option) {
          $(option).text( $(option).val() );
        });
        $selected.text( $selected.val().split(' ')[0] );

  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="ddlFruits" id="ddlFruits">
  <option value="1 Apple">1 Apple</option>
  <option value="2 Banana">2 Banana</option>
  <option value="3 Mango">3 Mango</option>
</select>


问:
How to use Box2D allocator?
There are two questions here. First if I need to create b2BlockAllocator before Clone and then delete(where?) after clone? Xcode profiling instrument doesn't show C++ leaks...

```<code>b2FixtureDef fixd = fix->fixture;
const b2Shape *shape = fixd.shape;
if(shape->GetType()== b2Shape::e_polygon && flip)
{
    b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(new b2BlockAllocator());
    for(int i=0;i<ps->m_vertexCount;i++)
    {
        ps->m_vertices[i].x *= -1;
        ps->m_vertices[i].y *= -1;
    }

    ps->Set(&ps->m_vertices[0], ps->m_vertexCount);
    body->CreateFixture(ps, 1.0f);
...
</code>```

In this code I take cached shape object, clone it, modify vertices, set to calculate normals and assigning it object to body. Question - is this legal?

Update:

```<code>-(void) addFixturesToBody:(b2Body*)body forShapeName:(NSString*)shapeName flip:(BOOL)flip
{
    BodyDef *so = [shapeObjects_ objectForKey:shapeName];
    assert(so);

    FixtureDef *fix = so->fixtures;
    while(fix)
    {
        b2FixtureDef fixd = fix->fixture;
        const b2Shape *shape = fixd.shape;
        if(shape->GetType()== b2Shape::e_polygon && flip)
        {
            b2BlockAllocator allocator;
            b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&allocator);
            for(int i=0;i<ps->m_vertexCount;i++)
            {
                ps->m_vertices[i].x *= -1;
                ps->m_vertices[i].y *= -1;
            }

            ps->Set(&ps->m_vertices[0], ps->m_vertexCount);
            body->CreateFixture(ps, 1.0f);
        }
        else
        {
            NSLog(@"noflip...%@", shapeName);
            body->CreateFixture(&fix->fixture);
        }
        fix = fix->next;
    }
}
</code>```

答:
I reply 4 years late while trying to find a similar answer. It seems few people have gone the extra mile with Box2D.

So, you are definitely leaking since new b2BlockAllocator doesn't get deleted anywhere, neither by you nor by the Clone function.

Just create a local b2BlockAllocator so that it will be destroyed when out-of-scope. And that's it.

```<code>    b2BlockAllocator cloneHelper;
    b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&cloneHelper);
</code>```

Title: How to use Box2D allocator?

Body:
There are two questions here. First if I need to create b2BlockAllocator before Clone and then delete(where?) after clone? Xcode profiling instrument doesn't show C++ leaks...

b2FixtureDef fixd = fix->fixture;
const b2Shape *shape = fixd.shape;
if(shape->GetType()== b2Shape::e_polygon && flip)
{
    b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(new b2BlockAllocator());
    for(int i=0;i<ps->m_vertexCount;i++)
    {
        ps->m_vertices[i].x *= -1;
        ps->m_vertices[i].y *= -1;
    }

    ps->Set(&ps->m_vertices[0], ps->m_vertexCount);
    body->CreateFixture(ps, 1.0f);
...

In this code I take cached shape object, clone it, modify vertices, set to calculate normals and assigning it object to body. Question - is this legal?

Update:

-(void) addFixturesToBody:(b2Body*)body forShapeName:(NSString*)shapeName flip:(BOOL)flip
{
    BodyDef *so = [shapeObjects_ objectForKey:shapeName];
    assert(so);

    FixtureDef *fix = so->fixtures;
    while(fix)
    {
        b2FixtureDef fixd = fix->fixture;
        const b2Shape *shape = fixd.shape;
        if(shape->GetType()== b2Shape::e_polygon && flip)
        {
            b2BlockAllocator allocator;
            b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&allocator);
            for(int i=0;i<ps->m_vertexCount;i++)
            {
                ps->m_vertices[i].x *= -1;
                ps->m_vertices[i].y *= -1;
            }

            ps->Set(&ps->m_vertices[0], ps->m_vertexCount);
            body->CreateFixture(ps, 1.0f);
        }
        else
        {
            NSLog(@"noflip...%@", shapeName);
            body->CreateFixture(&fix->fixture);
        }
        fix = fix->next;
    }
}

Body:
I reply 4 years late while trying to find a similar answer. It seems few people have gone the extra mile with Box2D.

So, you are definitely leaking since new b2BlockAllocator doesn't get deleted anywhere, neither by you nor by the Clone function.

Just create a local b2BlockAllocator so that it will be destroyed when out-of-scope. And that's it.

    b2BlockAllocator cloneHelper;
    b2PolygonShape* ps = (b2PolygonShape*)shape->Clone(&cloneHelper);


问:
How to show datetime in Django in specific timezone?
I have a Django (v1.10.6) project that has some models with datetime fields, for example:

```<code>created_at = models.DateTimeField(auto_now_add=True)
</code>```

that are stored in PostgreSQL database without timezone information:

```<code>created_at timestamp without time zone NOT NULL
</code>```

postgresql.conf:

```<code>timezone = 'UTC'
</code>```

I want all the dates of my application to be shown in America/Bogota time zone (it shouldn't depend on user's actual time zone), so my settings.py file has the following configuration:

```<code>TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True

SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'
</code>```

but when I write

```<code>{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}
</code>```

in templates, it still shows the date in UTC format.

Update:

I added the following middleware, but it didn't help:

```<code>class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        timezone.activate(pytz.timezone(settings.TIME_ZONE))
</code>```

Update 2:

It works the following way:

```<code>import pytz
from django.utils import timezone

timezone.is_naive(object.created_at)  # True
object.created_at.replace(tzinfo=timezone.utc)
</code>```

(forcing the date to be in UTC timezone and then passing it to template without localize filter) but I don't understand why Django still returns naive datetime when USE_TZ is set to True.

答:
You need to select the current timezone.

You should set the current time zone to the end user’s actual time zone with activate(). Otherwise, the default time zone is used.

Some relevant extracts from the docs below.

The default time zone is the time zone defined by the TIME_ZONE setting.

The current time zone is the time zone that’s used for rendering.

You should set the current time zone to the end user’s actual time zone with activate(). Otherwise, the default time zone is used.

From: https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#default-time-zone-and-current-time-zone

I recommend having all the datetime's stored internally in UTC so setting TIME_ZONE = 'UTC' in your settings.py and then switching the current timezone to the timezone you wish output to be in. This will make it much easier for you to add further timezones later and will make any date or time arithmetic much easier especially if you have to consier any daylight savings time changes. If you really don't need it maybe it is easier to disable the timezones completely.

Body:
I have a Django (v1.10.6) project that has some models with datetime fields, for example:

created_at = models.DateTimeField(auto_now_add=True)

that are stored in PostgreSQL database without timezone information:

created_at timestamp without time zone NOT NULL

postgresql.conf:

timezone = 'UTC'

I want all the dates of my application to be shown in America/Bogota time zone (it shouldn't depend on user's actual time zone), so my settings.py file has the following configuration:

TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True

SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'

but when I write

{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}

in templates, it still shows the date in UTC format.

Update:

I added the following middleware, but it didn't help:

class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        timezone.activate(pytz.timezone(settings.TIME_ZONE))

Update 2:

It works the following way:

import pytz
from django.utils import timezone

timezone.is_naive(object.created_at)  # True
object.created_at.replace(tzinfo=timezone.utc)

(forcing the date to be in UTC timezone and then passing it to template without localize filter) but I don't understand why Django still returns naive datetime when USE_TZ is set to True.


问:
my google analytics shows data from realtime stream but no hits in standard report

I can see traffics in realtime stream, there are active users on my site.

But I can't see visitor information in standard report.

My site was set up long times ago, and previously data collecting works fine, so it shouldn't be the 'new property not display data within 24 hours' issue.

I did modify my property yesterday, I've added 'referral exclusion' item, and deleted few minutes later.

There're no filters in my view anymore.

No hits collected mostly like happen after I've done item 4(change property).

How can I fix this issue, any ideas?

答:
Did you check your monthly quota? (admin > property settings > property hit volume > last month).

In the free version of GA you've 10 million hits per month per property.(https://developers.google.com/analytics/devguides/collection/analyticsjs/limits-quotas).

Moreover if you send more than 200,000 sessions per day to Analytics will result in the reports being refreshed only once a day. This can delay updates to reports and metrics for up to two days.
(https://support.google.com/analytics/answer/1070983?hl=en)

Maybe one of these conditions is the cause of the issue.


问:
How to configure sandbox security in in Rhino JavaScript engine
I want to interpret html pages scripts, but want to disable any posibility of harming my computer. Is there are any official tutorial or example how to configure such feature? (i dont find it in offcial site)</p>

答: I haven't seen any official example, but see this SO question and particularly this article on sandboxing in Rhino. The article gives a pretty good overview of the things you'll have to set up and guard against.</p>


问:
how can i close the gab between the rows
I have six blocks. I combined the top and bottom and now there is a gap. anyway to move this row up without breaking anything?I would like to know how to solve this issue with bootstrap.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="" crossorigin="anonymous">

                    ss

```

答:
NOTE: This answer was posted before OP changed his question's title....

Keeping the answer simple, you could structure the page like following:

```<code><div>
    <div id="col1"></div>
    <div id="col2"></div>
</div>

<div id="tallBlock">

</div>

<div>
    <div id="col3"></div>
    <div id="col4"></div>
</div>
</code>```

If you use column-count on the top and bottom divs, then they would be split into 2 columns. You should manually set the height on the col divs to ensure they don't try to flow into the second column when they are not post to.

Body:
NOTE: This answer was posted before OP changed his question's title....

Keeping the answer simple, you could structure the page like following:

<div>
    <div id="col1"></div>
    <div id="col2"></div>
</div>

<div id="tallBlock">

</div>

<div>
    <div id="col3"></div>
    <div id="col4"></div>
</div>

If you use column-count on the top and bottom divs, then they would be split into 2 columns. You should manually set the height on the col divs to ensure they don't try to flow into the second column when they are not post to.


问:
Special Routing Plolicy using BGP
Assume I have 2 ASs (AS1, AS2). The topology looks like this.
RA1.1 --- RA2.1 --- RA2.2 where RA1.1 is a router in AS1 and the other 2 routers belong to AS2. There is a eBGP session between RA1.1 and RA2.1 and an iBGP session between RA2.1 and RA2.2.
How can I apply filters in RA1.1 so that I only allow traffic directly generated in RA2.1 but not traffic generated by RA2.2?</p>

答:
The point of ASes (Autonomous Systems) is that they are autonomous. AS1 really has no way to know which BGP speakers in AS2 are advertising which prefixes. AS2 can certainly restrict which prefixes are advertised to AS1, but, normally, AS1 has no idea of the network structure or policies in AS2.

If the two ASes cooperate at a business level, and the administrator of AS2 tells the administrator of AS1 which BGP speakers are advertising which prefixes, then the administrator of AS1 could restrict by prefix, but not by BGP speaker. That could be a mistake because AS2 is free to change its network at any time; it is autonomous from AS1.

In reality, AS1 is only aware of the eBGP peer to which it connects.

Title: Special Routing Plolicy using BGP


问:
C++ append int to wstring
Before(using ASCII) i was using std::string as buffer like this:

```<code>std::string test = "";
int value = 6;
test.append("some string");
test.append((char*)value, 4);
test.append("some string");
</code>```

with expected value in test:

"some srtring\x6\x0\x0\x0somestring"

Now i am tring to use Unicode and i wanna keep the same "code" but trubles happens:

```<code>std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 4); (buffer overflow cause reading 8 bytes)
test.append("some string");
</code>```

How can i append bytes like in std::string?
Doing:

```<code>std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 2);
test.append("some string");
</code>```

Solve partially the problem cause after i can't append bools.

EDIT:
i can even use wstringstream if a binary copy is applied.(normally not)

答:
You're confusing unicode and character encodings. An std::string can represent unicode code points just fine, using the UTF-8 encoding.

Windows uses the UTF-16LE (or UTF-16 with a BOM, I believe) encoding to represent unicode glyphs. Most others use UTF-8.

An std::string which is encoded in UTF-8 and which uses only ASCII characters can actually be interpreted as an ASCII string. This is the beauty of UTF-8. It's a natural extension.

Anyway,

i need a "binary" dynamic buffer, where i can add the real size of types(bool 1, int 4 etc)

An std::vector<uint8_t> is probably more suitable for this task. It communicates that it is not something human-readable, per se. If you need to embed strings into this buffer, make sure that sizeof(char) == sizeof(uint8_t) on the platform, and then just write the data as-is to this buffer.

If you're saving this buffer on one machine and try to read it on another machine, you have to take care of endianness too.

Title: C++ append int to wstring

Body:
Before(using ASCII) i was using std::string as buffer like this:

std::string test = "";
int value = 6;
test.append("some string");
test.append((char*)value, 4);
test.append("some string");

with expected value in test:

"some srtring\x6\x0\x0\x0somestring"

Now i am tring to use Unicode and i wanna keep the same "code" but trubles happens:

std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 4); (buffer overflow cause reading 8 bytes)
test.append("some string");

How can i append bytes like in std::string?
Doing:

std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 2);
test.append("some string");

Solve partially the problem cause after i can't append bools.

EDIT:
i can even use wstringstream if a binary copy is applied.(normally not)


问:
URL in Ajax open()
This is my first Ajax program and I can't fix the code because I'm not sure where/what the problem is.

The error(which I'm unable to interpret) while using the debugger is,
XMLHttpRequest cannot load http://localhost/function.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

```<code>function calling()
{
    var x;
    if (window.XMLHttpRequest) {
    x = new XMLHttpRequest();
    } else {

    x = new ActiveXObject("Microsoft.XMLHTTP");
    }

    x.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200)
        {
            document.getElementById("block").innerHTML = this.responseText;
        }

    };
    x.open("GET", "http://localhost/function.txt",true);
    x.send();
}
</code>```

function.txt

```<code><html>
<head></head>
<body>
<h2>Ajax is working</h2>
</body>
</html>
</code>```

答: You are attempting a CORS request, which is unsafe and is prohibited by browsers by default. If you are in control of the target site, you can enable CORS. If that's not the case, then you will need to write a page which will be used as a proxy, that is, you will send the request to this page instead of the target site's page. The page, on its turn will send the request to the target page and send the output to the browser. While this is a workable solution you will need to make sure that all the absolute paths of the target site are handled well.</p>

Title: URL in Ajax open()

Body:
This is my first Ajax program and I can't fix the code because I'm not sure where/what the problem is.

The error(which I'm unable to interpret) while using the debugger is,
XMLHttpRequest cannot load http://localhost/function.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

function calling()
{
    var x;
    if (window.XMLHttpRequest) {
    x = new XMLHttpRequest();
    } else {

    x = new ActiveXObject("Microsoft.XMLHTTP");
    }

    x.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200)
        {
            document.getElementById("block").innerHTML = this.responseText;
        }

    };
    x.open("GET", "http://localhost/function.txt",true);
    x.send();
}

function.txt

Ajax is working


问:
Moodle event observer not triggered in local plugin
I have created a plugin at this location moodle/local/redirectafterlogin with the following structure :

```<code>redirectafterlogin/
├── db
│   ├── classes
│   │   └── observer.php
│   └── events
│       └── events.php
└── version.php
</code>```

version.php:

```<code>defined('MOODLE_INTERNAL') || die();

$plugin->version = 20170333;
$plugin->requires = 2015111000;
$plugin->component = 'local_redirectafterlogin';
</code>```

events.php:

```<code>defined('MOODLE_INTERNAL') || die();

    $observers = array(
        array(
            'eventname' => 'core\event\user_loggedin',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
        array(
            'eventname' => 'core\event\user_loggedout',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
    );
</code>```

observer.php:

```<code>class local_redirectafterlogin_observer
{
    public static function user_loggedin(core\event\base $event)
    {
        $event_data = $event->get_data();
        var_dump($event_data);
        die();
    }
}
</code>```

Cached has been cleared a lot of time and version number has been bumped too but the callback is never called!

What's wrong, why does the callback is not triggered?

How can I debug events (is there a way in Moodle to see dispatched events)?

答:
I don't think the automatic class loading will be able to find your observer class.

Try adding to the top of the observer class file:

```<code>namespace local_redirectafterlogin;
</code>```

Then change the events.php to:

```<code>'callback' => 'local_redirectafterlogin\local_redirectafterlogin_observer'
</code>```

(You could also greatly shorten the class name, now it is namespaced). Make sure you bump the version number, to reload the events.php file.

You may want to reconsider the naming of your plugin, though, as redirection is not allowed from within an event handler, as that would cause a great many problems.

Body:
I have created a plugin at this location moodle/local/redirectafterlogin with the following structure :

redirectafterlogin/
├── db
│   ├── classes
│   │   └── observer.php
│   └── events
│       └── events.php
└── version.php

version.php:

defined('MOODLE_INTERNAL') || die();

$plugin->version = 20170333;
$plugin->requires = 2015111000;
$plugin->component = 'local_redirectafterlogin';

events.php:

defined('MOODLE_INTERNAL') || die();

    $observers = array(
        array(
            'eventname' => 'core\event\user_loggedin',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
        array(
            'eventname' => 'core\event\user_loggedout',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
    );

observer.php:

class local_redirectafterlogin_observer
{
    public static function user_loggedin(core\event\base $event)
    {
        $event_data = $event->get_data();
        var_dump($event_data);
        die();
    }
}

Cached has been cleared a lot of time and version number has been bumped too but the callback is never called!

What's wrong, why does the callback is not triggered?

How can I debug events (is there a way in Moodle to see dispatched events)?

Body:
I don't think the automatic class loading will be able to find your observer class.

Try adding to the top of the observer class file:

namespace local_redirectafterlogin;

Then change the events.php to:

'callback' => 'local_redirectafterlogin\local_redirectafterlogin_observer'

(You could also greatly shorten the class name, now it is namespaced). Make sure you bump the version number, to reload the events.php file.

You may want to reconsider the naming of your plugin, though, as redirection is not allowed from within an event handler, as that would cause a great many problems.


问:
URL Param rewrite in node express
Whenever a tag is submitted with spaces, the spaces show up as %20 in the response. How would I rewrite each space so in either the request and response it can be a dash? Are there any reliable library's for this? Thanks!

Route

```<code> router.get('/search/:tag', function(req, res) {
      const tag = req.params.tag;
      tag.toLowerCase();
      shopify.article.list(86289414)
      .then(function (response) {
        response.reverse();

        response = response.map(function(element) {
            return {
              author: element.author,
              blog_id: element.blog_id,
              body_html: element.body_html,
              created_at: element.created_at,
              handle: element.handle,
              id: element.id,
              image: element.image,
              published_at: element.published_at,
              summary_html: element.summary_html,
              tags: element.tags.toString().toLowerCase(),
              template_suffix: element.template_suffix,
              title: element.title,
              updated_at: element.updated_at,
              user_id: element.user_id
            }
        })

        response = response.filter(function(item) {
         return item.tags.indexOf(tag) > -1;
       });

        var data = {
          articles: response.map((article) => {
            return {
              author: article.author,
              id: article.id,
              html: article.body_html,
              tags: article.tags.split(","),
              date: moment(article.published_at).format("Do MMM YYYY"),
              slug: article.handle,
              title: article.title,
            } // return
          }) // map
        } // data

          console.log(data);
          res.render('blog-tags' , data);

      }) // then
        .catch(err => console.log(err) )
    });
</code>```

答:
First of all this will not do what you expect:

```<code>tag.toLowerCase();
</code>```

You need to use:

```<code>tag = tag.toLowerCase();
</code>```

if you want the value in the tag variable to change.

That is because strings in JavaScript are immutable and no operation can change a string, you can only replace the values of variables with new strings. And methods like .toLowerCase() always return a new string.

Now, if your variable already contains '%20' etc. then you need to use:

```<code>tag = decodeURIComponent(tag);
</code>```

but note that this is likely to already be handled by the framework.

Now, to change spaces to underscores, use:

```<code>tag = tag.replace(/ /g, '_');
</code>```

You can combine all of that as:

```<code>tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_');
</code>```

Or this if your variable already contains decoded string:

```<code>tag = tag.toLowerCase().replace(/ /g, '_');
</code>```

Example:

```<code>let tag = 'Aaa%20BbB%20cCC';
tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_');
console.log(tag);
// prints: aaa_bbb_ccc
</code>```

Title: URL Param rewrite in node express

Body:
Whenever a tag is submitted with spaces, the spaces show up as %20 in the response. How would I rewrite each space so in either the request and response it can be a dash? Are there any reliable library's for this? Thanks!

Route

 router.get('/search/:tag', function(req, res) {
      const tag = req.params.tag;
      tag.toLowerCase();
      shopify.article.list(86289414)
      .then(function (response) {
        response.reverse();

        response = response.map(function(element) {
            return {
              author: element.author,
              blog_id: element.blog_id,
              body_html: element.body_html,
              created_at: element.created_at,
              handle: element.handle,
              id: element.id,
              image: element.image,
              published_at: element.published_at,
              summary_html: element.summary_html,
              tags: element.tags.toString().toLowerCase(),
              template_suffix: element.template_suffix,
              title: element.title,
              updated_at: element.updated_at,
              user_id: element.user_id
            }
        })

        response = response.filter(function(item) {
         return item.tags.indexOf(tag) > -1;
       });

        var data = {
          articles: response.map((article) => {
            return {
              author: article.author,
              id: article.id,
              html: article.body_html,
              tags: article.tags.split(","),
              date: moment(article.published_at).format("Do MMM YYYY"),
              slug: article.handle,
              title: article.title,
            } // return
          }) // map
        } // data

          console.log(data);
          res.render('blog-tags' , data);

      }) // then
        .catch(err => console.log(err) )
    });

Body:
First of all this will not do what you expect:

tag.toLowerCase();

You need to use:

tag = tag.toLowerCase();

if you want the value in the tag variable to change.

That is because strings in JavaScript are immutable and no operation can change a string, you can only replace the values of variables with new strings. And methods like .toLowerCase() always return a new string.

Now, if your variable already contains '%20' etc. then you need to use:

tag = decodeURIComponent(tag);

but note that this is likely to already be handled by the framework.

Now, to change spaces to underscores, use:

tag = tag.replace(/ /g, '_');

You can combine all of that as:

tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_');

Or this if your variable already contains decoded string:

tag = tag.toLowerCase().replace(/ /g, '_');

Example:

let tag = 'Aaa%20BbB%20cCC';
tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_');
console.log(tag);
// prints: aaa_bbb_ccc


问:
Should a MMORPG use encryption?
First of all,
do those successful commercial MMORPGs use encryption for game data transmission?

I got an impression that many developers tend to not use encryption, because it can not prevent reverse engineering for cheating and making private server, but doesn't it effectively reduce the number of those?

Encryption also impacts performance, even just a little.

Good encryption does prevent network sniffering and man-in-the-middle, are these important for MMORPGs?

How about protecting chat messages for privacy concerns?

How do you think?

PS: I'm talking about game data, not user/password, auth info need to be encrypted for sure.

答:
You don't need encryption for security per se.

Consider this 'packet':

```<code><USER_ID><COMMAND><MD5HASH>
</code>```

The MD5HASH is generated from the USER_ID + COMMAND + some other value both the server and client know, but is not transmitted over the wire (user email or some token supplied securely during login). The server can reconstruct the string used for hashing and verify the authenticity of the command. If some man-in-the-middle changes the COMMAND, the hash won't match.

Besides validating authenticity this method also allows you to check you received the entire instruction. (It's possible that your 'game packet' is spread across multiple TCP/IP packets, some might get lost, etc.)

This does not prevent snooping around in messages, but is does prevent tampering. It's a game, who cares about what players say? I mean, emails are unencrypted and nobody cares about those, while their contents is more valuable than the average in-game chat.

Title: Should a MMORPG use encryption?

Body:
You don't need encryption for security per se.

Consider this 'packet':

<USER_ID><COMMAND><MD5HASH>

The MD5HASH is generated from the USER_ID + COMMAND + some other value both the server and client know, but is not transmitted over the wire (user email or some token supplied securely during login). The server can reconstruct the string used for hashing and verify the authenticity of the command. If some man-in-the-middle changes the COMMAND, the hash won't match.

Besides validating authenticity this method also allows you to check you received the entire instruction. (It's possible that your 'game packet' is spread across multiple TCP/IP packets, some might get lost, etc.)

This does not prevent snooping around in messages, but is does prevent tampering. It's a game, who cares about what players say? I mean, emails are unencrypted and nobody cares about those, while their contents is more valuable than the average in-game chat.


问:
Arcball Implementation Dependency on View Plane
I have a perfectly working fine Arcball implementation. Usually in opengl the standard camera is facing -Z, meaning XY plane is parallel to the viewing plane.

```<code>glm::vec3 Arcball::_plane2sphere(glm::vec2 &v)
{
glm::vec2         f = v;
glm::vec3         r;
double            lenSquared;
double            len;

  f         /= _radius;
  lenSquared = f.x * f.x + f.y * f.y;
  len        = sqrt(lenSquared);

  if (lenSquared > 1.0)
  {
    r = glm::vec3(f.x / len,f.y / len, 0.0f );
  }

  else
  {
    double fz = sqrt(1 - lenSquared);

      r                 = glm::vec3(f.x, f.y, fz);
  }
  return r;
}
</code>```

Now if I change my camera to face -Y, meaning XZ is parallel to the viewing plane, the same arcball implementation doesnt hold good. I had to change my arcball implementation as follows. The 'Y's taking place of 'Z's and vice versa.

```<code>glm::vec3 Arcball::_plane2sphere(glm::vec2 &v)
{
glm::vec2         f = v;
glm::vec3         r;
double            lenSquared;
double            len;

  f         /= _radius;
  lenSquared = f.x * f.x + f.y * f.y;
  len        = sqrt(lenSquared);

  if (lenSquared > 1.0)
  {
    r = glm::vec3(f.x / len, 0.0f, f.y / len);
  }

  else
  {
    double fz = sqrt(1 - lenSquared);

      r                 = glm::vec3(f.x, fz, f.y);
  }
  return r;
}
</code>```

While this does make sense to me, I was wondering what if I had a very arbitrary camera. When I have an arbitrary camera, the rotations to my object are not intuitive.

Any help is appreciated!
Thanks!

答:
Your arcball code computes on NDC space, whose axis are parallel to Camera space axis. The computed rotation can be applied directly on Camera space, before projecting into NDC.

If you want to rotate the camera, then you need to convert the axis of rotation to World space.

Notice that all of above applies whatever camera position and orientation are. So, your second version is a way to get rotation in World space for that particular camera orientation. For an arbitrary camera, use matrix transformation from Camera to World.

Body:
I have a perfectly working fine Arcball implementation. Usually in opengl the standard camera is facing -Z, meaning XY plane is parallel to the viewing plane.

glm::vec3 Arcball::_plane2sphere(glm::vec2 &v)
{
glm::vec2         f = v;
glm::vec3         r;
double            lenSquared;
double            len;

  f         /= _radius;
  lenSquared = f.x * f.x + f.y * f.y;
  len        = sqrt(lenSquared);

  if (lenSquared > 1.0)
  {
    r = glm::vec3(f.x / len,f.y / len, 0.0f );
  }

  else
  {
    double fz = sqrt(1 - lenSquared);

      r                 = glm::vec3(f.x, f.y, fz);
  }
  return r;
}

Now if I change my camera to face -Y, meaning XZ is parallel to the viewing plane, the same arcball implementation doesnt hold good. I had to change my arcball implementation as follows. The 'Y's taking place of 'Z's and vice versa.

glm::vec3 Arcball::_plane2sphere(glm::vec2 &v)
{
glm::vec2         f = v;
glm::vec3         r;
double            lenSquared;
double            len;

  f         /= _radius;
  lenSquared = f.x * f.x + f.y * f.y;
  len        = sqrt(lenSquared);

  if (lenSquared > 1.0)
  {
    r = glm::vec3(f.x / len, 0.0f, f.y / len);
  }

  else
  {
    double fz = sqrt(1 - lenSquared);

      r                 = glm::vec3(f.x, fz, f.y);
  }
  return r;
}

While this does make sense to me, I was wondering what if I had a very arbitrary camera. When I have an arbitrary camera, the rotations to my object are not intuitive.

Any help is appreciated!
Thanks!


问:
how to compile and run vuforia sample code for iOS
I have download the Vuforia SDK and Sample Code from given website but it is giving

<QCAR/QCAR.h> file not found

http://www.qualcomm.com/solutions/augmented-reality

答:
For folks like me, who still had issue after adding samples to the SDK folder, pls use the below. The solution was mentioned in the vuforia developer forums(https://developer.vuforia.com/forum/ios/getting-error-lexical-or-prepocessor-issue-qcartoolh) and it helped fix the problem for me.

Step 1:

Copying the build folder (containing the include, lib folders within) in the Project directory.

Step 2:

Link the 'libVuforia.a' to your local build folder copied in the project directory.

Step 3:

and updating the Build Settings for the keys below.

a)  Header Search Paths  =  $(PROJECT_DIR)/build/include

b)  Library Search Paths  =  $(PROJECT_DIR)/build/lib/arm


问:
Linker error when including header in files other than main.cpp
I'm trying to add some utility functions and global variables to my code in such a way that I can be able to use them in every class I want in my project. I would like to use a .hpp file for the definitions end a .cpp file for the implementation.

This is a summary of these two files:

```<code>// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp

namespace utils {

    int global_variable1;

    int global_variable2;

    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */
</code>```

and the implementation:

```<code>// This is Utilities.cpp
#include "Utilities.hpp"

namespace utils {

    void utility_function1(...) {
        // Some code
    }

    void utility_function2(...) {
        // Some code
    }

    void utility_function3(...) {
        // Some code
    }

}
</code>```

Other than my main.cpp file I have two other classes. My main.cpp file includes Class1.hpp header that includes Class2.hpp header.

Now I thought that I could put another #include "Utilities.hpp" in Class1.hpp or Class2.hpp without any problems since I've used the guards in that header. The thing is that when I try to do that the linker throws me this error: Apple Mach-O Linker (ld) Error Group - clang: error: linker command failed with exit code 1 (use -v to see invocation) and I can't understand why or what to do to solve it.

I'm using Xcode 8.3 on a macOS Sierra 10.12.4.

I hope I was able to explain my problem, thank you all very much in advance.

答:
You've violated the One Definition Rule.  global_variable1 and global_variable2 should be declared extern in your header and defined in exactly one translation unit (probably Utilities.cpp).

You've defined global variables in a header that gets included in multiple translation units, so there's a utils::global_variable1 defined in main.cpp, and one in Utilities.cpp.  When it comes to link time, the linker has no way to know which global_variable1 to use, so it throws an error.

To fix it, add the extern keyword to your declarations and add a definition in "Utilities.cpp":

Utilities.hpp:

```<code>// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp

namespace utils {

    extern int global_variable1;
  //^^^^^^ <-----HERE
    extern int global_variable2;
  //^^^^^^ <-----HERE
    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */
</code>```

Utilities.cpp:

```<code>// This is Utilities.cpp
#include "Utilities.hpp"

namespace utils {

    int global_variable1;  //<---- Definitions added
    int global_variable2;

    void utility_function1(...) {
        // Some code
    }

    void utility_function2(...) {
        // Some code
    }

    void utility_function3(...) {
        // Some code
    }
}
</code>```

Body:
I'm trying to add some utility functions and global variables to my code in such a way that I can be able to use them in every class I want in my project. I would like to use a .hpp file for the definitions end a .cpp file for the implementation.

This is a summary of these two files:

// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp

namespace utils {

    int global_variable1;

    int global_variable2;

    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */

and the implementation:

// This is Utilities.cpp
#include "Utilities.hpp"

namespace utils {

    void utility_function1(...) {
        // Some code
    }

    void utility_function2(...) {
        // Some code
    }

    void utility_function3(...) {
        // Some code
    }

}

Other than my main.cpp file I have two other classes. My main.cpp file includes Class1.hpp header that includes Class2.hpp header.

Now I thought that I could put another #include "Utilities.hpp" in Class1.hpp or Class2.hpp without any problems since I've used the guards in that header. The thing is that when I try to do that the linker throws me this error: Apple Mach-O Linker (ld) Error Group - clang: error: linker command failed with exit code 1 (use -v to see invocation) and I can't understand why or what to do to solve it.

I'm using Xcode 8.3 on a macOS Sierra 10.12.4.

I hope I was able to explain my problem, thank you all very much in advance.

Body:
You've violated the One Definition Rule.  global_variable1 and global_variable2 should be declared extern in your header and defined in exactly one translation unit (probably Utilities.cpp).

You've defined global variables in a header that gets included in multiple translation units, so there's a utils::global_variable1 defined in main.cpp, and one in Utilities.cpp.  When it comes to link time, the linker has no way to know which global_variable1 to use, so it throws an error.

To fix it, add the extern keyword to your declarations and add a definition in "Utilities.cpp":

Utilities.hpp:

// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp

namespace utils {

    extern int global_variable1;
  //^^^^^^ <-----HERE
    extern int global_variable2;
  //^^^^^^ <-----HERE
    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */

Utilities.cpp:

// This is Utilities.cpp
#include "Utilities.hpp"

namespace utils {

    int global_variable1;  //<---- Definitions added
    int global_variable2;

    void utility_function1(...) {
        // Some code
    }

    void utility_function2(...) {
        // Some code
    }

    void utility_function3(...) {
        // Some code
    }
}