问:
ShrarePoint moveto operation flags issue
I am trying to use the SharePoint REST API method moveto(newurl, flags) to move a document library to a Archived library. However, I am having some issue with the flags.

```<code>$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + path + "')/moveto(newurl='Archived',flags=1)",
        method: "POST",
        headers: {
             "Accept": "application/json; odata=verbose",
                       "X-RequestDigest" : $('#__REQUESTDIGEST').val()
             },
            success: function (data) {
                    console.log("Moved");
            },
            error: function (error) {
                    console.log("Error");
            }
});
</code>```

path is just the path to the document library.

The error response I am getting is

{"error":{"code":"-1,
  Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The
  parameter name flags is not valid."}}}

I am not sure what is wrong with the flags in the request.

答:
I realized that folders don't have a moveto or copyto operation so I will have to copy the contents into a new folder.

Used this :

https://sharepoint.stackexchange.com/questions/105460/spfolder-moveto-functionality-in-javascript

Body:
I am trying to use the SharePoint REST API method moveto(newurl, flags) to move a document library to a Archived library. However, I am having some issue with the flags.

$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + path + "')/moveto(newurl='Archived',flags=1)",
        method: "POST",
        headers: {
             "Accept": "application/json; odata=verbose",
                       "X-RequestDigest" : $('#__REQUESTDIGEST').val()
             },
            success: function (data) {
                    console.log("Moved");
            },
            error: function (error) {
                    console.log("Error");
            }
});

path is just the path to the document library.

The error response I am getting is

{"error":{"code":"-1,
  Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The
  parameter name flags is not valid."}}}

I am not sure what is wrong with the flags in the request.


来源: stackexchange

问:
php project works on linux server but not on windows
So I have two copies of exactly the same project. The configuration of the servers is the same. The script has to write some data to database and then redirect the user to the appropriate page with the header() function depending on the data written to the database.

It works fine on the Linux server, though in Windows it tries to redirect first, and then write to the database, which, of course, doesn't work, because there's no data written. If I comment out the header() function in the Windows version, it writes to the database, but doesn't do the redirection.

How can two exact scripts work so different?

Edit:

I'm not sure how do I show the code, since there's so much of it and it's so scattered. But basically, it's just a function that sets the header() and then the function that writes to db. And when it redirects, it should select the data that was written to the database and display it.

That's a very simplified version of it. Bear in mind, the header is set BEFORE the writing to the database. I believe this to be the culprit, but I didn't write the code, and I can't change the architecture of it, since it works perfectly on 2 Linux servers, I just don't understand how. I just need to make it work on the Windows server.

It makes the redirection ok, I mean it sends me to the link that it should send me to, but it doesn't write to the database. But it I comment out the header() part, it writes to the database, but doesn't make the redirection.

答:
Try adding an if statement like this:

```<code>if(mysql_query('...') && mysql_affected_rows()){
   header("Location: redirectScript.php");exit();
}
</code>```

Hope this helps...

ContentLicense: CC BY-SA 2.5

Body:
Try adding an if statement like this:

if(mysql_query('...') && mysql_affected_rows()){
   header("Location: redirectScript.php");exit();
}

Hope this helps...


问:
Unable to save ManyToMany relationship in Hibernate
This is really puzzling me.

I have the following classes:

Ingredient.java

```<code>@Entity
@Table(name = "INGREDIENTS", uniqueConstraints =
{@UniqueConstraint(columnNames = "NAME")})
public class Ingredient implements Serializable{

@Id
@GeneratedValue
@Column(name = "ingredient_id")
private Long id;

@Column(nullable = false, name = "name")
private String name;

@Column(nullable = false, name = "name")
private Long calories;

public Ingredient() {
}

public Ingredient(String name, Long calories) {
    this.name = name;
    this.calories = calories;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getCalories() {
    return calories;
}

public void setCalories(Long calories) {
    this.calories = calories;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}
</code>```

}

Meal.java

```<code>@Entity
@Table(name = "MEALS")
public class Meal implements Serializable {

@ManyToOne
private User user;

@Id
@GeneratedValue
@Column(name = "meal_id")
private Long id;

@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);

//More fields and constructors

@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
    return ingredients;
}

public void setIngredients(List<Ingredient> ingredients) {
    this.ingredients = ingredients;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}
</code>```

This is the code where I persist the entities:

```<code>SessionFactory sessionFactory =
entityManagerFactory.unwrap(SessionFactory.class);

Session session = sessionFactory.openSession();
session.beginTransaction();

 /***/
Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0), "8 -
Moules Frites", 1000L);
coolMeal.getIngredients().add(new Ingredient("Fish2", 100L));
        session.persist(coolMeal);
    try{
        session.getTransaction().commit();
    }catch(Throwable e){
        e.printStackTrace();
        throw e;
    }
    session.close();
</code>```

But I keep getting this exception:

```<code>org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: calories.tracker.app.model.Ingredient
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:165)
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:899)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1308)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at
</code>```

However if I persist the objects in this way:

```<code>    Ingredient i1 = new Ingredient("Potatoes2", 100L);
    session.persist(i1);
    Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0),
    "8 -  Moules Frites", 1000L);
    coolMeal.getIngredients().add(i1);
</code>```

It works fine, why? Everything is exactly the same as here.

答:
You declare two mappings for the ingredients field.

One in the field and another in the getter :

```<code>@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);
 ....
@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
    return ingredients;
}
</code>```

You should remove the annotation for the field :

```<code>@ElementCollection(targetClass = Ingredient.class)
</code>```

@ElementCollection is designed to map non-entity classes while Ingredient is an Entity :

According to the Javadoc :

ElementCollection

Defines a collection of instances of a basic type or embeddable class

ContentLicense: CC BY-SA 3.0

Body:
This is really puzzling me.

I have the following classes:

Ingredient.java

@Entity
@Table(name = "INGREDIENTS", uniqueConstraints =
{@UniqueConstraint(columnNames = "NAME")})
public class Ingredient implements Serializable{

@Id
@GeneratedValue
@Column(name = "ingredient_id")
private Long id;

@Column(nullable = false, name = "name")
private String name;

@Column(nullable = false, name = "name")
private Long calories;

public Ingredient() {
}

public Ingredient(String name, Long calories) {
    this.name = name;
    this.calories = calories;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getCalories() {
    return calories;
}

public void setCalories(Long calories) {
    this.calories = calories;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}

}

Meal.java

@Entity
@Table(name = "MEALS")
public class Meal implements Serializable {

@ManyToOne
private User user;

@Id
@GeneratedValue
@Column(name = "meal_id")
private Long id;

@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);

//More fields and constructors

@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
    return ingredients;
}

public void setIngredients(List<Ingredient> ingredients) {
    this.ingredients = ingredients;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}

This is the code where I persist the entities:

SessionFactory sessionFactory =
entityManagerFactory.unwrap(SessionFactory.class);

Session session = sessionFactory.openSession();
session.beginTransaction();

 /***/
Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0), "8 -
Moules Frites", 1000L);
coolMeal.getIngredients().add(new Ingredient("Fish2", 100L));
        session.persist(coolMeal);
    try{
        session.getTransaction().commit();
    }catch(Throwable e){
        e.printStackTrace();
        throw e;
    }
    session.close();

But I keep getting this exception:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: calories.tracker.app.model.Ingredient
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:165)
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:899)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1308)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at

However if I persist the objects in this way:

    Ingredient i1 = new Ingredient("Potatoes2", 100L);
    session.persist(i1);
    Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0),
    "8 -  Moules Frites", 1000L);
    coolMeal.getIngredients().add(i1);

It works fine, why? Everything is exactly the same as here.

Body:
You declare two mappings for the ingredients field.

One in the field and another in the getter :

@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);
 ....
@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
    return ingredients;
}

You should remove the annotation for the field :

@ElementCollection(targetClass = Ingredient.class)

@ElementCollection is designed to map non-entity classes while Ingredient is an Entity :

According to the Javadoc :

ElementCollection

Defines a collection of instances of a basic type or embeddable class


问:
How to save tensorflow dynamic_rnn model and restore them as an decoder in a new encoder-decoder model?
I am trying to train a encoder-decoder model to automatically generate summary. the encoder part use CNN to encode article's abstract. the decoder part is RNN to generate article's title.

so the skeleton looks like:

```<code>encoder_state = CNNEncoder(encoder_inputs)
decoder_outputs, _ = RNNDecoder(encoder_state,decoder_inputs)
</code>```

But I want to pre-trained the RNN decoder to teach the model to learn how to speak first. the decoder part is:

```<code>def RNNDecoder(encoder_state,decoder_inputs):
    decoder_inputs_embedded = tf.nn.embedding_lookup(embeddings, decoder_inputs)
    #from tensorflow.models.rnn import rnn_cell, seq2seq
    cell = rnn.GRUCell(memory_dim)
    decoder_outputs, decoder_final_state = tf.nn.dynamic_rnn(
        cell, decoder_inputs_embedded,
        initial_state=encoder_state,
        dtype=tf.float32,scope="plain_decoder1"
    )
    return decoder_outputs, decoder_final_state
</code>```

So my concern is how to save the save and restore RNNDecoder part separately?

答:
Here you can take the output of the dynamic RNN first.

```<code>decoder_cell = tf.contrib.rnn.LSTMCell(decoder_hidden_units)
decoder_outputs, decoder_final_state = tf.nn.dynamic_rnn(decoder_cell, decoder_inputs_embedded,initial_state=encoder_final_state,dtype=tf.float32, time_major=True, scope="plain_decoder")
</code>```

Take the decoder_outputs. Then use a softmax layer to fully connect it.

```<code>decoder_logits = tf.contrib.layers.linear(decoder_outputs, vocab_`size)
</code>```

Then you can create a softmax loss with decoder_logits and train it in the noramal way.

When you want to restore the parameters you this kind of method in a session

```<code>with tf.Session() as session:
        saver = tf.train.Saver()
        saver.restore(session, checkpoint_file)
</code>```

Here the checkpoint file should be your exact checkpoint file. So when running what happen is it will only restore your decoder weights and train with the main model.

Body:
I am trying to train a encoder-decoder model to automatically generate summary. the encoder part use CNN to encode article's abstract. the decoder part is RNN to generate article's title.

so the skeleton looks like:

encoder_state = CNNEncoder(encoder_inputs)
decoder_outputs, _ = RNNDecoder(encoder_state,decoder_inputs)

But I want to pre-trained the RNN decoder to teach the model to learn how to speak first. the decoder part is:

def RNNDecoder(encoder_state,decoder_inputs):
    decoder_inputs_embedded = tf.nn.embedding_lookup(embeddings, decoder_inputs)
    #from tensorflow.models.rnn import rnn_cell, seq2seq
    cell = rnn.GRUCell(memory_dim)
    decoder_outputs, decoder_final_state = tf.nn.dynamic_rnn(
        cell, decoder_inputs_embedded,
        initial_state=encoder_state,
        dtype=tf.float32,scope="plain_decoder1"
    )
    return decoder_outputs, decoder_final_state

So my concern is how to save the save and restore RNNDecoder part separately?

Body:
Here you can take the output of the dynamic RNN first.

decoder_cell = tf.contrib.rnn.LSTMCell(decoder_hidden_units)
decoder_outputs, decoder_final_state = tf.nn.dynamic_rnn(decoder_cell, decoder_inputs_embedded,initial_state=encoder_final_state,dtype=tf.float32, time_major=True, scope="plain_decoder")

Take the decoder_outputs. Then use a softmax layer to fully connect it.

decoder_logits = tf.contrib.layers.linear(decoder_outputs, vocab_`size)

Then you can create a softmax loss with decoder_logits and train it in the noramal way.

When you want to restore the parameters you this kind of method in a session

with tf.Session() as session:
        saver = tf.train.Saver()
        saver.restore(session, checkpoint_file)

Here the checkpoint file should be your exact checkpoint file. So when running what happen is it will only restore your decoder weights and train with the main model.


问:
C# project builds OK , but no binaries produced
Using VS 2012, I build a C# project for a Debug build.  The build succeeds, but the directory ..\bin\debug is empty.

What can cause that and what can cure it?

Update:  This project builds a DLL

答: Thanks all for chiming in.  After a double-check I found the error.  The dev had renamed the folder for the project.  I was looking in the old folder!  (face-palm!)</p>


问:
How would I tell a browser to render a string, not display it
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

```<code>@Html.MyMenu()
</code>```

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

```<code><div id="menucontainer">

                <a href="/Anuncio/Electronics">Electronics</a><a href="/Anuncio/Clothes">Clothes</a><a href="/Anuncio/Domestic">Domestic</a><a href="/Anuncio/Garden">Garden</a>

            </div>
</code>```

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

```<code><%: this is rendered, right? %>
</code>```

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.

答:
Razor escapes HTML by default.

To avoid that, please do something like this:

Writing/outputting HTML strings unescaped

OwnerDisplayName: delete

Body:
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

@Html.MyMenu()

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

                ElectronicsClothesDomesticGarden

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

<%: this is rendered, right? %>

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.


问:
How to exclude property from Lombok builder?
I have a class called as "XYZClientWrapper" , which have following structure:

```<code>@Builder
XYZClientWrapper{
    String name;
    String domain;
    XYZClient client;
}
</code>```

What I want no build function generated for property XYZClient client

Does Lombok supports such use case?

答:
Create the builder in code and add a private setter for your property.</p>

```<code>@Builder
XYZClientWrapper{
    String name;
    String domain;
    XYZClient client;

    public static class XYZClientWrapperBuilder {
        private XYZClientWrapperBuilder client(XYZClient client) { return this; }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a class called as "XYZClientWrapper" , which have following structure:

@Builder
XYZClientWrapper{
    String name;
    String domain;
    XYZClient client;
}

What I want no build function generated for property XYZClient client

Does Lombok supports such use case?

Body:
Create the builder in code and add a private setter for your property.

@Builder
XYZClientWrapper{
    String name;
    String domain;
    XYZClient client;

    public static class XYZClientWrapperBuilder {
        private XYZClientWrapperBuilder client(XYZClient client) { return this; }
    }
}


问:
Vertical centering inside an anchor tag
How can I vertically center the text “Don’t click me”:

Don’t click me

https://jsfiddle.net/r1t99rfz/

答:
```<code>.anchor {
  background-color:red;
  display:inline-block;
  line-height: 100px;
  height: 100px;
}
</code>```

Set line-height to the same value as height

Title: Vertical centering inside an anchor tag

Body:
.anchor {
  background-color:red;
  display:inline-block;
  line-height: 100px;
  height: 100px;
}

Set line-height to the same value as height


问:
What could stop the Apache redirects. And what cause these redirects?
What could stop the Apache redirects. And what cause these redirects?

.htaccess

```<code>RewriteEngine On
RewriteBase /
Options -MultiViews
DirectoryIndex /public/index.php

RewriteCond %{HTTPS} off
RewriteRule ^https://somedomain.com%{REQUEST_URI} [NE]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{ENV:REQUEST_FILENAME} !-d
RewriteCond %{ENV:REQUEST_FILENAME} !-f
RewriteCond %{ENV:REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ https://%{HTTP_HOST}/public/index\.php?url=$1 [QSA,R=301,L]
</code>```

Using somedomain.com/login
I am getting ERR_TOO_MANY_REDIRECTS

https://somedomain.com/public/index.php?url=public/index.php&url=public/index.php<...>

I believe L should stop the redirects? Does not?

答:
I believe L should stop the redirects? Does not?

No L doesn't stop redirect. L flag (Last) just stops current mod_rewrite loop and causes mod_rewrite rules to loop again from start so it works like continue in a while loop.

You must remove http:// and R=301 flag from your last routing rule to avoid an external redirection.

```<code>Options -MultiViews
DirectoryIndex index.php
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

RewriteCond %{ENV:REQUEST_FILENAME} !-d
RewriteCond %{ENV:REQUEST_FILENAME} !-f
RewriteRule ^t/(.*)$ public/index.php?url=$1 [QSA,L,NC]
</code>```

Make sure to clear your browser cache before testing this change.

Body:
What could stop the Apache redirects. And what cause these redirects?

.htaccess

RewriteEngine On
RewriteBase /
Options -MultiViews
DirectoryIndex /public/index.php

RewriteCond %{HTTPS} off
RewriteRule ^https://somedomain.com%{REQUEST_URI} [NE]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{ENV:REQUEST_FILENAME} !-d
RewriteCond %{ENV:REQUEST_FILENAME} !-f
RewriteCond %{ENV:REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ https://%{HTTP_HOST}/public/index\.php?url=$1 [QSA,R=301,L]

Using somedomain.com/login
I am getting ERR_TOO_MANY_REDIRECTS

https://somedomain.com/public/index.php?url=public/index.php&url=public/index.php<...>

I believe L should stop the redirects? Does not?

Body:
I believe L should stop the redirects? Does not?

No L doesn't stop redirect. L flag (Last) just stops current mod_rewrite loop and causes mod_rewrite rules to loop again from start so it works like continue in a while loop.

You must remove http:// and R=301 flag from your last routing rule to avoid an external redirection.

Options -MultiViews
DirectoryIndex index.php
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

RewriteCond %{ENV:REQUEST_FILENAME} !-d
RewriteCond %{ENV:REQUEST_FILENAME} !-f
RewriteRule ^t/(.*)$ public/index.php?url=$1 [QSA,L,NC]

Make sure to clear your browser cache before testing this change.


问:
Wordpress template files in subdirectory's
A while ago i started a new Wordpress project. But i got into an issue. Since there are multiple designs i need to create multiple templates for pages, posts and text format outputs for on the different page-templates.

So since the're are so many template files i wanted to create some subdirectory's. i know that since Wordpress 3.4 and higher you're able to use the subdirectory name page-templates for all the page templates but how could i use that for the format files and for the post files.

Yes i did try to add functions like:

```<code> get_template_part('/template-parts/page-templates' , 'page');
</code>```

And

```<code>require( get_template_directory() . '/template-parts/template-tags.php' );
</code>```

The ideal directory structure i would like to create is as follows:

```<code>wp-content/themes/mytheme
- archive
- 404
- CSS
- JS
- Images
- template-parts (dir)
-- page-templates (dir for page-template files.)
-- format-templates (dir for format-templates.)
-- post-templates (dir for post-templates.)
- header
- footer
</code>```

So to be clear. I want to create the structure for template files like above. Don't mind the folders like CSS etc. Those are set the correct way. The intention is, after i've succesfully created the structure, to be able to select the templates like a page temple from the /wp-admin edit page section.

答:
You need to create a Template file(inside "page-templates" directory) for each diferent design you will have.

For creating a template file accessible from de Backend(wp-admin) you need to add:

```<code><?php
/*
Template Name: TEMPLATE-NAME
*/
?>
</code>```

in the top of each file(template). Then inside each file, you can add the blocks or modules of the design using get_template_part() function.

Body:
A while ago i started a new Wordpress project. But i got into an issue. Since there are multiple designs i need to create multiple templates for pages, posts and text format outputs for on the different page-templates.

So since the're are so many template files i wanted to create some subdirectory's. i know that since Wordpress 3.4 and higher you're able to use the subdirectory name page-templates for all the page templates but how could i use that for the format files and for the post files.

Yes i did try to add functions like:

 get_template_part('/template-parts/page-templates' , 'page');

And

require( get_template_directory() . '/template-parts/template-tags.php' );

The ideal directory structure i would like to create is as follows:

wp-content/themes/mytheme
- archive
- 404
- CSS
- JS
- Images
- template-parts (dir)
-- page-templates (dir for page-template files.)
-- format-templates (dir for format-templates.)
-- post-templates (dir for post-templates.)
- header
- footer

So to be clear. I want to create the structure for template files like above. Don't mind the folders like CSS etc. Those are set the correct way. The intention is, after i've succesfully created the structure, to be able to select the templates like a page temple from the /wp-admin edit page section.

Body:
You need to create a Template file(inside "page-templates" directory) for each diferent design you will have.

For creating a template file accessible from de Backend(wp-admin) you need to add:

<?php
/*
Template Name: TEMPLATE-NAME
*/
?>

in the top of each file(template). Then inside each file, you can add the blocks or modules of the design using get_template_part() function.


问:
Asp.net convert textbox input to upper case on key down with jQuery
I want to convert the text in a textbox to uppercase as the user writes it.

Html/aspx:

```<code><asp:TextBox runat="server" ID="mytextbox" onkeydown="toUpperCase()"></asp:TextBox>
</code>```

jQuery

```<code>function toUpperCase() {
    $(this.val) = this.val.toUpperCase();
}
</code>```

答:
Use the below code that fulfils your requirement. We provided all code to change upper case on key down and key up. You can use both html and Asp control for that.

function toUpperCase(ctrl) {
    $(ctrl).val($(ctrl).val().toUpperCase());
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<table>
<tr>
<td>Enter value to change per character:-</td><td><input type="text" id="txt1" onkeyup="toUpperCase(this);" /></td>
</tr>
<tr>
<td>Enter value to change previous character:- </td><td><input type="text" id="txt2" onkeydown="toUpperCase(this);" /></td>
</tr>
</table>
</body>
</html></code>```

Body:
I want to convert the text in a textbox to uppercase as the user writes it.

Html/aspx:

<asp:TextBox runat="server" ID="mytextbox" onkeydown="toUpperCase()"></asp:TextBox>

jQuery

function toUpperCase() {
    $(this.val) = this.val.toUpperCase();
}

Body:
Use the below code that fulfils your requirement. We provided all code to change upper case on key down and key up. You can use both html and Asp control for that.

function toUpperCase(ctrl) {
    $(ctrl).val($(ctrl).val().toUpperCase());
}

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<table>
<tr>
<td>Enter value to change per character:-</td><td><input type="text" id="txt1" onkeyup="toUpperCase(this);" /></td>
</tr>
<tr>
<td>Enter value to change previous character:- </td><td><input type="text" id="txt2" onkeydown="toUpperCase(this);" /></td>
</tr>
</table>
</body>
</html>


问:
Strange object assignment behaviour c++
I have a strange behavior with object assignments. I will much appreciate, if you can explain why this assignment works like this. It has cost me already a lot of time.
I am using Visual Studio Enterprise 2017 (all default settings).

Code:

```<code>#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
public:

    Test()
    {
        cout << "Constructor of " << this << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << endl;
    }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();

    int i = 0;
    cin >> i;
    return 0;
}
</code>```

Output (up to cin):

```<code>Assignment 1
Constructor of 006FFC9F
Assignment 2
Constructor of 006FFBC7
Destructor of 006FFBC7
</code>```

Expected Output (up to cin):

```<code>Assignment 1
Constructor of 006FFC9F
Assignment 2
Destructor of 006FFC9F
Constructor of 006FFBC7
</code>```

I wanted to write a test function which creates an object of my (template) class, do some tests, then create a new object and do some more testing. The problem is that t holds the already destructed object after the second assignment.
I know that I can just use dynamic allocation which results in the expected behavior, but why does this program behave different?

Thank you very much.
Regards.

PS: Results are the same, independent of Release/Debug or 64/32 bit compilation

EDIT: More verbose example:

```<code>#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
private:
    float* val;
public:
    Test()
    {
        val = new float;
        cout << "Constructor of " << this << ", addr. of val: " << val << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << ", addr. of val: " << val << " --> DELETING VAL!" << endl;
        delete val;
    }

    float* getVal() { return this->val; }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();
    cout << "Val Address: " << t.getVal() << endl;

    int i = 0;
    cin >> i;
    return 0;
}
</code>```

Output (it holds a deleted pointer at the end!!!):

```<code>Assignment 1
Constructor of 004FFBDC, addr. of val: 0072AEB0
Assignment 2
Constructor of 004FFB04, addr. of val: 00723928
Destructor of 004FFB04, addr. of val: 00723928 --> DELETING VAL!
Val Address: 00723928
</code>```

答:
With

```<code>auto t = Test();
</code>```

you actually construct two objects. First is the Test() which constructs a temporary object. The second is the construction of t which is made through copy-construction. There is no assignment being made here, even if the = operator is used, it's copy-construction.

If you add a copy-constructor to the Test class similar to your constructor and destructor, you should see it clearly.

As for

```<code>t = Test();
</code>```

here a temporary object is created with Test(). That temporary object is then passed to the (compiler-generated) assignment operator of the Test class, and then the temporary object is promptly destructed.

The object t itself is not destructed, it should not be as it is the destination of the assignment.

Title: Strange object assignment behaviour c++

Body:
I have a strange behavior with object assignments. I will much appreciate, if you can explain why this assignment works like this. It has cost me already a lot of time.
I am using Visual Studio Enterprise 2017 (all default settings).

Code:

#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
public:

    Test()
    {
        cout << "Constructor of " << this << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << endl;
    }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();

    int i = 0;
    cin >> i;
    return 0;
}

Output (up to cin):

Assignment 1
Constructor of 006FFC9F
Assignment 2
Constructor of 006FFBC7
Destructor of 006FFBC7

Expected Output (up to cin):

Assignment 1
Constructor of 006FFC9F
Assignment 2
Destructor of 006FFC9F
Constructor of 006FFBC7

I wanted to write a test function which creates an object of my (template) class, do some tests, then create a new object and do some more testing. The problem is that t holds the already destructed object after the second assignment.
I know that I can just use dynamic allocation which results in the expected behavior, but why does this program behave different?

Thank you very much.
Regards.

PS: Results are the same, independent of Release/Debug or 64/32 bit compilation

EDIT: More verbose example:

#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
private:
    float* val;
public:
    Test()
    {
        val = new float;
        cout << "Constructor of " << this << ", addr. of val: " << val << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << ", addr. of val: " << val << " --> DELETING VAL!" << endl;
        delete val;
    }

    float* getVal() { return this->val; }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();
    cout << "Val Address: " << t.getVal() << endl;

    int i = 0;
    cin >> i;
    return 0;
}

Output (it holds a deleted pointer at the end!!!):

Assignment 1
Constructor of 004FFBDC, addr. of val: 0072AEB0
Assignment 2
Constructor of 004FFB04, addr. of val: 00723928
Destructor of 004FFB04, addr. of val: 00723928 --> DELETING VAL!
Val Address: 00723928

Body:
With

auto t = Test();

you actually construct two objects. First is the Test() which constructs a temporary object. The second is the construction of t which is made through copy-construction. There is no assignment being made here, even if the = operator is used, it's copy-construction.

If you add a copy-constructor to the Test class similar to your constructor and destructor, you should see it clearly.

As for

t = Test();

here a temporary object is created with Test(). That temporary object is then passed to the (compiler-generated) assignment operator of the Test class, and then the temporary object is promptly destructed.

The object t itself is not destructed, it should not be as it is the destination of the assignment.


问:
How do I apply a groupFooterTemplate to one group in a Kendo Grid?
I have a kendo grid with two levels of groups.  I have groupHeaderTemplates defined for these two groups.  I have a groupFooterTemplate defined for my aggregate value which is timeWorked.  The problem is the groupHeaderTemplate is now defined for both the groups.  I need it defined for only the other group.

I tried the CSS way of hiding the extra records but the problem with this is there is no defining characteristics in the .k-group-footer rows to distinguish what group it belongs to and $("#grid .k-grid-content") doesn't show the hierarchy.

http://www.telerik.com/forums/how-to-do-custom-aggregate-functions
Shows how to get the groupId in the footer.  However, it will not work because the groupId uses a global variable which will be overwritten with whatever groupHeaderTemplate function is called first.  Since the groupHeaderTemplates are done before any groupFooterTemplates, I still have no way of knowing what the groupId refers to.

This is what my group option looks like:
[ {field: “projectDescription”, aggregates: [ {field: "timeWorked", aggregate: "sum"} ]}, {field: "entryDate"} ];

答:
for more than 2 subgroups
to show only the footer of the lowest child group, add a css like this

```<code>.k-group-footer {
   display: none !important;
}
.k-master-row + .k-group-footer {
   display: table-row !important;
}
</code>```

Body:
for more than 2 subgroups
to show only the footer of the lowest child group, add a css like this

.k-group-footer {
   display: none !important;
}
.k-master-row + .k-group-footer {
   display: table-row !important;
}


问:
Can't run python on windows anymore
Since the most recent update to Windows 10, I have been seeing this message every time I try to do anything with Python

I have reinstalled it, tried running it as administrator.  Nothing works.

答:
First make sure that python.exe exists in the given directory and that its not a zero-length file.  More likely though is that you installed the wrong version of python.  Make sure you download and install the x86 version as it will work on both 64-bit and x86 systems.  Do a full uninstall and install python via the Windows x86 MSI installer.

Edit:

If this doesn't work please provide more information on which specific Windows 10 version you are running and which python installer you are using.

Edit 2:

You can also get more information from the Windows Event Log

Title: Can't run python on windows anymore


问:
deploy docker container on AWS EC2 instance without being logged in
I'm a beginner with microservices and have spent hours on the most tiny painful things of AWS today, would appreciate any expert advice as I suspect the next step is very small but could take me hours to work it out otherwise.

So I deployed a nano instance then ssh into it. Had to actually redo it to fix the security group but anyway it worked eventually. Used scp to put my docker image up there per the instructions here, in summary docker save to make a .tar out of the image locally and docker load to put it into the system remotely after waiting 15 minutes for scp to upload. Then typed docker run at the command prompt.

Had resorted to these (linux) terminal measures as over the last 3 days had twice tried and failed to do it from the AWS console, as in it uploaded but wouldn't run.

Now it runs fantastically when I type docker run my_image and I can see it in there with both the commands docker images and docker ps -a !

But the command prompt on my AWS instance is busy while it runs.. if I close the terminal window it will surely die. Now that I know it works there, how can I 'deploy' it, ie let it run and continue to run for a month or until further notice? I think it might need some kind of json file called 'task definition' but don't really know at all what to do next. Can this task definition and all remaining tasks be done from within a terminal logged into the instance?

答:
I see a few things wrong:

You should use a Docker registry service instead of SCPing an image. On AWS there is EC2 Container Registry or you can also use Docker Hub as well. This will make it much easier to get your images onto your instances.

I'm not sure why you weren't able to start your container using the console. I assume you are using AWS ECS? You might try the troubleshooting guide to help you figure out why your task wasn't running.

It sounds like you are starting a docker container in the foreground (attached to your shell) rather than in the background. Try adding the -d flag to your docker run command to run the container in the background so you can close your SSH session. Note that if the application process inside your container crashes the container will still stop. This is one reason for using an orchestrator such as AWS ECS to define a service that will attempt to always run a certain number of your tasks. ECS also helps with getting the docker container onto the instance and starting it for you in the background automatically.


问:
invalid comparison between distintc pointer types: 'type*' and 'type&(*)()'
I cannot understand why the compiler is complaining about a bad comparison attempt.

The offending comparison is this:

```<code>method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble) {
        ...
    }
...
}
</code>```

And here are the type declarations of the compared items:

```<code>const fltSemantics &getSemantics() const;
static const fltSemantics &IEEEdouble();
</code>```

The error indicated by the compiler looks like this:

comparison between distinct pointer types 'const llvm::fltSemantics*' and 'const llvm::fltSemantics& (*)()' lacks a cast [-fpermissive]

Can anybody help me understand this? I am a beginner but to me it looks both terms in the comparison are of type const fltsemantics &&.

PS: I am compiling with gcc and C++11 compliance.

答:
to me it looks both terms in the comparison are of type const fltsemantics &&.

There is no such type as fltsemantics&&, so neither expression can have such type.

```<code>V.getSemantics()
</code>```

This is a function invocation (a function call). We know that it is an invocation, because of the argument list (). The type of the expression is fltSemantics& because that is what the function returns.

```<code>&V.getSemantics()
</code>```

When applied to a reference, the addressof operator returns a pointer to the referred object. So, the type of the addressof expression is fltSemantics*.

```<code>APFloat::IEEEdouble
</code>```

This is the name of a function. There is no function call, because there is no argument list. The type of the function is type&().

```<code>&APFloat::IEEEdouble
</code>```

When applied to a function name, the addressof operator returns a function pointer. The type of the function pointer is type&(*)() in this case.

I suspect that you intended to call both of the functions, and compare the return values. To call APFloat::IEEEdouble, you need the (empty) argument list:

```<code>APFloat::IEEEdouble()
</code>```

Body:
I cannot understand why the compiler is complaining about a bad comparison attempt.

The offending comparison is this:

method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble) {
        ...
    }
...
}

And here are the type declarations of the compared items:

const fltSemantics &getSemantics() const;
static const fltSemantics &IEEEdouble();

The error indicated by the compiler looks like this:

comparison between distinct pointer types 'const llvm::fltSemantics*' and 'const llvm::fltSemantics& (*)()' lacks a cast [-fpermissive]

Can anybody help me understand this? I am a beginner but to me it looks both terms in the comparison are of type const fltsemantics &&.

PS: I am compiling with gcc and C++11 compliance.

Body:
to me it looks both terms in the comparison are of type const fltsemantics &&.

There is no such type as fltsemantics&&, so neither expression can have such type.

V.getSemantics()

This is a function invocation (a function call). We know that it is an invocation, because of the argument list (). The type of the expression is fltSemantics& because that is what the function returns.

&V.getSemantics()

When applied to a reference, the addressof operator returns a pointer to the referred object. So, the type of the addressof expression is fltSemantics*.

APFloat::IEEEdouble

This is the name of a function. There is no function call, because there is no argument list. The type of the function is type&().

&APFloat::IEEEdouble

When applied to a function name, the addressof operator returns a function pointer. The type of the function pointer is type&(*)() in this case.

I suspect that you intended to call both of the functions, and compare the return values. To call APFloat::IEEEdouble, you need the (empty) argument list:

APFloat::IEEEdouble()


问:
Unary and Binary Operations in Assembly
I've been working through my textbook on the chapter concerning assembly language and have come to a practice problem that I do not understand (the section on unary and binary operations is quite minimal so I'm pretty lost).

Here are two instructions from the practice problem. I am supposed to give the destination and value of each instruction:

addq %rcx, (%rax)

imulq $16 , (%rax, %rdx, 8)

Where %rax's value is 0x100, %rdx's value is 0x3 and %rcx's value is 0x1.

Can anyone explain in detail how to solve both instructions? I have the answer in the back of the book but there's no real explanation to go along with it. Thanks.

答:
This is from Practice Problem 3.8 in CS:APP 3/e (global edition)

```<code>Address    Value
0x100      0XFF
0x118      0x11

Register   Value
%rax       0x100
%rcx       0x1
%rdx       0x3
</code>```

addq %rcx,(%rax)

For this question, you take the qword at %rax (0XFF) and add %rcx to it, so 0XFF + 0x1 = 0x100. Note the brackets around (%rax) which points to the contents held in memory (0XFF) not it's address (0x100).

imulq $16,(%rax, %rdx, 8)

As noted by jester, the right-hand side (%rax + (%rdx * 8)) which is 0x118. The value stored at that address is 0x11. imulq now multiplies 0x11 * 0x10 (note, 16 converted to hex is 0x10) and answer 0x110.

Title: Unary and Binary Operations in Assembly

Body:
This is from Practice Problem 3.8 in CS:APP 3/e (global edition)

Address    Value
0x100      0XFF
0x118      0x11

Register   Value
%rax       0x100
%rcx       0x1
%rdx       0x3

addq %rcx,(%rax)

For this question, you take the qword at %rax (0XFF) and add %rcx to it, so 0XFF + 0x1 = 0x100. Note the brackets around (%rax) which points to the contents held in memory (0XFF) not it's address (0x100).

imulq $16,(%rax, %rdx, 8)

As noted by jester, the right-hand side (%rax + (%rdx * 8)) which is 0x118. The value stored at that address is 0x11. imulq now multiplies 0x11 * 0x10 (note, 16 converted to hex is 0x10) and answer 0x110.


问:
What do the "(?<!…)" symbols mean in a Python regular expression?
I have the regular expression re.sub(r"(?<!\s)\}", r' }', string). What does the (?<!…) sequence indicate?

答:
Its a lookback. See the explanation here: http://www.rexegg.com/regex-disambiguation.html#negative-lookbehind

Quoted from the source:

Negative Lookbehind After the Match: \d{3}(?<!USD\d{3})

  Explanation: \d{3} matches 100, then the negative lookbehind (?<!USD\d{3}) asserts that at that position in the string, what immediately precedes is not the characters "USD" then three digits.


问:
How to retain the entered data in an html form after clicking submit
I have a form in an html page that ends up being cleared after i click the submit button. I wanted to know how I to make the data stay in the form after clicking submit in case the user needs to fix any errors. Any help would be appreciated!

Here is the html code:

```<code><form id = "contactform" action = "">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />
</p>
</form>
</code>```

and here is the javascript code:

```<code>function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');

if(firstname.value == "") {
    alert("Make sure the first name field is filled");
    return false;
    }

if(lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
        }
if(address.value == "") {
        alert("Make sure the address field is filled");
        return false;
        }
if(postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
        }
</code>```

答:
Add return with onclick onclick="return validate()"

function validate() {

  var firstname = document.getElementById('firstname');
  var lastname = document.getElementById('lastname');
  var address = document.getElementById('address');
  var postcode = document.getElementById('postcode');

  if (firstname.value == "") {
    alert("Make sure the first name field is filled");
    return false;
  }

  if (lastname.value == "") {
    alert("Make sure the last name field is filled");
    return false;
  }
  if (address.value == "") {
    alert("Make sure the address field is filled");
    return false;
  }
  if (postcode.value == "") {
    alert("Make sure the post code field is filled");
    return false;
  }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="contactform" action="">
  <label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
  <label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
  <label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
  <label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
  <input type="submit" value="Submit" onclick="return validate()" />
  <input type="reset" value="Clear" />

</form></code>```

Body:
I have a form in an html page that ends up being cleared after i click the submit button. I wanted to know how I to make the data stay in the form after clicking submit in case the user needs to fix any errors. Any help would be appreciated!

Here is the html code:

<form id = "contactform" action = "">
 Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>

 Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />

 Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>

 Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />

<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />

</form>

and here is the javascript code:

function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');

if(firstname.value == "") {
    alert("Make sure the first name field is filled");
    return false;
    }

if(lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
        }
if(address.value == "") {
        alert("Make sure the address field is filled");
        return false;
        }
if(postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
        }

Body:
Add return with onclick onclick="return validate()"

function validate() {

  var firstname = document.getElementById('firstname');
  var lastname = document.getElementById('lastname');
  var address = document.getElementById('address');
  var postcode = document.getElementById('postcode');

  if (firstname.value == "") {
    alert("Make sure the first name field is filled");
    return false;
  }

  if (lastname.value == "") {
    alert("Make sure the last name field is filled");
    return false;
  }
  if (address.value == "") {
    alert("Make sure the address field is filled");
    return false;
  }
  if (postcode.value == "") {
    alert("Make sure the post code field is filled");
    return false;
  }
  }

<form id="contactform" action="">
  <label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
  <label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
  <label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
  <label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
  <input type="submit" value="Submit" onclick="return validate()" />
  <input type="reset" value="Clear" />

</form>


问:
Decode binary file in Visual Studio Code programmatically
When trying to open a binary file in Visual Studio Code, the following message will show:

The file will not be displayed in the editor because it is either binary, very large or uses an unsupported text encoding

This is likely a protection to avoid the editor from freezing.

I would love to decode the file before showing it in the editor and have a function ready to handle that. The problem is, that I never have a chance to run my function since the following code never triggers:

```<code>vscode.workspace.onDidOpenTextDocument(function (doc) {
    if (doc && doc.fileName.endsWith('.scpt')) {
        console.log("You're trying to open a binary AppleScript file")
    }
});
</code>```

Unfortunately, the API doesn't provide an equivalent event to onWillSaveTextDocument for opening files, which would fire before the message above shows. Does anybody know of a different solution?

答:
There is an Extension for VSCode called HexDump that you can use to Display a specified file in hexadecimal.

Once installed:

right-click on the file, and select "Show HexDump".

And will display the following:

Body:
When trying to open a binary file in Visual Studio Code, the following message will show:

The file will not be displayed in the editor because it is either binary, very large or uses an unsupported text encoding

This is likely a protection to avoid the editor from freezing.

I would love to decode the file before showing it in the editor and have a function ready to handle that. The problem is, that I never have a chance to run my function since the following code never triggers:

vscode.workspace.onDidOpenTextDocument(function (doc) {
    if (doc && doc.fileName.endsWith('.scpt')) {
        console.log("You're trying to open a binary AppleScript file")
    }
});

Unfortunately, the API doesn't provide an equivalent event to onWillSaveTextDocument for opening files, which would fire before the message above shows. Does anybody know of a different solution?


答:
It's a bit more than the < symbol, in the regular expression you've provided.

What's actually there is a 'Negative lookbehind': (?<!    ) which is saying "What's before this is not...".  In your case, it's looking for }, on the condition that what comes before it is not \s - whitespace (tabs, spaces...)

Title: What do the "(?<!…)" symbols mean in a Python regular expression?

Body: I have the regular expression re.sub(r"(?<!\s)\}", r' }', string). What does the (?<!…) sequence indicate?


问:
build dynamic array for charts.js
i'm having trouble with building an array in js to pass into a charts.js obj. I have the following array;

```<code>{"Questions":{"name":"Hello World"},"Options":{"inner":{"No":"723","Yes":"6","Maybe":"0"}}}
</code>```

Which is passed through to the function below as 'response'. I want to cycle through each item in the 'inner' array and build an array of objects to pass into my chart.js.

```<code>function drawChart(response){
    var array = JSON.parse(response)
    var options = array['Options']['inner'];

    for(var option in options){
      var datasetValue = [];

      datasetValue.push = {
          value: parseInt(options[option]),
          color: "#F7464A",
          highlight: "#FF5A5E",
          label: option
      }
    }
    console.log(datasetValue);
    var mydata = {
        datasetValue
    }

    var pieData = [
        {
            value: 300,
            color: "#F7464A",
            highlight: "#FF5A5E",
            label: "Red"
        },
        {
            value: 50,
            color: "#46BFBD",
            highlight: "#5AD3D1",
            label: "Green"
        },
        {
            value: 100,
            color: "#FDB45C",
            highlight: "#FFC870",
            label: "Yellow"
        },
        {
            value: 40,
            color: "#949FB1",
            highlight: "#A8B3C5",
            label: "Grey"
        },
        {
            value: 120,
            color: "#4D5360",
            highlight: "#616774",
            label: "Dark Grey"
        }
    ];
    var ctxOptions = {
        responsive: true,
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
        showTooltips: false,
    };
    var pie_ctx = document.getElementById("donut").getContext("2d");
    var chart = new Chart(pie_ctx).Doughnut(mydata, ctxOptions);
  }
</code>```

You can see above i have two arrays, my dynamic array i'm trying to build 'datasetValue' and 'pieData'. pieData is a sample, and if i pass this array into my new chart, the array works fine, but my datasetValue only seems to contain the last item, rather that all the objects as pieData does. Heres an output from my console.log(datasetValue);

```<code>[push: Object]
push
:
Object
color
:
"#F7464A"
highlight
:
"#FF5A5E"
label
:
"Maybe"
value
:
0
</code>```

What i'm i doing wring in rebuilding my array to match the pieData array format?

答:
Your datasetValue contains only last item because you instantiate it in for loop. Every time you go in a for loop, datasetValue will be recreated (set to empty array), therefore you only log the 'last' item. You should instantiate it outside the for loop.</p>

```<code>var datasetValue = [];
for(var option in options){

  datasetValue.push = {
      value: parseInt(options[option]),
      color: "#F7464A",
      highlight: "#FF5A5E",
      label: option
  }
}
</code>```

Title: build dynamic array for charts.js

Body:
i'm having trouble with building an array in js to pass into a charts.js obj. I have the following array;

{"Questions":{"name":"Hello World"},"Options":{"inner":{"No":"723","Yes":"6","Maybe":"0"}}}

Which is passed through to the function below as 'response'. I want to cycle through each item in the 'inner' array and build an array of objects to pass into my chart.js.

function drawChart(response){
    var array = JSON.parse(response)
    var options = array['Options']['inner'];

    for(var option in options){
      var datasetValue = [];

      datasetValue.push = {
          value: parseInt(options[option]),
          color: "#F7464A",
          highlight: "#FF5A5E",
          label: option
      }
    }
    console.log(datasetValue);
    var mydata = {
        datasetValue
    }

    var pieData = [
        {
            value: 300,
            color: "#F7464A",
            highlight: "#FF5A5E",
            label: "Red"
        },
        {
            value: 50,
            color: "#46BFBD",
            highlight: "#5AD3D1",
            label: "Green"
        },
        {
            value: 100,
            color: "#FDB45C",
            highlight: "#FFC870",
            label: "Yellow"
        },
        {
            value: 40,
            color: "#949FB1",
            highlight: "#A8B3C5",
            label: "Grey"
        },
        {
            value: 120,
            color: "#4D5360",
            highlight: "#616774",
            label: "Dark Grey"
        }
    ];
    var ctxOptions = {
        responsive: true,
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%>
<span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%>
<%}%>
",
        showTooltips: false,
    };
    var pie_ctx = document.getElementById("donut").getContext("2d");
    var chart = new Chart(pie_ctx).Doughnut(mydata, ctxOptions);
  }

You can see above i have two arrays, my dynamic array i'm trying to build 'datasetValue' and 'pieData'. pieData is a sample, and if i pass this array into my new chart, the array works fine, but my datasetValue only seems to contain the last item, rather that all the objects as pieData does. Heres an output from my console.log(datasetValue);

[push: Object]
push
:
Object
color
:
"#F7464A"
highlight
:
"#FF5A5E"
label
:
"Maybe"
value
:
0

What i'm i doing wring in rebuilding my array to match the pieData array format?

Body:
Your datasetValue contains only last item because you instantiate it in for loop. Every time you go in a for loop, datasetValue will be recreated (set to empty array), therefore you only log the 'last' item. You should instantiate it outside the for loop.

var datasetValue = [];
for(var option in options){

  datasetValue.push = {
      value: parseInt(options[option]),
      color: "#F7464A",
      highlight: "#FF5A5E",
      label: option
  }
}


问:
AvalonDock slower in 64 bit
I'm using AvalonDock in my application and have noticed that when I target x64, it seems to perform much slower when loading a layout. When I target x86, the layout loads instantly, yet in 64bit it freezes for around a second or so before you see the result.

The problem seems to be related to the XmlSerializer performing worse when running in 64bit, and googling around, people have advised to use sgen.exe to generate a *.XmlSerializers.dll at compile time. Unfortunately though, this doesn't seem to work as running the sgen post built event :

```<code>“$(SDK40ToolsPath)\x64\sgen.exe” /a:"$(TargetPath)" /force /r "Xceed.Wpf.AvalonDock.dll"
</code>```

produces the following error :

```<code>1>EXEC : error : Cannot deserialize type 'Microsoft.Windows.Shell.SystemParameters2' because it contains property 'IsGlassEnabled' which has no public setter.
</code>```

I don't really want to have to use the /t command to target every type.

Have any other people experienced the issue and have a solution?

答:
I ran into this problem as well and the only solution I found was to specify the types individually. I found this article by Mikhail Shilkov which shows a succinct way to specify multiple types for the post build tasks in the .csproj file. I specified only the types referenced in new XmlSerializer() constructor calls:

```<code><Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
  <!-- This contents of this list was determined by looking at the new XmlSerializer() calls in the code. -->
  <ItemGroup>
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutRoot" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorablePaneGroup" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorablePane" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorable" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocumentPaneGroup" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocumentPane" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocument" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorGroup" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutPanel" />
  </ItemGroup>
  <Delete Files="$(TargetDir)$(TargetName).XmlSerializers.dll" ContinueOnError="true" />
  <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)" Types="@(SgenTypes)">
    <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
  </SGen>
</Target>
</code>```

After making these changes, I ran into another error:

Generated serialization assembly is not signed

This was resolved by disabling signing by removing the following lines from AssemblyInfo.cs:

```<code>#pragma warning disable 1699
[assembly: AssemblyDelaySign( false )]
[assembly: AssemblyKeyFile( @"..\..\sn.snk" )]
[assembly: AssemblyKeyName( "" )]
#pragma warning restore 1699
</code>```

Another solution may be to enable signing in Project Properties > Signing, but I have not tried this.

Title: AvalonDock slower in 64 bit

Body:
I'm using AvalonDock in my application and have noticed that when I target x64, it seems to perform much slower when loading a layout. When I target x86, the layout loads instantly, yet in 64bit it freezes for around a second or so before you see the result.

The problem seems to be related to the XmlSerializer performing worse when running in 64bit, and googling around, people have advised to use sgen.exe to generate a *.XmlSerializers.dll at compile time. Unfortunately though, this doesn't seem to work as running the sgen post built event :

“$(SDK40ToolsPath)\x64\sgen.exe” /a:"$(TargetPath)" /force /r "Xceed.Wpf.AvalonDock.dll"

produces the following error :

1>EXEC : error : Cannot deserialize type 'Microsoft.Windows.Shell.SystemParameters2' because it contains property 'IsGlassEnabled' which has no public setter.

I don't really want to have to use the /t command to target every type.

Have any other people experienced the issue and have a solution?

Body:
I ran into this problem as well and the only solution I found was to specify the types individually. I found this article by Mikhail Shilkov which shows a succinct way to specify multiple types for the post build tasks in the .csproj file. I specified only the types referenced in new XmlSerializer() constructor calls:

<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
  <!-- This contents of this list was determined by looking at the new XmlSerializer() calls in the code. -->
  <ItemGroup>
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutRoot" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorablePaneGroup" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorablePane" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorable" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocumentPaneGroup" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocumentPane" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocument" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorGroup" />
    <SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutPanel" />
  </ItemGroup>
  <Delete Files="$(TargetDir)$(TargetName).XmlSerializers.dll" ContinueOnError="true" />
  <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)" Types="@(SgenTypes)">
    <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
  </SGen>
</Target>

After making these changes, I ran into another error:

Generated serialization assembly is not signed

This was resolved by disabling signing by removing the following lines from AssemblyInfo.cs:

#pragma warning disable 1699
[assembly: AssemblyDelaySign( false )]
[assembly: AssemblyKeyFile( @"..\..\sn.snk" )]
[assembly: AssemblyKeyName( "" )]
#pragma warning restore 1699

Another solution may be to enable signing in Project Properties > Signing, but I have not tried this.


问:
Short Solution to Sort a C++ Vector of Objects with Dependencies to Each Other?
I just wrote part of a software where fields are ordered in the correct way for processing. Each field can depend on 0-n other fields. Loops are already checked and prevented in a previous step.

My current code works, but it is not very elegant. I iterate through the list and move dependent entries to the front, until there is no move required.

Here a minimal example illustrating the problem:

```<code>#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Obj {
    std::string name;
    std::vector<std::string> dependencies;
};

std::vector<Obj*> objects;

void printObjList(std::string title) {
    std::cout << title << std::endl;
    for (auto obj : objects) {
        std::cout << "- " << obj->name << std::endl;
    }
}

int main()
{
    objects.push_back(new Obj {"d", {}});
    objects.push_back(new Obj {"a", {"c", "d"}});
    objects.push_back(new Obj {"b", {}});
    objects.push_back(new Obj {"c", {"e", "d"}});
    objects.push_back(new Obj {"e", {"b"}});
    printObjList("Unsorted");
    std::stable_sort(objects.begin(), objects.end(), [](Obj *a, Obj *b) {
        return a->name < b->name;
    });
    //std::stable_sort(objects.begin(), objects.end(), [](Obj *a, Obj *b) {
        // ???
    //});
    printObjList("Sorted by Dependencies");
    return 0;
}
</code>```

Play with the code here:
http://coliru.stacked-crooked.com/a/902e91b00924a925

An object which is part of dependencies in another object has to be sorted before this object which contains the reference in the dependencies list.

I assume there is some well known algorithm to solve this kind of problem?

答:
Elaborating on my quick comment:

If you have already checked that there are no loops in your items, then what you have is a  directed acyclic graph (DAG).

Sorting that is the problem known as Topological sorting:
 (https://en.wikipedia.org/wiki/Topological_sorting) which has known efficient solutions, like Kahn's algorithm, though to take advantage of it's efficiency, you'll have to be careful how you store your nodes and edges, so that some operations (for example, finding a node with no incoming edges) is efficient (constant time)

Some well known libraries, like boost also provide implementations:
http://www.boost.org/doc/libs/1_33_1/libs/graph/doc/topological_sort.html

Body:
I just wrote part of a software where fields are ordered in the correct way for processing. Each field can depend on 0-n other fields. Loops are already checked and prevented in a previous step.

My current code works, but it is not very elegant. I iterate through the list and move dependent entries to the front, until there is no move required.

Here a minimal example illustrating the problem:

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Obj {
    std::string name;
    std::vector<std::string> dependencies;
};

std::vector<Obj*> objects;

void printObjList(std::string title) {
    std::cout << title << std::endl;
    for (auto obj : objects) {
        std::cout << "- " << obj->name << std::endl;
    }
}

int main()
{
    objects.push_back(new Obj {"d", {}});
    objects.push_back(new Obj {"a", {"c", "d"}});
    objects.push_back(new Obj {"b", {}});
    objects.push_back(new Obj {"c", {"e", "d"}});
    objects.push_back(new Obj {"e", {"b"}});
    printObjList("Unsorted");
    std::stable_sort(objects.begin(), objects.end(), [](Obj *a, Obj *b) {
        return a->name name;
    });
    //std::stable_sort(objects.begin(), objects.end(), [](Obj *a, Obj *b) {
        // ???
    //});
    printObjList("Sorted by Dependencies");
    return 0;
}

Play with the code here:
http://coliru.stacked-crooked.com/a/902e91b00924a925

An object which is part of dependencies in another object has to be sorted before this object which contains the reference in the dependencies list.

I assume there is some well known algorithm to solve this kind of problem?


问:
Multiple JVMs vs single app server
I'm dealing with a system that runs a Java application per customer in its own JVM. We've got about a half dozen dedicated servers that are running close to 100 JVMs total now and sets of custom scripts for managing these JVMs. This setup is really showing its age at this point: managing that many JVMs is becoming a monitoring/management nightmare and we are constantly dealing with heap sizing issues. We'd like to move to a more modern approach and just run a bunch of applications in a single app server per physical machine. However, keeping the applications separate does have distinct advantages in terms of isolation (e.g. out of memory errors only affect one customer). Each customer's software stack has memory requirements that vary widely.

My question: is there a way to have the best of both worlds here and run multiple applications in one JVM (app server) and still maintain some level of isolation? Or is it just a modern fact of life that you need to manage memory requirements of a set of applications these days? Are there other solutions here besides an app server or Java EE container (e.g. Wildfly or Spring) that I'm missing here? It seems like this system is a holdout from another era!

答:
Another important reason to have multiple JVM instead of one is when facing numa groups. You cannot distribute your threads within one JVM appropriate over numa groups as you can with multiple jvm processes. At least i never found a way to do so.

We have here machines with two cpu's, each having 18 cores, This gives two numa groups and we cannot enforce 34 Threads to be spread upon both cpu if only one JVM is used. This is obviously because it assumes that all threads of the same JVM process need to have fast access to the same memory which is not the case.

Having 34 Processes the system assumes they have no need for shared memory and thus spread them over both cpus.

If someone knows a better way of doing this i would be very glad to hear it.

Title: Multiple JVMs vs single app server


问:
How to map a usb device with a known bus address to the mounted path?
I have an application which is using libusb for detecting connected usb devices. This library gives me the VID/PID and bus as well as port number of the connected devices. I however need (after recognizing the device by PID/VID) to talk to the device via boost::asio::io_service, for this i need the device path in the /dev directory. The device usually gets mounted as something like /dev/ttyUSBx. How do I match the bus and port number to the path? A cross platform solution which works on linux and macOS would be preferable. If there is no cross platform solution, are there ways for both OS?

Thanks a lot!

答:
The not so straight forward but feasible way is to use sysfs like this:
Find the USB device you are looking for by browsing /sys/class/tty/ttyUSBx

cd into the directory of the device of your choice.

Execute realpath .

This will show you something like this: /sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/ttyUSB0/tty/ttyUSB0

cd to /sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0 and cat uevent.
This will contain the USB VID/PID under PRODUCT=xxxxxxxx

There is obviously some work required to automate it with C++ but it is doable.


问:
Joomla current path
I have Joomla Component administrator/components/com_mycomp

And I have import.php file in this folder.

How I can access import.php from com_mycomp.php.

```<code>require_once('./import.php');
</code>```

Gives error file not found. Because current path is /administrator , instead of administrator/components/com_mycomp.

答:
The easiest way is to use PHP's __DIR__ constant, that always points to the current file's directory.

```<code><?php
require_once __DIR__ . '/import.php';
</code>```

Title: Joomla current path

Body:
I have Joomla Component administrator/components/com_mycomp

And I have import.php file in this folder.

How I can access import.php from com_mycomp.php.

require_once('./import.php');

Gives error file not found. Because current path is /administrator , instead of administrator/components/com_mycomp.

Body:
The easiest way is to use PHP's __DIR__ constant, that always points to the current file's directory.

<?php
require_once __DIR__ . '/import.php';


问:
Restoring database failed in SQL Server 2005 enterprise edition
I have tried to restore a database in SQL Server 2005 enterprise edition on Windows Server 2003. It shows the following error.

```<code>    Restored failed for Server 'MYS'. (Microsoft.SqlServer.Express.Smo)
    Additional information:
    System.Data.SqlClient.SqlError: The database was backed up on a server running version
 9.00.4053. That version is incompatible with this server, which is running version
9.00.1187. Either restore the database on a server that supports the backup, or use a
backup that is compatible with this server.  (Microsoft.SqlServer.Express.Smo)
</code>```

What should I do?

答:
The backup was made using SQL Server 2005 SP3, but your server appears to be running an older SQL Server 2005 CTP edition.  </p>

<p>You will need to upgrade your server to SQL 2005 SP3.  </p>

Body:
I have tried to restore a database in SQL Server 2005 enterprise edition on Windows Server 2003. It shows the following error.

    Restored failed for Server 'MYS'. (Microsoft.SqlServer.Express.Smo)
    Additional information:
    System.Data.SqlClient.SqlError: The database was backed up on a server running version
 9.00.4053. That version is incompatible with this server, which is running version
9.00.1187. Either restore the database on a server that supports the backup, or use a
backup that is compatible with this server.  (Microsoft.SqlServer.Express.Smo)

What should I do?

Body:
The backup was made using SQL Server 2005 SP3, but your server appears to be running an older SQL Server 2005 CTP edition.

You will need to upgrade your server to SQL 2005 SP3.


问:
ResultSetMetadata column types for count()/sum()
In MySQL select:

count(BIGINT) returns type=-5 (BigInteger), I expected Long

sum(SMALLINT) returns type=3 (BigDecimal), I expected Integer

Is there anything that can be done?

答:
The value of -5 indicates java.sql.Types.BIGINT, which is the JDBC/SQL equivalent of a Java long, so this value is entirely expected.

As to why SUM is mapped to 3, or java.sql.DECIMAL, I'm not sure. It might just be that is what MySQL does when summing not floating-point types.


问:
How to transpose Excel columns into a new range ignoring blank cells
I'm new at VBA and tried finding already existing solutions but none answered fully my requirements:

My initial list has holes (blanks) and I need to list the results as transposed without these blank fields

column A has files # and then 5 columns with prices but some are having only one price others 2 others 3 etc but never more than 3 prices. And these are varying from one month to another with hundred lines of it.

My first trials were no success as I couldn't find the totals expected.
My initial code was the following but it doesn't catch last 2 columns as there are blank fields in between:

```<code>Dim LR As Long, Rw As Long, Col As Long, LastCol As Long, CurRw As Long
Application.ScreenUpdating = False

LR = Range("A" & Rows.Count).End(xlUp).Row
Range("B:B").Insert xlShiftToRight

For Rw = LR To 2 Step -1
    If Range("D" & Rw) <> "" Then
        LastCol = Cells(Rw, Columns.Count).End(xlToLeft).Column
        Rows(Rw + 1).Resize(LastCol - 3).Insert xlShiftDown
        Range("A" & Rw).Resize(LastCol - 2) = Range("A" & Rw)
        Range("B" & Rw).Resize(LastCol - 2).Value = Range("C" & Rw).Resize(LastCol + 5).Value
        Range("C" & Rw).Resize(1, LastCol - 2).Copy
        Range("B" & Rw).Resize(LastCol - 2).PasteSpecial xlPasteAll, Transpose:=True
        Range("C1").Resize(1, LastCol - 2).Copy
        Range("C" & Rw).PasteSpecial xlPasteAll, Transpose:=True
    Else
        Range("C" & Rw).Copy Range("B" & Rw)
        Range("C1").Copy Range("C" & Rw)
    End If
Next Rw"
</code>```

Thanks for your help. wishing this is now easier to understand and assist ;-)

Result to reach:

答: You can use formula, like this =IFERROR(INDEX($B$2:$J$2,1,SMALL(IF($B$2:$J$2<>"",COLUMN($B$2:$J$2)-1),ROWS($L$1:L1))),"---") filled down

Body:
I'm new at VBA and tried finding already existing solutions but none answered fully my requirements:

My initial list has holes (blanks) and I need to list the results as transposed without these blank fields

column A has files # and then 5 columns with prices but some are having only one price others 2 others 3 etc but never more than 3 prices. And these are varying from one month to another with hundred lines of it.

My first trials were no success as I couldn't find the totals expected.
My initial code was the following but it doesn't catch last 2 columns as there are blank fields in between:

Dim LR As Long, Rw As Long, Col As Long, LastCol As Long, CurRw As Long
Application.ScreenUpdating = False

LR = Range("A" & Rows.Count).End(xlUp).Row
Range("B:B").Insert xlShiftToRight

For Rw = LR To 2 Step -1
    If Range("D" & Rw) <> "" Then
        LastCol = Cells(Rw, Columns.Count).End(xlToLeft).Column
        Rows(Rw + 1).Resize(LastCol - 3).Insert xlShiftDown
        Range("A" & Rw).Resize(LastCol - 2) = Range("A" & Rw)
        Range("B" & Rw).Resize(LastCol - 2).Value = Range("C" & Rw).Resize(LastCol + 5).Value
        Range("C" & Rw).Resize(1, LastCol - 2).Copy
        Range("B" & Rw).Resize(LastCol - 2).PasteSpecial xlPasteAll, Transpose:=True
        Range("C1").Resize(1, LastCol - 2).Copy
        Range("C" & Rw).PasteSpecial xlPasteAll, Transpose:=True
    Else
        Range("C" & Rw).Copy Range("B" & Rw)
        Range("C1").Copy Range("C" & Rw)
    End If
Next Rw"

Thanks for your help. wishing this is now easier to understand and assist ;-)

Result to reach:


问:
Mapping a single function is slower than twice mapping two separate functions?
The following example seems to imply run time optimisation that I do not understand

Can anyone explain this behavior and how it may apply to more generic cases?

Example

Consider the following simple (example) functions

```<code>def y(x): # str output
    y = 1 if x else 0
    return str(y)

def _y(x): # no str
    y = 1 if x else 0
    return y
</code>```

Assume I want to apply the function y upon all elements in a list

```<code>l = range(1000) # test input data
</code>```

Result

A map operation will have to iterate through all elements in the list. It seems counter intuitive that breaking the function apart into a double map significantly outperforms the single map function

```<code>%timeit map(str, map(_y, l))
1000 loops, best of 3: 206 µs per loop

%timeit map(y, l)
1000 loops, best of 3: 241 µs per loop
</code>```

More generically, this also applies to non standard library nested functions for example

```<code>def f(x):
    return _y(_y(x))

%timeit map(_y, map(_y, l))
1000 loops, best of 3: 235 µs per loop
%timeit map(f, l)
1000 loops, best of 3: 294 µs per loop
</code>```

Is this a python overhead issue where map is compiling the low level python code where possible and consequently being throttled when it has to interpret a nested function?

答:
The difference is that map() is implemented in C code, and calling to other C-implemented functions is cheap, while calling to Python code is expensive. On top of that, calling out to other callables from Python code is expensive too:

```<code>>>> timeit.timeit('f(1)', 'def f(x): return str(x)')
0.21682000160217285
>>> timeit.timeit('str(1)')
0.140916109085083
</code>```

and thirdly, you are passing in the function objects to map() (so no further lookups are done), but y() has to look up the str name each and every time. Global lookups are relatively expensive compared to local lookups; binding a global to a function argument to make it a local can help offset this a little:

```<code>>>> timeit.timeit('f(1)', 'def f(x, _str=str): return _str(x)')
0.19425392150878906
</code>```

Much closer to the str(1) version, even though that had to use a global too; it can still beat the function call hands-down if you gave the time test a local too:

```<code>>>> timeit.timeit('_str(1)', '_str = str')
0.10266494750976562
</code>```

So, Python bytecode execution requires an additional object, a stack frame, to be created for each call. That stack frame object has to be managed on a dedicated Python call stack when calling out to other code. Moreover, your y function looks up the str name as a global each time, whereas the map(str, ...) call keeps a single reference to that object and uses it over and over again.

By moving the str() call out of the y function and letting map() call str() directly instead through the single reference, you removed the stack handling and global name lookups, and sped things up marginally.

As a diagram, map(y, l) executes, per input value:

Create stackframe for y, execute the body

look up str as a global

push y stackframe onto stack

execute str(...)

pop stackframe from stack

return result

whereas map(str, map(_y, l)) executes

Create stackframe for _y

return result

execute str(...)

The same applies to your f() function setup:

```<code>>>> def f(x):
...     return _y(_y(x))
...
>>> timeit.timeit("map(_y, map(_y, l))", 'from __main__ import _y, testdata as l', number=10000)
2.691640853881836
>>> timeit.timeit("map(f, l)", 'from __main__ import f, testdata as l', number=10000)
3.104063034057617
</code>```

Calling map() on _y twice is faster than nesting the _y(_y(x)) call in another function, which then has to do global name look-ups and stress the Python stack some more; in your f() example each map() iteration has to create 3 stack frames and push and pop these on and off the stack, while in your map(_y, map(_y, ...)) setup, only 2 frames are created per iterated item:

Create stackframe for f, execute the body

look up _y as a global

push f stackframe onto stack

Create stackframe for _y, execute the body

pop stackframe from stack

look up _y as a global  (yes, again)

push f stackframe onto stack

Create stackframe for _y, execute the body

pop stackframe from stack

return result

versus:

Create stackframe for _y, execute the body

return result

Create stackframe for _y, execute the body

return result

Again, using locals can off-set the difference a little:

```<code>>>> def f(x, _y=_y):
...     return _y(_y(x))
...
>>> timeit.timeit("map(f, l)", 'from __main__ import f, testdata as l', number=10000)
2.981696128845215
</code>```

but that extra Python frame object is still hobbling the single map(f, ...) call.

TLDR: Your y() function suffers from O(N) additional global name lookups and O(N) additional stack frame objects being pushed onto and off the Python stack, compared to the double map() version.

If speed matters this match, try to avoid creating Python stack frames and global name lookups in a tight loop.

Body:
The following example seems to imply run time optimisation that I do not understand

Can anyone explain this behavior and how it may apply to more generic cases?

Example

Consider the following simple (example) functions

def y(x): # str output
    y = 1 if x else 0
    return str(y)

def _y(x): # no str
    y = 1 if x else 0
    return y

Assume I want to apply the function y upon all elements in a list

l = range(1000) # test input data

Result

A map operation will have to iterate through all elements in the list. It seems counter intuitive that breaking the function apart into a double map significantly outperforms the single map function

%timeit map(str, map(_y, l))
1000 loops, best of 3: 206 µs per loop

%timeit map(y, l)
1000 loops, best of 3: 241 µs per loop

More generically, this also applies to non standard library nested functions for example

def f(x):
    return _y(_y(x))

%timeit map(_y, map(_y, l))
1000 loops, best of 3: 235 µs per loop
%timeit map(f, l)
1000 loops, best of 3: 294 µs per loop

Is this a python overhead issue where map is compiling the low level python code where possible and consequently being throttled when it has to interpret a nested function?

Body:
The difference is that map() is implemented in C code, and calling to other C-implemented functions is cheap, while calling to Python code is expensive. On top of that, calling out to other callables from Python code is expensive too:

>>> timeit.timeit('f(1)', 'def f(x): return str(x)')
0.21682000160217285
>>> timeit.timeit('str(1)')
0.140916109085083

and thirdly, you are passing in the function objects to map() (so no further lookups are done), but y() has to look up the str name each and every time. Global lookups are relatively expensive compared to local lookups; binding a global to a function argument to make it a local can help offset this a little:

>>> timeit.timeit('f(1)', 'def f(x, _str=str): return _str(x)')
0.19425392150878906

Much closer to the str(1) version, even though that had to use a global too; it can still beat the function call hands-down if you gave the time test a local too:

>>> timeit.timeit('_str(1)', '_str = str')
0.10266494750976562

So, Python bytecode execution requires an additional object, a stack frame, to be created for each call. That stack frame object has to be managed on a dedicated Python call stack when calling out to other code. Moreover, your y function looks up the str name as a global each time, whereas the map(str, ...) call keeps a single reference to that object and uses it over and over again.

By moving the str() call out of the y function and letting map() call str() directly instead through the single reference, you removed the stack handling and global name lookups, and sped things up marginally.

As a diagram, map(y, l) executes, per input value:

Create stackframe for y, execute the body

look up str as a global

push y stackframe onto stack

execute str(...)

pop stackframe from stack

return result

whereas map(str, map(_y, l)) executes

Create stackframe for _y

return result

execute str(...)

The same applies to your f() function setup:

>>> def f(x):
...     return _y(_y(x))
...
>>> timeit.timeit("map(_y, map(_y, l))", 'from __main__ import _y, testdata as l', number=10000)
2.691640853881836
>>> timeit.timeit("map(f, l)", 'from __main__ import f, testdata as l', number=10000)
3.104063034057617

Calling map() on _y twice is faster than nesting the _y(_y(x)) call in another function, which then has to do global name look-ups and stress the Python stack some more; in your f() example each map() iteration has to create 3 stack frames and push and pop these on and off the stack, while in your map(_y, map(_y, ...)) setup, only 2 frames are created per iterated item:

Create stackframe for f, execute the body

look up _y as a global

push f stackframe onto stack

Create stackframe for _y, execute the body

pop stackframe from stack

look up _y as a global  (yes, again)

push f stackframe onto stack

Create stackframe for _y, execute the body

pop stackframe from stack

return result

versus:

Create stackframe for _y, execute the body

return result

Create stackframe for _y, execute the body

return result

Again, using locals can off-set the difference a little:

>>> def f(x, _y=_y):
...     return _y(_y(x))
...
>>> timeit.timeit("map(f, l)", 'from __main__ import f, testdata as l', number=10000)
2.981696128845215

but that extra Python frame object is still hobbling the single map(f, ...) call.

TLDR: Your y() function suffers from O(N) additional global name lookups and O(N) additional stack frame objects being pushed onto and off the Python stack, compared to the double map() version.

If speed matters this match, try to avoid creating Python stack frames and global name lookups in a tight loop.


问:
How to set Eclipse's output directory from Gradle
I am using Gradle's eclipse plugin. For cross-project reference reasons, I need Eclipse's output directory to not be the default bin, rather ecbuild.

Everytime I run ./gradlew eclipse, it overwrites this output directory setting.

How to make sure it doesn't, or how to set it within gradle build script ?

答:
Add this to the build.gradle script:

```<code>eclipse {
   classpath { defaultOutputDir = file('ecbuild') }
}
</code>```

This might require you to upgrade the version of your gradle wrapper.

If so, run :

```<code>./gradlew wrapper --gradle-version 3.3
</code>```

Body:
Add this to the build.gradle script:

eclipse {
   classpath { defaultOutputDir = file('ecbuild') }
}

This might require you to upgrade the version of your gradle wrapper.

If so, run :

./gradlew wrapper --gradle-version 3.3


问:
Custom SharePoint 2010 forms
Am I required to use InfoPath to create custom forms for SharePoint 2010, or can I create them using Visual Studio? For example, when a Task is being edited, I want to be able to either edit the form, or create one from scratch.

Many thanks.

答:
You can create your own form for a custom list definition. Inside your list you have a file schema.xml. In the end you will find sth like this:

```<code><Forms>
  <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>
</code>```

Then create files with those names inside list definition, make adjustments in SharePointProjectItem.spdata file (it's hidden) and there you have it.

Title: Custom SharePoint 2010 forms

Body:
You can create your own form for a custom list definition. Inside your list you have a file schema.xml. In the end you will find sth like this:

<Forms>
  <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>

Then create files with those names inside list definition, make adjustments in SharePointProjectItem.spdata file (it's hidden) and there you have it.