问:
Linear Model requires variable as input plus output
So I'm new to coding, R and data science and have been picking up all of this mostly through online tutorials. I have written a shiny app where i am trying to implement a few things:

Run a linear regression

Run a Monte Carlo simulation

Be dynamic in nature

So for this I used the iris data set. The purpose of the app is to allow a user to select input and output variables which will be passed on to a linear regression model. The user will then propose a distribution for his selected variables and use the linear model which was generated in a Monte Carlo simulation and output a histogram of the result.

However something doesn't seem right as I can only generate the histogram when I have the same variable selected under input and output and I cant seem to know why? What i mean by this is that for example I need to select Species under Select input and output

```<code>library(shiny)
ui <- fluidPage(
  fluidRow(
    column(4,
           wellPanel(
             sliderInput("sampleSize","Please Select Sample Size:",
                         min = 0,max = 5000,value = 1000,step = 100),
             uiOutput("invar"),
             uiOutput("outvar"),
             uiOutput("moC")))
    ),

  mainPanel(
    plotOutput("histogram")
  )
)
server <- function(input, output) {

  sorted <-  reactive({
    data <- iris[ ,c(input$inv)]
    data})

  output$invar<-renderUI({
    selectizeInput('invar',"Select Regression Input Variables", choices = names(iris), multiple = TRUE)
  })

  output$outvar<-renderUI({
    selectizeInput('outvar',"Select Regression Output Variable", choices = names(iris), multiple = FALSE)

  })

  sorted <-  reactive({
    iris[input$invar]
  })

  output$moC <- renderUI({
    numvar<- length(input$invar)

    lapply(1:numvar, function(i) {
      tagList(
        selectInput("inv",paste0("Please Select Probability Distribution of ", input$invar[i]),
                    choices = c("Normal","Uniform")),
        conditionalPanel(condition = "input.inv=='Normal'",
                         textInput("invarpdfmean","Please Select Input Variable Mean:",2),
                         textInput("invarpdfsd","Please Select Input Variable Standard Deviation", 0.02)),
        conditionalPanel(condition = "input.inv=='Uniform'",
                         textInput("invarpdfmin","Please Select Minimum Input Variable Value:",1),
                         textInput("invarpdfmax","Please Select Maximum Input Variable Value", 5))

      )})})

  output$histogram <- renderPlot({
    n <- input$sampleSize
    numvar<- length(input$invar)
    SelectedVars <- input$invar
    vartopredict <- input$outvar
    fmla <- reformulate(SelectedVars, response = vartopredict)

    lapply(1:numvar, function(i) {
    if(input$invar[i]=="Normal"){

      invarpdfVec <- rnorm(n,mean = as.numeric(input$invarpdfmean),sd= as.numeric(input$invarpdfsd))
    }

    if(input$invar[i]=="Uniform"){

      invarpdfVec <- runif(n,min = as.numeric(input$invarpdfmin),max = as.numeric(input$invarpdfmax))
    }
    })

    MCtab <- iris[ , input$invar]
    pred.model=lm(fmla,MCtab)

    for (n in 1:input$sampleSize){
      h <- predict(pred.model,MCtab)
    }

    h<- hist(h,breaks=30,col="red",freq=F)
    # Define the quartiles for the Min, Max, P10, P50 and P90

  }

)
}

shinyApp(ui, server)
</code>```

答:
The problem you are most likely running into is with the MCtab variable. Try

```<code>output$histogram <- renderPlot({
  #...
  MCtab <- iris[ , unique(c(SelectedVars, vartopredict)), drop=FALSE]
  #...
})
</code>```

You need to make sure your data.frame as all the variables you are trying to use in the formula you are creating.

Body:
So I'm new to coding, R and data science and have been picking up all of this mostly through online tutorials. I have written a shiny app where i am trying to implement a few things:

Run a linear regression

Run a Monte Carlo simulation

Be dynamic in nature

So for this I used the iris data set. The purpose of the app is to allow a user to select input and output variables which will be passed on to a linear regression model. The user will then propose a distribution for his selected variables and use the linear model which was generated in a Monte Carlo simulation and output a histogram of the result.

However something doesn't seem right as I can only generate the histogram when I have the same variable selected under input and output and I cant seem to know why? What i mean by this is that for example I need to select Species under Select input and output

library(shiny)
ui <- fluidPage(
  fluidRow(
    column(4,
           wellPanel(
             sliderInput("sampleSize","Please Select Sample Size:",
                         min = 0,max = 5000,value = 1000,step = 100),
             uiOutput("invar"),
             uiOutput("outvar"),
             uiOutput("moC")))
    ),

  mainPanel(
    plotOutput("histogram")
  )
)
server <- function(input, output) {

  sorted <-  reactive({
    data <- iris[ ,c(input$inv)]
    data})

  output$invar<-renderUI({
    selectizeInput('invar',"Select Regression Input Variables", choices = names(iris), multiple = TRUE)
  })

  output$outvar<-renderUI({
    selectizeInput('outvar',"Select Regression Output Variable", choices = names(iris), multiple = FALSE)

  })

  sorted <-  reactive({
    iris[input$invar]
  })

  output$moC <- renderUI({
    numvar<- length(input$invar)

    lapply(1:numvar, function(i) {
      tagList(
        selectInput("inv",paste0("Please Select Probability Distribution of ", input$invar[i]),
                    choices = c("Normal","Uniform")),
        conditionalPanel(condition = "input.inv=='Normal'",
                         textInput("invarpdfmean","Please Select Input Variable Mean:",2),
                         textInput("invarpdfsd","Please Select Input Variable Standard Deviation", 0.02)),
        conditionalPanel(condition = "input.inv=='Uniform'",
                         textInput("invarpdfmin","Please Select Minimum Input Variable Value:",1),
                         textInput("invarpdfmax","Please Select Maximum Input Variable Value", 5))

      )})})

  output$histogram <- renderPlot({
    n <- input$sampleSize
    numvar<- length(input$invar)
    SelectedVars <- input$invar
    vartopredict <- input$outvar
    fmla <- reformulate(SelectedVars, response = vartopredict)

    lapply(1:numvar, function(i) {
    if(input$invar[i]=="Normal"){

      invarpdfVec <- rnorm(n,mean = as.numeric(input$invarpdfmean),sd= as.numeric(input$invarpdfsd))
    }

    if(input$invar[i]=="Uniform"){

      invarpdfVec <- runif(n,min = as.numeric(input$invarpdfmin),max = as.numeric(input$invarpdfmax))
    }
    })

    MCtab <- iris[ , input$invar]
    pred.model=lm(fmla,MCtab)

    for (n in 1:input$sampleSize){
      h <- predict(pred.model,MCtab)
    }

    h<- hist(h,breaks=30,col="red",freq=F)
    # Define the quartiles for the Min, Max, P10, P50 and P90

  }

)
}

shinyApp(ui, server)

Body:
The problem you are most likely running into is with the MCtab variable. Try

output$histogram <- renderPlot({
  #...
  MCtab <- iris[ , unique(c(SelectedVars, vartopredict)), drop=FALSE]
  #...
})

You need to make sure your data.frame as all the variables you are trying to use in the formula you are creating.


来源: stackexchange

问:
ASP.net Membership provider client or serverside authentication
I am developing an MVC2 application an am using the built in Membership provider. I am just asking myself if the authentication is on the server or the client?</p>

答:
Authentication is on the server.

Really wanted to say "In the middle of nowhere" =)

ContentLicense: CC BY-SA 2.5


问:
Enabling @KafkaListener to take in variable topic names from application.yml file
I am attempting to load in multiple topics to a single @KafkaListener but am running into trouble as I believe it is looking for a constant value, but initializing the topics variable from the application.yml file causing something issues, I was wondering if someone could help me troubleshoot this issue, or provide me with direction into how to load multiple Kafka topics into a single KafkaListener.

I am able to listen to multiple topics in the same @KafkaListener by passing them in a comma delimited object as seen below:

```<code>@KafkaListener(topics = {
           "flight-events",
           "flight-time-events",
           "service-events",
           "flight-delay-events"
   })
</code>```

I realize I could do an object with comma delimited values representing the topics, but I want to be able to add topics through a config file, rather than changing code in the code base.

I believe there may be the problem in that @KafkaListener needs to take in a constant value, and I am unable to define an annotation as a constant, is there any way around this?

KafkaWebSocketConnector.java

```<code>@Component
public class KafkaWebSocketConnector
{

   @Value("${spring.kafka.topics}")
   private String[] topics;

   @KafkaListener(topics = topics)
   public void listen(ConsumerRecord<?, Map<String, String>> message)
   {
      log.info("Received messages on topic [{}]: [{}]", message.topic(), message.value());
      String dest = "/" + message.topic();
      log.info("destination = {}", dest);
      log.info("msg: {}", message);
      messageTemplate.convertAndSend(dest, message.value());
   }
}
</code>```

application.yml

```<code>spring:
  kafka:
    consumer:
      auto-offset-reset: earliest
      group-id: kafka-websocket-connector
    topics: flight-events,
      flight-time-events,
      canceled-events,
      pax-events,
      flight-delay-events
</code>```

答:
Answer provided from @Gary Russell from this GitHub issue:

https://github.com/spring-projects/spring-kafka/issues/361

You can use a SpEL expression; there's an example in EnableKafkaIntegrationTests...

```<code>@KafkaListener(id = "foo", topics = "#{'${topicOne:annotated1,foo}'.split(',')}")
</code>```

In my case "#{'${spring.kafka.topics}'.split(',')}"

I was able to implement the above code, (provided by Gary Russell) in order to answer the above question.

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to load in multiple topics to a single @KafkaListener but am running into trouble as I believe it is looking for a constant value, but initializing the topics variable from the application.yml file causing something issues, I was wondering if someone could help me troubleshoot this issue, or provide me with direction into how to load multiple Kafka topics into a single KafkaListener.

I am able to listen to multiple topics in the same @KafkaListener by passing them in a comma delimited object as seen below:

@KafkaListener(topics = {
           "flight-events",
           "flight-time-events",
           "service-events",
           "flight-delay-events"
   })

I realize I could do an object with comma delimited values representing the topics, but I want to be able to add topics through a config file, rather than changing code in the code base.

I believe there may be the problem in that @KafkaListener needs to take in a constant value, and I am unable to define an annotation as a constant, is there any way around this?

KafkaWebSocketConnector.java

@Component
public class KafkaWebSocketConnector
{

   @Value("${spring.kafka.topics}")
   private String[] topics;

   @KafkaListener(topics = topics)
   public void listen(ConsumerRecord<?, Map<String, String>> message)
   {
      log.info("Received messages on topic [{}]: [{}]", message.topic(), message.value());
      String dest = "/" + message.topic();
      log.info("destination = {}", dest);
      log.info("msg: {}", message);
      messageTemplate.convertAndSend(dest, message.value());
   }
}

application.yml

spring:
  kafka:
    consumer:
      auto-offset-reset: earliest
      group-id: kafka-websocket-connector
    topics: flight-events,
      flight-time-events,
      canceled-events,
      pax-events,
      flight-delay-events

Body:
Answer provided from @Gary Russell from this GitHub issue:

https://github.com/spring-projects/spring-kafka/issues/361

You can use a SpEL expression; there's an example in EnableKafkaIntegrationTests...

@KafkaListener(id = "foo", topics = "#{'${topicOne:annotated1,foo}'.split(',')}")

In my case "#{'${spring.kafka.topics}'.split(',')}"

I was able to implement the above code, (provided by Gary Russell) in order to answer the above question.


问:
Performance issue in bulk importing data in Dynamics CRM
I am importing data to Dynamics CRM using C# console application. I am using following code:

```<code>    public static void Main(string[] args)
    {
            int totalRecords = dbcon.GetDataCount();
            int rowCount = totalRecords / 10;

            for (int i = 1, j = 1; i <= totalRecords; i = i + rowCount, j = j + 1)
            {
                Task myTask = new Task(() => TestMethod(i, (rowCount * j)));
                myTask.Start();
            }
          Task.WaitAll();
     }

public static void TestMethod(int startSeqNo, int endSeqNo)
{
   IOrganizationService service = getServiceProxcy();
    DBConnection dbcon = new DBConnection();
    DataTable dt = dbcon.GetData(startSeqNo, endSeqNo);
    // Insert Commented
    BulkCreate(service, dt);
 }

public static void BulkCreate(IOrganizationService service, DataTable dt)
{
  // Create an ExecuteMultipleRequest object.
  ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
  {
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = true
    },
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};

foreach (DataRow row in dt.Rows)
{
    Entity entity = new Entity("new_dataimporttest");
    entity["new_name"] = row["name"].ToString();
    entity["new_telephone"] = row["telephone1"].ToString();
    if (multipleRequest.Requests.Count == 1000)
    {
        // Execute all the requests in the request collection using a single web method call.
        ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
        multipleRequest.Requests.Clear();
    }
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleRequest.Requests.Add(createRequest);
}

// Execute all the requests in the request collection using a single web method call.
if (multipleRequest.Requests.Count > 0)
{
    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
}
</code>```

I am using Task Parallel Library. It works fine but issue is that when following line is executed it takes time.

```<code>// Execute all the requests in the request collection using a single web method call.
    //            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
</code>```

I want to improve performance of code as I am importing large amount of data nearly 1 million records. Currently it takes 1h 50 mins. How do I improve code to reduce execution time.

答: If just data import is what intended here, try using SqlBulkCopy to write data directly to server (Sample Code). </p>

ContentLicense: CC BY-SA 4.0

Body:
I am importing data to Dynamics CRM using C# console application. I am using following code:

    public static void Main(string[] args)
    {
            int totalRecords = dbcon.GetDataCount();
            int rowCount = totalRecords / 10;

            for (int i = 1, j = 1; i <= totalRecords; i = i + rowCount, j = j + 1)
            {
                Task myTask = new Task(() => TestMethod(i, (rowCount * j)));
                myTask.Start();
            }
          Task.WaitAll();
     }

public static void TestMethod(int startSeqNo, int endSeqNo)
{
   IOrganizationService service = getServiceProxcy();
    DBConnection dbcon = new DBConnection();
    DataTable dt = dbcon.GetData(startSeqNo, endSeqNo);
    // Insert Commented
    BulkCreate(service, dt);
 }

public static void BulkCreate(IOrganizationService service, DataTable dt)
{
  // Create an ExecuteMultipleRequest object.
  ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
  {
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = true
    },
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};

foreach (DataRow row in dt.Rows)
{
    Entity entity = new Entity("new_dataimporttest");
    entity["new_name"] = row["name"].ToString();
    entity["new_telephone"] = row["telephone1"].ToString();
    if (multipleRequest.Requests.Count == 1000)
    {
        // Execute all the requests in the request collection using a single web method call.
        ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
        multipleRequest.Requests.Clear();
    }
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleRequest.Requests.Add(createRequest);
}

// Execute all the requests in the request collection using a single web method call.
if (multipleRequest.Requests.Count > 0)
{
    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
}

I am using Task Parallel Library. It works fine but issue is that when following line is executed it takes time.

// Execute all the requests in the request collection using a single web method call.
    //            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

I want to improve performance of code as I am importing large amount of data nearly 1 million records. Currently it takes 1h 50 mins. How do I improve code to reduce execution time.


问:
open file with Illegal characters in path
So, I am copied images and renamed thems by GUID and didn't meet any problems.
But when I wanted to open this image for example into picturebox, I got this:

Generated name with path in debuger looks like:@"images\full_45e72053-440f-4f20-863c-3d80ef96876f.jpeg"

How I can open this file?

This is my code which show me this problem:

```<code>private void picBoxMini2_Click(object sender, EventArgs e)
        {
            string dir = ConfigurationManager.AppSettings["imageFolderPath"].ToString();
            string imgName = this.picBoxMini2.ImageLocation;
            string[] tmp = imgName.Split('_');
            this.picBoxMain.Image = Image.FromFile($"{dir}\full_{tmp[tmp.Length - 1]}");
        }
</code>```

ImageLocation contains 100% info, I insured on this situation:

```<code> string dir = ConfigurationManager.AppSettings["imageFolderPath"].ToString();
            if (imgs.Length >= 1)
            {
                this.picBoxMain.Image = Image.FromFile($@"{dir}\full_{imgs[0]}");
                this.picBoxMain.ImageLocation = $@"{dir}\full_{imgs[0]}";
                this.picBoxMini1.Image = Image.FromFile($@"{dir}\85_{imgs[0]}");
                this.picBoxMini1.ImageLocation = $@"{dir}\85_{imgs[0]}";

                this.picBoxMini2.Image = null;
                this.picBoxMini2.ImageLocation = null;
                this.picBoxMini3.Image = null;
                this.picBoxMini3.ImageLocation = null;
            }
            if (imgs.Length >= 2)
            {
                this.picBoxMini2.Image = Image.FromFile($@"{dir}\85_{imgs[1]}");
                this.picBoxMini2.ImageLocation = $@"{dir}\85_{imgs[1]}";
            }
            if (imgs.Length == 3)
            {
                this.picBoxMini3.Image = Image.FromFile($@"{dir}\85_{imgs[2]}");
                this.picBoxMini3.ImageLocation = $@"{dir}\85_{imgs[2]}";
            }
</code>```

答:
The problem is on this line:

```<code>this.picBoxMain.Image = Image.FromFile($"{dir}\full_{tmp[tmp.Length - 1]}");
</code>```

You forgot the @ that tells the compiler to treat the string as verbatim.  Without that mark it thinks your path has an embedded ctrl+f character (from the \f in \full), which is not a legal character for filenames in Windows.

Your options are:

Include the @: this.picBoxMain.Image = Image.FromFile($@"{dir}\full_{tmp[tmp.Length - 1]}")

Escape the directory separator: this.picBoxMain.Image = Image.FromFile($"{dir}\\full_{tmp[tmp.Length - 1]}")

Do something else fancy with System.IO.Path.Combine to automatically handle the directory / filename separators. this.picBoxMain.Image = Image.FromFile(System.IO.Path.Combine(dir, $"full_{tmp[tmp.Length - 1]}")) (This probably the safest, most portable solution, but it might be overkill for your needs.)

Body:
So, I am copied images and renamed thems by GUID and didn't meet any problems.
But when I wanted to open this image for example into picturebox, I got this:

Generated name with path in debuger looks like:@"images\full_45e72053-440f-4f20-863c-3d80ef96876f.jpeg"

How I can open this file?

This is my code which show me this problem:

private void picBoxMini2_Click(object sender, EventArgs e)
        {
            string dir = ConfigurationManager.AppSettings["imageFolderPath"].ToString();
            string imgName = this.picBoxMini2.ImageLocation;
            string[] tmp = imgName.Split('_');
            this.picBoxMain.Image = Image.FromFile($"{dir}\full_{tmp[tmp.Length - 1]}");
        }

ImageLocation contains 100% info, I insured on this situation:

 string dir = ConfigurationManager.AppSettings["imageFolderPath"].ToString();
            if (imgs.Length >= 1)
            {
                this.picBoxMain.Image = Image.FromFile($@"{dir}\full_{imgs[0]}");
                this.picBoxMain.ImageLocation = $@"{dir}\full_{imgs[0]}";
                this.picBoxMini1.Image = Image.FromFile($@"{dir}\85_{imgs[0]}");
                this.picBoxMini1.ImageLocation = $@"{dir}\85_{imgs[0]}";

                this.picBoxMini2.Image = null;
                this.picBoxMini2.ImageLocation = null;
                this.picBoxMini3.Image = null;
                this.picBoxMini3.ImageLocation = null;
            }
            if (imgs.Length >= 2)
            {
                this.picBoxMini2.Image = Image.FromFile($@"{dir}\85_{imgs[1]}");
                this.picBoxMini2.ImageLocation = $@"{dir}\85_{imgs[1]}";
            }
            if (imgs.Length == 3)
            {
                this.picBoxMini3.Image = Image.FromFile($@"{dir}\85_{imgs[2]}");
                this.picBoxMini3.ImageLocation = $@"{dir}\85_{imgs[2]}";
            }

Body:
The problem is on this line:

this.picBoxMain.Image = Image.FromFile($"{dir}\full_{tmp[tmp.Length - 1]}");

You forgot the @ that tells the compiler to treat the string as verbatim.  Without that mark it thinks your path has an embedded ctrl+f character (from the \f in \full), which is not a legal character for filenames in Windows.

Your options are:

Include the @: this.picBoxMain.Image = Image.FromFile($@"{dir}\full_{tmp[tmp.Length - 1]}")

Escape the directory separator: this.picBoxMain.Image = Image.FromFile($"{dir}\\full_{tmp[tmp.Length - 1]}")

Do something else fancy with System.IO.Path.Combine to automatically handle the directory / filename separators. this.picBoxMain.Image = Image.FromFile(System.IO.Path.Combine(dir, $"full_{tmp[tmp.Length - 1]}")) (This probably the safest, most portable solution, but it might be overkill for your needs.)


问:
How do I edit a symlink using Atom?
On GitHub I can view symlinks as text - they are just a path to the target.
However, if I edit a symlink in Atom it opens the file that the symlink points to. This is reasonable behaviour but not what I am trying to do.

Can I edit them in a similar way using Atom on my local machine?

If now, is there another text editor that can?

答:
You can't change a symbolic link's target by editing the symlink file.

There are cases where the target of a symlink is stored in the symlink file, but that is not usually the case. For most target paths, the target is stored in the inode data directly.

Then there are symlink-like things various filesystems have implemented, such as macOS aliases, or Windows NTFS which has symlinks but they are not exactly the same as Unix/POSIX symlinks.

To manage symlinks you should be using the tools your OS provides, such as the ln command.

That said, I'm not aware of any packages for Atom which offer an in-editor method of managing symlinks. The tree-view package does not seem to offer it.

Title: How do I edit a symlink using Atom?


问:
How to add multi line comments in makefiles
Is there a way to comment out multiple lines in makefiles like as in C syntax /* */ ?

答:
No, there is nothing like C-style /* */ comments in makefiles.  As somebody else suggested, you can make a multi-line comment by using line continuations.  For example:

```<code># This is the first line of a comment \
and this is still part of the comment \
as is this, since I keep ending each line \
with a backslash character
</code>```

However, I imagine that you are probably looking to temporarily comment out a chunk of your makefile for debugging reasons, and adding a backslash on every line is not really practical.  If you are using GNU make, I suggest you use the ifeq directive with a deliberately false expression.  For example:

```<code>ifeq ("x","y")
# here's all your 'commented' makefile content...
endif
</code>```

Body:
No, there is nothing like C-style /* */ comments in makefiles.  As somebody else suggested, you can make a multi-line comment by using line continuations.  For example:

# This is the first line of a comment \
and this is still part of the comment \
as is this, since I keep ending each line \
with a backslash character

However, I imagine that you are probably looking to temporarily comment out a chunk of your makefile for debugging reasons, and adding a backslash on every line is not really practical.  If you are using GNU make, I suggest you use the ifeq directive with a deliberately false expression.  For example:

ifeq ("x","y")
# here's all your 'commented' makefile content...
endif


问:
.htaccess, Redirect to HTTPS on main domain and to HTTP on subdomain
Now, I have the following code in my .htaccess file

```<code># redirect to https www
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)(builders-steps\.ru)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]

# redirect to http subdomain
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^((?!www).+\.builders-steps\.ru)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</code>```

and it's working fine but main domain is now available on both https and http but I need the main domain to work only on HTTPS.   Subdomain is working fine with the current code (only on HTTP).

Can you guys help me with advice?

Thanks.

答:
Not sure if it´s working. Cannot try code here.

For rewriting All your main domain, try first redirecting the
  subdomain if it´s informed (higher restrictive) and later, if it´s not
  applied, you will check if for the main domain.

```<code># redirect to http subdomain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^((?!www).+\.builders-steps\.ru)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} ^(?:www\.)(builders-steps\.ru)$ [NC]
RewriteCond %{SERVER_PORT} !443
RewriteRule ^(.*)$ https://www.builders-steps.ru/$1 [R,L]
</code>```

Body:
Now, I have the following code in my .htaccess file

# redirect to https www
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)(builders-steps\.ru)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]

# redirect to http subdomain
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^((?!www).+\.builders-steps\.ru)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

and it's working fine but main domain is now available on both https and http but I need the main domain to work only on HTTPS.   Subdomain is working fine with the current code (only on HTTP).

Can you guys help me with advice?

Thanks.

Body:
Not sure if it´s working. Cannot try code here.

For rewriting All your main domain, try first redirecting the
  subdomain if it´s informed (higher restrictive) and later, if it´s not
  applied, you will check if for the main domain.

# redirect to http subdomain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^((?!www).+\.builders-steps\.ru)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} ^(?:www\.)(builders-steps\.ru)$ [NC]
RewriteCond %{SERVER_PORT} !443
RewriteRule ^(.*)$ https://www.builders-steps.ru/$1 [R,L]


问:
Creating postgresql database in Docker with Django project
I would like to create postgresql database in docker with my Django project. I'm trying to do it using init.sql file but it doesn't work:

settings.py:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'aso',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}
</code>```

init.sql:

```<code>CREATE USER postgres;
CREATE DATABASE aso;
GRANT ALL PRIVILEGES ON DATABASE aso TO postgres;
</code>```

My updated Dockerfile:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
FROM library/postgres
ADD init.sql /docker-entrypoint-initdb.d/
</code>```

Unfortunately I get:

```<code>db_1   | LOG:  database system was shut down at 2017-07-05 14:02:41 UTC
web_1  | /usr/local/bin/docker-entrypoint.sh: line 145: exec: python3: not found
db_1   | LOG:  MultiXact member wraparound protections are now enabled
db_1   | LOG:  autovacuum launcher started
db_1   | LOG:  database system is ready to accept connections
dockerpri_web_1 exited with code 127
</code>```

I was trying with this Dockerfile, too:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB aso
</code>```

My docker-compose.yml:

```<code>version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python3 PROJECT/backend/project/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
</code>```

答:
First, your Dockerfile example isn't valid. It should just have one FROM instruction. Remove the PostgreSQL stuff so it is just:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
</code>```

Next, I am going to answer the question of how to create a PostgreSQL user and database since that is what your init.sql is doing.

According to the postgres image documentation at https://hub.docker.com/_/postgres/, there are POSTGRES_USER and POSTGRES_PASSWORD environment variables available to us. The POSTGRES_USER variable will create a user and database with privileges to that user. An example amend to your docker-compose.yml would be:

```<code>version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  web:
    build: .
    command: python3 PROJECT/backend/project/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
</code>```

On start, this will initialize the PostgreSQL database with a username of aso, a database of aso, and a password of somepass. Then, you can just amend your settings.py to use this username, database, and password.

I'll also add, that if you wanted to run other arbitrary SQL or scripts during database startup, you can do so by adding sql or sh files to the postgres image at /docker-entrypoint-initdb.d/. Read more about this at https://github.com/docker-library/docs/tree/master/postgres#how-to-extend-this-image.

Body:
I would like to create postgresql database in docker with my Django project. I'm trying to do it using init.sql file but it doesn't work:

settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'aso',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

init.sql:

CREATE USER postgres;
CREATE DATABASE aso;
GRANT ALL PRIVILEGES ON DATABASE aso TO postgres;

My updated Dockerfile:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
FROM library/postgres
ADD init.sql /docker-entrypoint-initdb.d/

Unfortunately I get:

db_1   | LOG:  database system was shut down at 2017-07-05 14:02:41 UTC
web_1  | /usr/local/bin/docker-entrypoint.sh: line 145: exec: python3: not found
db_1   | LOG:  MultiXact member wraparound protections are now enabled
db_1   | LOG:  autovacuum launcher started
db_1   | LOG:  database system is ready to accept connections
dockerpri_web_1 exited with code 127

I was trying with this Dockerfile, too:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB aso

My docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python3 PROJECT/backend/project/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db

Body:
First, your Dockerfile example isn't valid. It should just have one FROM instruction. Remove the PostgreSQL stuff so it is just:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/

Next, I am going to answer the question of how to create a PostgreSQL user and database since that is what your init.sql is doing.

According to the postgres image documentation at https://hub.docker.com/_/postgres/, there are POSTGRES_USER and POSTGRES_PASSWORD environment variables available to us. The POSTGRES_USER variable will create a user and database with privileges to that user. An example amend to your docker-compose.yml would be:

version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  web:
    build: .
    command: python3 PROJECT/backend/project/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db

On start, this will initialize the PostgreSQL database with a username of aso, a database of aso, and a password of somepass. Then, you can just amend your settings.py to use this username, database, and password.

I'll also add, that if you wanted to run other arbitrary SQL or scripts during database startup, you can do so by adding sql or sh files to the postgres image at /docker-entrypoint-initdb.d/. Read more about this at https://github.com/docker-library/docs/tree/master/postgres#how-to-extend-this-image.


问:
Access ApiController User in class library
I have a Web API 2.2 application and want to filter data based on the current user that is accessing the Web API. The User property on the ApiController has the information that I need. But how can I get that information to my service class? Of course I don't want to pass everything around via parameters, but via my DI. </p>

答: You want to pass your principal into the methods of the service class, not as a constructor parameter.  Depending on how you are using DI, that service class can hang around for a while, and you don't want the class to have the principal in that case.  You want your principal to be short lived.</p>


问:
Does Clojure Ring create a thread for each request?
I am making a Messenger bot and I am using Ring as my http framework.

Sometime I want to apply delays between messages sent by the bot. My expectation would be that it is safe to use Thread/sleep because this will make the active thread sleep and not the entire server. Is that so, or should I resort to clojure/core.async?

This is the code I would be writing without async:

```<code>  (match [reply]

    ; The bot wants to send a message (text, images, videos etc.) after n milliseconds
    [{:message message :delay delay}]
    (do
      (Thread/sleep interval delay)
      (facebook/send-message sender-id message))
    ; More code would follow...
</code>```

A link to Ring code where its behaviour in this sense is clear would be appreciated, as well as any other with explanation on the matter.

答:
Assuming you're talking about code in a handler, Thread/sleep in Ring does make the thread for the request sleep. If you have multiple requests you are burning up expensive server threads.

The reason why Ring blocks is because the (non-async) model is based on function composition, where the result of one function is the output for another. So they have to wait, where exactly I can pinpoint this in the code I don't know.

Putting it in a go-block is better, because then you are not blocking server threads. It can return the response while you send the message. Do note that you cannot use results from the go block.

If you also want a response asynchronously (without blocking a server thread) you can for example use Pedestal.

For most servers synchronous handlers are sufficient, but if you are using Thread/sleeps AND want a response I would recommend using asynchronous Ring handlers or Pedestal or another framework.

Body:
I am making a Messenger bot and I am using Ring as my http framework.

Sometime I want to apply delays between messages sent by the bot. My expectation would be that it is safe to use Thread/sleep because this will make the active thread sleep and not the entire server. Is that so, or should I resort to clojure/core.async?

This is the code I would be writing without async:

  (match [reply]

    ; The bot wants to send a message (text, images, videos etc.) after n milliseconds
    [{:message message :delay delay}]
    (do
      (Thread/sleep interval delay)
      (facebook/send-message sender-id message))
    ; More code would follow...

A link to Ring code where its behaviour in this sense is clear would be appreciated, as well as any other with explanation on the matter.


问:
Use secondary/backup observable as long as primary observable hasn't emitted any value
The following is what I'm trying to achieve:

```<code>|--------------------A-A-A-A-A-A| primary (behavior subject)
|-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-| secondary (flowable)
|-B-B-B-B-B-B-B-B-B-BA-A-A-A-A-A| result (flowable)
</code>```

Basically, I'm waiting for user input (through primary observable) but I would like to provide system generated values if user hasn't inputted anything yet. Once user input is received, the secondary observable will not be used anymore.

I looked into switchIfEmpty and combineLatest but they don't fit my needs because:

switchIfEmpty only works if primary observable signals onComplete.

combineLatest only works if both observables emit a value

Is there any way to do this?

答:
I'm never sure if it's the easiest or most elegant way to do it, but this works:

```<code>const a = Observable.interval(5000);
const b = Observable.interval(1000);

const sharedA = a.shareReplay(1);

const result = b.takeUntil(sharedA).concat(sharedA);
</code>```

Demo

Another, maybe simple way, would be

```<code>const sharedA = a.share();
const result = b.takeUntil(sharedA).merge(sharedA);
</code>```

Demo

Body:
The following is what I'm trying to achieve:

|--------------------A-A-A-A-A-A| primary (behavior subject)
|-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-| secondary (flowable)
|-B-B-B-B-B-B-B-B-B-BA-A-A-A-A-A| result (flowable)

Basically, I'm waiting for user input (through primary observable) but I would like to provide system generated values if user hasn't inputted anything yet. Once user input is received, the secondary observable will not be used anymore.

I looked into switchIfEmpty and combineLatest but they don't fit my needs because:

switchIfEmpty only works if primary observable signals onComplete.

combineLatest only works if both observables emit a value

Is there any way to do this?

Body:
I'm never sure if it's the easiest or most elegant way to do it, but this works:

const a = Observable.interval(5000);
const b = Observable.interval(1000);

const sharedA = a.shareReplay(1);

const result = b.takeUntil(sharedA).concat(sharedA);

Demo

Another, maybe simple way, would be

const sharedA = a.share();
const result = b.takeUntil(sharedA).merge(sharedA);

Demo


问:
Reading between certain lines
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!</p>

```<code># DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789
</code>```

答:
Try reading in paragraph mode:

```<code>local $/ = "";
while (<>) {
    print "paragraph: $_";
}
</code>```

I leave figuring out which paragraphs and what processing you want to you.

Output for your sample data:

```<code>paragraph: # DATA FILE

paragraph: Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

paragraph: Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

paragraph: Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

paragraph: Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789
</code>```

Title: Reading between certain lines

Body:
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!

# DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Body:
Try reading in paragraph mode:

local $/ = "";
while (<>) {
    print "paragraph: $_";
}

I leave figuring out which paragraphs and what processing you want to you.

Output for your sample data:

paragraph: # DATA FILE

paragraph: Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

paragraph: Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

paragraph: Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

paragraph: Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789


问:
How to correctly write this "simple" T-SQL query
I took a test with a bunch T-SQL exercises. I did well in all but one of them. I took a picture of it to find out later the correct answer. I don't consider myself an expert but I know my way around SQL. Yet, I cannot write what should be a not so hard query to come up with.

Here is the exercise:

I probably need to group by Name and Sum the price but I am still kinda lost. Help with this one! Thank you

答:
I would do it like this:</p>

```<code>SELECT
  people.name,
  sum(case when sales.fk_people is not null then 1 else 0) as total_sales,
  sum(coalesce(sales.price,0.0)) as total_amount
FROM people
LEFT JOIN sales ON people.id = sales.fk_people
GROUP BY people.id
-- Could also be ORDER BY sum(coalesce(sales.price,0.0)) desc
ORDER BY people.id;
</code>```

Body:
I would do it like this:

SELECT
  people.name,
  sum(case when sales.fk_people is not null then 1 else 0) as total_sales,
  sum(coalesce(sales.price,0.0)) as total_amount
FROM people
LEFT JOIN sales ON people.id = sales.fk_people
GROUP BY people.id
-- Could also be ORDER BY sum(coalesce(sales.price,0.0)) desc
ORDER BY people.id;


问:
Angular update textarea field from component
I have a textarea and I am trying to push an update to that field.  I can't seem to figure out how to do this.  I am successfully getting my combobox to pass the selected item into dropdownSourceSelected.  From there I want to:
1) update the textarea field
2) clear the combobox value (return it to undefined so the placeholder returns

I cannot figure out how to do this.  I have seen references to using $scope but when I tried this I got an error about $scope being unknown.

```<code>table-widget.component.html
      <textarea vertical-align:top ng-model="filterSelection" readonly name="selectedfilters" cols = "50" rows = "1"></textarea>

table.component.ts
  public dropdownSourceSelected(selection: string): void  {
    if (this.filterSelection != '')
      this.filterSelection += '&';
    this.filterSelection += "source=";
    this.filterSelection += selection;
    console.log('filter selection: ', this.filterSelection);
  }
</code>```

答:
This code:

```<code>ng-model="filterSelection"
</code>```

Needs to be this:

```<code>[(ngModel)]="filterSelection"
</code>```

And FYI $scope is AngularJS (v1). AngularJS and Angular have very different syntax so any posts you find with solutions in AngularJS won't work in Angular.

To set a property in a nested component, use an @Input property in the component and set that property using property binding in the HTML. So something like this:

```<code>import { Component, OnChanges, Input, EventEmitter, Output } from '@angular/core';

@Component({
    selector: 'pm-star',
    templateUrl: './star.component.html',
    styleUrls: ['./star.component.css']
})
export class StarComponent implements OnChanges {
    @Input() rating: number;
    starWidth: number;
    @Output() ratingClicked: EventEmitter<string> =
            new EventEmitter<string>();

    ngOnChanges(): void {
        this.starWidth = this.rating * 86 / 5;
    }

    onClick(): void {
        this.ratingClicked.emit(`The rating ${this.rating} was clicked!`);
    }
}
</code>```

You then set the rating property like this:

```<code>                        <pm-star [rating]='product.starRating'
                            (ratingClicked)='onRatingClicked($event)'>
                        </pm-star>
</code>```

Body:
I have a textarea and I am trying to push an update to that field.  I can't seem to figure out how to do this.  I am successfully getting my combobox to pass the selected item into dropdownSourceSelected.  From there I want to:
1) update the textarea field
2) clear the combobox value (return it to undefined so the placeholder returns

I cannot figure out how to do this.  I have seen references to using $scope but when I tried this I got an error about $scope being unknown.

table-widget.component.html
      <textarea vertical-align:top ng-model="filterSelection" readonly name="selectedfilters" cols = "50" rows = "1"></textarea>

table.component.ts
  public dropdownSourceSelected(selection: string): void  {
    if (this.filterSelection != '')
      this.filterSelection += '&';
    this.filterSelection += "source=";
    this.filterSelection += selection;
    console.log('filter selection: ', this.filterSelection);
  }

Body:
This code:

ng-model="filterSelection"

Needs to be this:

[(ngModel)]="filterSelection"

And FYI $scope is AngularJS (v1). AngularJS and Angular have very different syntax so any posts you find with solutions in AngularJS won't work in Angular.

To set a property in a nested component, use an @Input property in the component and set that property using property binding in the HTML. So something like this:

import { Component, OnChanges, Input, EventEmitter, Output } from '@angular/core';

@Component({
    selector: 'pm-star',
    templateUrl: './star.component.html',
    styleUrls: ['./star.component.css']
})
export class StarComponent implements OnChanges {
    @Input() rating: number;
    starWidth: number;
    @Output() ratingClicked: EventEmitter<string> =
            new EventEmitter<string>();

    ngOnChanges(): void {
        this.starWidth = this.rating * 86 / 5;
    }

    onClick(): void {
        this.ratingClicked.emit(`The rating ${this.rating} was clicked!`);
    }
}

You then set the rating property like this:

                        <pm-star [rating]='product.starRating'
                            (ratingClicked)='onRatingClicked($event)'>
                        </pm-star>


问:
How to check of a column in a data frame equals a certain data type in Pandas?
I need to convert all my columns that are of the data type objects into strings.

For simplicity, here is the column headers:

```<code>keys= [Name, Age, Passport, Date, Location, Height]
</code>```

'Name' and 'Location' are of type object. I need to identify these columns are of type object, and convert the columns into strings.

My loop that I attempted to write:

```<code>while variable_1 < len(keys):
  if df[variable_1].dtypes == object:
    df[variable_1] = df[variable_1].astype(str)
    variable_1 = variable_1 + 1
</code>```

This is throwing an obvious error, I am sort of stuck on the syntax.

答:
Consider the dataframe df

```<code>df = pd.DataFrame(dict(
        A=[1, 2, 3],
        B=[[1], [2], [3]],
        C=['1', '2', '3'],
        D=[1., 2., 3.]))
</code>```

Use applymap with type to see the types of each element.

```<code>df.applymap(type)

               A               B              C                D
0  <class 'int'>  <class 'list'>  <class 'str'>  <class 'float'>
1  <class 'int'>  <class 'list'>  <class 'str'>  <class 'float'>
2  <class 'int'>  <class 'list'>  <class 'str'>  <class 'float'>
</code>```

Using select_dytpes to take just object columns and update to update the dataframe

```<code>df.update(df.select_dtypes(include=[np.object]).astype(str))

df.applymap(type)

               A              B              C                D
0  <class 'int'>  <class 'str'>  <class 'str'>  <class 'float'>
1  <class 'int'>  <class 'str'>  <class 'str'>  <class 'float'>
2  <class 'int'>  <class 'str'>  <class 'str'>  <class 'float'>
</code>```

Body:
I need to convert all my columns that are of the data type objects into strings.

For simplicity, here is the column headers:

keys= [Name, Age, Passport, Date, Location, Height]

'Name' and 'Location' are of type object. I need to identify these columns are of type object, and convert the columns into strings.

My loop that I attempted to write:

while variable_1 < len(keys):
  if df[variable_1].dtypes == object:
    df[variable_1] = df[variable_1].astype(str)
    variable_1 = variable_1 + 1

This is throwing an obvious error, I am sort of stuck on the syntax.

Body:
Consider the dataframe df

df = pd.DataFrame(dict(
        A=[1, 2, 3],
        B=[[1], [2], [3]],
        C=['1', '2', '3'],
        D=[1., 2., 3.]))

Use applymap with type to see the types of each element.

df.applymap(type)

               A               B              C                D
0  <class 'int'>  <class 'list'>  <class 'str'>  <class 'float'>
1  <class 'int'>  <class 'list'>  <class 'str'>  <class 'float'>
2  <class 'int'>  <class 'list'>  <class 'str'>  <class 'float'>

Using select_dytpes to take just object columns and update to update the dataframe

df.update(df.select_dtypes(include=[np.object]).astype(str))

df.applymap(type)

               A              B              C                D
0  <class 'int'>  <class 'str'>  <class 'str'>  <class 'float'>
1  <class 'int'>  <class 'str'>  <class 'str'>  <class 'float'>
2  <class 'int'>  <class 'str'>  <class 'str'>  <class 'float'>


问:
How to align radio buttons and labels?
I am styling an integration into a 3rd party system, and need to format some radio buttons. The vendor gives us this HTML:

```<code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span>
</code>```

and I need it to render it like so:

I tried, and failed, using flexbox to accomplish this:

span.radiocontainer {
  float: none;
  display: flex;
  align-items: left;
  justify-content: left;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: left;
}

span.radiocontainer > label.selected.radiolabel {
  box-shadow: none;
  width: 50%;
  border: 0px;
}

span.radiocontainer > input {
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span></code>```

Is there any way for me to format the radio buttons on the left? Or do I need to change my design?

I cannot change the HTML, as it is from a vendor, CSS is the only thing we get to customize.

答:
I am shooting in the dark here, but comment out all your code and try this

```<code>label{float:right; width:calc(100% - 30px);}
</code>```

.radiocontainer label{float:right; width:calc(100% - 30px);}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span></code>```

I removed all the original styles in the fiddle you provided and added just these styles. They did align as you wanted. However your stylesheet might contain other styles like line-height and margin. I think you can get the alignment you want with some tweaking. If it doesn't work you can revert back to your code and continue from there. Do let me know how it goes.

Title: How to align radio buttons and labels?

Body:
I am styling an integration into a 3rd party system, and need to format some radio buttons. The vendor gives us this HTML:

    Male
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    Female
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">

and I need it to render it like so:

I tried, and failed, using flexbox to accomplish this:

span.radiocontainer {
  float: none;
  display: flex;
  align-items: left;
  justify-content: left;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: left;
}

span.radiocontainer > label.selected.radiolabel {
  box-shadow: none;
  width: 50%;
  border: 0px;
}

span.radiocontainer > input {
  width: 50%;
}

    Male
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    Female
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">

Is there any way for me to format the radio buttons on the left? Or do I need to change my design?

I cannot change the HTML, as it is from a vendor, CSS is the only thing we get to customize.

Body:
I am shooting in the dark here, but comment out all your code and try this

label{float:right; width:calc(100% - 30px);}

.radiocontainer label{float:right; width:calc(100% - 30px);}

<span class="radiocontainer">
    <label for="genderMale" class="radiolabel">Male</label>
    <input class="selector" id="genderMale" name="Gender" type="radio" value="2">
    <label for="genderFemale" class="radiolabel">Female</label>
    <input class="selector" id="genderFemale" name="Gender" type="radio" value="1">
</span>

I removed all the original styles in the fiddle you provided and added just these styles. They did align as you wanted. However your stylesheet might contain other styles like line-height and margin. I think you can get the alignment you want with some tweaking. If it doesn't work you can revert back to your code and continue from there. Do let me know how it goes.


问:
Losing the error output from a command in the (set) element of batch file FOR statement
I have a batch file that does a git pull on a git repository.  I want to see the output in the console window and in a log file.  I have a bunch of script code in the batch file to get me to the correct directory and then it runs the following:

```<code>FOR /F "tokens=*" %%f IN ('git pull --ff-only') DO (
    SET z=%%f
    ECHO   !z:^|=^^^|! 2>&1 | C:\Bin\tee.exe -a %logFile%
)
</code>```

tee.exe is a little program the sends the output to the console and the specified log file.

This works fine as long as the git command succeeds.  I see the list of changed files, etc... in both the console and the log file.  However, if the git command generates an error, for example the pull would overwrite local changes, I see the following in the console window:

```<code>Pulling repository \GitHub\Dummy
error: Your local changes to the following files would be overwritten by merge:
        Dummy/Dummy.Tests/Dummy.Tests.csproj
        Dummy/Dummy.Tests/packages.config
        Dummy/Dummy/Dummy.csproj
        Dummy/Dummy/packages.config
Please commit your changes or stash them before you merge.
Aborting
    Updating 8b9f90e..410251c
</code>```

However, in the log file, I only see this:

```<code>Pulling repository \GitHub\Dummy
    Updating 8b9f90e..410251c
</code>```

Is there a way to get the error information dumped to the log file?

答:
for only handles STDOUT, not STDERR, so you have to redirect STDERR to STDOUT inside the for loop. When echoing %%f, it's already too late:

```<code>FOR /F "tokens=*" %%f IN ('git pull --ff-only 2^>^&1') DO (
    ECHO %%f| C:\Bin\tee.exe -a C:\Bin\GitPull.log
)
</code>```

(and escape special chars like <>&|,=)

Body:
I have a batch file that does a git pull on a git repository.  I want to see the output in the console window and in a log file.  I have a bunch of script code in the batch file to get me to the correct directory and then it runs the following:

FOR /F "tokens=*" %%f IN ('git pull --ff-only') DO (
    SET z=%%f
    ECHO   !z:^|=^^^|! 2>&1 | C:\Bin\tee.exe -a %logFile%
)

tee.exe is a little program the sends the output to the console and the specified log file.

This works fine as long as the git command succeeds.  I see the list of changed files, etc... in both the console and the log file.  However, if the git command generates an error, for example the pull would overwrite local changes, I see the following in the console window:

Pulling repository \GitHub\Dummy
error: Your local changes to the following files would be overwritten by merge:
        Dummy/Dummy.Tests/Dummy.Tests.csproj
        Dummy/Dummy.Tests/packages.config
        Dummy/Dummy/Dummy.csproj
        Dummy/Dummy/packages.config
Please commit your changes or stash them before you merge.
Aborting
    Updating 8b9f90e..410251c

However, in the log file, I only see this:

Pulling repository \GitHub\Dummy
    Updating 8b9f90e..410251c

Is there a way to get the error information dumped to the log file?

Body:
for only handles STDOUT, not STDERR, so you have to redirect STDERR to STDOUT inside the for loop. When echoing %%f, it's already too late:

FOR /F "tokens=*" %%f IN ('git pull --ff-only 2^>^&1') DO (
    ECHO %%f| C:\Bin\tee.exe -a C:\Bin\GitPull.log
)

(and escape special chars like <>&|,=)


问:
iMessage Extensions: Root Navigation Controller results in all delegate methods to not get called in my MSMessagesAppViewController
I have a new iMessage Extension project where I tried 2 ways of structuring the navigation stack:

In my storyboard I set the entry point to a UINavigationController that has my MSMessagesAppViewController as the root controller.

Or I set my MSMessagesAppViewController directly as the Entry point in my storyboard.  (No UINavigationController that owns it).

For scenario #1 above, the navigation controller works fine, and I can push new screens on the stack. (with the exception of the whole nav bar being hidden in Expanded view, which is a separate issue that I still have to figure out).   However, NONE of the delegate methods of my MSMessagesAppViewController get called with this configuration. Such as:
willTransitionToPresentationStyle
didTransitionToPresentationStyle,
willBecomeActiveWithConversation,
didSelectMessage
(none of these get called)

For scenario #2 above, the MSMessagesAppViewController methods DO get called.  (because the UINavigationController is not the entry point in the Storyboard).

So my question is:  How can I have a UINavigationController be at the root of my iMessage Extension application, so I can perform Push navigation, but at the same time have the methods of MSMessagesAppViewController get called, as described by the Apple API?

答:
Although it doesn't seem to be documented, it looks like message extensions expect the entry point to be a subclass of MSMessagesAppViewController. Those methods aren't delegate methods, they're superclass overrides, so there's no way to arrange for them to go anywhere else. The message extension system could handle the case you describe but-- aparently-- does not.

What I'd try is:

Make the entry point a subclass of MSMessagesAppViewController.

Early in that object's life cycle (maybe in viewDidLoad) create a UINavigationController and add it as a child view controller of your MSMessagesAppViewController subclass. Make it fill the entire screen.

Now-- in effect-- your navigation controller is the root of the extension. It's not really the root since message events like willTransitionToPresentationStyle will still go through the MSMessagesAppViewController subclass. But everything else starts there. It's the root of the UI and the navigation.

In the meantime it might be good to file an enhancement request with Apple. It's reasonable to think that the message extension system would check the root VC of a navigation controller to see if it's the right class, and maybe they'll add that in the future.


问:
Woocommerce rest api - Create product via ajax in wordpress
Well, the problem is here. I created a local project to create a product in Woocommerce mounted in wordpress on a remote server. My local project code is this one

```<code>    <?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
function creaProd(){
$precio = $_POST['Total'];
$imagen = $_POST['Imagen'];
$descrip = $_POST['Descripcion'];
$tipo = $_POST['Tipo'];

$woocommerce = new Client(
    'http://example.com',
    'ck_sdfsdfsdfsfdxxx',
    'cs_sdfsdfsfsdfaxxx',
    [
        'wp_api' => true,
        'version' => 'wc/v1',
    ]
);

$data = [
    'name' => $tipo,
    'type' => 'simple',
    'regular_price' => $precio,
    'description' => $descrip,
    'short_description' => $descrip,
    'categories' => [
        [
            'id' => 9
        ],
        [
            'id' => 14
        ]
    ],
    'images' => [
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 0
        ],
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 1
        ]
    ]
];

print_r($woocommerce->post('products', $data));
}
creaProd();
</code>```

And evertything works fine, the problem is, that I have tried a bunch of things, but I just don't get to create the product working in the wordpress project.

I put it in the wp-includes folder and the wp-content, but didn't work.

I tried to call an ajax to example.com/wp-includes/myFile.php but I can't reach it, I can reach files like example.com/wp-includes/option.php and all the files already there, but if I upload that one, I just can't, and I don't know where to put the vendor folder either.

Which is the right way to integrate this project to my real site in Wordpress?

Hope someone knows how to do this. Thanks.

答:
[Note to reviewer I am the same person as user 8256950. When I tried to create a login for 8256950 it create a new login 8262086 instead. Don't know why but I do destroy all cookies daily.]

Your project is a REST client which is usually run from a different server. It is not part of the WordPress server and I would put its files in its own directory. It is not a plugin. It is also not AJAX. (No JavaScript is used in the REST client to REST server communication but of course the client can be invoked by Javascript.)

Concerning your specific problem reaching files it would be helpful if you provided the Network log from your browser. On Chrome 'More tools' -> 'Developer tools' -> 'Network'. Look for the request for you file and see if there is an error message.

Body:
Well, the problem is here. I created a local project to create a product in Woocommerce mounted in wordpress on a remote server. My local project code is this one

    <?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
function creaProd(){
$precio = $_POST['Total'];
$imagen = $_POST['Imagen'];
$descrip = $_POST['Descripcion'];
$tipo = $_POST['Tipo'];

$woocommerce = new Client(
    'http://example.com',
    'ck_sdfsdfsdfsfdxxx',
    'cs_sdfsdfsfsdfaxxx',
    [
        'wp_api' => true,
        'version' => 'wc/v1',
    ]
);

$data = [
    'name' => $tipo,
    'type' => 'simple',
    'regular_price' => $precio,
    'description' => $descrip,
    'short_description' => $descrip,
    'categories' => [
        [
            'id' => 9
        ],
        [
            'id' => 14
        ]
    ],
    'images' => [
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 0
        ],
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
            'position' => 1
        ]
    ]
];

print_r($woocommerce->post('products', $data));
}
creaProd();

And evertything works fine, the problem is, that I have tried a bunch of things, but I just don't get to create the product working in the wordpress project.

I put it in the wp-includes folder and the wp-content, but didn't work.

I tried to call an ajax to example.com/wp-includes/myFile.php but I can't reach it, I can reach files like example.com/wp-includes/option.php and all the files already there, but if I upload that one, I just can't, and I don't know where to put the vendor folder either.

Which is the right way to integrate this project to my real site in Wordpress?

Hope someone knows how to do this. Thanks.


问:
How to install wxWidgets with Code::Blocks?
I'm a windows developer and I need to use Code::Blocks
to develope multiplataform C++ GUI applications.

After installing Code::Blocks and wxWidgets in my first try to do a simple "Hello World" application, the IDE show me a box with $(#wx)

What is the $(#wx) ?

Googling for tutorials I see this

What is the -g ?

Finally the following error message appear:

For 3 days I'm trying over and over again without success !

I even try wxPack. Nothing works !

With VC++, C++Builder and even wxDev-C++ this is straightforward

Only Code::Blocks is so difficult !

Googling, I find many people with the same error, but the advices they get didn't work for me !

Can someone tell me step by step what I must do?

Thank you.

答:
Your frustration comes, as usually does, from your ignorance. If your are required to learn about C::B, well, that's life. Don't waste time on getting so angry, life is short.

CodeBlocks are not tied to a compiler. You can use VC++, MinGW, TDM-GCC, GCC, etc. Thus, you must tell C::B the compiler to use. You may use different compilers for different "targets" (see below).

C::B is not tied to any library either. If you want to use wxWidgets you must tell C::B about the needed files and where to find them.

It's very common that people who use C::B use MinGW as the compiler. That's why when you first install C::B it searches for MinGW and, if found, set it as the default compiler. You can set your own preference in Settings->Compiler. Same goes for the debugger, usually GDB.

As a side note, be aware that MinGW is ONLY 32 bits. There's a different compiler (MinGW 64). TDM-GCC offers both compilers (and their GDB versions) at once, I recommend installing 32/64 versions in different folders and setting them in C::B as different compilers. For Linux, the "mother" GCC is the de-facto standard.

When you build your app you must define a target. This is nothing else but a way of telling things like "I want a 32 bit library" or "I want a 64 executable". In your required project you may set several targets. Select the desired one before compiling (combobox in the main tool bar).

While developing it's very advisable to set a target as a "debug". This means you want to use the debugger. This requires to use "debug symbols". With GCC (or one of its "children", MinGW...) you acomplish it but adding -g as a flag to the compiler.

Now you understand that probably you set not only one, but several targets like "release 64 exe", "debug 32 exe" etc. Right?

wxWidgets joins in scene

Despite C::B is made with wxWidgets, it doesn't ship with it. Download the version you like from wxWidgets site. While some binaries are offered, if you use some other compiler or some other parameters then you need to compile wxWidgets on your own. See the docs/msw/install.txt and learn about the different configurations (release, debug, static/dynamic lib, etc). Your "target" must match the wxWidgets configuration, so better build several versions, same as your targets. And don't forget to use the same parameters for your app target as you used to each wxWidgets target. You can do this at Project->Build options.

As with any compiler you must tell where to find the libraries and the headers. And the libraries you want to use. The Windows libraries (kernel32, user32, etc, they are a lot, ask in another thread) and the wxWidgets libraries.

When you update your app perhaps you use a newer wxWidgets version, but also want to support an older version with other wxWidgets version. You have several folders. For your project you should update all directories. Can this be done shortly? Yes. in C::B you can define variables(e.g. $wx31dir) and use them like $(wx31dir)/include. Redefining the var saves you a lot of typing.

You can use a global var $(#wx31dir) or several, project fitted vars. Your decision.

Finally, C::B offers a project template for a wxWidgets app. It will ask you some locations (wx dirs) and vars. If you don't understand well what it does, better don't use it and set everything on your own. First time is hard, I know. Go ahead and you'll get it if you pay attention to needed steps.

Have you read the CodeBlocks manual?


问:
Generate a list of existing functions across multiple files in C
Due to paperwork that has to be filled out, I need to know how many functions exist in an entire C project.

The project is split across multiple folders, so ideally what I am looking for is something where you can type in:

```<code>FindAllTheFunctions --recursive /path/to/folder
</code>```

And the result is written something like:

```<code>/path.../filename: int foo(float bar)
.
.
.
/path.../final/filename: double foo2(int bar2)
</code>```

How could I get results of this nature?

Many thanks!

答:
The cross reference feature of ctags may help you.

Install Universal-ctags (https://ctags.io)

Run find $dir --name '*.c' | ctags --kinds-C=f -x --_xformat='%F: %{C.properties} %t %N%S'

```<code>$ find ./main -name '*.c' | ./ctags --kinds-C=f -x --_xformat='%F: %{C.properties} %t %N%S' -L - | head
./main/args.c: extern Arguments * argNewFromArgv(char * const * const argv)
./main/args.c: extern Arguments * argNewFromFile(FILE * const fp)
./main/args.c: extern Arguments * argNewFromLineFile(FILE * const fp)
./main/args.c: extern Arguments * argNewFromString(const char * const string)
./main/args.c: extern bool argOff(const Arguments * const current)
./main/args.c: extern char * argItem(const Arguments * const current)
./main/args.c: extern void argDelete(Arguments * const current)
./main/args.c: extern void argForth(Arguments * const current)
./main/args.c: extern void argSetLineMode(Arguments * const current)
./main/args.c: extern void argSetWordMode(Arguments * const current)
</code>```

Body:
Due to paperwork that has to be filled out, I need to know how many functions exist in an entire C project.

The project is split across multiple folders, so ideally what I am looking for is something where you can type in:

FindAllTheFunctions --recursive /path/to/folder

And the result is written something like:

/path.../filename: int foo(float bar)
.
.
.
/path.../final/filename: double foo2(int bar2)

How could I get results of this nature?

Many thanks!

Body:
The cross reference feature of ctags may help you.

Install Universal-ctags (https://ctags.io)

Run find $dir --name '*.c' | ctags --kinds-C=f -x --_xformat='%F: %{C.properties} %t %N%S'

$ find ./main -name '*.c' | ./ctags --kinds-C=f -x --_xformat='%F: %{C.properties} %t %N%S' -L - | head
./main/args.c: extern Arguments * argNewFromArgv(char * const * const argv)
./main/args.c: extern Arguments * argNewFromFile(FILE * const fp)
./main/args.c: extern Arguments * argNewFromLineFile(FILE * const fp)
./main/args.c: extern Arguments * argNewFromString(const char * const string)
./main/args.c: extern bool argOff(const Arguments * const current)
./main/args.c: extern char * argItem(const Arguments * const current)
./main/args.c: extern void argDelete(Arguments * const current)
./main/args.c: extern void argForth(Arguments * const current)
./main/args.c: extern void argSetLineMode(Arguments * const current)
./main/args.c: extern void argSetWordMode(Arguments * const current)


问:
Has anybody used Manco.net Licensing for .Net?
http://www.mancosoftware.com/licensing/index.htm

Just wondering what your thoughts are on it, if it's relatively good for the 80$ charge. We realize stuff will still get cracked, but prevention from the masses is also good to consider.

Any input is appreciated.

答:
Is the choice between some kind of enforcement and no enforcement, or are you looking for experience with that particular product?

Though I've never used Manco in particular, I've used other licensing options, and my only suggestion would be that if you decide to add licensing at all, you stick to the bare minimum - in this case, just key unlocking, or their basic package. When you start to add an activation web service, and then you don't let customers move their software from one PC to another, you start to inconvenience regular users who've already paid for your software, and that's never a good thing.

You're right that it will always be cracked anyway, and in the end, you have to do a cost benefit analysis to determine if adding licensing is really worthwhile. The formula looks like this:

If (Purchases from people who wouldn't have paid for the software if you didn't have licensing) - (Lost sales from people who are scared off or have problems and demand a refund because of your licensing) - $80 > 0

then add licensing. If it's not (i.e. sales/customers lost > additional purchases), then release it without enforcement, since you're better off that way (you can still release both a time-limited demo, as well as a special purchase-only download on your website)

It looks like they offer a 15-day trial for this product - if it works, it's worth the $80 to you as a developer, but only if it doesn't inconvenience your users at all. If you run into any problems during your trial, you can be sure they'll run into problems too, and it's not worth it.

PS: Eric Sink talks about this in his book.

OwnerDisplayName: Matt

LastEditorDisplayName: Osama ALASSIRY

OwnerDisplayName: rwmnau

LastEditorDisplayName: rwmnau


问:
Git workflow for small web team
I know there are already many questions here on this topic, but I've had trouble finding exactly what I need.

We're a small team of developers currently using SVN but soon to be making a switch to Git.  We are used to checking in changes and pushing to the live website throughout the day but currently lack any formal testing procedures, which is something we'd like to add.  The way I'm used to doing this with SVN is:

develop in a personal test environment

check in your changes

send the current repository files to a global (production-like) testing webserver, and test

send the current repository files to the live webservers

This obviously can create some problems, especially if communication is not good.  I've experienced times when untested changes have gone live and that's something we'd definitely like to avoid.

What I'm envisioning is a master Git repository that holds the tested code that is running on the live servers.  Then have a clone of that repository that is used to test revisions.  I'd like to have a script that is responsible for pulling changes from the requesting developer, putting them in a branch on the test repository, and running some automated tests to make sure nothing major is broken.  When that all checks out, that branch can be merged and pushed up to the master and out to the live servers.

I'd like to hear any comments about this possible workflow and any suggestions for improvement or how to do it differently.  Also, any specifics on how to set this up would also be appreciated.  Thanks!

EDIT: I've used the above method for a while now and it's worked out pretty well.

答:
I found this to be extremely helpful:

http://nvie.com/posts/a-successful-git-branching-model/

Title: Git workflow for small web team


问:
Output from Get-Content and File Path
I have a set of .txt files in a folder. For example:

```<code>1.txt
2.txt
3.txt
</code>```

These contain a date following by a filename. For example, 1.txt may contain:

```<code>06/11/2017 randomdocument.txt
06/12/2017 otherdocument.txt
07/11/2017 yadocument.txt
01/02/2017 randomdocument.txt
</code>```

I want to:

get the line that matches a particular date regex pattern

write the line, and the path of the file it is in, to a new document.

My code does the first part. I've tried various iterations with no cigar with the second part. Any help would be appreciated.

Code

```<code>Set-Location c:\users\john.smith\desktop\FORREPORT
$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $line = Get-ChildItem -recurse | Get-Content | Select-String $SearchPattern
  $d = $line | Select-Object file.FullName
  $d | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt

}
</code>```

Desired Output:

```<code> 06/12/2017 randomdocument.txt in c:\users\john.smith\desktop\FORREPORT\1.txt
</code>```

答:
With minimal changes to the code:

```<code>Set-Location c:\users\john.smith\desktop\FORREPORT

$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $lines =  Get-Content $file | Select-String $SearchPattern
  if($lines){
      foreach($line in $lines){
        "$line`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
      }
  }
}
</code>```

This prints each line on a new line in the new document. If you want all matching lines on a single line, remove the foreach:

```<code>Set-Location c:\users\john.smith\desktop\FORREPORT

$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $lines =  Get-Content $file | Select-String $SearchPattern
  if($lines){
        "$lines`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
  }
}
</code>```

if will also check see that matched lines were actually found so that you don't get ouput of just $file.Fullname with $lines is empty.

PS Your question and code are the best examples I can think of to use this quote. heed it! ;-p

Title: Output from Get-Content and File Path

Body:
I have a set of .txt files in a folder. For example:

1.txt
2.txt
3.txt

These contain a date following by a filename. For example, 1.txt may contain:

06/11/2017 randomdocument.txt
06/12/2017 otherdocument.txt
07/11/2017 yadocument.txt
01/02/2017 randomdocument.txt

I want to:

get the line that matches a particular date regex pattern

write the line, and the path of the file it is in, to a new document.

My code does the first part. I've tried various iterations with no cigar with the second part. Any help would be appreciated.

Code

Set-Location c:\users\john.smith\desktop\FORREPORT
$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $line = Get-ChildItem -recurse | Get-Content | Select-String $SearchPattern
  $d = $line | Select-Object file.FullName
  $d | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt

}

Desired Output:

 06/12/2017 randomdocument.txt in c:\users\john.smith\desktop\FORREPORT\1.txt

Body:
With minimal changes to the code:

Set-Location c:\users\john.smith\desktop\FORREPORT

$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $lines =  Get-Content $file | Select-String $SearchPattern
  if($lines){
      foreach($line in $lines){
        "$line`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
      }
  }
}

This prints each line on a new line in the new document. If you want all matching lines on a single line, remove the foreach:

Set-Location c:\users\john.smith\desktop\FORREPORT

$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"

Foreach ($file in $files) {
  $lines =  Get-Content $file | Select-String $SearchPattern
  if($lines){
        "$lines`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
  }
}

if will also check see that matched lines were actually found so that you don't get ouput of just $file.Fullname with $lines is empty.

PS Your question and code are the best examples I can think of to use this quote. heed it! ;-p


问:
What is the compile-time type of the "throw" expression in C# 7?
In C# 7 it is possible to raise an exception inside an expression:

```<code>int n = list != null ? list.Count : throw new NullReferenceException("list");
</code>```

In this position, the throw expression can substitute an expression of any type.

Now I want to define a function that executes some action before raising an exception:

```<code>??? DoSomethingAndThrowException(Exception e)
{
    MessageBox.Show("Prepare for an exception!");
    throw e;
}
</code>```

What would be the return type of such function, so that it can be used in the same places as the original throw expression:

```<code>int n = list != null ? list.Count : DoSomethingAndThrowException(new NullReferenceException("list"));
</code>```

There's the option to declare it as a generic method:

```<code>T DoSomethingAndThrowException<T>(Exception e) {...}
</code>```

But this seems cumbersome, as the generic type doesn't occur anywhere in the function body. Is this the only way to do it, or is there some type I don't know of, and which is assignable to any type (an "anti-object" type, so to speak)?

答:
The type you're talking about is known as the bottom type, the subtype of all types, as opposed to the top type, the supertype of all types.

As you noted, the top type in C# is called object*. On the other hand, C# does not have the bottom type (though there is a proposal to add it).

Though there actually is one type that has implicit conversions to any other type: dynamic. This means that if you set the return type of DoSomethingAndThrowException to dynamic, your code would compile. But I don't think dynamic is a good choice here, because it's too infectious. For example, if you used var in your statement (var n = list != null ? list.Count : DoSomethingAndThrowException(new NullReferenceException("list"));), then the type of n would be dynamic, with all the baggage that brings.

I think this means that your conclusion is correct: generics are your best option.

* Technically, object is not the top type, because object is not the supertype of pointer types. But I think that's a distinction that doesn't matter much.

Body:
In C# 7 it is possible to raise an exception inside an expression:

int n = list != null ? list.Count : throw new NullReferenceException("list");

In this position, the throw expression can substitute an expression of any type.

Now I want to define a function that executes some action before raising an exception:

??? DoSomethingAndThrowException(Exception e)
{
    MessageBox.Show("Prepare for an exception!");
    throw e;
}

What would be the return type of such function, so that it can be used in the same places as the original throw expression:

int n = list != null ? list.Count : DoSomethingAndThrowException(new NullReferenceException("list"));

There's the option to declare it as a generic method:

T DoSomethingAndThrowException<T>(Exception e) {...}

But this seems cumbersome, as the generic type doesn't occur anywhere in the function body. Is this the only way to do it, or is there some type I don't know of, and which is assignable to any type (an "anti-object" type, so to speak)?


问:
Is it possible to add a prebuilt APK to an AOSP build as an user app?
I am looking to add a prebuilt APK to my AOSP build. I can already do this by doing the following:

Add the APK to the $root_of_my_source_tree/packages/apps folder.

Create an Android.mk file. The file has the following contents:

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := optional

LOCAL_MODULE := <name of APK>

LOCAL_SRC_FILES := <Name of APK>.apk

LOCAL_MODULE_CLASS := APPS

LOCAL_MODULE_SUFFIX := $(COMMON_ANDROID_PACKAGE_SUFFIX)

LOCAL_CERTIFICATE := platform

include $(BUILD_PREBUILT)
</code>```

Add:

```<code>PRODUCT_PACKAGES += \ <name of APK>
</code>```

To a make file that gets picked up by the AOSP build system.

This adds the APK to the /system/app folder which is read-only so the user will not be able to update the APK. I would like the APK to be placed in the /data/app folder so the user can actually update the prebuilt APK.

I have tried the suggestions in this question and they did not work. I tried the suggestion in this question and while it did output the APK to the /data/app folder of the finished build, once I flashed the image onto my device, the app was not there. The second answer in that question does provide a possible explanation for this but no other suggestions.

Ultimately, I need an APK preloaded in my build that can be updated so if this doesn't work or is a bad approach, I am open to suggestions.

答:
I found the standard behavior of the PackageManager class good enough for my use case. So here are a couple tidbits worth explaining:

Lavakush's answer does work and it does output the APK to the out/target/product/vendor/data/app folder in the source tree but the APK does not show up under /data/app in the system image once it's flashed onto a device. According to this answer, the Android build system does not build anything into /data/ so that explains that. I still find it confusing that it does show up as output in the out/target/product/vendor/data/app folder however.

In my use case, I need to preload APKs onto a build and then update them as needed. Due to the read-only nature of the /system/app folder I assumed that I would not be able to update my app which is why I wanted to preload it to /data/app. As in turns out, according to this answer & to my testing, the PackageInstaller class' standard behavior is to install the updated APK to the data/app folder and to start running this APK instead of the preloaded /system/app APK. The answer also says that the settings->apps screen will give you the option to uninstall the updated APK and then you'll be left with the original system/app APK. I did observe this behavior and it is fine for my use case.

Body:
I am looking to add a prebuilt APK to my AOSP build. I can already do this by doing the following:

Add the APK to the $root_of_my_source_tree/packages/apps folder.

Create an Android.mk file. The file has the following contents:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := optional

LOCAL_MODULE := <name of APK>

LOCAL_SRC_FILES := <Name of APK>.apk

LOCAL_MODULE_CLASS := APPS

LOCAL_MODULE_SUFFIX := $(COMMON_ANDROID_PACKAGE_SUFFIX)

LOCAL_CERTIFICATE := platform

include $(BUILD_PREBUILT)

Add:

PRODUCT_PACKAGES += \ <name of APK>

To a make file that gets picked up by the AOSP build system.

This adds the APK to the /system/app folder which is read-only so the user will not be able to update the APK. I would like the APK to be placed in the /data/app folder so the user can actually update the prebuilt APK.

I have tried the suggestions in this question and they did not work. I tried the suggestion in this question and while it did output the APK to the /data/app folder of the finished build, once I flashed the image onto my device, the app was not there. The second answer in that question does provide a possible explanation for this but no other suggestions.

Ultimately, I need an APK preloaded in my build that can be updated so if this doesn't work or is a bad approach, I am open to suggestions.


问:
How to pass data from gRPC interceptor to service method call?
I need to pass some data from my ServerAuthIntereptor to call.

ServerAuthInterceptor:

```<code>// used in context parameters map
private static final String AUTH_CONTEXT = "authContext";
private static final Context.Key<Object> AUTH_CONTEXT_KEY = Context.key(AUTH_CONTEXT);

// ...

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

    // check credentials from header

    // remember account and session token for usage later (eg. in logout)
    AuthContext authContext = new AuthContext();
    authContext.account = account;
    authContext.sessionToken = sessionToken;

    logger.info("Call {} allowed (account={}, authContext={})",
        new Object[] { call, account, authContext });

    Context context = Context
        .current()
        .withValue(AUTH_CONTEXT_KEY, authContext);

    return Contexts.interceptCall(context, call, headers, next);
}

// ...

/**
 * To be used from services
 * @return
 */
public static Account getCurrentContextAccount() {
    AuthContext authContext = (AuthContext) Context.current().key(AUTH_CONTEXT).get();
    return authContext.account;
}
</code>```

In some service method implementation i try to access that stored 'authContext' from current context:

```<code>@Override
public void list(ListRequest request, StreamObserver<ListResponse> responseObserver) {
    logger.info("Starting list({}) ...", request);

     // ...

     account = ServerAuthInterceptor.getCurrentContextAccount();
</code>```

But authContext is null.
It's working sometimes so i believe it's related to threads(locals).

What is proper way to do it?

答:
For some reason it does not work fot AuthContext class, but it works if i pass 2 context values separately:

ServerAuthInterceptor:

```<code>Context context = Context
        .current()
        .withValue(AUTH_TOKEN_KEY, sessionToken)
        .withValue(AUTH_ACCOUNT_KEY, account);
</code>```

Service call:

```<code>/**
 * To be used from services
 * @return
 */
public static Account getCurrentContextAccount() {
    return (Account) AUTH_ACCOUNT_KEY.get();
}

/**
 * To be used from services
 * @return
 */
public static String getCurrentContextSessionToken() {
    return (String) AUTH_TOKEN_KEY.get();
}
</code>```

Body:
I need to pass some data from my ServerAuthIntereptor to call.

ServerAuthInterceptor:

// used in context parameters map
private static final String AUTH_CONTEXT = "authContext";
private static final Context.Key<Object> AUTH_CONTEXT_KEY = Context.key(AUTH_CONTEXT);

// ...

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

    // check credentials from header

    // remember account and session token for usage later (eg. in logout)
    AuthContext authContext = new AuthContext();
    authContext.account = account;
    authContext.sessionToken = sessionToken;

    logger.info("Call {} allowed (account={}, authContext={})",
        new Object[] { call, account, authContext });

    Context context = Context
        .current()
        .withValue(AUTH_CONTEXT_KEY, authContext);

    return Contexts.interceptCall(context, call, headers, next);
}

// ...

/**
 * To be used from services
 * @return
 */
public static Account getCurrentContextAccount() {
    AuthContext authContext = (AuthContext) Context.current().key(AUTH_CONTEXT).get();
    return authContext.account;
}

In some service method implementation i try to access that stored 'authContext' from current context:

@Override
public void list(ListRequest request, StreamObserver<ListResponse> responseObserver) {
    logger.info("Starting list({}) ...", request);

     // ...

     account = ServerAuthInterceptor.getCurrentContextAccount();

But authContext is null.
It's working sometimes so i believe it's related to threads(locals).

What is proper way to do it?

Body:
For some reason it does not work fot AuthContext class, but it works if i pass 2 context values separately:

ServerAuthInterceptor:

Context context = Context
        .current()
        .withValue(AUTH_TOKEN_KEY, sessionToken)
        .withValue(AUTH_ACCOUNT_KEY, account);

Service call:

/**
 * To be used from services
 * @return
 */
public static Account getCurrentContextAccount() {
    return (Account) AUTH_ACCOUNT_KEY.get();
}

/**
 * To be used from services
 * @return
 */
public static String getCurrentContextSessionToken() {
    return (String) AUTH_TOKEN_KEY.get();
}


问:
Connecting application SMS and user's reply Twilio
I am trying to use Twilio to follow through a workflow depending on responses to a SMS. I trigger the SMS in an application I have written and I want the user's reply to then cancel an action. There can be multiple instances of each action but each will have a unique ID. I need a way to link the users reply to the original message that is triggered by the app as the body will contain the unique ID. Thanks in advance.</p>

答:
I'm not sure I fully understand your use case so forgive me if this is way off the mark, but isn't it just a case of logging the MessageSid of your outgoing SMS which is returned by Twilio when your app sends the first SMS, then saving this in a local database associated with the phone number it was sent to?

Then when you receive an incoming SMS you take the number of the sender provided by Twilio and perform a database query to search for the MessageSid which corresponds to that number.

Now you have the unique MessageSid you use the Twilio API to retrieve the body of the original message your app sent and you have your unique ID.

On an even simpler level, if your app is only sending one SMS to each user then no need to log the original MessageSid. Upon receiving a reply just submit the incoming phone number as the "To" parameter to the Twilio SMS API and you can retrieve the content of your original outgoing SMS.