问:
How would you tidy up this controller logic?
I've got some logic in a controller that sets a status of an object if certain conditions are met:

```<code>if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end
</code>```

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

答:
Break it down into nested if statements.</p>

```<code>if params[:concept][:consulted_legal] == '0'
  if params[:concept][:consulted_marketing] == '1'
    @concept.attributes = { :status => 'Awaiting Compliance Approval' }
  else
    @concept.attributes = { :status => 'Awaiting Marketing & Legal Approval' }
  end
else
  if params[:consulted_marketing] == '1'
    @concept.attributes = { :status => 'Awaiting Marketing Approval' }
  else
    @concept.attributes = { :status => "Pending Approval" }
  end
end
</code>```

OwnerDisplayName: The Pied Pipes

Body:
I've got some logic in a controller that sets a status of an object if certain conditions are met:

if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

Body:
Break it down into nested if statements.

if params[:concept][:consulted_legal] == '0'
  if params[:concept][:consulted_marketing] == '1'
    @concept.attributes = { :status => 'Awaiting Compliance Approval' }
  else
    @concept.attributes = { :status => 'Awaiting Marketing & Legal Approval' }
  end
else
  if params[:consulted_marketing] == '1'
    @concept.attributes = { :status => 'Awaiting Marketing Approval' }
  else
    @concept.attributes = { :status => "Pending Approval" }
  end
end

OwnerDisplayName: Radar


来源: stackexchange

问:
Keyboard hook only working in the calling process
I am doing a VoIP program where I use keyboard hook to check push-to-talk button is pressed down.
It works locally from the process which installs the hook, but my aim is to have it check all global input too.
Here's what I use:

```<code>SetWindowsHookEx(WH_KEYBOARD,hook_hookproc,hookInst,0);
</code>```

According to MSDN and other sources, I need to inject my hooking dll into all other processes... which would be painful, and I doubt ventrilo/teamspeak etc does that. Is it possible to inject it unto the system process, and then all child processes (everything) inherit the hook call that way? Or do you HAVE to inject it into every single process?

cheers

答:
A global hook like WH_KEYBOARD indeed requires a DLL that can be injected.  You typically have to add some IPC code to tell somebody else about it.  Beware that you are crossing a process boundary doing this so you need something like a pipe to talk.

Have you considered using a low-level keyboard hook (WH_KEYBOARD_LL).  It doesn't require an injectable DLL, Windows switches context to your process to call the hook.  It is almost always good enough to detect a specific keystroke, perhaps combined with GetAsyncKeyState() to check for modifier keys.

A hotkey registered with RegisterHotKey() could perhaps work as well.  It should be your first choice since it has much less impact on the machine.

ContentLicense: CC BY-SA 2.5

Body:
I am doing a VoIP program where I use keyboard hook to check push-to-talk button is pressed down.
It works locally from the process which installs the hook, but my aim is to have it check all global input too.
Here's what I use:

SetWindowsHookEx(WH_KEYBOARD,hook_hookproc,hookInst,0);

According to MSDN and other sources, I need to inject my hooking dll into all other processes... which would be painful, and I doubt ventrilo/teamspeak etc does that. Is it possible to inject it unto the system process, and then all child processes (everything) inherit the hook call that way? Or do you HAVE to inject it into every single process?

cheers


问:
How do you create a python script for a Triangular Irregular Network in a stand alone script?
This is my code. I keep getting an error that says my parameters are not valid:

```<code>import arcpy
arcpy.env.workspace = r"C:\Users\Aliza\Desktop\GIS Programming
Fundamentals\Final_Project\Contours"
arcpy.CheckOutExtension("3D")
out_tin = "SampleTin"
in_features = r"C:\Users\Aliza\Desktop\GIS Programming
Fundamentals\Final_Project\Contours\Site_37_Contours.shp"
height_fields = "None"
sr = arcpy.Describe(in_features).spatialReference
arcpy.CreateTin_3d(out_tin, sr, in_features = in_features, height_field =
None )
</code>```

My goal is to take a contour data set (line shapefile) and turn it into a TIN.

答:
Shouldn't it be something like?

```<code>arcpy.CreateTin_3d(out_tin, sr, in_features, Shape.Z <None> )
</code>```

http://desktop.arcgis.com/en/arcmap/10.3/tools/3d-analyst-toolbox/create-tin.htm

ContentLicense: CC BY-SA 3.0

Body:
This is my code. I keep getting an error that says my parameters are not valid:

import arcpy
arcpy.env.workspace = r"C:\Users\Aliza\Desktop\GIS Programming
Fundamentals\Final_Project\Contours"
arcpy.CheckOutExtension("3D")
out_tin = "SampleTin"
in_features = r"C:\Users\Aliza\Desktop\GIS Programming
Fundamentals\Final_Project\Contours\Site_37_Contours.shp"
height_fields = "None"
sr = arcpy.Describe(in_features).spatialReference
arcpy.CreateTin_3d(out_tin, sr, in_features = in_features, height_field =
None )

My goal is to take a contour data set (line shapefile) and turn it into a TIN.

Body:
Shouldn't it be something like?

arcpy.CreateTin_3d(out_tin, sr, in_features, Shape.Z <None> )

http://desktop.arcgis.com/en/arcmap/10.3/tools/3d-analyst-toolbox/create-tin.htm


问:
Echo database user Name with Posted email
I'm trying to get the user's name from a database after posting his email on a form but its not showing the name, if I add a success message it shows it so it's working but its not showing me the name :(

<?php

$conn = mysqli_connect("xxx", "xxx", "xxxxxxxx", "xxxxxxx");

$email = $_POST['email_r'];

$sqlr = "SELECT * FROM participantes WHERE email='$email'";
$result = $conn->query($sqlr);

if(!$row = mysqli_fetch_assoc($result)) {
    echo "Email Incorrecto: No se a registrado.";
} else {
    echo "your name is: ->" . $row['name'] . " <- that is it.";
}

?>```

答:
If I had to guess, I'd say your table does not have a name column. Either that or the matching record has an empty name value.

This should at least help you pinpoint any potential issues as well as resolve your SQL injection vulnerability...

```<code><?php
// show any errors
ini_set('display_errors', 'On');

// show all errors
error_reporting(E_ALL);

// make MySQLi throw exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$conn = mysqli_connect("xxx", "xxx", "xxxxxxxx", "xxxxxxx");

// safely get the request parameter
$email = isset($_POST['email_r']) ? $_POST['email_r'] : null;

// Prepare a statement with a placeholder for the "email" parameter
$stmt = $conn->prepare('SELECT `name` FROM `participantes` WHERE `email` = ?');

// bind the parameter
$stmt->bind_param('s', $email);
$stmt->execute();

// bind results. This seems easier than fetch_assoc IMHO
$stmt->bind_result($name);

// fetch records, if any
if ($stmt->fetch()) {
    echo 'your name is: ->', $name, ' <- that is it.';
} else {
    echo "Email Incorrecto: No se a registrado.";
}

$stmt->close();
</code>```

Body:
If I had to guess, I'd say your table does not have a name column. Either that or the matching record has an empty name value.

This should at least help you pinpoint any potential issues as well as resolve your SQL injection vulnerability...

<?php
// show any errors
ini_set('display_errors', 'On');

// show all errors
error_reporting(E_ALL);

// make MySQLi throw exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$conn = mysqli_connect("xxx", "xxx", "xxxxxxxx", "xxxxxxx");

// safely get the request parameter
$email = isset($_POST['email_r']) ? $_POST['email_r'] : null;

// Prepare a statement with a placeholder for the "email" parameter
$stmt = $conn->prepare('SELECT `name` FROM `participantes` WHERE `email` = ?');

// bind the parameter
$stmt->bind_param('s', $email);
$stmt->execute();

// bind results. This seems easier than fetch_assoc IMHO
$stmt->bind_result($name);

// fetch records, if any
if ($stmt->fetch()) {
    echo 'your name is: ->', $name, ' <- that is it.';
} else {
    echo "Email Incorrecto: No se a registrado.";
}

$stmt->close();


问:
What is the difference between an array with shape (N,1) and one with shape (N)? And how to convert between the two?
Python newbie here coming from a MATLAB background.

I have a 1 column array and I want to move that column into the first column of a 3 column array. With a MATLAB background this is what I would do:

```<code>import numpy as np

A = np.zeros([150,3]) #three column array

B = np.ones([150,1]) #one column array which needs to replace the first column of A

#MATLAB-style solution:

A[:,0] = B
</code>```

However this does not work because the "shape" of A is (150,3) and the "shape" of B is (150,1). And apparently the command A[:,0] results in a "shape" of (150).

Now, what is the difference between (150,1) and (150)? Aren't they the same thing: a column vector? And why isn't Python "smart enough" to figure out that I want to put the column vector, B, into the first column of A?

Is there an easy way to convert a 1-column vector with shape (N,1) to a 1-column vector with shape (N)?

I am new to Python and this seems like a really silly thing that MATLAB does much better...

答:
Use squeeze method to eliminate the dimensions of size  1.

```<code>A[:,0] = B.squeeze()
</code>```

Or just create B one-dimensional to begin with:

```<code>B = np.ones([150])
</code>```

The fact that NumPy maintains a distinction between a 1D array and 2D array with one of dimensions being 1 is reasonable, especially when one begins working with n-dimensional arrays.

To answer the question in the title: there is an evident structural difference between an array of shape (3,) such as

```<code>[1, 2, 3]
</code>```

and  an array of shape (3, 1) such as

```<code>[[1], [2], [3]]
</code>```

Body:
Python newbie here coming from a MATLAB background.

I have a 1 column array and I want to move that column into the first column of a 3 column array. With a MATLAB background this is what I would do:

import numpy as np

A = np.zeros([150,3]) #three column array

B = np.ones([150,1]) #one column array which needs to replace the first column of A

#MATLAB-style solution:

A[:,0] = B

However this does not work because the "shape" of A is (150,3) and the "shape" of B is (150,1). And apparently the command A[:,0] results in a "shape" of (150).

Now, what is the difference between (150,1) and (150)? Aren't they the same thing: a column vector? And why isn't Python "smart enough" to figure out that I want to put the column vector, B, into the first column of A?

Is there an easy way to convert a 1-column vector with shape (N,1) to a 1-column vector with shape (N)?

I am new to Python and this seems like a really silly thing that MATLAB does much better...

Body:
Use squeeze method to eliminate the dimensions of size  1.

A[:,0] = B.squeeze()

Or just create B one-dimensional to begin with:

B = np.ones([150])

The fact that NumPy maintains a distinction between a 1D array and 2D array with one of dimensions being 1 is reasonable, especially when one begins working with n-dimensional arrays.

To answer the question in the title: there is an evident structural difference between an array of shape (3,) such as

[1, 2, 3]

and  an array of shape (3, 1) such as

[[1], [2], [3]]


问:
stop quartz debug logging log4j
i'm stuck trying to turn off the annoying  DEBUG logging of quartz.
i'm using log4j as logging framework and i've already tried to add this line to the lg4j proprieties file

```<code>"log4j.logger.org.quartz=ERROR"
</code>```

i'm still getting tons of these debugging logging messages

```<code>13:35:44.680 [MyScheduler_QuartzSchedulerThread] DEBUG o.quartz.core.QuartzSchedulerThread - batch acquisition of 0 triggers
</code>```

how can i turn this function off ?

EDIT. i've moved my configuration to xml file...but still getting the same annoying problem

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration>
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <logger name="org.quartz" >
        <level value="ERROR" />
        <appender-ref ref="console" />
    </logger>

    <logger name="org.hibernate">
        <level value="ERROR" />
        <appender-ref ref="console" />
    </logger>

    <logger name="com.mchange.v2.c3p0" additivity="false">
        <level value="ERROR" />
        <appender-ref ref="console" />
    </logger>

    <root>
        <priority value="ERROR" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>
</code>```

EDIT2...here's my pom.xml file (interesting part)

```<code><!-- slf4j-log4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.9</version>
        </dependency>
<!-- QUARTZ -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.1.7</version>
        </dependency>
</code>```

EDIT3 jar in classpath

```<code>activation-1.1.jar
ant-1.8.2.jar
ant-launcher-1.8.2.jar
antlr-2.7.7.jar
asm-1.5.3.jar
asm-attrs-1.5.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
bcmail-jdk14-1.38.jar
bcmail-jdk14-138.jar
bcprov-jdk14-1.38.jar
bcprov-jdk14-138.jar
bctsp-jdk14-1.38.jar
c3p0-0.9.1.1.jar
castor-1.2.jar
cglib-2.1_3.jar
commons-beanutils-1.8.3.jar
commons-codec-1.5.jar
commons-collections-3.2.1.jar
commons-digester-2.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
filename.txt
freemarker-2.3.18.jar
groovy-all-2.1.3.jar
hibernate-3.2.7.ga.jar
hibernate-annotations-3.3.0.ga.jar
hibernate-c3p0-4.1.10.Final.jar
hibernate-commons-annotations-3.3.0.ga.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.10.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
itext-2.1.7.jar
jackson-annotations-2.0.5.jar
jackson-core-2.0.5.jar
jackson-databind-2.0.5.jar
jasperreports-5.1.0.jar
javassist-3.11.0.GA.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
jcommon-1.0.15.jar
jdbc-mysql.jar
jdtcore-3.1.0.jar
jfreechart-1.0.12.jar
jta-1.1.jar
log4j-1.2.9.jar
logback-classic-1.0.10.jar
logback-core-1.0.11.jar
mail-1.4.jar
mysql-connector-java-5.1.6.jar
ognl-3.0.4.jar
ooxml-schemas-1.1.jar
openxml4j-1.0-beta.jar
poi-3.9.jar
poi-contrib-3.7-beta3.jar
poi-examples-3.9.jar
poi-excelant-3.9.jar
poi-ooxml-3.9.jar
poi-ooxml-schemas-3.9.jar
poi-scratchpad-3.9.jar
quartz-2.1.7.jar
servlet-api-2.5.jar
slf4j-api-1.7.2.jar
slf4j-log4j12-1.6.1.jar
stax-api-1.0.1.jar
struts2-core-2.3.1.2.jar
struts2-json-plugin-2.3.1.2.jar
xml-apis-1.0.b2.jar
xmlbeans-2.3.0.jar
xwork-core-2.3.1.2.jar
</code>```

答:
I reset my log4j.xml to </p>

```<code> <root>
    <priority value ="info" />
    <appender-ref ref="console" />
  </root>
</code>```

Title: stop quartz debug logging log4j

Body:
i'm stuck trying to turn off the annoying  DEBUG logging of quartz.
i'm using log4j as logging framework and i've already tried to add this line to the lg4j proprieties file

"log4j.logger.org.quartz=ERROR"

i'm still getting tons of these debugging logging messages

13:35:44.680 [MyScheduler_QuartzSchedulerThread] DEBUG o.quartz.core.QuartzSchedulerThread - batch acquisition of 0 triggers

how can i turn this function off ?

EDIT. i've moved my configuration to xml file...but still getting the same annoying problem

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration>
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <logger name="org.quartz" >
        <level value="ERROR" />
        <appender-ref ref="console" />
    </logger>

    <logger name="org.hibernate">
        <level value="ERROR" />
        <appender-ref ref="console" />
    </logger>

    <logger name="com.mchange.v2.c3p0" additivity="false">
        <level value="ERROR" />
        <appender-ref ref="console" />
    </logger>

    <root>
        <priority value="ERROR" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

EDIT2...here's my pom.xml file (interesting part)

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.9</version>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.1.7</version>
        </dependency>

EDIT3 jar in classpath

activation-1.1.jar
ant-1.8.2.jar
ant-launcher-1.8.2.jar
antlr-2.7.7.jar
asm-1.5.3.jar
asm-attrs-1.5.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
bcmail-jdk14-1.38.jar
bcmail-jdk14-138.jar
bcprov-jdk14-1.38.jar
bcprov-jdk14-138.jar
bctsp-jdk14-1.38.jar
c3p0-0.9.1.1.jar
castor-1.2.jar
cglib-2.1_3.jar
commons-beanutils-1.8.3.jar
commons-codec-1.5.jar
commons-collections-3.2.1.jar
commons-digester-2.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
filename.txt
freemarker-2.3.18.jar
groovy-all-2.1.3.jar
hibernate-3.2.7.ga.jar
hibernate-annotations-3.3.0.ga.jar
hibernate-c3p0-4.1.10.Final.jar
hibernate-commons-annotations-3.3.0.ga.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.10.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
itext-2.1.7.jar
jackson-annotations-2.0.5.jar
jackson-core-2.0.5.jar
jackson-databind-2.0.5.jar
jasperreports-5.1.0.jar
javassist-3.11.0.GA.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
jcommon-1.0.15.jar
jdbc-mysql.jar
jdtcore-3.1.0.jar
jfreechart-1.0.12.jar
jta-1.1.jar
log4j-1.2.9.jar
logback-classic-1.0.10.jar
logback-core-1.0.11.jar
mail-1.4.jar
mysql-connector-java-5.1.6.jar
ognl-3.0.4.jar
ooxml-schemas-1.1.jar
openxml4j-1.0-beta.jar
poi-3.9.jar
poi-contrib-3.7-beta3.jar
poi-examples-3.9.jar
poi-excelant-3.9.jar
poi-ooxml-3.9.jar
poi-ooxml-schemas-3.9.jar
poi-scratchpad-3.9.jar
quartz-2.1.7.jar
servlet-api-2.5.jar
slf4j-api-1.7.2.jar
slf4j-log4j12-1.6.1.jar
stax-api-1.0.1.jar
struts2-core-2.3.1.2.jar
struts2-json-plugin-2.3.1.2.jar
xml-apis-1.0.b2.jar
xmlbeans-2.3.0.jar
xwork-core-2.3.1.2.jar

Body:
I reset my log4j.xml to

 <root>
    <priority value ="info" />
    <appender-ref ref="console" />
  </root>


问:
Removing from a list without affecting a dummy variable
```<code> from random import choice

inputs=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
func={}
code=""
z=len(inputs)
x=z-1
temp=inputs
while x>=0:
    y=choice(temp)
    print(str(x)+"   "+inputs[x]+"   "+y)
    func[inputs[x]]=y
    code=code+inputs[x]+y
    del temp[x]
    x=x-1
    print(temp)
    print(inputs)
</code>```

Why does this code not asign every element of inputs to a unique and random element of inputs(as the temp dummy set)? it seems to delete items from both temp and inputs when only told to delete items from the dummy set.

Thanks for any help.

答:
You are not making a copy of 'inputs' when you do 'temp=inputs', but making a new variable to access the same content. If you want a new copy of the list, then use 'temp = inputs[:]'. Otherwise you are just creating a new reference to the same object, but not duplicating the object itself.

You can find more about this in the official Python FAQ.

Body:
 from random import choice

inputs=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
func={}
code=""
z=len(inputs)
x=z-1
temp=inputs
while x>=0:
    y=choice(temp)
    print(str(x)+"   "+inputs[x]+"   "+y)
    func[inputs[x]]=y
    code=code+inputs[x]+y
    del temp[x]
    x=x-1
    print(temp)
    print(inputs)

Why does this code not asign every element of inputs to a unique and random element of inputs(as the temp dummy set)? it seems to delete items from both temp and inputs when only told to delete items from the dummy set.

Thanks for any help.


问:
Javascript get 3 day before from date formate '2017-11-10' without time
I have a variable has a value of 2017-11-10 and like to get 3 days before from 2017-11-10 which is 2017-11-7

Seems like it only works if you have entire timestamp. However, I removed time from my timestamp.

```<code>let d = new Date();
d.setDate(d.getDate()-1);
</code>```

Is there any ways to do this without time?

答:
You can just init your date string to javascript Date as below example</p>

```<code>let d = new Date(2017, 10, 10);
d.setDate(d.getDate()-3);
</code>```

Body:
I have a variable has a value of 2017-11-10 and like to get 3 days before from 2017-11-10 which is 2017-11-7

Seems like it only works if you have entire timestamp. However, I removed time from my timestamp.

let d = new Date();
d.setDate(d.getDate()-1);

Is there any ways to do this without time?

Body:
You can just init your date string to javascript Date as below example

let d = new Date(2017, 10, 10);
d.setDate(d.getDate()-3);


问:
UILabel wrong size calculations on iPhone
I am adjusting my old apps to iPhone 4 using the simulator at the moment and I can across a very strange behavior with UILabel drawing and  sizeWithFont:constrainedToSize: that I currently see only on the iPhone 4 simulator.

I am trying to show the following error text to the user:
@"Incorrect user name or password"
This text sits inside a dynamic error box that is built from three parts: top, center and bottom and therefore I calculate the size of the label so I can change the center background image frame accordingly.

Here is an example of the UILabel size calculation code:

```<code>CGRect errorFrame = CGRectMake(40, 0, 240.0, 22.0);
UILabel *errorlabel = [[UILabel alloc] initWithFrame:errorFrame];
errorlabel.adjustsFontSizeToFitWidth = NO;
errorlabel.font = [UIFont fontWithName:@"HelveticaNeue" size:16];
errorlabel.textAlignment = UITextAlignmentLeft;
errorlabel.numberOfLines = 0;
errorlabel.text = @"Incorrect user name or password";
// since only the width is fixed I will use a really large height value
CGSize errorLabelSize = [errorlabel.text sizeWithFont:errorlabel.font constrainedToSize:CGSizeMake(240.0, 4600.0)];
CGRect newFrame = errorlabel.frame;
newFrame.size.height = errorLabelSize.height;
errorlabel.frame = newFrame;
    // added so I can easily see the new frame
errorlabel.backgroundColor = [UIColor redColor];
[self.errorView addSubview:errorlabel];
[errorlabel release];
</code>```

When I run the code on the iPhone 3 simulator the sizeWithFont:constrainedToSize: method returns a height of 1 line and draws this error text on 1 line.
When I run the same code on the iPhone 4 simulator sizeWithFont:constrainedToSize: returns a size of (170.0, 42.0) which is needed for two lines but label itself is drawn on 1 line.
It is as if the sizeWithFont code doesn't use the same logics of the rendering code.

Since changing the error text is no option :) any idea how to bypass this issue or resolve it?

Thanks in advance

答: I noticed this issue. Also noticed that when using iPhone 4, a blank space that is included in a string of text is calculated as 4 pts wide, but if you calculate the width of a blank space by itself, it is calculated as 5pts wide....  (using ArialMT, 14pt)</p>

Body:
I am adjusting my old apps to iPhone 4 using the simulator at the moment and I can across a very strange behavior with UILabel drawing and  sizeWithFont:constrainedToSize: that I currently see only on the iPhone 4 simulator.

I am trying to show the following error text to the user:
@"Incorrect user name or password"
This text sits inside a dynamic error box that is built from three parts: top, center and bottom and therefore I calculate the size of the label so I can change the center background image frame accordingly.

Here is an example of the UILabel size calculation code:

CGRect errorFrame = CGRectMake(40, 0, 240.0, 22.0);
UILabel *errorlabel = [[UILabel alloc] initWithFrame:errorFrame];
errorlabel.adjustsFontSizeToFitWidth = NO;
errorlabel.font = [UIFont fontWithName:@"HelveticaNeue" size:16];
errorlabel.textAlignment = UITextAlignmentLeft;
errorlabel.numberOfLines = 0;
errorlabel.text = @"Incorrect user name or password";
// since only the width is fixed I will use a really large height value
CGSize errorLabelSize = [errorlabel.text sizeWithFont:errorlabel.font constrainedToSize:CGSizeMake(240.0, 4600.0)];
CGRect newFrame = errorlabel.frame;
newFrame.size.height = errorLabelSize.height;
errorlabel.frame = newFrame;
    // added so I can easily see the new frame
errorlabel.backgroundColor = [UIColor redColor];
[self.errorView addSubview:errorlabel];
[errorlabel release];

When I run the code on the iPhone 3 simulator the sizeWithFont:constrainedToSize: method returns a height of 1 line and draws this error text on 1 line.
When I run the same code on the iPhone 4 simulator sizeWithFont:constrainedToSize: returns a size of (170.0, 42.0) which is needed for two lines but label itself is drawn on 1 line.
It is as if the sizeWithFont code doesn't use the same logics of the rendering code.

Since changing the error text is no option :) any idea how to bypass this issue or resolve it?

Thanks in advance


问:
Kubernetes/Azure ACS: Why can't I access external IPs of my Service?
Using Kubernetes on Azure Container Service (not the new AKS though).

I'm deploying a front-end up like this:

```<code>apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: frontend-deployment
spec:
  selector:
    matchLabels:
      app: frontend
  replicas: 2
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: etc/etc
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: frontend
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 3000
  selector:
    app: frontend
</code>```

I can see that it's started correctly from the logs.

From kubectl get services I can see that it has been assigned an External IP. But when I try to access that via HTTP it just hangs.

I also can see in the Azure Portal that the Azure Load Balancer was created and is pointing to the correct external IP and backend pool.

Can anyone tell me if I somehow messed up the port assignments in the pod definition?

--

Update: Somehow it started working on it's own (or seemed like). But when I tried to re-create it as a Service instead of Deployment it stopped working

Here's my Service:

This is my config:

```<code>apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  name: meteor
spec:
  externalTrafficPolicy: Cluster
  ports:
  - port: 80
    protocol: TCP
    targetPort: http-server
  selector:
    app: frontend
  sessionAffinity: ClientIP
  type: LoadBalancer
</code>```

It creates the external IP for the load balancer, and I can see that it is properly matching the pods. but I get a timeout when I try to connect to the external IP. Meanwhile the load balancer that was created as part of the deployment continues to work just fine.

答:
do you know how to change the agent VM size in an existing ACS
  deployment?

We can change k8s agent via Azure portal, the agent in Azure is a VM, we should resize the VM :

Hope this helps.

Body:
Using Kubernetes on Azure Container Service (not the new AKS though).

I'm deploying a front-end up like this:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: frontend-deployment
spec:
  selector:
    matchLabels:
      app: frontend
  replicas: 2
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: etc/etc
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: frontend
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 3000
  selector:
    app: frontend

I can see that it's started correctly from the logs.

From kubectl get services I can see that it has been assigned an External IP. But when I try to access that via HTTP it just hangs.

I also can see in the Azure Portal that the Azure Load Balancer was created and is pointing to the correct external IP and backend pool.

Can anyone tell me if I somehow messed up the port assignments in the pod definition?

--

Update: Somehow it started working on it's own (or seemed like). But when I tried to re-create it as a Service instead of Deployment it stopped working

Here's my Service:

This is my config:

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  name: meteor
spec:
  externalTrafficPolicy: Cluster
  ports:
  - port: 80
    protocol: TCP
    targetPort: http-server
  selector:
    app: frontend
  sessionAffinity: ClientIP
  type: LoadBalancer

It creates the external IP for the load balancer, and I can see that it is properly matching the pods. but I get a timeout when I try to connect to the external IP. Meanwhile the load balancer that was created as part of the deployment continues to work just fine.


问:
Office update killed my VBA code to paste Excel tables to an existing PowerPoint file and slides
After a recent Office 365 update, my code to copy tables from Excel to Power Point stopped working.

Previous code:

```<code>Sub GeneratePresentation()

Dim pptApp As PowerPoint.Application
Dim pptPrez As PowerPoint.Presentation
Dim pSlide As PowerPoint.Slide
Dim objPPT As Object
Dim myRange As Excel.Range

Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True

MonthNo = Month(Worksheets("inputs").Range("B3"))
MonthData = Worksheets("inputs").Cells(MonthNo + 10, 9)

If MonthData = "" Then
    MsgBox "Please update losses"

Else

    FilePath = "\\Model\"
    Filename = "Template Monthly reports.pptx"
    file = FilePath & Filename
    Set pptPrez = objPPT.Presentations.Open(file)

    Set pptApp = GetObject(Class:="PowerPoint.Application")
    Set pptPrez = pptApp.ActivePresentation

'Slide 1 title 1
    Set pSlide = pptPrez.Slides(1)
    Sheets("01").Range("D3") = "= ""Midstream Monthly Production Report "" & Text(Inputs!B3, ""Mmmm YYYY"") & "" - internal"""
    Sheets("01").Range("D3").Copy
    Set osh = pSlide.Shapes.PasteSpecial(ppPasteDefault)(1)
    With osh
        .Top = 160
        .Left = 135
        .Height = 80
        .Width = 550
    End With
</code>```

Code continues to paste tables and pictures. then

```<code>End if
End sub
</code>```

I get the following error:

VBA error Run-time '-2147188160 (80048240)': Shapes (unknown member)

I have tried most variants of paste but it only lets me paste pictures or text. I noticed that the VBA refernce library revision seems to have reduced to Microsoft PowerPoint 14.0 Object library when I am fairly sure it was build 15 or 16 before. Would this be the cause?

I have come up with a solution which is to use

```<code>'Slide 1 title 1
i = 1
Set pSlide = pptPrez.Slides(i)
Sheets("01").Range("D3") = "= ""Midstream Monthly Production Report "" & Text(Inputs!B3, ""Mmmm YYYY"") & "" - internal"""
Sheets("01").Range("D3").Copy
pptPrez.Windows(1).Activate
pptPrez.Windows(1).View.GotoSlide i
pptPrez.Slides(i).Shapes("Title").Select
pptApp.CommandBars.ExecuteMso ("PasteSourceFormatting")
With pptPrez.Slides(i)
    With .Shapes("Title")
        .LockAspectRatio = msoFalse
        .Top = 160
        .Left = 135
        .Height = 70
        .Width = 550
        '.TextFrame.TextRange.Font.Name = "Futura Bold"
        '.TextFrame.TextRange.Font.Size = 24
        '.TextFrame.TextRange.ParagraphFormat.Alignment = ppAlignLeft
        '.TextFrame.TextRange.ParagraphFormat.WordWrap = msoTrue
    End With
End With
</code>```

For the alternative, I have to create all the tables manually then name them and select them in the code which works, but it seems less consistent and reliable requiring the windows to be active being more to go wrong.

Any ideas how to get the first code working again? I can paste manually still but it seems not using pastespecial. Why would an update remove this ability? I've tried proven code from this forum using this paste function but it won't work either which used to, It's definitely the update as all our computers now have the same issue which I find hard to believe too.

答:
I decided to write an answer instead of a bunch of comments, since I wanted to post my code.

Those Office 365 updates have caught me a time or three. But I don't know what's the problem.

The code fails on PasteSpecial? PasteSpecial is a relative newcomer to PowerPoint VBA, but I thought it was around for Office 14 (2010). The reference to version 14.0 of the PowerPoint library is strange. Can you go to Tools > References and scroll to version 16.0? If so, check that one instead. What version of Office are you using: go to File tab > Account, and find the version number and build number.

Why do you have both CreateObject and GetObject. For PowerPoint, you only need to do this once, using CreateObject. If PowerPoint is running, CreateObject returns the running instance; if not, it returns a new instance. Probably not important, but it adds clutter. Move CreateObject up to where GetObject is, and change objPPT to pptApp (since you don't need both).

Also, you've used three variables which are not declared. Declare MonthNo and MonthData as Variant and osh as PowerPoint.Shape (actually, in my code I renamed it pptShape and pSlide to pptSlide for consistency).

With the additional modification to use the active presentation instead of opening one at a given path and file name, your code works fine for me. I'm running Version 1711, Build 8711.2037, for what it's worth.

And here's the code that ran fine for me.

```<code>Sub GeneratePresentation()
  Dim pptApp As PowerPoint.Application
  Dim pptPrez As PowerPoint.Presentation
  Dim pptSlide As PowerPoint.Slide
  Dim myRange As Excel.Range
  Dim pptShape As PowerPoint.Shape
  Dim MonthNo As Variant
  Dim MonthData As Variant

  MonthNo = Month(Worksheets("inputs").Range("B3"))
  MonthData = Worksheets("inputs").Cells(MonthNo + 10, 9)

  If MonthData = "" Then
    MsgBox "Please update losses"

  Else
    Set pptApp = GetObject(Class:="PowerPoint.Application")
    Set pptPrez = pptApp.ActivePresentation

    '' JP - use active presentation instead of opening one
    ''FilePath = "\\Model\"
    ''Filename = "Template Monthly reports.pptx"
    ''file = FilePath & Filename
    ''Set pptPrez = objPPT.Presentations.Open(file)
    Set pptPrez = pptApp.ActivePresentation

    'Slide 1 title 1
    Set pptSlide = pptPrez.Slides(1)
    Sheets("01").Range("D3") = "= ""Midstream Monthly Production Report "" _
        & Text(Inputs!B3, ""Mmmm YYYY"") & "" - internal"""
    Sheets("01").Range("D3").Copy
    Set pptShape = pptSlide.Shapes.PasteSpecial(ppPasteDefault)(1)
    With pptShape
      .Top = 160
      .Left = 135
      .Height = 80
      .Width = 550
    End With
  End If
End Sub
</code>```

Body:
After a recent Office 365 update, my code to copy tables from Excel to Power Point stopped working.

Previous code:

Sub GeneratePresentation()

Dim pptApp As PowerPoint.Application
Dim pptPrez As PowerPoint.Presentation
Dim pSlide As PowerPoint.Slide
Dim objPPT As Object
Dim myRange As Excel.Range

Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True

MonthNo = Month(Worksheets("inputs").Range("B3"))
MonthData = Worksheets("inputs").Cells(MonthNo + 10, 9)

If MonthData = "" Then
    MsgBox "Please update losses"

Else

    FilePath = "\\Model\"
    Filename = "Template Monthly reports.pptx"
    file = FilePath & Filename
    Set pptPrez = objPPT.Presentations.Open(file)

    Set pptApp = GetObject(Class:="PowerPoint.Application")
    Set pptPrez = pptApp.ActivePresentation

'Slide 1 title 1
    Set pSlide = pptPrez.Slides(1)
    Sheets("01").Range("D3") = "= ""Midstream Monthly Production Report "" & Text(Inputs!B3, ""Mmmm YYYY"") & "" - internal"""
    Sheets("01").Range("D3").Copy
    Set osh = pSlide.Shapes.PasteSpecial(ppPasteDefault)(1)
    With osh
        .Top = 160
        .Left = 135
        .Height = 80
        .Width = 550
    End With

Code continues to paste tables and pictures. then

End if
End sub

I get the following error:

VBA error Run-time '-2147188160 (80048240)': Shapes (unknown member)

I have tried most variants of paste but it only lets me paste pictures or text. I noticed that the VBA refernce library revision seems to have reduced to Microsoft PowerPoint 14.0 Object library when I am fairly sure it was build 15 or 16 before. Would this be the cause?

I have come up with a solution which is to use

'Slide 1 title 1
i = 1
Set pSlide = pptPrez.Slides(i)
Sheets("01").Range("D3") = "= ""Midstream Monthly Production Report "" & Text(Inputs!B3, ""Mmmm YYYY"") & "" - internal"""
Sheets("01").Range("D3").Copy
pptPrez.Windows(1).Activate
pptPrez.Windows(1).View.GotoSlide i
pptPrez.Slides(i).Shapes("Title").Select
pptApp.CommandBars.ExecuteMso ("PasteSourceFormatting")
With pptPrez.Slides(i)
    With .Shapes("Title")
        .LockAspectRatio = msoFalse
        .Top = 160
        .Left = 135
        .Height = 70
        .Width = 550
        '.TextFrame.TextRange.Font.Name = "Futura Bold"
        '.TextFrame.TextRange.Font.Size = 24
        '.TextFrame.TextRange.ParagraphFormat.Alignment = ppAlignLeft
        '.TextFrame.TextRange.ParagraphFormat.WordWrap = msoTrue
    End With
End With

For the alternative, I have to create all the tables manually then name them and select them in the code which works, but it seems less consistent and reliable requiring the windows to be active being more to go wrong.

Any ideas how to get the first code working again? I can paste manually still but it seems not using pastespecial. Why would an update remove this ability? I've tried proven code from this forum using this paste function but it won't work either which used to, It's definitely the update as all our computers now have the same issue which I find hard to believe too.

Body:
I decided to write an answer instead of a bunch of comments, since I wanted to post my code.

Those Office 365 updates have caught me a time or three. But I don't know what's the problem.

The code fails on PasteSpecial? PasteSpecial is a relative newcomer to PowerPoint VBA, but I thought it was around for Office 14 (2010). The reference to version 14.0 of the PowerPoint library is strange. Can you go to Tools > References and scroll to version 16.0? If so, check that one instead. What version of Office are you using: go to File tab > Account, and find the version number and build number.

Why do you have both CreateObject and GetObject. For PowerPoint, you only need to do this once, using CreateObject. If PowerPoint is running, CreateObject returns the running instance; if not, it returns a new instance. Probably not important, but it adds clutter. Move CreateObject up to where GetObject is, and change objPPT to pptApp (since you don't need both).

Also, you've used three variables which are not declared. Declare MonthNo and MonthData as Variant and osh as PowerPoint.Shape (actually, in my code I renamed it pptShape and pSlide to pptSlide for consistency).

With the additional modification to use the active presentation instead of opening one at a given path and file name, your code works fine for me. I'm running Version 1711, Build 8711.2037, for what it's worth.

And here's the code that ran fine for me.

Sub GeneratePresentation()
  Dim pptApp As PowerPoint.Application
  Dim pptPrez As PowerPoint.Presentation
  Dim pptSlide As PowerPoint.Slide
  Dim myRange As Excel.Range
  Dim pptShape As PowerPoint.Shape
  Dim MonthNo As Variant
  Dim MonthData As Variant

  MonthNo = Month(Worksheets("inputs").Range("B3"))
  MonthData = Worksheets("inputs").Cells(MonthNo + 10, 9)

  If MonthData = "" Then
    MsgBox "Please update losses"

  Else
    Set pptApp = GetObject(Class:="PowerPoint.Application")
    Set pptPrez = pptApp.ActivePresentation

    '' JP - use active presentation instead of opening one
    ''FilePath = "\\Model\"
    ''Filename = "Template Monthly reports.pptx"
    ''file = FilePath & Filename
    ''Set pptPrez = objPPT.Presentations.Open(file)
    Set pptPrez = pptApp.ActivePresentation

    'Slide 1 title 1
    Set pptSlide = pptPrez.Slides(1)
    Sheets("01").Range("D3") = "= ""Midstream Monthly Production Report "" _
        & Text(Inputs!B3, ""Mmmm YYYY"") & "" - internal"""
    Sheets("01").Range("D3").Copy
    Set pptShape = pptSlide.Shapes.PasteSpecial(ppPasteDefault)(1)
    With pptShape
      .Top = 160
      .Left = 135
      .Height = 80
      .Width = 550
    End With
  End If
End Sub


问:
Static IP address doesn't work in docker compose v3
From the official document, the static ip address should work with docker compose v3 + docker swarm. But I cannot make it work.

This is my docker compose yaml:

```<code>version: '3'

networks:
test:
    ipam:
    driver: default
    config:
        - subnet: 10.1.0.0/24

services:
one:
    image: mongo
    networks:
    test:
        ipv4_address: '10.1.0.100'

two:
    image: mongo
    networks:
    test:
        ipv4_address: '10.1.0.101'
three:
    image: mongo
    networks:
    test:
        ipv4_address: '10.1.0.102'
</code>```

I use docker stack up -c xxx.yml test to deploy. I found the ip of the created containers are 10.1.0.3, 10.1.0.5, ...

答:
That works in non-swarm mode, but not in swarm mode. You may subscribe to this ticket to find out when/if support is added.

At the moment, there's an anecdotal claim of a workaround, but nobody else seems to have corroborated it.

Body:
From the official document, the static ip address should work with docker compose v3 + docker swarm. But I cannot make it work.

This is my docker compose yaml:

version: '3'

networks:
test:
    ipam:
    driver: default
    config:
        - subnet: 10.1.0.0/24

services:
one:
    image: mongo
    networks:
    test:
        ipv4_address: '10.1.0.100'

two:
    image: mongo
    networks:
    test:
        ipv4_address: '10.1.0.101'
three:
    image: mongo
    networks:
    test:
        ipv4_address: '10.1.0.102'

I use docker stack up -c xxx.yml test to deploy. I found the ip of the created containers are 10.1.0.3, 10.1.0.5, ...


问:
What's the best way to add add 'All' value to <Select> Control?
//Update: I use this <select> control in Filter Bar

In  control of UI5，if I select one item, I can't go back to non-selected state, so I want to add 'All' value in items:

This works:

```<code><Select>
    <core:Item key="" text="All" />
    <core:Item key="another value" text="another value"/>
</Select>
</code>```

But "All" disapear in this example:

```<code><Select
    items="{
        path: '/PRODUCTS'
    }">
    <core:Item key="" text="All" />
    <core:Item key="{ID}" text="{Route_Name}" />
</Select>
</code>```

What should I do?

答:
Similar to @vivek' answer, append an All when data loaded:</p>

```<code>    onHazardTabBarSelect : function(oEvent) {
        var oTabBar = oEvent.getSource(),
        sSelectedTabId = oTabBar.getSelectedKey(),
        oSelectedTab = sap.ui.getCore().byId(sSelectedTabId),
        sAssignmentPath = oSelectedTab.getBindingContext().getPath();

        this._oModel.read( sAssignmentPath + "/assignedControls", {
            urlParameters: {
                "$expand": "control"
            },
            success: this.addControlSelectData.bind(this),
            error: this.errorCallback.bind(this)
        });
    },

    addControlSelectData : function(oEvent) {
        var oSelectControl = this.byId("controlSelect"),
        aControlResults = oEvent.results,
        aResult = [{
            "control" : {
                id: "All",
                name: "All"
            }
        }],
        aData = aResult.concat(aControlResults);
        oSelectControl.setModel(new sap.ui.model.json.JSONModel(aData));
    },
</code>```

Body:
//Update: I use this <select> control in Filter Bar

In  control of UI5，if I select one item, I can't go back to non-selected state, so I want to add 'All' value in items:

This works:

<Select>
    <core:Item key="" text="All" />
    <core:Item key="another value" text="another value"/>
</Select>

But "All" disapear in this example:

<Select
    items="{
        path: '/PRODUCTS'
    }">
    <core:Item key="" text="All" />
    <core:Item key="{ID}" text="{Route_Name}" />
</Select>

What should I do?

Body:
Similar to @vivek' answer, append an All when data loaded:

    onHazardTabBarSelect : function(oEvent) {
        var oTabBar = oEvent.getSource(),
        sSelectedTabId = oTabBar.getSelectedKey(),
        oSelectedTab = sap.ui.getCore().byId(sSelectedTabId),
        sAssignmentPath = oSelectedTab.getBindingContext().getPath();

        this._oModel.read( sAssignmentPath + "/assignedControls", {
            urlParameters: {
                "$expand": "control"
            },
            success: this.addControlSelectData.bind(this),
            error: this.errorCallback.bind(this)
        });
    },

    addControlSelectData : function(oEvent) {
        var oSelectControl = this.byId("controlSelect"),
        aControlResults = oEvent.results,
        aResult = [{
            "control" : {
                id: "All",
                name: "All"
            }
        }],
        aData = aResult.concat(aControlResults);
        oSelectControl.setModel(new sap.ui.model.json.JSONModel(aData));
    },


问:
Avro serializer and deserializer with kafka java api
Kafka Avro serializer and deserializer is not working. I tried consuming the messages using the kafka console consumer and i could see the messages published.

```<code>public class AvroProducer<T> {

    private static Properties props;
    static {
        props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
        props.put(ProducerConfig.CLIENT_ID_CONFIG, "Kafka Avro Producer");
    }

    private static KafkaProducer producer = new KafkaProducer<>(props);

    public byte[] createRecords(T pojo) throws IOException{
        Schema.Parser parser = new Schema.Parser();
        Schema schema = null;
        try {
            schema = parser.parse(AvroProducer.class.getClassLoader().getResourceAsStream("syslog.avsc"));
        } catch (IOException e) {
            System.out.println(e.getLocalizedMessage());
        }

        final GenericData.Record record = new GenericData.Record(schema);
        schema.getFields().forEach(r -> record.put(r.name(), PropertyAccessorFactory.forDirectFieldAccess(pojo).getPropertyValue(r.name())));
        SpecificDatumWriter<GenericRecord> writer = new SpecificDatumWriter<>(schema);
        try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
            BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(os, null);

            writer.write(record, encoder);
            encoder.flush();
            byte[] bytemessage = os.toByteArray();
            return bytemessage;
        }

    }

    public static void sendMessage(byte[] bytemessage){
        ProducerRecord precord = new ProducerRecord<StringSerializer, byte[]>("jason", bytemessage);
        producer.send(precord);
    }
}

    public class AvroConsumer {

    private static Properties kafkaProps;

    static {
        kafkaProps = new Properties();
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "AvroConsumer-GroupOne");
    }

    @SuppressWarnings("unchecked")
    public static void recieveRecord() throws IOException{
        try (KafkaConsumer<String,byte[]> kafkaConsumer = new KafkaConsumer<>(kafkaProps)) {
            kafkaConsumer.subscribe(Arrays.asList("jason"));
            while (true) {
                ConsumerRecords<String,byte[]> records = kafkaConsumer.poll(100);
                Schema.Parser parser = new Schema.Parser();
                final Schema schema = parser.parse(AvroProducer.class.getClassLoader().getResourceAsStream("syslog.avsc"));
                records.forEach(record -> {
                    SpecificDatumReader<GenericRecord> datumReader = new SpecificDatumReader<>(schema);
                    ByteArrayInputStream is = new ByteArrayInputStream(record.value());
                    BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(is, null);
                    try {
                        Syslog log = (Syslog) datumReader.read(null, binaryDecoder);

                        System.out.println("Value: " + log);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }

}
</code>```

Stack trace is as below.Please find the details. Can someone guide me with the right implementation. The problem seems to be with the casting record.how to access the value. How to read the data using the Specific Datum Reader.

```<code>Exception in thread "Thread-1" java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to com.cisco.daas.kafka.Syslog
at com.cisco.daas.kafka.AvroConsumer.lambda$0(AvroConsumer.java:46)
at java.lang.Iterable.forEach(Unknown Source)
at com.cisco.daas.kafka.AvroConsumer.recieveRecord(AvroConsumer.java:41)
at com.cisco.daas.kafka.MainApp$1.run(MainApp.java:32)
at java.lang.Thread.run(Unknown Source)
</code>```

This is the schema i am trying to parse

```<code>{
    "namespace": "com.example.syslogmessage",
    "type": "record",
    "name": "SysLogMessage",
    "fields": [{
            "name": "partyID",
            "type": "long"
        },
        {
            "name": "applianceID",
            "type": "string"
        },
        {
            "name": "message",
            "type": "string"
        },
        {
            "name": "severity",
            "type": "long"
        },
        {
            "name": "messageType",
            "type": "string"
        },
        {
            "name": "eventtime",
            "type": "long",
            "logicalType": "timestamp-millis"
        },
        {
            "name": "ipaddress",
            "type": "string"
        },
        {
            "name": "hostname",
            "type": "string"
        }
    ]
}
</code>```

答:
The issue is resolved by using the key, value of the GenericRecord</p>
```<code>public class AvroConsumer<T> {

    private static Properties kafkaProps;

    static {
        kafkaProps = new Properties();
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "AvroConsumer-GroupOne");
    }

    public void recieveRecord() throws IOException {
       Schema.Parser parser = new Schema.Parser();
       final Schema schema = parser
                        .parse(AvroConsumer.class.getClassLoader().getResourceAsStream("syslog.avsc"));
        SpecificDatumReader<T> datumReader = new SpecificDatumReader<>(schema);
        try (KafkaConsumer<String, byte[]> kafkaConsumer = new KafkaConsumer<>(kafkaProps)) {
            kafkaConsumer.subscribe(Arrays.asList("jason"));
            while (true) {
                ConsumerRecords<String, byte[]> records = kafkaConsumer.poll(100);
                records.forEach(record -> {
                    ByteArrayInputStream is = new ByteArrayInputStream(record.value());
                    BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(is, null);
                    try {
                        T log = datumReader.read(null, binaryDecoder);
                        System.out.println("Value: " + log);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }

}
</code>```

Body:
Kafka Avro serializer and deserializer is not working. I tried consuming the messages using the kafka console consumer and i could see the messages published.

public class AvroProducer<T> {

    private static Properties props;
    static {
        props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
        props.put(ProducerConfig.CLIENT_ID_CONFIG, "Kafka Avro Producer");
    }

    private static KafkaProducer producer = new KafkaProducer<>(props);

    public byte[] createRecords(T pojo) throws IOException{
        Schema.Parser parser = new Schema.Parser();
        Schema schema = null;
        try {
            schema = parser.parse(AvroProducer.class.getClassLoader().getResourceAsStream("syslog.avsc"));
        } catch (IOException e) {
            System.out.println(e.getLocalizedMessage());
        }

        final GenericData.Record record = new GenericData.Record(schema);
        schema.getFields().forEach(r -> record.put(r.name(), PropertyAccessorFactory.forDirectFieldAccess(pojo).getPropertyValue(r.name())));
        SpecificDatumWriter<GenericRecord> writer = new SpecificDatumWriter<>(schema);
        try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
            BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(os, null);

            writer.write(record, encoder);
            encoder.flush();
            byte[] bytemessage = os.toByteArray();
            return bytemessage;
        }

    }

    public static void sendMessage(byte[] bytemessage){
        ProducerRecord precord = new ProducerRecord<StringSerializer, byte[]>("jason", bytemessage);
        producer.send(precord);
    }
}

    public class AvroConsumer {

    private static Properties kafkaProps;

    static {
        kafkaProps = new Properties();
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "AvroConsumer-GroupOne");
    }

    @SuppressWarnings("unchecked")
    public static void recieveRecord() throws IOException{
        try (KafkaConsumer<String,byte[]> kafkaConsumer = new KafkaConsumer<>(kafkaProps)) {
            kafkaConsumer.subscribe(Arrays.asList("jason"));
            while (true) {
                ConsumerRecords<String,byte[]> records = kafkaConsumer.poll(100);
                Schema.Parser parser = new Schema.Parser();
                final Schema schema = parser.parse(AvroProducer.class.getClassLoader().getResourceAsStream("syslog.avsc"));
                records.forEach(record -> {
                    SpecificDatumReader<GenericRecord> datumReader = new SpecificDatumReader<>(schema);
                    ByteArrayInputStream is = new ByteArrayInputStream(record.value());
                    BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(is, null);
                    try {
                        Syslog log = (Syslog) datumReader.read(null, binaryDecoder);

                        System.out.println("Value: " + log);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }

}

Stack trace is as below.Please find the details. Can someone guide me with the right implementation. The problem seems to be with the casting record.how to access the value. How to read the data using the Specific Datum Reader.

Exception in thread "Thread-1" java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to com.cisco.daas.kafka.Syslog
at com.cisco.daas.kafka.AvroConsumer.lambda$0(AvroConsumer.java:46)
at java.lang.Iterable.forEach(Unknown Source)
at com.cisco.daas.kafka.AvroConsumer.recieveRecord(AvroConsumer.java:41)
at com.cisco.daas.kafka.MainApp$1.run(MainApp.java:32)
at java.lang.Thread.run(Unknown Source)

This is the schema i am trying to parse

{
    "namespace": "com.example.syslogmessage",
    "type": "record",
    "name": "SysLogMessage",
    "fields": [{
            "name": "partyID",
            "type": "long"
        },
        {
            "name": "applianceID",
            "type": "string"
        },
        {
            "name": "message",
            "type": "string"
        },
        {
            "name": "severity",
            "type": "long"
        },
        {
            "name": "messageType",
            "type": "string"
        },
        {
            "name": "eventtime",
            "type": "long",
            "logicalType": "timestamp-millis"
        },
        {
            "name": "ipaddress",
            "type": "string"
        },
        {
            "name": "hostname",
            "type": "string"
        }
    ]
}

Body:
The issue is resolved by using the key, value of the GenericRecord

public class AvroConsumer<T> {

    private static Properties kafkaProps;

    static {
        kafkaProps = new Properties();
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "AvroConsumer-GroupOne");
    }

    public void recieveRecord() throws IOException {
       Schema.Parser parser = new Schema.Parser();
       final Schema schema = parser
                        .parse(AvroConsumer.class.getClassLoader().getResourceAsStream("syslog.avsc"));
        SpecificDatumReader<T> datumReader = new SpecificDatumReader<>(schema);
        try (KafkaConsumer<String, byte[]> kafkaConsumer = new KafkaConsumer<>(kafkaProps)) {
            kafkaConsumer.subscribe(Arrays.asList("jason"));
            while (true) {
                ConsumerRecords<String, byte[]> records = kafkaConsumer.poll(100);
                records.forEach(record -> {
                    ByteArrayInputStream is = new ByteArrayInputStream(record.value());
                    BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(is, null);
                    try {
                        T log = datumReader.read(null, binaryDecoder);
                        System.out.println("Value: " + log);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }

}

ContentLicense: CC BY-SA 4.0


问:
Why do I have to put media queries at the bottom of the stylesheet?
I am new to learning responsive design. What I have noticed on my journey is that when I put media queries at the bottom of the stylesheet, everything works flawlessly in regards to  breakpoints. If I put the media queries at the top of the stylesheet, nothing works, and only recently I found out that I need to add !important and max-DEVICE-width ( as opposed to max-width) to the css that is being changed.

Why is this? Why do the media queries work on both desktop and mobile when put at the bottom of the stylesheet.

Why is it that when I put media queries on the top of the stylesheet I need to add !important and also max-DEVICE-width in order for the breakpoints to work on desktop and mobile?

答:
Media queries cascade with the rest of the stylesheet. You can intersperse media queries within your stylesheet, and so you can also cascade styles as needed.

For example:

```<code>.my-class {
    color: red;
}

.my-class--modifier {
    color: blue;
}

@media screen and (min-width: 760px) {
    .my-class--modifier {
        color: green;
    }
}

.some-other-class {
    width: 200px;
}

@media screen and (min-width: 760px) {
    .some-other-class {
        width: 700px;
        background-color: gray;
    }
    .some-other-class .my-class {
        border: 2px solid red;
        border-radius: 4pt;
    }
}
</code>```

This works precisely due to CSS's cascading nature. You can organize media queries as required based on sections, individual selectors and more.

Body:
Media queries cascade with the rest of the stylesheet. You can intersperse media queries within your stylesheet, and so you can also cascade styles as needed.

For example:

.my-class {
    color: red;
}

.my-class--modifier {
    color: blue;
}

@media screen and (min-width: 760px) {
    .my-class--modifier {
        color: green;
    }
}

.some-other-class {
    width: 200px;
}

@media screen and (min-width: 760px) {
    .some-other-class {
        width: 700px;
        background-color: gray;
    }
    .some-other-class .my-class {
        border: 2px solid red;
        border-radius: 4pt;
    }
}

This works precisely due to CSS's cascading nature. You can organize media queries as required based on sections, individual selectors and more.


问:
How to check whether input value is integer or float?
How to check whether input value is integer or float?

Suppose 312/100=3.12
Here i need check whether 3.12 is a float value or integer value, i.e., without any decimal place value.

答:
Math.round() returns the nearest integer to your given input value. If your float already has an integer value the "nearest" integer will be that same value, so all you need to do is check whether Math.round() changes the value or not:

```<code>if (value == Math.round(value)) {
  System.out.println("Integer");
} else {
  System.out.println("Not an integer");
}
</code>```

Body:
Math.round() returns the nearest integer to your given input value. If your float already has an integer value the "nearest" integer will be that same value, so all you need to do is check whether Math.round() changes the value or not:

if (value == Math.round(value)) {
  System.out.println("Integer");
} else {
  System.out.println("Not an integer");
}


问:
In React, Is it possible to get access to Redux action creators from inside a utility function?
I have a form input validation function that just returns an empty errors object or a populated errors object.

```<code>const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  return errors
}

export default validate
</code>```

Is there a way to hook an action creator into this function?

This is what I am trying to achieve:

```<code>const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  props.onErrorEvent('do something')
  return errors
}

export default connect(null, { onErrorEvent })(validate)
</code>```

My issue is that since it's not a class, I don't have access to this.props, and I have never tried to make a container before that doesn't render any JSX.

I also can't create a callback into the parent because the validate function is controlled by Redux-Form.

It's used like this in the parent container:

```<code>export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)
</code>```

Is it possible to wire an action creator into a utility function that doesn't render JSX and can't callback to parent?

I'd also like to know if this is bordering into any kind of horrendous anti-pattern territory because I can't find any information about allowing random utility functions to call action creators.

I didn't see a solution with bindActionCreators, but maybe I just didn't see how it relates to this scenario.

Is there a way I can create a HOC in this scenario?

答:
Redux Thunk would be a good way to do this. It's a middleware that allows you to write action creators that return functions, gives you access to the store, and allows you to dispatch other actions from action creators.

import { onErrorEvent } from '../wherever';

const validate = function validateSomeInput({ field1, field2 }) {
  return function(dispatch, getState) {
    const errors = {}
    // some logic
    dispatch(onErrorEvent('do something'))
    return errors
  }
}```

Body:
I have a form input validation function that just returns an empty errors object or a populated errors object.

const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  return errors
}

export default validate

Is there a way to hook an action creator into this function?

This is what I am trying to achieve:

const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  props.onErrorEvent('do something')
  return errors
}

export default connect(null, { onErrorEvent })(validate)

My issue is that since it's not a class, I don't have access to this.props, and I have never tried to make a container before that doesn't render any JSX.

I also can't create a callback into the parent because the validate function is controlled by Redux-Form.

It's used like this in the parent container:

export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)

Is it possible to wire an action creator into a utility function that doesn't render JSX and can't callback to parent?

I'd also like to know if this is bordering into any kind of horrendous anti-pattern territory because I can't find any information about allowing random utility functions to call action creators.

I didn't see a solution with bindActionCreators, but maybe I just didn't see how it relates to this scenario.

Is there a way I can create a HOC in this scenario?


问:
Can I refresh `node_modules` without restarting my nodejs application?
Is that possible to refresh some dependencies when a node.js application is running ?

For instance, I'm using a specific version of lodash, a new version is released, can I trigger the refresh directly from my app, or I'll add necessariliy to edit package.json and rebuild the app manually?

答:
Just to get a few facts straight:

Once a module is loaded, the operative code lives in memory in the JS interpreter.  Changing the file on disk has no affect at all.

Once a module is loaded and other modules have a reference to it, there is no systematic way to replace that module reference with a new one.  You could conceivably delete the prior module from the module cache, load a new module, get a new module handle and manually tell every piece of code that was using the prior module that they should switch over to using the new module handle, but that's a lot of custom code and there are likely some caveats to making that work properly in some circumstances.

node.js does not have any built-in way to replace code with a new version of the code.

The usual way to "upgrade" your code is to replace the code with the updated code and then restart your app so it will load the new version of the code.

Is that possible to refresh some dependencies when a node.js application is running ?

So, it is technically feasible to manually delete a module from the module cache, then manually load an update version of the module and then manually tell everyone who was using the old module handle that they should switch over to the new module handle.  But, this all assumes that there's no state in the original module that needs to be preserved and assumes that you have some way of giving every user of the module a new module handle.  It's a big hand coded project with a lot of limitations (e.g. only works in very limited circumstances).

For instance, I'm using a specific version of lodash, a new version is released, can I trigger the refresh directly from my app or I'll add necessariliy to edit package.json and rebuild the app manually?

Replace code with updated code, restart your app.  That's the usual way.


问:
How to display and store images from a server on the client side?
In my React app currently, I give the users an option to list an item with a maximum of 5 pictures they can pick. Upon clicking on the Submit item button I send those images to S3 and store the returned S3 urls into the database associated with that specific item.

My question is very general (I apologize for that) but when displaying the items on the Item View page, I retrieve the most recent 20 items and I take the items url's in the response and download the image from S3.

Is it ok to store the base64 version of that URL in the Redux store? Since I am having a hard time understanding how to cache the images. Since if the user navigates away from the Item view page and comes back I want to be able to grab the images from the Redux store rather than having to go redownload the image again from the internet.

Can someone point me on how to store downloaded images efficiently on the browser?

答:
Caching images in this way will overload browser memory.

Also, downloading images frequently will cost you as you are using AWS S3.

Between two issues, you can solve your issue by :

using Cloudfront as a distribution of this S3 bucket. Then you should build your client-side code to communicate with CloudFront endpoint instead of S3 endpoint.

Using Cloudfront will cache S3 content in edge locations for TTL. So when user requests an image, it will cost you only the first request until TTL expires .

Then ,  I recommend to keep downloading images and your redux store should save only images links . From deployment perpective,  you should  make  a wedding between  S3❤ CloudFront.

You may need to look at this type of articles.


问:
verify if a <asp:ContentPlaceHolder exist in page via js file
in the master page there is a ContentPlaceHolder

page.Master:

```<code><asp:ContentPlaceHolder ID="HeadLastPlaceHolder" runat="server" />
</code>```

is it possible through external JS file to verify if it exist on page?

something like,

external.js:

```<code>var HeadLastPlaceHolder = document.getElementById("HeadLastPlaceHolder");
if(HeadLastPlaceHolder != null){
// exist
}else{
// not exist
}
</code>```

答:
The short answer for content placeholder ID search in client-side is no.

Based from my tests, with default ClientID configuration you can retrieve a content placeholder name using this.[ContentPlaceHolderName].ClientID inside master page markup like this example:

```<code><script type="text/javascript">
    // returns 'HeadLastPlaceHolder'
    var HeadLastPlaceHolder = "<%= this.HeadLastPlaceHolder.ClientID %>";
    if(HeadLastPlaceHolder != null) {
        // content placeholder exists
    }
    else {
        // content placeholder doesn't exist
    }
</script>
</code>```

However if you want to use document.getElementById with ClientID retrieved above, it will return null since no HTML element in page matches with that placeholder name, an expected behavior of ContentPlaceHolder class as described below:

A ContentPlaceHolder control defines a relative region for content in
  a master page, and renders all text, markup, and server controls from
  a related Content control found in a content page.

When handling master pages, contents of individual asp:Content controls will merge into corresponding asp:ContentPlaceHolder controls, and merged result renders in client's browser. Hence, no HTML markup is generated for ContentPlaceHolder itself, it contains markup from asp:Content instead (see Master Pages Overview).

Of course you can't retrieve content placeholder ID which doesn't actually exist, because it will throwing error like this:

ASP.site_master does not contain a definition for
  [ContentPlaceHolderName] ...

Body:
in the master page there is a ContentPlaceHolder

page.Master:

<asp:ContentPlaceHolder ID="HeadLastPlaceHolder" runat="server" />

is it possible through external JS file to verify if it exist on page?

something like,

external.js:

var HeadLastPlaceHolder = document.getElementById("HeadLastPlaceHolder");
if(HeadLastPlaceHolder != null){
// exist
}else{
// not exist
}

Body:
The short answer for content placeholder ID search in client-side is no.

Based from my tests, with default ClientID configuration you can retrieve a content placeholder name using this.[ContentPlaceHolderName].ClientID inside master page markup like this example:

<script type="text/javascript">
    // returns 'HeadLastPlaceHolder'
    var HeadLastPlaceHolder = "<%= this.HeadLastPlaceHolder.ClientID %>";
    if(HeadLastPlaceHolder != null) {
        // content placeholder exists
    }
    else {
        // content placeholder doesn't exist
    }
</script>

However if you want to use document.getElementById with ClientID retrieved above, it will return null since no HTML element in page matches with that placeholder name, an expected behavior of ContentPlaceHolder class as described below:

A ContentPlaceHolder control defines a relative region for content in
  a master page, and renders all text, markup, and server controls from
  a related Content control found in a content page.

When handling master pages, contents of individual asp:Content controls will merge into corresponding asp:ContentPlaceHolder controls, and merged result renders in client's browser. Hence, no HTML markup is generated for ContentPlaceHolder itself, it contains markup from asp:Content instead (see Master Pages Overview).

Of course you can't retrieve content placeholder ID which doesn't actually exist, because it will throwing error like this:

ASP.site_master does not contain a definition for
  [ContentPlaceHolderName] ...


问:
GAE Datastore Performance (Column vs ListProperty)
After watching "Google IO 2009: Building scalable, complex apps on App Engine" I performed some tests to help understand the impact on list de-serialization, but the results are quite surprising. Below are the test descriptions.

All tests are run on GAE server.

Each test is performed 5 times with its time and CPU usage recorded.

This test is to compare the speed of fetching (float) data in Columns V.S List

Both Column and List tables contain an extra datetime column for query.

Same query is used to fetch data on both Column and List tables.

TEST 1

- Fetch Single Row

- Table size: 500 Columns vs List of 500 (both contain 500 rows)

Table:ChartTestDbRdFt500C500R <-- 500 Columns x 500 Rows

OneRowCol Result <-- Fetching one row

[0] 0.02 (52) <-- Test 0, time taken = 0.02, CPU usage = 52

[1] 0.02 (60)

[2] 0.02 (56)

[3] 0.01 (46)

[4] 0.02 (57)

Table:ChartTestDbRdFt500L500R <-- List of 500 x 500 Rows

OneRowLst Result

[0] 0.01 (40)

[1] 0.02 (38)

[2] 0.01 (42)

[3] 0.05 (154)

[4] 0.01 (41)

TEST 2

- Fetch All Rows

- Table size: 500 Columns vs List of 500 (both contain 500 rows)

Table:ChartTestDbRdFt500C500R

AllRowCol Result

[0] 11.54 (32753)

[1] 10.99 (31140)

[2] 11.07 (31245)

[3] 11.55 (37177)

[4] 10.96 (34300)

Table:ChartTestDbRdFt500L500R

AllRowLst Result

[0] 7.46 (20872)

[1] 7.02 (19632)

[2] 6.8 (18967)

[3] 6.33 (17709)

[4] 6.81 (19006)

TEST 3

- Fetch Single Row

- Table size: 4500 Columns vs List of 4500 (both contain 10 rows)

Table:ChartTestDbRdFt4500C10R

OneRowCol Result

[0] 0.15 (419)

[1] 0.15 (433)

[2] 0.15 (415)

[3] 0.23 (619)

[4] 0.14 (415)

Table:ChartTestDbRdFt4500L10R

OneRowLst Result

[0] 0.08 (212)

[1] 0.16 (476)

[2] 0.07 (215)

[3] 0.09 (242)

[4] 0.08 (217)

CONCLUSION

Fetching a list of N items is actually quicker than N columns. Does anyone know why this is the case? I thought there is a performance hit on list de-serialization? Or did I performed my tests incorrectly? Any insight will be helpful, thanks!

答:
BigTable is a column-oriented database.

That means that fetching a 'row' of N columns is in fact N different read operations, all on the same index.


问:
How do I build sphinx (readthedocs) documentation for Google App Engine projects?
I have a Google App Engine project named gaend. I am attempting to build better documentation for it using readthedocs. I have used

```<code>> sphinx-quickstart
</code>```

to build my base sphinx project. Followed by

```<code>> sphinx-apidoc -o . ../gaend
</code>```

to generate a API list of the project. I then run

```<code>sphinx-autobuild . _build/html

+--------- manually triggered build ---------------------------------------------
| Running Sphinx v1.5.2
| loading pickled environment... done
| building [mo]: targets for 0 po files that are out of date
| building [html]: targets for 0 source files that are out of date
| updating environment: 0 added, 1 changed, 0 removed
| reading sources... [100%] gaend
/Users/stephen/gaend/docs/gaend.rst:10: WARNING: autodoc: failed to import module u'gaend.bigquery'; the following exception was raised:
Traceback (most recent call last):
File "/Users/stephen/.virtualenvs/gaend/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 551, in import_object
__import__(self.modname)
File "/Users/stephen/gaend/gaend/bigquery.py", line 1, in <module>
   from google.cloud import bigquery
ImportError: No module named google.cloud
...
ImportError: No module named google.appengine.ext
</code>```

I recognize that the problem is that it does not have access to the Google Cloud SDK. I have had similar issues with running my unit test, and the work around to doing this is in runner.py. However, this relies on having the Google Cloud SDK (with the Python Google App Engine module installed) somewhere on my system. How am I going to get the Google Cloud SDK (and Python GAE) on the readthedocs server that build my documentation?

答:
I just solved the same issue. There are not many questions asking about Sphinx + GAE, so I'm posting the conf.py code that got it working for me in the hopes it helps others:

```<code>import os
import sys
project_id = 'gae-project-id'
# environment variables that several utils are assuming are present
if not os.environ.get('SERVER_SOFTWARE', None):
    os.environ['SERVER_SOFTWARE'] = 'Development-'+project_id
if not os.environ.get('APPLICATION_ID', None):
    os.environ['APPLICATION_ID'] = 'dev~'+project_id
# project root
sys.path.insert(0, os.path.dirname(__file__))
# downloaded third party libs
sys.path.insert(0, os.path.dirname(__file__)+"/lib")
# path to gae sdk
sdk_path = os.path.join('~/google-cloud-sdk', 'platform/google_appengine')
try:
    import google
    google.__path__.append("{0}/google".format(sdk_path))
except ImportError:
    pass
sys.path.insert(0, os.path.expanduser(sdk_path))
import dev_appserver
dev_appserver.fix_sys_path()
</code>```

Body:
I have a Google App Engine project named gaend. I am attempting to build better documentation for it using readthedocs. I have used

> sphinx-quickstart

to build my base sphinx project. Followed by

> sphinx-apidoc -o . ../gaend

to generate a API list of the project. I then run

sphinx-autobuild . _build/html

+--------- manually triggered build ---------------------------------------------
| Running Sphinx v1.5.2
| loading pickled environment... done
| building [mo]: targets for 0 po files that are out of date
| building [html]: targets for 0 source files that are out of date
| updating environment: 0 added, 1 changed, 0 removed
| reading sources... [100%] gaend
/Users/stephen/gaend/docs/gaend.rst:10: WARNING: autodoc: failed to import module u'gaend.bigquery'; the following exception was raised:
Traceback (most recent call last):
File "/Users/stephen/.virtualenvs/gaend/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 551, in import_object
__import__(self.modname)
File "/Users/stephen/gaend/gaend/bigquery.py", line 1, in <module>
   from google.cloud import bigquery
ImportError: No module named google.cloud
...
ImportError: No module named google.appengine.ext

I recognize that the problem is that it does not have access to the Google Cloud SDK. I have had similar issues with running my unit test, and the work around to doing this is in runner.py. However, this relies on having the Google Cloud SDK (with the Python Google App Engine module installed) somewhere on my system. How am I going to get the Google Cloud SDK (and Python GAE) on the readthedocs server that build my documentation?

Body:
I just solved the same issue. There are not many questions asking about Sphinx + GAE, so I'm posting the conf.py code that got it working for me in the hopes it helps others:

import os
import sys
project_id = 'gae-project-id'
# environment variables that several utils are assuming are present
if not os.environ.get('SERVER_SOFTWARE', None):
    os.environ['SERVER_SOFTWARE'] = 'Development-'+project_id
if not os.environ.get('APPLICATION_ID', None):
    os.environ['APPLICATION_ID'] = 'dev~'+project_id
# project root
sys.path.insert(0, os.path.dirname(__file__))
# downloaded third party libs
sys.path.insert(0, os.path.dirname(__file__)+"/lib")
# path to gae sdk
sdk_path = os.path.join('~/google-cloud-sdk', 'platform/google_appengine')
try:
    import google
    google.__path__.append("{0}/google".format(sdk_path))
except ImportError:
    pass
sys.path.insert(0, os.path.expanduser(sdk_path))
import dev_appserver
dev_appserver.fix_sys_path()


问:
Javascript Snake Game (Prevent reverse while maintaining responsiveness)
I have a snake game that's "finished" except for one pretty serious annoyance.

Previously, I had the following problem.
Say the snake is going right. If the player changed directions multiple times in quick succession, e.g., by pressing down then left, then the snake would go back into itself and reverse direction. Once I added collision detection code, this would cause the game to end and the player to lose because the snake collided with itself by going inward into itself. This problem was made possible because direction could be changed multiple times in one interval, e.g., from right to down then from down to left.

This problem was fixed by adding a bool that would store whether or not direction was allowed to change this interval. If the direction had not been changed yet this interval, then direction was allowed to change. If it had already been changed this interval, then it would have to wait until next interval to change again. This prevented the snake from ever going inward into itself because it guaranteed that the snake's direction could only change once per interval. But this created another problem in that in each interval, every key press after the first would not register.

Now, the problem is that the game no longer feels responsive. If the snake is going to the right, there is no reason that spamming down right in quick succession shouldn't do what the player expects. As it stands, the second right sometimes doesn't register because it was pressed too quickly (on the same interval as down was pressed). So by fixing one big issue in this way, I created another annoyance. How do I get the best of both worlds. How do I stay rid of the possibility to go inward into myself while restoring responsiveness?

I can provide code if necessary, but I thought that the question was pretty clear even in abstraction.

答:
It sounds like the game either acts on the new direction in the next interval or the direction is lost until the user presses again.

Have you tried queuing the next direction? for instance, at every interval, you can check the queue to see if there is a new direction. If there is, change direction. If not, continue in the current direction.

This will probably accomplish the responsiveness you want while still being accurate to the user’s input.

Good luck