问:
Using <q> element when referring to elements of a page in text
In a web app's help/instructions and error message we often need to refer to parts of a page.

Example: Enter your message in the "body" field.

Example: The "body" field's content cannot exceed 250 characters

Question: in terms of html markup, would it make sense to use the <q> element for the "body" word above? What would be the semantically correct markup to use?

```<code>Enter your message in the <q>body</q> field.
The <q>body</q> field's content cannot exceed 250 characters
</code>```

Looking for opinions, suggestions.

Notes:

Don't care about the use of quotation marks, I want something that is semantically correct, i.e. it give the right meaning.

Would like a simple tag that a tech writer/translator could easily deal with.

Would like to avoid body as it is long and give no semantic meaning to its contents.

Found this:

When referring to a word’s form rather than its meaning, use quotation marks to draw the reader’s attention

  http://termiumplus.gc.ca/tcdnstyl-chap?lang=fra&lettr=chapsect8&info0=8.11#zz8

Conclusion

Going to go with the good old body. I guess I was wishing for an html tag for something like "text references". Thanks for the feedback.

Marc

答:
Personally, if you're referring to an input field, I'd suggest using a label element:

```<code><span class="errorMessage">Please enter information in the <label for="body">body</label> field.</span>
<!-- other content -->

<label for="body">body</label>
<input type="text" id="body" name="body" />
</code>```

I'm not sure, but I get the impression that you considered using a q because you were using quotes as an aesthetic/presentational choice, but it's not a quote, which removes the semantic argument for using a q element. If you want to use quotes, you can use CSS:

```<code>.errorMessage label:before,
.errorMessage label:after {
    content: '"';
}
</code>```

Body:
In a web app's help/instructions and error message we often need to refer to parts of a page.

Example: Enter your message in the "body" field.

Example: The "body" field's content cannot exceed 250 characters

Question: in terms of html markup, would it make sense to use the <q> element for the "body" word above? What would be the semantically correct markup to use?

Enter your message in the <q>body</q> field.
The <q>body</q> field's content cannot exceed 250 characters

Looking for opinions, suggestions.

Notes:

Don't care about the use of quotation marks, I want something that is semantically correct, i.e. it give the right meaning.

Would like a simple tag that a tech writer/translator could easily deal with.

Would like to avoid body as it is long and give no semantic meaning to its contents.

Found this:

When referring to a word’s form rather than its meaning, use quotation marks to draw the reader’s attention

  http://termiumplus.gc.ca/tcdnstyl-chap?lang=fra&lettr=chapsect8&info0=8.11#zz8

Conclusion

Going to go with the good old body. I guess I was wishing for an html tag for something like "text references". Thanks for the feedback.

Marc

Body:
Personally, if you're referring to an input field, I'd suggest using a label element:

<span class="errorMessage">Please enter information in the <label for="body">body</label> field.</span>
<!-- other content -->

<label for="body">body</label>
<input type="text" id="body" name="body" />

I'm not sure, but I get the impression that you considered using a q because you were using quotes as an aesthetic/presentational choice, but it's not a quote, which removes the semantic argument for using a q element. If you want to use quotes, you can use CSS:

.errorMessage label:before,
.errorMessage label:after {
    content: '"';
}


来源: stackexchange

问:
C pointer to another struct
i'm currently reading some source codes for packet sending. For the following pseudo code, for the line "packet->packet2 = (char*) data", what does it mean actually? Can i understand as storing the character datatype in variable data into packet2, which is also defined as a character datatype?</p>

```<code>struct Node1
{
    char packet1;
    int num1;
}

struct Node2
{
   char *packet2;
   int num2;
}

int main(void)
{
   struct Node1 *data;
   struct Node1 var1;

   struct Node2 *packet;
   struct node2 var2;

   data = &var1;
   packet = &var2;

   packet->packet2 = (char*) data;
}
</code>```

答:
packet2 is of type char you can not put a pointer in to this field of the structure.Char variable can't hold a pointer.You have to change packet2 from type char to type char*.
This will mean that you can use each byte separately since dereferencing a char poiner gives you a byte.

```<code>packet2[0]
</code>```

will give you acces to the first byte of the var1 structure.
It's important to note that when you are doing such things you have to be very careful becouse there might be padding bytes.For such cases you can use the macro offsetof.

```<code>packet->packet2[0] = 5;
</code>```

will be equivalent to

```<code>var1.packet1 = 5;
</code>```

ContentLicense: CC BY-SA 3.0

Title: C pointer to another struct

Body:
i'm currently reading some source codes for packet sending. For the following pseudo code, for the line "packet->packet2 = (char*) data", what does it mean actually? Can i understand as storing the character datatype in variable data into packet2, which is also defined as a character datatype?

struct Node1
{
    char packet1;
    int num1;
}

struct Node2
{
   char *packet2;
   int num2;
}

int main(void)
{
   struct Node1 *data;
   struct Node1 var1;

   struct Node2 *packet;
   struct node2 var2;

   data = &var1;
   packet = &var2;

   packet->packet2 = (char*) data;
}

Body:
packet2 is of type char you can not put a pointer in to this field of the structure.Char variable can't hold a pointer.You have to change packet2 from type char to type char*.
This will mean that you can use each byte separately since dereferencing a char poiner gives you a byte.

packet2[0]

will give you acces to the first byte of the var1 structure.
It's important to note that when you are doing such things you have to be very careful becouse there might be padding bytes.For such cases you can use the macro offsetof.

packet->packet2[0] = 5;

will be equivalent to

var1.packet1 = 5;


问:
Returning value after several Runnable finish
Currently I have a code as follow :

```<code>public String getValue()
{
   StringBuilder builder = new StringBuilder();
   // 1st step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString1);
   // 2nd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString2);
   // 3rd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString3);

   return builder.toString();
}
</code>```

I've read about Runnable object that can be used to split process into several thread, which going change my code into something like this :

```<code>public String getValue()
{
     Thread firstTread = new Thread(new Process1());
     firstTread.start();
     Thread secondTread = new Thread(new Process1());
     secondTread.start();
     Thread thirdTread = new Thread(new Process1());
     thirdTread.start();

     // here i got confuse how to determine whether all thread allready finished
     // before returning builder.toString();
}
//this is internal class
class Process1 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process2 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process3 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}
</code>```

How can I achieve that my goal to split the process into several thread?

答:
What you are looking for is not Runnable, but a Callable. Unlike Runnable, a Callable returns a value. This is usually used together with ExecutorService (a thread pool).

It is always good to maintain your threads inside a thread pool instead of manually spawning them like that. This prevents unnecessary and expensive creation of threads. The idea is, instead of calling Thread.start(), you submit the instaces of Callable to your ExecutorService instance with predefined number of threads. Each submission returns a Future object. Future object allows you to wait for the return value of the Callable instances you have submitted to the ExecutorService.

Here is revised version of your original code:

```<code>class Process1 implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "Some string from this callable";
    }
}
// Insert implementation for Process2 and Process2 Callables
   ...

public static void main(String[] args) throws Exception {
   ExecutorService executor = Executors.newFixedThreadPool(3);

   Future<String> process1Future = executor.submit(new Process1());
   Future<String> process2Future = executor.submit(new Process2());
   Future<String> process3Future = executor.submit(new Process3());

   // It will wait here
   String processedStringByProcess1 = process1Future.get();
   String processedStringByProcess2 = process2Future.get();
   String processedStringByProcess3 = process3Future.get();

   StringBuilder builder = new StringBuilder();
   builder.append(processedStringByProcess1);
   builder.append(processedStringByProcess2);
   builder.append(processedStringByProcess3);

   System.out.println(builder.toString());
}
</code>```

Body:
Currently I have a code as follow :

public String getValue()
{
   StringBuilder builder = new StringBuilder();
   // 1st step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString1);
   // 2nd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString2);
   // 3rd step
   //some logic to retreive code from database returning value
   //doing something with the returned value add it to collection
   builder.append(someString3);

   return builder.toString();
}

I've read about Runnable object that can be used to split process into several thread, which going change my code into something like this :

public String getValue()
{
     Thread firstTread = new Thread(new Process1());
     firstTread.start();
     Thread secondTread = new Thread(new Process1());
     secondTread.start();
     Thread thirdTread = new Thread(new Process1());
     thirdTread.start();

     // here i got confuse how to determine whether all thread allready finished
     // before returning builder.toString();
}
//this is internal class
class Process1 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process2 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

class Process3 implements Runnable
{
    public void run()
    {
      //do something and add to StringBuilder
    }
}

How can I achieve that my goal to split the process into several thread?

Body:
What you are looking for is not Runnable, but a Callable. Unlike Runnable, a Callable returns a value. This is usually used together with ExecutorService (a thread pool).

It is always good to maintain your threads inside a thread pool instead of manually spawning them like that. This prevents unnecessary and expensive creation of threads. The idea is, instead of calling Thread.start(), you submit the instaces of Callable to your ExecutorService instance with predefined number of threads. Each submission returns a Future object. Future object allows you to wait for the return value of the Callable instances you have submitted to the ExecutorService.

Here is revised version of your original code:

class Process1 implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "Some string from this callable";
    }
}
// Insert implementation for Process2 and Process2 Callables
   ...

public static void main(String[] args) throws Exception {
   ExecutorService executor = Executors.newFixedThreadPool(3);

   Future<String> process1Future = executor.submit(new Process1());
   Future<String> process2Future = executor.submit(new Process2());
   Future<String> process3Future = executor.submit(new Process3());

   // It will wait here
   String processedStringByProcess1 = process1Future.get();
   String processedStringByProcess2 = process2Future.get();
   String processedStringByProcess3 = process3Future.get();

   StringBuilder builder = new StringBuilder();
   builder.append(processedStringByProcess1);
   builder.append(processedStringByProcess2);
   builder.append(processedStringByProcess3);

   System.out.println(builder.toString());
}


问:
unable to build new java spring project
i am trying to build a simple java spring project i got setup which contains my hibernate .hbm mappings, the POJO'S that go with each mappings and one SimpleFormController class that looks like this:

```<code>package com.jr.user.controller;

import org.springframework.web.portlet.mvc.SimpleFormController;

public class RegisterNewUser extends SimpleFormController{

}
</code>```

Its empty as you can see but when i try to build it i get the following error below:

BUILD FAILED
  C:\Users\xxxxxxxxxxxxx\Work\Online
  Racing League\build.xml:45: Unable to
  find a javac compiler;
  com.sun.tools.javac.Main is not on the
  classpath. Perhaps JAVA_HOME does not
  point to the JDK. It is currently set

to "C:\Program Files (x86)\Java\jre6"

Total time: 237 milliseconds

Also, whats weird is that the package line on the above code is highlighted in a red underline indicating a syntax or code error and when i mouse over to that line, this is what it says:

The type javax.portlet.PortletContext
  cannot be resolved. It is indirectly
  referenced from required .class files

My build.xml looks like this:

```<code><?xml version="1.0"?>

<project name="Online Racing League" basedir="." default="usage">
    <property file="build.properties"/>

    <property name="src.dir" value="src"/>
    <property name="web.dir" value="war"/>
    <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
    <property name="name" value="Online Racing League"/>

    <path id="master-classpath">
        <fileset dir="${web.dir}/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>
        <!-- We need the servlet API classes: -->
        <!--  * for Tomcat 5/6 use servlet-api.jar -->
        <!--  * for other app servers - check the docs -->
        <fileset dir="${appserver.lib}">
            <include name="servlet*.jar"/>
        </fileset>
        <pathelement path="${build.dir}"/>
    </path>

    <target name="usage">
        <echo message=""/>
        <echo message="${name} build file"/>
        <echo message="-----------------------------------"/>
        <echo message=""/>
        <echo message="Available targets are:"/>
        <echo message=""/>
        <echo message="build     --> Build the application"/>
        <echo message="deploy    --> Deploy application as directory"/>
        <echo message="deploywar --> Deploy application as a WAR file"/>
        <echo message="install   --> Install application in Tomcat"/>
        <echo message="reload    --> Reload application in Tomcat"/>
        <echo message="start     --> Start Tomcat application"/>
        <echo message="stop      --> Stop Tomcat application"/>
        <echo message="list      --> List Tomcat applications"/>
        <echo message=""/>
    </target>

    <target name="build" description="Compile main source tree java files">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"
               deprecation="false" optimize="false" failonerror="true">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>
        </javac>
    </target>

    <target name="deploy" depends="build" description="Deploy application">
        <copy todir="${deploy.path}/${name}" preservelastmodified="true">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </copy>
    </target>

    <target name="deploywar" depends="build" description="Deploy application as a WAR file">
        <war destfile="${deploy.path}/${name}.war"
             webxml="${web.dir}/WEB-INF/web.xml">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </war>
        <copy todir="${deploy.path}" preservelastmodified="true">
            <fileset dir=".">
                <include name="*.war"/>
            </fileset>
        </copy>
    </target>

    <!-- ============================================================== -->
    <!-- Tomcat tasks - remove these if you don't have Tomcat installed -->
    <!-- ============================================================== -->

        <path id="catalina-ant-classpath">
            <!-- We need the Catalina jars for Tomcat -->
            <!--  * for other app servers - check the docs -->
            <fileset dir="${appserver.lib}">
                <include name="catalina-ant.jar"/>
            </fileset>
        </path>

        <taskdef name="install" classname="org.apache.catalina.ant.DeployTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="list" classname="org.apache.catalina.ant.ListTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="start" classname="org.apache.catalina.ant.StartTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="stop" classname="org.apache.catalina.ant.StopTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>

        <target name="install" description="Install application in Tomcat">
            <install url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"
                     war="${name}"/>
        </target>

        <target name="reload" description="Reload application in Tomcat">
            <reload url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"/>
        </target>

        <target name="start" description="Start Tomcat application">
            <start url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"/>
        </target>

        <target name="stop" description="Stop Tomcat application">
            <stop url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"/>
        </target>

        <target name="list" description="List Tomcat applications">
            <list url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"/>
        </target>

    <!-- End Tomcat tasks -->

    </project>
</code>```

And my build properties is looks like this:

```<code># Ant properties for building the springapp

appserver.home=C:/Program Files/Apache Software Foundation/Tomcat 7.0
# for Tomcat 5 use $appserver.home}/server/lib
# for Tomcat 6 use $appserver.home}/lib
appserver.lib=${appserver.home}/lib/

deploy.path=${appserver.home}/webapps

tomcat.manager.url=http://localhost:8080/manager
tomcat.manager.username=
tomcat.manager.password=
</code>```

Whats strange is that if i do not extend SimpleFormController . the error:

The type javax.portlet.PortletContext
  cannot be resolved. It is indirectly
  referenced from required .class files

dissapears but i still fail to build it with the exact same error.

im currently using eclipse IDE and tomcat 7

I have the necessary libs needed to run spring and hibernate so i cant quite figure out whats the issue.

i checked the JAVA home path and my java is installed there correctly.

Thanks in advance.

答:
Ok a small update. it now build fine and i did not have to do a single thing. i just opened the project and run the build.xml on  the SpringSource tool suite IDE which is another flavour of eclipse but spring based and it worked. the only thing is that the "package" line still is highlighted with an error but it still builds fine?

Very strange indeed.

ContentLicense: CC BY-SA 2.5

Title: unable to build new java spring project

Body:
i am trying to build a simple java spring project i got setup which contains my hibernate .hbm mappings, the POJO'S that go with each mappings and one SimpleFormController class that looks like this:

package com.jr.user.controller;

import org.springframework.web.portlet.mvc.SimpleFormController;

public class RegisterNewUser extends SimpleFormController{

}

Its empty as you can see but when i try to build it i get the following error below:

BUILD FAILED
  C:\Users\xxxxxxxxxxxxx\Work\Online
  Racing League\build.xml:45: Unable to
  find a javac compiler;
  com.sun.tools.javac.Main is not on the
  classpath. Perhaps JAVA_HOME does not
  point to the JDK. It is currently set

to "C:\Program Files (x86)\Java\jre6"

Total time: 237 milliseconds

Also, whats weird is that the package line on the above code is highlighted in a red underline indicating a syntax or code error and when i mouse over to that line, this is what it says:

The type javax.portlet.PortletContext
  cannot be resolved. It is indirectly
  referenced from required .class files

My build.xml looks like this:

<?xml version="1.0"?>

<project name="Online Racing League" basedir="." default="usage">
    <property file="build.properties"/>

    <property name="src.dir" value="src"/>
    <property name="web.dir" value="war"/>
    <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
    <property name="name" value="Online Racing League"/>

    <path id="master-classpath">
        <fileset dir="${web.dir}/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>

        <fileset dir="${appserver.lib}">
            <include name="servlet*.jar"/>
        </fileset>
        <pathelement path="${build.dir}"/>
    </path>

    <target name="usage">
        <echo message=""/>
        <echo message="${name} build file"/>
        <echo message="-----------------------------------"/>
        <echo message=""/>
        <echo message="Available targets are:"/>
        <echo message=""/>
        <echo message="build     --> Build the application"/>
        <echo message="deploy    --> Deploy application as directory"/>
        <echo message="deploywar --> Deploy application as a WAR file"/>
        <echo message="install   --> Install application in Tomcat"/>
        <echo message="reload    --> Reload application in Tomcat"/>
        <echo message="start     --> Start Tomcat application"/>
        <echo message="stop      --> Stop Tomcat application"/>
        <echo message="list      --> List Tomcat applications"/>
        <echo message=""/>
    </target>

    <target name="build" description="Compile main source tree java files">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"
               deprecation="false" optimize="false" failonerror="true">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>
        </javac>
    </target>

    <target name="deploy" depends="build" description="Deploy application">
        <copy todir="${deploy.path}/${name}" preservelastmodified="true">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </copy>
    </target>

    <target name="deploywar" depends="build" description="Deploy application as a WAR file">
        <war destfile="${deploy.path}/${name}.war"
             webxml="${web.dir}/WEB-INF/web.xml">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </war>
        <copy todir="${deploy.path}" preservelastmodified="true">
            <fileset dir=".">
                <include name="*.war"/>
            </fileset>
        </copy>
    </target>

        <path id="catalina-ant-classpath">

            <fileset dir="${appserver.lib}">
                <include name="catalina-ant.jar"/>
            </fileset>
        </path>

        <taskdef name="install" classname="org.apache.catalina.ant.DeployTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="list" classname="org.apache.catalina.ant.ListTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="start" classname="org.apache.catalina.ant.StartTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>
        <taskdef name="stop" classname="org.apache.catalina.ant.StopTask">
            <classpath refid="catalina-ant-classpath"/>
        </taskdef>

        <target name="install" description="Install application in Tomcat">
            <install url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"
                     war="${name}"/>
        </target>

        <target name="reload" description="Reload application in Tomcat">
            <reload url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"/>
        </target>

        <target name="start" description="Start Tomcat application">
            <start url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"/>
        </target>

        <target name="stop" description="Stop Tomcat application">
            <stop url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"
                     path="/${name}"/>
        </target>

        <target name="list" description="List Tomcat applications">
            <list url="${tomcat.manager.url}"
                     username="${tomcat.manager.username}"
                     password="${tomcat.manager.password}"/>
        </target>

    </project>

And my build properties is looks like this:

# Ant properties for building the springapp

appserver.home=C:/Program Files/Apache Software Foundation/Tomcat 7.0
# for Tomcat 5 use $appserver.home}/server/lib
# for Tomcat 6 use $appserver.home}/lib
appserver.lib=${appserver.home}/lib/

deploy.path=${appserver.home}/webapps

tomcat.manager.url=http://localhost:8080/manager
tomcat.manager.username=
tomcat.manager.password=

Whats strange is that if i do not extend SimpleFormController . the error:

The type javax.portlet.PortletContext
  cannot be resolved. It is indirectly
  referenced from required .class files

dissapears but i still fail to build it with the exact same error.

im currently using eclipse IDE and tomcat 7

I have the necessary libs needed to run spring and hibernate so i cant quite figure out whats the issue.

i checked the JAVA home path and my java is installed there correctly.

Thanks in advance.


问:
Custom reflection method for setting field
I'm fairly new to using reflection and am currently trying to implement a custom reflection util for setting fields.
Looking at springboots ReflectionsTestUtils, I've got a mild understanding of how the setFields is done. I'm currently trying to implement that by taking an Object and an ImmutableMap as parameters.

The thought is to match the Field/Key value from the hashmap with a field that exists in the object. I understand the overall idea but the method i’ve tried implementing doesn’t seem work for retrieving the field from the map and comparing the one in the object.

My question is:
Is there a more effiecient way to achieve this than what I have tried implementing below?

Not sure if i'm heading the right way here and would appreciate all the tips given:

```<code>    public static void setField(Object object, ImmutableMap<String, Object> map)
  throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
      if (object instanceof Object) {
        Field[] fields = object.getClass().getDeclaredFields();

        for (Field aField : fields) {
         for (Map.Entry<String, Object> entry : map.entrySet()) {
          if (entry.getKey() instanceof Object) {
           String value = entry.getKey();
           checkPrimitiveValue(aField, object, value);
         }
        }
       }
    }
</code>```

}

```<code>   private static void checkPrimitiveValue(Field field, Object object, String value) throws IllegalArgumentException, IllegalAccessException {
// Find out Primitive and parse the string to correct value
if (field.getType() == boolean.class) {
  field.setAccessible(true);
  field.set(object, Boolean.parseBoolean(value));
} else if (field.getType() == long.class) {
  field.setAccessible(true);
  field.set(object, Long.parseLong(value));
} else if (field.getType() == int.class) {
  field.setAccessible(true);
  field.set(object, Integer.parseInt(value));
} else if (field.getType() == double.class) {
  field.setAccessible(true);
  field.set(object, Double.parseDouble(value));
} else { // String is used
  field.setAccessible(true);
  field.set(object, value);
}
</code>```

}

答:
The test:

```<code> if (object instanceof Object)
</code>```

is useless, except in the case where object is null, so here is a better way to write it:

```<code> if (object != null)
</code>```

You're assigning every key in the map to every field of the object. I guess you wanted to do something like:

```<code>    public static void setField(Object object, ImmutableMap<String, Object> map)
  throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
        if (object != null) {
            Field[] fields = object.getClass().getDeclaredFields();

            for (Field aField: fields) {
                Object value = map.get(aField.getName());
                assignValue(aField, object, value);
            }
        }
    }
</code>```

Now I don't get why you're passing assuming that the values in the map are Strings (the static type is Object).

```<code>private static void assignValue(Field field, Object object, Object value)
    throws IllegalArgumentException, IllegalAccessException,
            NoSuchFieldException, SecurityException {
    field.setAccessible(true);
    if (field.getType().isPrimitive())
        if (value == null) {
            value = defaultValue(field.getType());
        } else if (value instanceof String) {
            value = parseValue(field.getType(), (String)value);
        }
    }
    field.set(object, value);
}
</code>```

Default value of a primitive type:

```<code>private static Object defaultValue(Class<?> clazz) {
    if (clazz == boolean.class) {
        return Boolean.FALSE;
    } else if (clazz == char.class) {
        return (char)0;
    } else if (clazz == byte.class) {
        return (byte)0;
    } else if (clazz == short.class) {
        return (short)0;
    } else if (clazz == int.class) {
        return 0;
    } else if (clazz == long.class) {
        return 0L;
    } else if (clazz == float.class) {
        return 0F;
    } else if (clazz == double.class) {
        return 0.0;
    } else {
        throw new IllegalArgumentException("Not a primitive type");
    }
}
</code>```

Conversion from a string to a primitive type (I don't get why you're doing it, but here it is):

```<code>private static Object parseValue(Class<?> type, String s) {
    if (type == boolean.class) {
        return Boolean.valueOf(s);
    } else if (type == char.class) {
        return (char)Integer.parseInt(s);
    } else if (type == byte.class) {
        return Byte.valueOf(s);
    } else if (type == short.class) {
        return Short.valueOf(s);
    } else if (type == int.class) {
        return Integer.valueOf(s);
    } else if (type == long.class) {
        return Long.valueOf(s);
    } else if (type == float.class) {
        return Float.valueOf(s);
    } else if (type == double.class) {
        return Double.valueOf(s);
    } else {
        throw new IllegalArgumentException("Not a primitive type");
    }
}
</code>```

Body:
I'm fairly new to using reflection and am currently trying to implement a custom reflection util for setting fields.
Looking at springboots ReflectionsTestUtils, I've got a mild understanding of how the setFields is done. I'm currently trying to implement that by taking an Object and an ImmutableMap as parameters.

The thought is to match the Field/Key value from the hashmap with a field that exists in the object. I understand the overall idea but the method i’ve tried implementing doesn’t seem work for retrieving the field from the map and comparing the one in the object.

My question is:
Is there a more effiecient way to achieve this than what I have tried implementing below?

Not sure if i'm heading the right way here and would appreciate all the tips given:

    public static void setField(Object object, ImmutableMap<String, Object> map)
  throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
      if (object instanceof Object) {
        Field[] fields = object.getClass().getDeclaredFields();

        for (Field aField : fields) {
         for (Map.Entry<String, Object> entry : map.entrySet()) {
          if (entry.getKey() instanceof Object) {
           String value = entry.getKey();
           checkPrimitiveValue(aField, object, value);
         }
        }
       }
    }

}

   private static void checkPrimitiveValue(Field field, Object object, String value) throws IllegalArgumentException, IllegalAccessException {
// Find out Primitive and parse the string to correct value
if (field.getType() == boolean.class) {
  field.setAccessible(true);
  field.set(object, Boolean.parseBoolean(value));
} else if (field.getType() == long.class) {
  field.setAccessible(true);
  field.set(object, Long.parseLong(value));
} else if (field.getType() == int.class) {
  field.setAccessible(true);
  field.set(object, Integer.parseInt(value));
} else if (field.getType() == double.class) {
  field.setAccessible(true);
  field.set(object, Double.parseDouble(value));
} else { // String is used
  field.setAccessible(true);
  field.set(object, value);
}

}

Body:
The test:

 if (object instanceof Object)

is useless, except in the case where object is null, so here is a better way to write it:

 if (object != null)

You're assigning every key in the map to every field of the object. I guess you wanted to do something like:

    public static void setField(Object object, ImmutableMap<String, Object> map)
  throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
        if (object != null) {
            Field[] fields = object.getClass().getDeclaredFields();

            for (Field aField: fields) {
                Object value = map.get(aField.getName());
                assignValue(aField, object, value);
            }
        }
    }

Now I don't get why you're passing assuming that the values in the map are Strings (the static type is Object).

private static void assignValue(Field field, Object object, Object value)
    throws IllegalArgumentException, IllegalAccessException,
            NoSuchFieldException, SecurityException {
    field.setAccessible(true);
    if (field.getType().isPrimitive())
        if (value == null) {
            value = defaultValue(field.getType());
        } else if (value instanceof String) {
            value = parseValue(field.getType(), (String)value);
        }
    }
    field.set(object, value);
}

Default value of a primitive type:

private static Object defaultValue(Class<?> clazz) {
    if (clazz == boolean.class) {
        return Boolean.FALSE;
    } else if (clazz == char.class) {
        return (char)0;
    } else if (clazz == byte.class) {
        return (byte)0;
    } else if (clazz == short.class) {
        return (short)0;
    } else if (clazz == int.class) {
        return 0;
    } else if (clazz == long.class) {
        return 0L;
    } else if (clazz == float.class) {
        return 0F;
    } else if (clazz == double.class) {
        return 0.0;
    } else {
        throw new IllegalArgumentException("Not a primitive type");
    }
}

Conversion from a string to a primitive type (I don't get why you're doing it, but here it is):

private static Object parseValue(Class<?> type, String s) {
    if (type == boolean.class) {
        return Boolean.valueOf(s);
    } else if (type == char.class) {
        return (char)Integer.parseInt(s);
    } else if (type == byte.class) {
        return Byte.valueOf(s);
    } else if (type == short.class) {
        return Short.valueOf(s);
    } else if (type == int.class) {
        return Integer.valueOf(s);
    } else if (type == long.class) {
        return Long.valueOf(s);
    } else if (type == float.class) {
        return Float.valueOf(s);
    } else if (type == double.class) {
        return Double.valueOf(s);
    } else {
        throw new IllegalArgumentException("Not a primitive type");
    }
}


问:
Using both AND, OR in If condition Javascript
Similar questions haven't justified my actual question.
I have a If condition where if it satisfies 2 conditions it should set value as A else B. Below is the code block describing my question

```<code>if(($form[0].lang.value==SPN||PTB||GRM) && ("1" == "<awi:script script='IsTranslationON'/>"))
    {
    $form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT_Translation";
     }
    else
      {$form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT";}
 //Submit form
      submit=false;
      if(submit){$form[0].submit()}else{alert($form[0].$rtag.value)}
</code>```

Issue is - evrytime it gets deiplayed only statement from If condition. It is not checking value with $lang.value
Does any of the mates help me checking my if condition please.
EDIT- The value I am getting in alert box is "Test_IND_GENERAL_SUPPORT_Translation".

答:
This line

```<code>$form[0].lang.value==SPN||PTB||GRM
</code>```

Will compare $form[0].lang.value with SPN and then logical OR PTB and GRM. If any of PTB and GRM is truthy value, then this condition will succeed.

If SPN, PTB and GRM are variables, then put them in an array first.

```<code>var langArr =  [ SPN, PTB, GRM ];
if((langArr.indexOf( $form[0].lang.value) !=  - 1 ) && ("1" == "<awi:script script='IsTranslationON'/>"))
</code>```

Body:
Similar questions haven't justified my actual question.
I have a If condition where if it satisfies 2 conditions it should set value as A else B. Below is the code block describing my question

if(($form[0].lang.value==SPN||PTB||GRM) && ("1" == "<awi:script script='IsTranslationON'/>"))
    {
    $form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT_Translation";
     }
    else
      {$form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT";}
 //Submit form
      submit=false;
      if(submit){$form[0].submit()}else{alert($form[0].$rtag.value)}

Issue is - evrytime it gets deiplayed only statement from If condition. It is not checking value with $lang.value
Does any of the mates help me checking my if condition please.
EDIT- The value I am getting in alert box is "Test_IND_GENERAL_SUPPORT_Translation".

Body:
This line

$form[0].lang.value==SPN||PTB||GRM

Will compare $form[0].lang.value with SPN and then logical OR PTB and GRM. If any of PTB and GRM is truthy value, then this condition will succeed.

If SPN, PTB and GRM are variables, then put them in an array first.

var langArr =  [ SPN, PTB, GRM ];
if((langArr.indexOf( $form[0].lang.value) !=  - 1 ) && ("1" == "<awi:script script='IsTranslationON'/>"))


问:
i'am Getting This error. Conversion failed when converting the nvarchar value '- Select -' to data type int. My Code Is Given below
This Is my Sql table Structure so maybe its details what Is Problem Is...
This is the problem Iam getting In website

I am getting Error In this code:

```<code> protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Getreality();
            GetAds();
        }
    }

    private void Getreality()
    {
        conn.Open();
        cmd = new SqlCommand("Getallreality", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@Type", SqlDbType.NVarChar).Value = "Reality Show";
        DataTable dt = new DataTable();
        da.Fill(dt);
        ListViewSerials.DataSource = dt;
        ListViewSerials.DataBind();
        conn.Close();
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        Getreality();
    }
</code>```

答:
The error says it cant convert the nvarchar value '- Select -' to int .Which is because '- Select -' is not a valid int value.
Exclude that value from your SQL or post your SQL here for help</p>

Body:
This Is my Sql table Structure so maybe its details what Is Problem Is...
This is the problem Iam getting In website

I am getting Error In this code:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Getreality();
            GetAds();
        }
    }

    private void Getreality()
    {
        conn.Open();
        cmd = new SqlCommand("Getallreality", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@Type", SqlDbType.NVarChar).Value = "Reality Show";
        DataTable dt = new DataTable();
        da.Fill(dt);
        ListViewSerials.DataSource = dt;
        ListViewSerials.DataBind();
        conn.Close();
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        Getreality();
    }


问:
None vs nil in Elixir
What is the difference between None and nil in Elixir?

From Elixir's documentation if I understand correctly nil is a literal representing absence of value.

But even None seems to represent the same, though I could not find any documentation over it.

答:
As @JustMichael mentioned, None behaves nothing like you think.
None in elixir is just an atom without any further meaning, as you can determine via i(variable) in iex.

```<code>iex(1)> i(None)
Term
  None
Data type
  Atom
Raw representation
  :"Elixir.None"
Reference modules
  Atom
Implemented protocols
  IEx.Info, Inspect, String.Chars, List.Chars
iex(2)> is_nil(None)
false
</code>```

But looking at nil:

```<code>iex(3)> i(nil)
Term
  nil
Data type
  Atom
Reference modules
  Atom
Implemented protocols
  IEx.Info, Inspect, String.Chars, List.Chars
iex(4)> is_nil(nil)
true
</code>```

ContentLicense: CC BY-SA 4.0

Title: None vs nil in Elixir

Body:
As @JustMichael mentioned, None behaves nothing like you think.
None in elixir is just an atom without any further meaning, as you can determine via i(variable) in iex.

iex(1)> i(None)
Term
  None
Data type
  Atom
Raw representation
  :"Elixir.None"
Reference modules
  Atom
Implemented protocols
  IEx.Info, Inspect, String.Chars, List.Chars
iex(2)> is_nil(None)
false

But looking at nil:

iex(3)> i(nil)
Term
  nil
Data type
  Atom
Reference modules
  Atom
Implemented protocols
  IEx.Info, Inspect, String.Chars, List.Chars
iex(4)> is_nil(nil)
true


问:
Microsoft Azure Web Chat, trigger mic from other function
I have used Microsoft Bot Framework to create a bot for the client side. i.e. called WebChat. I have also added Speech SpeechRecognizer. However, I am trying to trigger a mic when a phrase is recited.

I couldn't find a function in Microsoft that does this. So I added my own speech recognizer that is called every second and once the phrase is called I want to call the mic function from the Cognitive Services.

How Can I achieve this?

I have got the speech recognizer from here

And the one I have written to identify a phrase is this:

```<code>function startDictation() {

            if (window.hasOwnProperty('webkitSpeechRecognition')) {

                var recognition = new webkitSpeechRecognition();

                recognition.continuous = false;
                recognition.interimResults = false;

                recognition.lang = "en-US";
                recognition.start();

                recognition.onresult = function (e) {
                    var foundText = e.results[0][0].transcript;
                    console.log(foundText);
                    if (foundText == "hello hello") {
                        console.log("found text");
                        //call cognitive service mic function
                        recognition.stop();
                    }
                    else {
                        console.log("text not found");
                        recognition.stop();
                        startDictation();
                    }
                };

                recognition.onerror = function (e) {
                    console.log("found error", e);
                    recognition.stop();
                }

            }
        }
</code>```

Do let me know if any information is missing or miss-leading.

For more:

答:
I tried to leverage startRecognizing() function in SpeechRecognizer class at https://github.com/Microsoft/BotFramework-WebChat/blob/master/src/CognitiveServices/SpeechRecognition.ts#L72 to trigger the recognize functionality. However, I found that only if I have click the mic item, then I could use startRecognizing() function to recognize the voice.

There is a trick workaround you can try to use at present:

I inspected the mic item, and try to triiger its click event in js, which worked exactly to recognize my speech.

You can try to use following js code snippet with jQuery:

```<code>$('.wc-mic').trigger("click")
</code>```

Hope it helps.

Body:
I have used Microsoft Bot Framework to create a bot for the client side. i.e. called WebChat. I have also added Speech SpeechRecognizer. However, I am trying to trigger a mic when a phrase is recited.

I couldn't find a function in Microsoft that does this. So I added my own speech recognizer that is called every second and once the phrase is called I want to call the mic function from the Cognitive Services.

How Can I achieve this?

I have got the speech recognizer from here

And the one I have written to identify a phrase is this:

function startDictation() {

            if (window.hasOwnProperty('webkitSpeechRecognition')) {

                var recognition = new webkitSpeechRecognition();

                recognition.continuous = false;
                recognition.interimResults = false;

                recognition.lang = "en-US";
                recognition.start();

                recognition.onresult = function (e) {
                    var foundText = e.results[0][0].transcript;
                    console.log(foundText);
                    if (foundText == "hello hello") {
                        console.log("found text");
                        //call cognitive service mic function
                        recognition.stop();
                    }
                    else {
                        console.log("text not found");
                        recognition.stop();
                        startDictation();
                    }
                };

                recognition.onerror = function (e) {
                    console.log("found error", e);
                    recognition.stop();
                }

            }
        }

Do let me know if any information is missing or miss-leading.

For more:

Body:
I tried to leverage startRecognizing() function in SpeechRecognizer class at https://github.com/Microsoft/BotFramework-WebChat/blob/master/src/CognitiveServices/SpeechRecognition.ts#L72 to trigger the recognize functionality. However, I found that only if I have click the mic item, then I could use startRecognizing() function to recognize the voice.

There is a trick workaround you can try to use at present:

I inspected the mic item, and try to triiger its click event in js, which worked exactly to recognize my speech.

You can try to use following js code snippet with jQuery:

$('.wc-mic').trigger("click")

Hope it helps.


问:
Get center LatLng point of a custom tile in Google Maps API v3
I've got a custom map type API I need to talk to.

I'd like to get the map images by using the 'tile' function of Google Maps. I've got the tiles setup like this: https://developers.google.com/maps/documentation/javascript/examples/maptype-overlay?hl=nl

The API to get the different tileimages requires me to have a center point for each of the tiles.

So how do I get/calculate the center LatLng point for each tile?

答:
You can calculate it also directly:

```<code>n = 2 ^ zoom
lon_deg = xtile / n * 360.0 - 180.0
lat_rad = arctan(sinh(π * (1 - 2 * ytile / n)))
lat_deg = lat_rad * 180.0 / π
</code>```

Source and code samples in various languages: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_numbers_to_lon..2Flat.

Body:
You can calculate it also directly:

n = 2 ^ zoom
lon_deg = xtile / n * 360.0 - 180.0
lat_rad = arctan(sinh(π * (1 - 2 * ytile / n)))
lat_deg = lat_rad * 180.0 / π

Source and code samples in various languages: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_numbers_to_lon..2Flat.


问:
web based version control with full management
I am looking for a web app I can host on my server that allows me to create/manage projects using version control. I've seen some nice interfaces, but most of them just manage what you already have.(which means I have to manually clean up/set up things for each new project) An example would be gitorious, in which creating a new project actually sets up the repo for you. I'd also like it if it could support access control too for different projects.</p>

答: Top of my list would be KForge -- give that a try :)  Good luck!</p>


问:
Different result mappings for the same query but with variable column - MyBatis 3
I need to get different java Pojo result mapping from same query with different  column in sql "Where" condition.
Es.

```<code>@Select("Select field1,fiel2,...,fieldn From table where #{column}=1")
List<Pojo> getGenericDetails(@Param(column));
</code>```

Mybatis "discriminator" doesn't make the job.
Can anyone know how to do that?

Thanks in advance

答:
The Mapping what you have written works But it works on same POJO .

If you need different POJOs based on the column in where clause then you Have to write  different queries for each of condition in where clause .

Which is as good as specifying column name in query .

So i suggest you to write different queryies and created Different POJOs and make the method name relevant to context where you will use those queryies

Body:
I need to get different java Pojo result mapping from same query with different  column in sql "Where" condition.
Es.

@Select("Select field1,fiel2,...,fieldn From table where #{column}=1")
List<Pojo> getGenericDetails(@Param(column));

Mybatis "discriminator" doesn't make the job.
Can anyone know how to do that?

Thanks in advance


问:
First saturday for a selected month and year
How could I find the first Saturday for a given month and year (month & year selected by a calender)?  I am using PHP.</p>

答:
Here is one-liner:

```<code>$firstSat = strtotime( 'first Saturday', strtotime( "$month $year" ) );
</code>```

Test:

```<code>foreach( array("Jan","Feb","Nov","Dec" ) as $month)
{
   $year = '2017';
   echo "$month, $year";
   $firstSat = strtotime( 'first Saturday', strtotime( "$month $year" ) );
   $date = date( 'Y-M-d', $firstSat );
   echo " $firstSat $date <br>" ;
}
</code>```

Outputs:

```<code>Jan, 2017 1483747200 2017-Jan-07
Feb, 2017 1486166400 2017-Feb-04
Nov, 2017 1509753600 2017-Nov-04
Dec, 2017 1512172800 2017-Dec-02
</code>```

Body:
Here is one-liner:

$firstSat = strtotime( 'first Saturday', strtotime( "$month $year" ) );

Test:

foreach( array("Jan","Feb","Nov","Dec" ) as $month)
{
   $year = '2017';
   echo "$month, $year";
   $firstSat = strtotime( 'first Saturday', strtotime( "$month $year" ) );
   $date = date( 'Y-M-d', $firstSat );
   echo " $firstSat $date <br>" ;
}

Outputs:

Jan, 2017 1483747200 2017-Jan-07
Feb, 2017 1486166400 2017-Feb-04
Nov, 2017 1509753600 2017-Nov-04
Dec, 2017 1512172800 2017-Dec-02


问:
How to separate data in SQL table
I have a .csv file with data records, each line containing departments of organisations. I would like to import them into a MySQL database and show them in a web application. A sample abstract of data records looks like this:

```<code>| Company A | Department aaa |
| Company A | Department bbb |
| Company A | Department ccc |
| Company B | Department ddd |
| Company B | Department eee |
| Company C | Department fff |
| Company C | Department ggg |
| Company C | Department hhh |
| Company D | Department iii |
| Company E | Department jjj |
| Company E | Department kkk |
</code>```

Of course I want to show each company once with its related departments attached, which makes it look this way, more or less:

```<code>| Company A | Department aaa |
|           | Department bbb |
|           | Department ccc |
| Company B | Department ddd |
|           | Department eee |
| Company C | Department fff |
|           | Department ggg |
|           | Department hhh |
| Company D | Department iii |
| Company E | Department jjj |
|           | Department kkk |
</code>```

My question is, what is the best way to concatenate these data records? Would you do it using the appropriate programing language (ie PHP, Ruby, Perl, whatever) or would you do it in the database using SQL query? If SQL is the choice, would you do it using stored procedures, temp tables, or even at the import interface? What would it look like if it was SQL? Thank you!

答:
While Bill's solution will certainly work, my bias is to create separate database entities (and by extension, separate tables) anytime there is a one to many relationship like the one you describe.

So I would create a company table and a department table and have the department reference rows in the company table by a foreign key company_id column.

```<code>TABLE: company
id
name

TABLE: department
id
company_id
name
</code>```

Then you could select all department records, join against the company table, and order by company_id... then you can post-process the query results into whatever data structure you need.

There are many reasons I prefer joins over lumping data into a single table; it feels more flexible and it mimics a tree structure of interrelated models. But the biggest reason is this:

You aren't duplicating data. If a company's name changes, you only have to update one records, instead of all records pertaining to that company.
2) It's more flexible. If you later

Title: How to separate data in SQL table

Body:
I have a .csv file with data records, each line containing departments of organisations. I would like to import them into a MySQL database and show them in a web application. A sample abstract of data records looks like this:

| Company A | Department aaa |
| Company A | Department bbb |
| Company A | Department ccc |
| Company B | Department ddd |
| Company B | Department eee |
| Company C | Department fff |
| Company C | Department ggg |
| Company C | Department hhh |
| Company D | Department iii |
| Company E | Department jjj |
| Company E | Department kkk |

Of course I want to show each company once with its related departments attached, which makes it look this way, more or less:

| Company A | Department aaa |
|           | Department bbb |
|           | Department ccc |
| Company B | Department ddd |
|           | Department eee |
| Company C | Department fff |
|           | Department ggg |
|           | Department hhh |
| Company D | Department iii |
| Company E | Department jjj |
|           | Department kkk |

My question is, what is the best way to concatenate these data records? Would you do it using the appropriate programing language (ie PHP, Ruby, Perl, whatever) or would you do it in the database using SQL query? If SQL is the choice, would you do it using stored procedures, temp tables, or even at the import interface? What would it look like if it was SQL? Thank you!

Body:
While Bill's solution will certainly work, my bias is to create separate database entities (and by extension, separate tables) anytime there is a one to many relationship like the one you describe.

So I would create a company table and a department table and have the department reference rows in the company table by a foreign key company_id column.

TABLE: company
id
name

TABLE: department
id
company_id
name

Then you could select all department records, join against the company table, and order by company_id... then you can post-process the query results into whatever data structure you need.

There are many reasons I prefer joins over lumping data into a single table; it feels more flexible and it mimics a tree structure of interrelated models. But the biggest reason is this:

You aren't duplicating data. If a company's name changes, you only have to update one records, instead of all records pertaining to that company.
2) It's more flexible. If you later


答:
For a concise check, you could put the values into an array and check with Array#includes.

```<code>[SPN, PTB, GRM].includes($form[0].lang.value)
</code>```

Title: Using both AND, OR in If condition Javascript

Body:
For a concise check, you could put the values into an array and check with Array#includes.

[SPN, PTB, GRM].includes($form[0].lang.value)


问:
Showing part of the ImageView which is cover by another ImageView
I have a Framelayout, where the first element is an ImageView which height and width is match parent and let the id is A. Second element is also an ImageView which height and width also match parent and let the id is B. Third element is a View which height and width is 100 dp and can be move to the whole screen and let the id is C. I am using transparent color in background C, so inside C we should see B, because B is above A. But I want to show A in inside C , how can I do that?</p>

答: You can set visibility of B to invisible or gone, if you don't want to show B. Or you can replace A with B. As frame layout work like stack first thing you put goes to the bottom. so you put in this format B->A->->C</p>


问:
Adding animation to my images with JQuery
Here is my home page:

```<code><%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">
<table id="home" style="margin-left: auto; margin-right:auto;">
    <td id="homeLinks">
        <div style="padding-left:35px;" id="homeListing" class="containerMid">
            <div id="homeView">
                <table style="margin-left: auto; margin-right:auto;">
                    <tr>
                        <tr>
                            <td id="btnIcOld" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />
                            </td>
                            <td id="btnIc" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />
                            </td>
                            <td id="btnPricing" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnSheets" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnPort" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />
                            </td>
                            <td id="btnAdmin" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />
                            </td>
                        </tr>
                        <tr>
                            <td id="Td1">
                                <b>Indications Calculator | </b>
                            </td>
                            <td id="lblIc">
                                <b>Indications Calculator - Beta | </b>
                            </td>
                            <td id="lblPricing">
                                <b>Managing Pricing Triggers | </b>
                            </td>
                            <td id="lblSheets">
                                <b>Creating Pricing Sheets | </b>
                            </td>
                            <td id="lblPort">
                                <b>Portfolio Analysis | </b>
                            </td>
                            <td id="lblAdmin">
                                <b>Administration</b>
                            </td>
                        </tr>
                    </tr>
                </table>
            </div>
        </div>
    </td>
</table>

<div id="pageMessage"></div>

<script>
    $(document).ready(function () {

        $('#btnIc').live('click', function () {
            window.location.href = "<%=Url.Action("Indications") %>";
        });

        $('#btnIcOld').live('click', function () {
            window.location.href = 'https://extranetint/swap';
        });

        $('#btnPricing').live('click', function () {
            //window.location.href = "<%=Url.Action("Triggers") %>";
        });

        $('#btnSheets').live('click', function () {
            //window.location.href = "<%=Url.Action("Sheets") %>";
        });

        $('#btnPort').live('click', function () {
            //window.location.href = "<%=Url.Action("Analysis") %>";
        });

        $('#btnAdmin').live('click', function () {
            //window.location.href = "<%=Url.Action("Admin") %>";
        });

    });
</script>
</asp:Content>
</code>```

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!

答: There's a tutorial for exactly what you want here - pretty much works the same way as your jsfiddle paste. Cheers!</p>

Body:
Here is my home page:

<%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />

                                Indications Calculator |

                                Indications Calculator - Beta |

                                Managing Pricing Triggers |

                                Creating Pricing Sheets |

                                Portfolio Analysis |

                                Administration

</asp:Content>

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!


问:
Unsupported Operand Types Python Power and Lists
One of the tutorial questions has us focus on creating a function which returns a simple expression. The expression is below:

EQ = cos*(pi/2)*x^2 + sin(pi/4)*x + x^3
Where x is an array of floats.

I have written the following code to answer this:

```<code>def  getStats(x):
    # Complete the function.
    y = float(numpy.cos((numpy.pi/2)*x**2) + numpy.sin((numpy.pi/4)*x) + x**3)
return y
</code>```

However I get an error saying unsupported operand types for pow or ** list or int.

I have tried to type cast this but it has not worked.
Apart from type casting I have tried breaking this down further but have been unsuccessful. Any ideas on what I can try next?

Thank you.

答:
You should evaluate the expression for each value of the input list. You can do this using list comprehension.

```<code>def  getStats(X):
    # Complete the function.
    y = [float(numpy.cos((numpy.pi/2)*x**2) + numpy.sin((numpy.pi/4)*x) + x**3) for x in X]
    return y
</code>```

The approach in the edit section is preferred (see below).

Edit: Converting the input list to numpy array and do the computation.

```<code>def  getStats(x):
    # Complete the function.
    x = numpy.array(x)
    y = numpy.cos((numpy.pi/2) * numpy.power(x, 2)) + numpy.sin((numpy.pi/4)*x) + numpy.power(x, 3)
    return y # if you want to return a list, use list(y)
</code>```

Body:
One of the tutorial questions has us focus on creating a function which returns a simple expression. The expression is below:

EQ = cos*(pi/2)*x^2 + sin(pi/4)*x + x^3
Where x is an array of floats.

I have written the following code to answer this:

def  getStats(x):
    # Complete the function.
    y = float(numpy.cos((numpy.pi/2)*x**2) + numpy.sin((numpy.pi/4)*x) + x**3)
return y

However I get an error saying unsupported operand types for pow or ** list or int.

I have tried to type cast this but it has not worked.
Apart from type casting I have tried breaking this down further but have been unsuccessful. Any ideas on what I can try next?

Thank you.

Body:
You should evaluate the expression for each value of the input list. You can do this using list comprehension.

def  getStats(X):
    # Complete the function.
    y = [float(numpy.cos((numpy.pi/2)*x**2) + numpy.sin((numpy.pi/4)*x) + x**3) for x in X]
    return y

The approach in the edit section is preferred (see below).

Edit: Converting the input list to numpy array and do the computation.

def  getStats(x):
    # Complete the function.
    x = numpy.array(x)
    y = numpy.cos((numpy.pi/2) * numpy.power(x, 2)) + numpy.sin((numpy.pi/4)*x) + numpy.power(x, 3)
    return y # if you want to return a list, use list(y)


问:
How to add sorting to a custom column on index in activeadmin?
I have these associations:

```<code>class Event < ApplicationRecord
  has_many :users_events
  has_many :users, through: :users_events
end

class UsersEvent < ApplicationRecord
  belongs_to :user
  belongs_to :event
end

class User < ApplicationRecord
  has_many :users_events
  has_many :events, through: :users_events
end
</code>```

In activeadmin I display my index page as:

```<code>index do
  # some columns
  column :total_participants do |event|
    event.users.count
  end
  # other columns
end
</code>```

Doing like this, the sorting is absent in this column. If I do this: column(:user_count, sortable: 'users') { |event| event.users.count }, the sorting appears, but the query seems to be wrong: Mysql2::Error: Unknown column 'users' in 'order clause': SELECT  'events'.* FROM 'events' ORDER BY 'users' desc LIMIT 30 OFFSET 0

So, what is the best way of adding sorting to a custom column, and what am I doing wrong? Thanks.

答:
Since you need to use this column multiple times, it's better to cache it.
To do so, it's better to add a new column to events called users_count with a default of 0 and increment it each time you have a new user:

migration:

```<code>add_column :events, :users_count, default: 0
add_index :events, :users_count
</code>```

model:

```<code>class UsersEvent < ApplicationRecord
  belongs_to :user
  belongs_to :event
  after_create -> {Event.increment_counter(:users_count, self.event.id)}
end
</code>```

I'm also not sure why your model is called UsersEvent not EventUser

Body:
I have these associations:

class Event < ApplicationRecord
  has_many :users_events
  has_many :users, through: :users_events
end

class UsersEvent < ApplicationRecord
  belongs_to :user
  belongs_to :event
end

class User < ApplicationRecord
  has_many :users_events
  has_many :events, through: :users_events
end

In activeadmin I display my index page as:

index do
  # some columns
  column :total_participants do |event|
    event.users.count
  end
  # other columns
end

Doing like this, the sorting is absent in this column. If I do this: column(:user_count, sortable: 'users') { |event| event.users.count }, the sorting appears, but the query seems to be wrong: Mysql2::Error: Unknown column 'users' in 'order clause': SELECT  'events'.* FROM 'events' ORDER BY 'users' desc LIMIT 30 OFFSET 0

So, what is the best way of adding sorting to a custom column, and what am I doing wrong? Thanks.

Body:
Since you need to use this column multiple times, it's better to cache it.
To do so, it's better to add a new column to events called users_count with a default of 0 and increment it each time you have a new user:

migration:

add_column :events, :users_count, default: 0
add_index :events, :users_count

model:

class UsersEvent < ApplicationRecord
  belongs_to :user
  belongs_to :event
  after_create -> {Event.increment_counter(:users_count, self.event.id)}
end

I'm also not sure why your model is called UsersEvent not EventUser


问:
lua OOP - how to write Class as a table of tables of functions

Context

I'm trying to write a class system which will generate melodies by performing permutations on the notes and rhythms. I'm gonna use this in the tool "xStream" in the "Renoise" software. My example here is a really dumbed down and generic version from what I really have.

I'm also making this as a learning opportunity. My OOP skills are weak, and I still haven't completely wrapped my head around metatables. So a preemptive sorry if I'm totally missing something. I'm doing all my code from the style of the basic OOP examples in the 3rd edition of Programming in Lua.

My question

What I want to do is have class methods with similar functionality all grouped into 'nested' tables. Eg, a table of 'melody permutations', a table of 'rhythm permutations', a table of miscellaneous utility methods, etc.

In the code, I have a class SomeClass. It has two types of print functions: print1_notes is in the 'main table' (ie, a key of SomeClass). print2.notes is in a 'nested' table print2, which is a key of SomeClass (ie, notes is just a key of SomeClass.print2).

I can call print1_notes just fine. The issue is when I call the print2 methods with the colon operator.
If I don't use sugar (eg, obj.print2.notes(obj)), then no problem. But when I do (eg, obj.print2:notes()), I get errors about "attempt to (blah blah) a function value ...".

How come it works without the colon operator?

Do methods in SomeClass.print2 have access to the keys in SomeClass? Do they have access the same way that the non-nested table keys do?

I was thinking that print2 needs an __index key to tell its methods to look up the keys in SomeClass when it doesn't know what self.a_key is. But self (inside the print2 methods) isn't a key. It's really just an alias for SomeClass. Is it though? Seems like there's a discrepancy with the nested table.

Do I need to make SomeClass the metatable of print2? Is that even possible, since print2 isn't a separate table from SomeClass?

Should I try a different approach? Maybe multiple inheritance?

Thanks. Sorry if this needs to be moved or if someone has asked this before.

My code

```<code>SomeClass = {
    new = function (self, t)
        t = t or {}
        setmetatable(t, self)
        self.__index = function (_, key)
            return self[key]
        end

        --should I add a setmetatable here? perhaps:
        --setmetatable(self.print2, self)

        return t
    end,

    notes = {},
    set_notes = function (self, t)
        self.notes = t or {}
        self.N = #self.notes
    end,

    print1_notes = function (self)
        print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
    end,

    --table of different print functions
    print2 = {
        notes = function (self)
            --is self an alias for SomeClass?
            assert(self.notes, "Error: self.notes = nil")
            print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
        end,

        first_note = function (self)
            fn = self.notes[1]
            print("first note is: ", fn)
        end,
    },

}

obj = SomeClass:new()
obj:set_notes{ 10,14,5, 10,14,5, 17 }

print("\ncalling print1_notes without sugar:")
obj.print1_notes(obj)
print("\ncalling print1_notes with sugar:")
obj:print1_notes()
print("\ncalling print2.notes without sugar")
obj.print2.notes(obj)
print("\ncalling print2.notes with sugar")
obj.print2:notes()  --this gives an error: "attempt to get length of a function value"

obj.print2.first_note(obj)  --this works fine
obj.print2:first_note()     --this gives an error:
                            --  "attempt to index a function value (field 'notes')"
</code>```

EDIT to code: instances of tostring(N) needed to be replaced with tostring(self.N).

EDIT: weird errors has to do with the fact that SomeClass.print2.notes has a notes member like SomeClass.notes. SomeClass.print2.first_note avoids this complication. (I'll explain more when I answer)

EDIT: I came up with a solution. It's not pretty, but it works. I'll post my answer below.

答:
After thinking about problem for a while, I noticed there is another approach to solving it and keeping the namespace idea.

Again, you can't use the colon syntax to pass the class to a function that's not in the class, but in a namespace of the class. What you can however do, is the following:

```<code>local function print2(instance)
  -- Does things
end

local function wrapper(namespace)
  print2(namespace.instance)
end

function someClass.new()
  ...
  notes = {print=wrapper,instance=t} -- every instance needs its own namespace table
  ...
end
</code>```

as you can see, every instance has its own namespace table, but they all have a reference to the same shared function and a reference to the instance they belong to. When you call instance.notes:print() it ends up calling print on instance.notes, but the function only calls the real function on instance.notes.instance, which points back to instance

Body:
Context

I'm trying to write a class system which will generate melodies by performing permutations on the notes and rhythms. I'm gonna use this in the tool "xStream" in the "Renoise" software. My example here is a really dumbed down and generic version from what I really have.

I'm also making this as a learning opportunity. My OOP skills are weak, and I still haven't completely wrapped my head around metatables. So a preemptive sorry if I'm totally missing something. I'm doing all my code from the style of the basic OOP examples in the 3rd edition of Programming in Lua.

My question

What I want to do is have class methods with similar functionality all grouped into 'nested' tables. Eg, a table of 'melody permutations', a table of 'rhythm permutations', a table of miscellaneous utility methods, etc.

In the code, I have a class SomeClass. It has two types of print functions: print1_notes is in the 'main table' (ie, a key of SomeClass). print2.notes is in a 'nested' table print2, which is a key of SomeClass (ie, notes is just a key of SomeClass.print2).

I can call print1_notes just fine. The issue is when I call the print2 methods with the colon operator.
If I don't use sugar (eg, obj.print2.notes(obj)), then no problem. But when I do (eg, obj.print2:notes()), I get errors about "attempt to (blah blah) a function value ...".

How come it works without the colon operator?

Do methods in SomeClass.print2 have access to the keys in SomeClass? Do they have access the same way that the non-nested table keys do?

I was thinking that print2 needs an __index key to tell its methods to look up the keys in SomeClass when it doesn't know what self.a_key is. But self (inside the print2 methods) isn't a key. It's really just an alias for SomeClass. Is it though? Seems like there's a discrepancy with the nested table.

Do I need to make SomeClass the metatable of print2? Is that even possible, since print2 isn't a separate table from SomeClass?

Should I try a different approach? Maybe multiple inheritance?

Thanks. Sorry if this needs to be moved or if someone has asked this before.

My code

SomeClass = {
    new = function (self, t)
        t = t or {}
        setmetatable(t, self)
        self.__index = function (_, key)
            return self[key]
        end

        --should I add a setmetatable here? perhaps:
        --setmetatable(self.print2, self)

        return t
    end,

    notes = {},
    set_notes = function (self, t)
        self.notes = t or {}
        self.N = #self.notes
    end,

    print1_notes = function (self)
        print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
    end,

    --table of different print functions
    print2 = {
        notes = function (self)
            --is self an alias for SomeClass?
            assert(self.notes, "Error: self.notes = nil")
            print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
        end,

        first_note = function (self)
            fn = self.notes[1]
            print("first note is: ", fn)
        end,
    },

}

obj = SomeClass:new()
obj:set_notes{ 10,14,5, 10,14,5, 17 }

print("\ncalling print1_notes without sugar:")
obj.print1_notes(obj)
print("\ncalling print1_notes with sugar:")
obj:print1_notes()
print("\ncalling print2.notes without sugar")
obj.print2.notes(obj)
print("\ncalling print2.notes with sugar")
obj.print2:notes()  --this gives an error: "attempt to get length of a function value"

obj.print2.first_note(obj)  --this works fine
obj.print2:first_note()     --this gives an error:
                            --  "attempt to index a function value (field 'notes')"

EDIT to code: instances of tostring(N) needed to be replaced with tostring(self.N).

EDIT: weird errors has to do with the fact that SomeClass.print2.notes has a notes member like SomeClass.notes. SomeClass.print2.first_note avoids this complication. (I'll explain more when I answer)

EDIT: I came up with a solution. It's not pretty, but it works. I'll post my answer below.

Body:
After thinking about problem for a while, I noticed there is another approach to solving it and keeping the namespace idea.

Again, you can't use the colon syntax to pass the class to a function that's not in the class, but in a namespace of the class. What you can however do, is the following:

local function print2(instance)
  -- Does things
end

local function wrapper(namespace)
  print2(namespace.instance)
end

function someClass.new()
  ...
  notes = {print=wrapper,instance=t} -- every instance needs its own namespace table
  ...
end

as you can see, every instance has its own namespace table, but they all have a reference to the same shared function and a reference to the instance they belong to. When you call instance.notes:print() it ends up calling print on instance.notes, but the function only calls the real function on instance.notes.instance, which points back to instance


问:
How to get all aggregates with Axon framework?
I am starting out with the Axon framework and hit a bit of a roadblock.

While I can load individual aggregates using their ID, I can’t figure out how to get a list of all aggregates, or a list of all aggregate IDs.

The EventSourcingRepository class only has load() methods that return one aggregate.

Is there a way to all aggregate (IDs) or am I supposed to keep a list of all aggregate IDs outside of axon?

To keep things simple I am only using an InMemoryEventStorageEngine for now.
I am using Axon 3.0.7.

答:
First off I'm was wondering why you would want to retrieve a complete list of all the aggregates from the Repository.
The Repository interface is set such that you can load an Aggregate to handle commands or to create a new Aggregate.

Asking the question you have, I'd almost guess you're using it for querying purposes rather than command handling.
This however isn't the intended use for the EventSourcingRepository.

One reason you'd want this I can think about, is that you want to implement an API call to publish a command to all Aggregates of a specific type in your application.
Taking that scenario then yes, you need to store the aggregateId references yourself.

But concluding with my earlier question: why do you want to retrieve a list of aggregates through the Repository interface?

Answer Update

Regarding your comment, I've added the following to my answer:

Axon helps you to set up your application with event sourcing in mind, but also with CQRS (Command Query Responsibility Segregation).
That thus means that the command and query side of your application are pulled apart.

The Aggregate Repository is the command side of your application, where you request to perform actions.
It thus does not provide a list-of-aggregates, as a command is an expression of intent on a aggregate. Hence it only requires the Repository user to retrieve one aggregate or create one.

The example you've got that you need of the list of Aggregates is the query side of your application.
The query side (your views/entities) is typically updated based on events (sourced through events).
For any query requirement you have in your application, you'd typically introduce a separate view tailored to your needs.

In your example, that means you'd introduce a Event Handling Component, listening to your Aggregate Events, which update a Repository with query models of your aggregate.


问:
Unable to generate google maps API code
Im trying to create API code for google maps but it won't work. I'm signed into my google account, I started with "get a key" "create new" and only get message "couldn't create project" Ive tried different browsers as well... same result. No help from google unless you have paid account.

答:
Try creating a project in Developer Console using your Google account.

If the problem still persists, do these following steps:

File an issue at Google Public Issue Tracker. You don't need to have a paid account for this.

Select the appropriate component, normally, just like this: Public Trackers > Google Maps APIs > Javascript3

In the description. make sure to give enough details so they can handle your issue immediately. Ambiguous description may result for further clarifications.

Issue Tracker is a tool used internally at Google to track bugs and feature requests during product development. It is available outside of Google for use by external public and partner users who need to collaborate with Google teams on specific projects.

You can learn more about Issue Tracker through this link.

Hope it helps!

Title: Unable to generate google maps API code


问:
Is it possible to record all executed information for later replay?
So i'm debugging a very rare case that SEGSEV occurs, I do not know when it will happen, but i know that when it happens, one local var is -1, so I did this in gdb

```<code>break file.c:100 if t1 == -1
</code>```

the problem is i have to go back many steps to find out what happened, is it possible to record all execution information, so that I can replay the execution?

答:
there is currently the rr project for linux which record the execution of your program and help you replay the execution in GDB.

Windows also seem to have some replay debugging capabilities with winDbg preview

Body:
So i'm debugging a very rare case that SEGSEV occurs, I do not know when it will happen, but i know that when it happens, one local var is -1, so I did this in gdb

break file.c:100 if t1 == -1

the problem is i have to go back many steps to find out what happened, is it possible to record all execution information, so that I can replay the execution?


问:
IIS/ASP.NET responds with cache-control: private for all requests
Why does all responses from ASP.NET contain Cache-Control: private? Even a 404 response? Is there something in IIS that sets this default value, and is there a way to configure it? Or is there something in ASP.NET that sets this?

For dynamic content (that is, all MVC results) I would not like it to be cached by the browser, since it is dynamic and can change at any time. Static content is hosted on a CDN, so is not served by IIS.

Edit:

To clarify, I understand very well what Cache-Control: private is, the difference between private, public, no-store, etc and how/when to use them. The question I have is why Cache-Control: private is added by default by IIS/ASP.NET and how to prevent it from being added by default. I understand that it can be useful to cache dynamic pages, but in my application I don't want to cache dynamic pages/responses. For example, I don't want XHR JSON responses to be cached, since they contain dynamic content. Unfortunately the server adds Cache-Control: private to all responses automatically, so I have to manually override it everywhere.

How to reproduce: Open visual studio and create a new ASP.NET Framework (yes, framework, no not Core. We are not able to migrate our system to core yet) solution with an MVC project. Now start the project in IIS Express (just press the play button), and use F12 devtools in the browser to look at the http response. You will see that it contains Cache-Control: private. My question is, what adds this header, and how can I prevent it from being added by default?

答:
An answer from RickNZ, copied from https://forums.asp.net

Cache-Control private says that it's OK for the client to cache the page, subject to its expiration date.  The expiration can either be provided with Cache-Control: max-age, or with an Expires HTTP header.  In the default case, the page is set to expire immediately, which means that it won't be cached.

One of the purposes of Cache-Control: private is really to tell intermediate proxies that they should not cache the page.

BTW, just because a page is dynamic doesn't mean that it should never be cached.  There are many cases where caching a dynamic page is appropriate.  You can cache not only at the client, but also in proxies and in the server's output cache.

More info:

IIS 7.0 - IIS adding "private" to cache-control, where is that coming from

Private vs Public in Cache-Control

https://msdn.microsoft.com/en-us/library/ms524721(v=vs.90).aspx

https://msdn.microsoft.com/en-us/library/system.web.httpcacheability(VS.71).aspx

https://forums.asp.net/t/1443346.aspx?Cache+control+private+

https://forums.asp.net/t/2052325.aspx?Remove+the+private+value+from+the+Cache+Control+in+the+Response+Header


问:
Order on Hive UNION ALL
Say I have two tables with the following data:

```<code>A1
| c1 | c2 |
| a  | b  |

A2
| c1 | c2 |
| c  | d  |
</code>```

I would like to run a select returning the data of both tables, with A1 data above A2 data:

```<code>A1 U A2
| c1 | c2 |
| a  | b  |
| c  | d  |
</code>```

So on Hive I could do something like:

```<code>SELECT * FROM A1
UNION ALL
SELECT * FROM A2
</code>```

But that does not produce the correct results. How could I enforce the order that the UNION ALL happens? Or would be another solution to produce this output?

答:
Without order by it gives arbitrary result, it doesn't guarantee same result every time. I recommended to append order by sort_char clause, to achieve same result every time.

Query:
select sort_char,c1,c2 from (select '1' as sort_char,c1,c2 from tbl1 union all select '2' as sort_char,c1,c2 from tbl2) a order by sort_char;

Title: Order on Hive UNION ALL

Body:
Say I have two tables with the following data:

A1
| c1 | c2 |
| a  | b  |

A2
| c1 | c2 |
| c  | d  |

I would like to run a select returning the data of both tables, with A1 data above A2 data:

A1 U A2
| c1 | c2 |
| a  | b  |
| c  | d  |

So on Hive I could do something like:

SELECT * FROM A1
UNION ALL
SELECT * FROM A2

But that does not produce the correct results. How could I enforce the order that the UNION ALL happens? Or would be another solution to produce this output?


问:
Failed to resolve: com.android.support:appcompat-v7:25.1.0
<img src="https://i.stack.imgur.com/okp2g.png" alt="enter image description here">My Android Studio is full of error android studio cannot identify libraries. </p>

```<code>Error:(27, 13) Failed to resolve: com.android.support:appcompat-v7:25.1.0
</code>```

答:
Firstly, you will go (your_folder_app)\app\app.iml, which open your notepad software.
After you will find:
and you change to 27 with your version, for example for me, i change to 25.

Secondly, you will change the build.gradle(Moudule:app) in your android studio. Red arrow show that you should to change.enter image description here.
Example for me:enter image description here

Finally, you will click "Try Again"

Body:
My Android Studio is full of error android studio cannot identify libraries.

Error:(27, 13) Failed to resolve: com.android.support:appcompat-v7:25.1.0


问:
C# How to sort int when value is too large
```<code>8
723
77715926535897932384626433832795
</code>```

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

答:
I've found the answer at other site as below:

```<code>   string[] unsorted = { "77715926535897932384626433832795", "2398798734", "11" };

    Array.Sort(unsorted,(string a,string b) => {
        if(a.Length == b.Length)
            return string.Compare(a,b,StringComparison.Ordinal);
        return a.Length - b.Length;
    });
</code>```

If I understand it correctly, this will compare each and every element using RAW bytes and hence most efficient.

Body:
8
723
77715926535897932384626433832795

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

Body:
I've found the answer at other site as below:

   string[] unsorted = { "77715926535897932384626433832795", "2398798734", "11" };

    Array.Sort(unsorted,(string a,string b) => {
        if(a.Length == b.Length)
            return string.Compare(a,b,StringComparison.Ordinal);
        return a.Length - b.Length;
    });

If I understand it correctly, this will compare each and every element using RAW bytes and hence most efficient.


问:
How to convert character to ASCII value in ELM
I'm very new to ELM and I would like to ask, how to convert character into its ASCII value (for example 'A' to 65).</p>

答:
As melpomene said you should use toCode. You will have to import it from the Char library. I made a quick example in Ellie:

https://ellie-app.com/7QyfZLsJza1/1

```<code>module Main exposing (main)

import Char exposing (toCode) -- importing toCode ascii conversion from Char
import Html exposing (Html, text)

main : Html msg
main =
    text (toString (toCode 'A'))
</code>```

Body:
As melpomene said you should use toCode. You will have to import it from the Char library. I made a quick example in Ellie:

https://ellie-app.com/7QyfZLsJza1/1

module Main exposing (main)

import Char exposing (toCode) -- importing toCode ascii conversion from Char
import Html exposing (Html, text)

main : Html msg
main =
    text (toString (toCode 'A'))


问:
Rails How to pass params from controller to after_save inside model
I have a Rfq contoller i am creating new or updating existing Rfqs, when i create or update the object is saved, what i want is as i have number of quotes params i want to update the line_items table with the quotes in params[:quotes] in quote_price column after saving the Rfqs

i know its confusing, but who are ror-ish should have got some hint wat i want to ask.

答:
I think you want to be able to have 1 form that saves both the main object and all of the child objects. If not, disregard.

In rails, this is named "nested_attributes"

you'll add this to your model:

```<code>accepts_nested_attributes_for :quotes
# assuming you have
has_many :quotes
</code>```

and then in your form view:

```<code><% form.fields_for :quotes do |child_form| %>
  <%= child_form.text_field :name %>
<% end %>
</code>```

Check this out at Ryan's Blog: Nested Attributes

Body:
I think you want to be able to have 1 form that saves both the main object and all of the child objects. If not, disregard.

In rails, this is named "nested_attributes"

you'll add this to your model:

accepts_nested_attributes_for :quotes
# assuming you have
has_many :quotes

and then in your form view:

<% form.fields_for :quotes do |child_form| %>
  <%= child_form.text_field :name %>
<% end %>

Check this out at Ryan's Blog: Nested Attributes


问:
Azure Kubernetes: TLS handshake timeout
I created a new cluster as per the Azure guide and created the cluster without issue but when I enter the kubectl get nodes to list the nodes I only get this response Unable to connect to the server: net/http: TLS handshake timeout.

I tried once in the Cloud Shell and once on my machine using the latest version of the Azure CLI (2.0.20).

I saw that there was a similar earlier issue regarding Service Principal credentials, which I updated but that didn't seem to solve my issue either.

Any guidance would be greatly appreciated.

答:
For now, Azure AKS still in preview. We have a general service outage in West US 2 that we are investigating.

During the time we investigate, cluster creations in West US 2 will not be possible and existing customers might not work.

We will update this thread when we fix the issue.

We apologize for the inconvenience.

Title: Azure Kubernetes: TLS handshake timeout


问:
How do I install a font on a user's machine in VB.NET so applications like Word can use it?
Need to install a font on all user's machines that will use the application I am writing which creates custom documents in Word.  It's a barcode font.

I've successfully added the font to my solution and set its build action to Embedded Resource and have also successfully written code to check if the font is already installed on the user's system.

Now I just need to figure out how to extract the font from my solution and install it onto the user's machine as if they installed the font themselves for use in Office applications, etc.

Most of the examples I've found out there are for using the font within the VB.NET application instead of outside it and the one's I have found which seem to fit my purpose aren't working for me.

答:
First you copy the font to the windows font folder then call AddFontResource using p/invoke.

Here is an example, it's in C# but you should be able to work it out:

UPDATE

New URL

http://brutaldev.com/post/2009/03/26/Installing-and-removing-fonts-using-C.aspx