问:
Looping through mysql database
I have series of mysql databases on my server. The names of these databases are stored in a separate database table (users) - column(dbname) . I want to loop through table (users), get the dbnames, connect to each and perform an operation on each database. How do I perform such looping?</p>

答:
After days of struggle I was able to come out with this solution. I took a lot of ideas from solutions that were provided to this question on this platform. the solutions themselves did not work for me but I had lots of ideas from them.

```<code><?php

    //db parameters
    $dbhost = "myhost"; // this will ususally be 'localhost', but can sometimes differ
    $dbname = "dbusers"; // the name of the database that you are going to use for this project
    $dbuser = "root"; // the username that you created, or were given, to access your database
    $dbpass = "mypassword"; // the password that you created, or were given, to access your database

    // I first connect to the db with names of the other dbs
    mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
    mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

    //select dbnames from the table with db names
    $query  = "SELECT dbname FROM users";
    $result = mysql_query($query);

    //loop through the results(dbname) and connect to each db
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    //put the dbname results into a variable
    $dbName =$row['dbname'];
    // connect to each db
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
    $db = mysql_select_db("mydbprefix_".$dbName) ;

       //do a query for each db this is because each db has same tables and structure
   //check to see if db exist
      if( $db ){

   //all the operation goes here in my case I wanted to count number of products for each table called products.
      $query2 = mysql_query("SELECT * FROM products");

    $num_rows = mysql_num_rows($query2);
    $pro = $num_rows;
    echo "this user has ".$pro." products"."<br/>";

    //another operation goes here for the same db.

    // then close connection for each db
    mysql_Close ($conn);
    }
     }
    ?>
</code>```

This was how I went around this problem. It might not be the best solution but this is what I have

Title: Looping through mysql database

Body:
After days of struggle I was able to come out with this solution. I took a lot of ideas from solutions that were provided to this question on this platform. the solutions themselves did not work for me but I had lots of ideas from them.

<?php

    //db parameters
    $dbhost = "myhost"; // this will ususally be 'localhost', but can sometimes differ
    $dbname = "dbusers"; // the name of the database that you are going to use for this project
    $dbuser = "root"; // the username that you created, or were given, to access your database
    $dbpass = "mypassword"; // the password that you created, or were given, to access your database

    // I first connect to the db with names of the other dbs
    mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
    mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

    //select dbnames from the table with db names
    $query  = "SELECT dbname FROM users";
    $result = mysql_query($query);

    //loop through the results(dbname) and connect to each db
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    //put the dbname results into a variable
    $dbName =$row['dbname'];
    // connect to each db
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
    $db = mysql_select_db("mydbprefix_".$dbName) ;

       //do a query for each db this is because each db has same tables and structure
   //check to see if db exist
      if( $db ){

   //all the operation goes here in my case I wanted to count number of products for each table called products.
      $query2 = mysql_query("SELECT * FROM products");

    $num_rows = mysql_num_rows($query2);
    $pro = $num_rows;
    echo "this user has ".$pro." products"."<br/>";

    //another operation goes here for the same db.

    // then close connection for each db
    mysql_Close ($conn);
    }
     }
    ?>

This was how I went around this problem. It might not be the best solution but this is what I have


来源: stackexchange

问:
Merging odd number of data frames with suffixes
I am trying to merge a list of data frames, and I came across many different answers in this community like this R - reduce with merge and more than 2 suffixes (or: how to merge multiple dataframes and keep track of columns) . But after working out on these answers it works on even number of data frames but not odd number of dataframes.

```<code>myDF <- cbind(typecar = rownames(mtcars), mtcars)
rownames(myDF) <- NULL
df1 <- myDF
df2 <-  myDF
df3<- myDF
df4 <- myDF

for(i in head(seq_along(list.df), -1)) {

  res <- merge(res, list.df[[i+1]], all = TRUE,
               suffixes = sfx[i:(i+1)], by = "typecar")
}
</code>```

Here the above code works as expected for even number of df, like following

```<code>list.df <- list(df1, df2, df3,df4)
sfx <- c(".df1", ".df2", ".df3", ".df4")
</code>```

But when trying on odd number the last .df3 is not added as suffix

```<code>list.df <- list(df1, df2, df3)
sfx <- c(".df1", ".df2", ".df3")
</code>```

here the colnames looks like this.

```<code> [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg"      "cyl"      "disp"
[27] "hp"       "drat"     "wt"       "qsec"     "vs"       "am"       "gear"     "carb"
</code>```

what I want is

```<code> [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg.df3"      "cyl.df3"      "disp.df3"
[27] "hp.df3"       "drat.df3"     "wt.df3"       "qsec.df3"     "vs.df3"       "am.df3"       "gear.df3"     "carb.df3"
</code>```

Tried with dplyr join but its the same case. Came across this https://github.com/tidyverse/dplyr/issues/1296 . Is there any approach to this that work on odd number of data frames ?

答:
You can use:</p>

```<code>do.call(rbind,list.df)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to merge a list of data frames, and I came across many different answers in this community like this R - reduce with merge and more than 2 suffixes (or: how to merge multiple dataframes and keep track of columns) . But after working out on these answers it works on even number of data frames but not odd number of dataframes.

myDF <- cbind(typecar = rownames(mtcars), mtcars)
rownames(myDF) <- NULL
df1 <- myDF
df2 <-  myDF
df3<- myDF
df4 <- myDF

for(i in head(seq_along(list.df), -1)) {

  res <- merge(res, list.df[[i+1]], all = TRUE,
               suffixes = sfx[i:(i+1)], by = "typecar")
}

Here the above code works as expected for even number of df, like following

list.df <- list(df1, df2, df3,df4)
sfx <- c(".df1", ".df2", ".df3", ".df4")

But when trying on odd number the last .df3 is not added as suffix

list.df <- list(df1, df2, df3)
sfx <- c(".df1", ".df2", ".df3")

here the colnames looks like this.

 [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg"      "cyl"      "disp"
[27] "hp"       "drat"     "wt"       "qsec"     "vs"       "am"       "gear"     "carb"

what I want is

 [1] "typecar"  "mpg.df1"  "cyl.df1"  "disp.df1" "hp.df1"   "drat.df1" "wt.df1"   "qsec.df1" "vs.df1"   "am.df1"   "gear.df1" "carb.df1" "mpg.df2"
[14] "cyl.df2"  "disp.df2" "hp.df2"   "drat.df2" "wt.df2"   "qsec.df2" "vs.df2"   "am.df2"   "gear.df2" "carb.df2" "mpg.df3"      "cyl.df3"      "disp.df3"
[27] "hp.df3"       "drat.df3"     "wt.df3"       "qsec.df3"     "vs.df3"       "am.df3"       "gear.df3"     "carb.df3"

Tried with dplyr join but its the same case. Came across this https://github.com/tidyverse/dplyr/issues/1296 . Is there any approach to this that work on odd number of data frames ?

Body:
You can use:

do.call(rbind,list.df)


问:
Is there any data race between std::weak_ptr and corresponding std::shared_ptr?
According to cppref, accessing const members of shared_ptr across multiple threads is safe. But is this statement valid when we have a weak_ptr that corresponds to a shared_ptr?

As an example assume the following code:

```<code>#include <memory>
#include <iostream>
#include <thread>

std::shared_ptr<int> sp;
std::weak_ptr<int> gw;

int main()
{
    sp = std::make_shared<int>(42);
    gw = sp;
    auto th1 = std::thread([]{
        for (int i = 0; i < 200; i++) {
            if (sp.use_count() > 1) {
                std::cout << i << "\n";
                std::this_thread::yield();
            }
        }
    });
    auto th2 = std::thread([]{
        for (int i = 0; i < 20; i++) {
            if (auto l = gw.lock()) {
                std::cout << "locked ->" << l.use_count() << "\n";
                std::this_thread::yield();
            }
        }
    });
    th1.join();
    th2.join();
}
</code>```

This code creates 2 threads. One checks use_count() of shared_ptr() which is a const method and the other one use lock() to lock weak_ptr() which also is a const method too. But in reality, when I call lock on weak_ptr, I practically increase reference count of shared_ptr which is not thread safe unless reference count is internally guarded. I wonder if I will have a data race in situations like this. Is this supposed to be thread-safe by standard?

答:
Yes. The reference counter is atomic, so there are no data races in your example.

That being said, mutable operations on objects pointed by std::shared_ptr are not atomic, so they must be guarded as you would guard access via a plain pointer.

Body:
According to cppref, accessing const members of shared_ptr across multiple threads is safe. But is this statement valid when we have a weak_ptr that corresponds to a shared_ptr?

As an example assume the following code:

#include <memory>
#include <iostream>
#include <thread>

std::shared_ptr<int> sp;
std::weak_ptr<int> gw;

int main()
{
    sp = std::make_shared<int>(42);
    gw = sp;
    auto th1 = std::thread([]{
        for (int i = 0; i < 200; i++) {
            if (sp.use_count() > 1) {
                std::cout << i << "\n";
                std::this_thread::yield();
            }
        }
    });
    auto th2 = std::thread([]{
        for (int i = 0; i < 20; i++) {
            if (auto l = gw.lock()) {
                std::cout << "locked ->" << l.use_count() << "\n";
                std::this_thread::yield();
            }
        }
    });
    th1.join();
    th2.join();
}

This code creates 2 threads. One checks use_count() of shared_ptr() which is a const method and the other one use lock() to lock weak_ptr() which also is a const method too. But in reality, when I call lock on weak_ptr, I practically increase reference count of shared_ptr which is not thread safe unless reference count is internally guarded. I wonder if I will have a data race in situations like this. Is this supposed to be thread-safe by standard?


问:
How to show an activity as popup intent when clicking on notification?
I am working on a reply action from the notification of the text message. Anyone please help me out how to intent an activity as popup or dialog from notification on click.
I already add reply option to the notification and intent an activity from it but not getting it as required.

Thanks in advance!

答:
I am also getting the same issue a few days back but now I resolved it by setting the theme of the activity in the manifest as:

```<code>android:theme="@style/Theme.AppCompat.Dialog"
</code>```

and also add :

```<code>android:autoRemoveFromRecents="true"
</code>```

You can simply create an activity layout for the reply and its context activity. On the intent of this activity, the layout comes up as a dialog to the user. As you mentioned that you already intent any activity from the reply action button in the notification, so just replace the activity name with this activity name.

It works surely.

Body:
I am also getting the same issue a few days back but now I resolved it by setting the theme of the activity in the manifest as:

android:theme="@style/Theme.AppCompat.Dialog"

and also add :

android:autoRemoveFromRecents="true"

You can simply create an activity layout for the reply and its context activity. On the intent of this activity, the layout comes up as a dialog to the user. As you mentioned that you already intent any activity from the reply action button in the notification, so just replace the activity name with this activity name.

It works surely.


问:
Regex python find uppercase names
I have a text file of the type:

[...speech...]

NAME_OF_SPEAKER_1: [...speech...]

NAME_OF_SPEAKER_2: [...speech...]

My aim is to isolate the speeches of the various speakers. They are clearly identified because the name  of each speaker is always indicated in uppercase letters (name+surname). However, in the speeches there can be nouns (not people's names) which are in uppercase letter, but there is only one word that is actually long enough to give me issue (it has four letter, say it is 'ABCD'). I was thinking to identifiy the position of each speaker's name (I assume every name long at least 3 letters) with something like

```<code>re.search('[A-Z^(ABCD)]{3,}',text_to_search)
</code>```

in order to exclude that specific (constant) word 'ABCD'. However, the command identifies that word instead of excluding it. Any ideas about how to overcome this problem?

答:
Square brackets [] match single characters, only. Also round brackets() inside of square brackets match single characters, only. That means:

[ABCD] and [(ABCD)] are the same as [A-D].

[^(ABCD)] matches any character, which is not one of A-D

I would try something different:

^[A-Z]*?: matches each word written in capital letters, which starts at the beginning of a line, and is followed by a colon

Title: Regex python find uppercase names

Body:
I have a text file of the type:

[...speech...]

NAME_OF_SPEAKER_1: [...speech...]

NAME_OF_SPEAKER_2: [...speech...]

My aim is to isolate the speeches of the various speakers. They are clearly identified because the name  of each speaker is always indicated in uppercase letters (name+surname). However, in the speeches there can be nouns (not people's names) which are in uppercase letter, but there is only one word that is actually long enough to give me issue (it has four letter, say it is 'ABCD'). I was thinking to identifiy the position of each speaker's name (I assume every name long at least 3 letters) with something like

re.search('[A-Z^(ABCD)]{3,}',text_to_search)

in order to exclude that specific (constant) word 'ABCD'. However, the command identifies that word instead of excluding it. Any ideas about how to overcome this problem?


问:
SQL where clause with case statement
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

```<code>AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END
</code>```

I'm not sure how to process the -1 to say select all users

Thanks

答:
Perhaps the following would work:

```<code>SELECT whatever
  FROM wherever
  WHERE something = somethingelse AND
        usertable.userid = CASE @user
                             WHEN -1 THEN usertable.userid
                             ELSE @user
                           END
</code>```

Share and enjoy.

ContentLicense: CC BY-SA 3.0

Title: SQL where clause with case statement

Body:
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END

I'm not sure how to process the -1 to say select all users

Thanks

Body:
Perhaps the following would work:

SELECT whatever
  FROM wherever
  WHERE something = somethingelse AND
        usertable.userid = CASE @user
                             WHEN -1 THEN usertable.userid
                             ELSE @user
                           END

Share and enjoy.


问:
How do you get the json from an use actix_web::HttpRequest into struct?
What is the simplest way to get json from the HttpRequest into a struct you created. Here is the main.rs

```<code>#[actix_rt::main]
async fn main() -> std::io::Result<()> {
  HttpServer::new(|| {
    App::new()
      .data(web::JsonConfig::default().limit(4096))
      .data(connect())
      .service(web::resource("/insert").route(web::post().to(handlers::tours::insert)))
  })
  .bind("127.0.0.1:8088")
  .unwrap()
  .run()
  .await
}
</code>```

And here is the struct in model/tour.rs:

```<code>#[derive(Serialize, Deserialize, Insertable)]
pub struct TourForm {
  pub name: String,
}
</code>```

And here is the handler in handlers/tours.rs::

```<code>pub async fn insert(
  tour_form: web::Json<TourForm>,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.name))
}
</code>```

I tried this variation because I thought this would make the code very simple:

```<code>pub async fn insert(
  tour_form: TourForm,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.name))
}
</code>```

But got the error:

```<code>^^ the trait `actix_web::extract::FromRequest` is not implemented for `model::tour::TourForm`
</code>```

Should I implement the FromRequest function into the TourForm struct or is there an easier way?

答:
I was able to get the TourForm object out of the web::Json simply by doing tour_form.0</p>

```<code>pub async fn insert(
  tour_form: web::Json<TourForm>,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.0))
}
</code>```

Body:
What is the simplest way to get json from the HttpRequest into a struct you created. Here is the main.rs

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
  HttpServer::new(|| {
    App::new()
      .data(web::JsonConfig::default().limit(4096))
      .data(connect())
      .service(web::resource("/insert").route(web::post().to(handlers::tours::insert)))
  })
  .bind("127.0.0.1:8088")
  .unwrap()
  .run()
  .await
}

And here is the struct in model/tour.rs:

#[derive(Serialize, Deserialize, Insertable)]
pub struct TourForm {
  pub name: String,
}

And here is the handler in handlers/tours.rs::

pub async fn insert(
  tour_form: web::Json<TourForm>,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.name))
}

I tried this variation because I thought this would make the code very simple:

pub async fn insert(
  tour_form: TourForm,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.name))
}

But got the error:

^^ the trait `actix_web::extract::FromRequest` is not implemented for `model::tour::TourForm`

Should I implement the FromRequest function into the TourForm struct or is there an easier way?

Body:
I was able to get the TourForm object out of the web::Json simply by doing tour_form.0

pub async fn insert(
  tour_form: web::Json<TourForm>,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.0))
}


问:
R function that evaluates numerics into the name of the given number
For example I'm looking for a function that with similar functionality to the example below

```<code>numNam(1234)
>> "1 thousand, 2 hundred, and 34"
</code>```

Does anyone know if this exists?

答:
The words function from the english package on CRAN should do what you want approximately.  It's styled a bit differently than your example output but should accomplish your goal.

https://cran.r-project.org/web/packages/english/english.pdf

Body:
For example I'm looking for a function that with similar functionality to the example below

numNam(1234)
>> "1 thousand, 2 hundred, and 34"

Does anyone know if this exists?


问:
Is google authentication method through firebase safe?
I've used firebase authentication for my react app.But later many people said that firebase authentication is not much secure and they suggest me to go with JWT authentication or passport.js authentication methods.

But I don't want to shift from firebase because of its simpleness.Now I'm thinking to use google authentication signIn method in firebase. Is google authentication in firebase is also not safe? Is it safe to opt google authentication in firebase?

答: There is nothing particularly "unsafe" about Firebase Authentication, especially compared to other options.  If another options meets your specific needs better, then go with it.  But without specific details on what you think to be unsafe about Firebase Auth, there is nothing really to say.</p>


问:
How to execute 'cd' command and then a linux command in java
I have directory /tmp
then I need to execute cd and go to that folder.
Then I need to execute ./executeScript</p>

答:
Preparation

To start solving the problem, I created a directory /home/vulpini99/tmp. In this directory, I created the bash-script test.sh, which will open firefox for us:

```<code>firefox
</code>```

Then I created a java-file named LinuxCommand.java in the directory /home/vulpini99.

Main part

cd is just an internal shell command and not an executable program, so I suggest to just use the full path of the bash-script. So the command we want to execute is

bash /home/vulpini99/tmp/test.sh.

In Java, you can use Runtime for this purpose:

```<code>import java.io.IOException;

public class LinuxCommand {

    public static void main(String[] args) {
        Runtime run = Runtime.getRuntime();
        try {
            run.exec("bash /home/vulpini99/tmp/test.sh");
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
Preparation

To start solving the problem, I created a directory /home/vulpini99/tmp. In this directory, I created the bash-script test.sh, which will open firefox for us:

firefox

Then I created a java-file named LinuxCommand.java in the directory /home/vulpini99.

Main part

cd is just an internal shell command and not an executable program, so I suggest to just use the full path of the bash-script. So the command we want to execute is

bash /home/vulpini99/tmp/test.sh.

In Java, you can use Runtime for this purpose:

import java.io.IOException;

public class LinuxCommand {

    public static void main(String[] args) {
        Runtime run = Runtime.getRuntime();
        try {
            run.exec("bash /home/vulpini99/tmp/test.sh");
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
}


问:
Executing function for lower iOS versions
Is there an way for executing functions only for lower iOS versions.
I mean we can execute always using the available attribute for iOS versions greater than the specific one ; but is there any way to do the other way round?</p>

答:
It's really annoying to write if statement and then catch what you want in the else statement. Nevertheless you can define global function to handle all cases in one place, which is also have its own issues. Never call it with a variable! Always use hardcoded string version number to check iOS version. If you accidentally checked unhandled version, just insert it and go. fatalError() will help you.

```<code>func available(version: String) -> Bool {
switch version {
case "13.5":
    if #available(iOS 13.5, *) { return true }
case "12":
    if #available(iOS 12, *) { return true }
default:
    fatalError("iOS \(version) is not handled. Insert:\n case \"\(version)\": \n if #available(iOS \(version), *) { return true }")
}

return false }
</code>```

Usage:

```<code>if !available(version: "10") {
    print("Not available")
}
</code>```

Body:
It's really annoying to write if statement and then catch what you want in the else statement. Nevertheless you can define global function to handle all cases in one place, which is also have its own issues. Never call it with a variable! Always use hardcoded string version number to check iOS version. If you accidentally checked unhandled version, just insert it and go. fatalError() will help you.

func available(version: String) -> Bool {
switch version {
case "13.5":
    if #available(iOS 13.5, *) { return true }
case "12":
    if #available(iOS 12, *) { return true }
default:
    fatalError("iOS \(version) is not handled. Insert:\n case \"\(version)\": \n if #available(iOS \(version), *) { return true }")
}

return false }

Usage:

if !available(version: "10") {
    print("Not available")
}


问:
Mojolicious API not showing JSON data
I'm trying to pass the following JSON object using AJAX, but can't see the data in the log file. How should I look for the 'data' part of my Ajax call in the API?

```<code>var jsObject = {
        myIds : [1234,5678],
        myType : 1
};
$.ajax({
            type : "POST",
            url : "/myAddress",
            dataType: "json",
            data : JSON.stringify(jsObject),
            contentType : 'application/json',
            success: function(data)
            {
                console.log('Success', data);
            },
            error: function(data)
            {
              console.log('Failed', data);
            }
        });
</code>```

Here is my API to show the data in the log file:

```<code> sub my_sub {

    my $c = shift;

    my %params = %{$c->req->params};

    $c->app->log->debug(Dumper(\%params));
}
</code>```

And this is what I see in the log file:

```<code>$VAR1 = {
      'charset' => 'UTF-8',
      'pairs' => []
};
</code>```

答:
Try this: $c->req->json;

Read more in Mojolicious::Controller documentation.

Title: Mojolicious API not showing JSON data

Body:
I'm trying to pass the following JSON object using AJAX, but can't see the data in the log file. How should I look for the 'data' part of my Ajax call in the API?

var jsObject = {
        myIds : [1234,5678],
        myType : 1
};
$.ajax({
            type : "POST",
            url : "/myAddress",
            dataType: "json",
            data : JSON.stringify(jsObject),
            contentType : 'application/json',
            success: function(data)
            {
                console.log('Success', data);
            },
            error: function(data)
            {
              console.log('Failed', data);
            }
        });

Here is my API to show the data in the log file:

 sub my_sub {

    my $c = shift;

    my %params = %{$c->req->params};

    $c->app->log->debug(Dumper(\%params));
}

And this is what I see in the log file:

$VAR1 = {
      'charset' => 'UTF-8',
      'pairs' => []
};


问:
There is an error of exception in thread "main" and i need to have a message entered
I don't see the issue or how to input the message. The full error that I keep getting is below. I can't see any problems with the code and I can't find a way to a message into the code.</p>

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of ran
ge: 30
    at java.base/java.lang.StringLatin1.charAt (String.java:47)
    at java.base/java.lang.String.charAt (String.java:693
    at Main.main (Main.java:15)
</code>```

```<code>import java.util.Scanner;

public class Main
{
    public static void main( String[] args )
    {
        Scanner kb = new Scanner(System.in);

        System.out.println("What is your message? ");
        String message ="" + "\n";

        System.out.println("\nYour message is " +  " characters long.");
        System.out.println("The first character is at position 0 and is '" +  "'.");
        int lastpos = 30;
        System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
        System.out.println("\nHere are all the characters, one at a time:\n");

        for ( int i=0; i<message.length(); i++ )
        {
            System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
        }

        int a_count = 0;

        for ( int i=0; i<message.length(); i++ )
        {
            char letter = message.charAt(i);
            if ( letter == 'a' || letter == 'A' );
            {
                a_count++;
            }
        }

        System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");

    }
}
</code>```

答:
I have made 3 changes from the code that you have written. They are the following:

Read the message using kb.nextLine(); instead of "" + "\n";

The first character of the message is message.charAt(0) instead of "'."

To count the number of characters, you have given semicolon after the if condition. Remove that. The semicolon after if is not needed.

Check the snippet below for better understanding.

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);

        System.out.println("What is your message? ");
        String message = kb.nextLine();

        System.out.println("\nYour message is " + " characters long.");
        System.out.println("The first character is at position 0 and is '" + message.charAt(0));
        int lastpos = 30;
        System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
        System.out.println("\nHere are all the characters, one at a time:\n");

        for (int i = 0; i < message.length(); i++) {
            System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
        }

        int a_count = 0;

        for (int i = 0; i < message.length(); i++) {
            char letter = message.charAt(i);
            if (letter == 'a' || letter == 'A') {
                a_count++;
            }
        }

        System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");

    }
}
</code>```

Body:
I don't see the issue or how to input the message. The full error that I keep getting is below. I can't see any problems with the code and I can't find a way to a message into the code.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of ran
ge: 30
    at java.base/java.lang.StringLatin1.charAt (String.java:47)
    at java.base/java.lang.String.charAt (String.java:693
    at Main.main (Main.java:15)

import java.util.Scanner;

public class Main
{
    public static void main( String[] args )
    {
        Scanner kb = new Scanner(System.in);

        System.out.println("What is your message? ");
        String message ="" + "\n";

        System.out.println("\nYour message is " +  " characters long.");
        System.out.println("The first character is at position 0 and is '" +  "'.");
        int lastpos = 30;
        System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
        System.out.println("\nHere are all the characters, one at a time:\n");

        for ( int i=0; i<message.length(); i++ )
        {
            System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
        }

        int a_count = 0;

        for ( int i=0; i<message.length(); i++ )
        {
            char letter = message.charAt(i);
            if ( letter == 'a' || letter == 'A' );
            {
                a_count++;
            }
        }

        System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");

    }
}

Body:
I have made 3 changes from the code that you have written. They are the following:

Read the message using kb.nextLine(); instead of "" + "\n";

The first character of the message is message.charAt(0) instead of "'."

To count the number of characters, you have given semicolon after the if condition. Remove that. The semicolon after if is not needed.

Check the snippet below for better understanding.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);

        System.out.println("What is your message? ");
        String message = kb.nextLine();

        System.out.println("\nYour message is " + " characters long.");
        System.out.println("The first character is at position 0 and is '" + message.charAt(0));
        int lastpos = 30;
        System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
        System.out.println("\nHere are all the characters, one at a time:\n");

        for (int i = 0; i < message.length(); i++) {
            System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
        }

        int a_count = 0;

        for (int i = 0; i < message.length(); i++) {
            char letter = message.charAt(i);
            if (letter == 'a' || letter == 'A') {
                a_count++;
            }
        }

        System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");

    }
}


问:
How to debug Maya plugin with Xcode?
I have a Maya 2019 Plugin that I want to step through in Xcode 11.4's debugger.  Even though I can attach to the Maya process and see the output from the plugin in Xcode's console (and in the terminal if I launch Maya from there) the plugin breakpoints are never reached.  Does anyone have detailed steps for setting this up?

These are some resources I've already looked at:

http://www.sonictk.com/post/tutorial-debugging-maya-plugins-crossplatform/

https://medium.com/@yuping37/write-a-custom-skinning-maya-plugin-and-debug-with-xcode-8de6512b494d

Debugging Maya Plugin with Xcode

答:
Go to the product menu in Xcode and select "Edit Scheme"

In the Edit Scheme screen’s input field for Executable, select “other”.  This will open a screen titled “Choose an executable to launch” to browse for the path to maya.  Leave this screen open.

Open the Mac Finder app and navigate to Applications, right click on Maya and select “Show Package contents". Navigate to the package's /Contents/bin/ folder and select maya unix executable and drag it to the “Choose an executable to launch” screen opened in step 2. Then close.

Go to Build Settings set "Generate Debug Symbols" to YES. Debugger should now work when running or Attaching to process by PID or Name.

Title: How to debug Maya plugin with Xcode?


问:
Nodejs - .node_libraries/ for www-data
I want to use uglifyjs (https://github.com/mishoo/UglifyJS) from my PHP application. UglifyJS is built using Nodejs, so I need a .node_libraries/ dir in my homedir (/home/peppe).

I want to execute uglifyjs by shell_exec() in PHP. But where am I supposed to add the .node_libraries/ dir since www-data user doesn't have a home dir?

Addition: I solved it. The solution was to set NODE_PATH and execute the command like this in PHP:
shell_exec('NODE_PATH="/opt/www_node_libraries/"; export NODE_PATH; uglifyjs options filename');

答:
Quoting the OP and @Bill so we can get this removed from unanswered list.

Addition: I solved it.

  The solution was to set NODE_PATH and execute the command like this in PHP:

```<code>shell_exec('NODE_PATH="/opt/www_node_libraries/"; export NODE_PATH; uglifyjs options filename');
</code>```

Title: Nodejs - .node_libraries/ for www-data

Body:
Quoting the OP and @Bill so we can get this removed from unanswered list.

Addition: I solved it.

  The solution was to set NODE_PATH and execute the command like this in PHP:

shell_exec('NODE_PATH="/opt/www_node_libraries/"; export NODE_PATH; uglifyjs options filename');


问:
Pandas - String Concatenation with Array column
I am trying to make a new string from two columns in my dataframe. One of my columns contains 1 value. The other column contains an array. The end result should look like the third column below.

```<code>  Alpha  Val                Result
0   A    ['1, 2, 3']    ['A1', 'A2', 'A3']
</code>```

I had tried list comprehension but it just returns an error "can only concatenate str (not "list") to str"

[alpha + val for alpha in df['Alpha'].str.split(",") for val in df['Val'].str.split(",")]

This kind of like a 1X1 matrix by a 1X3 matrix (but concatenating the strings) but I'm not sure how to achieve this using pandas.

答:
using the data courtesy @challasandeep420 we can also do : </p>

```<code>df['Result'] = (df['Val'].str[0].str.split(',').explode().str.strip()
                         .radd(df['Alpha']).groupby(level=0).agg(list))
print(df)

  Alpha           Val            Result
0     A     [1, 2, 3]      [A1, A2, A3]
1     B  [4, 5, 6, 7]  [B4, B5, B6, B7]
</code>```

Body:
I am trying to make a new string from two columns in my dataframe. One of my columns contains 1 value. The other column contains an array. The end result should look like the third column below.

  Alpha  Val                Result
0   A    ['1, 2, 3']    ['A1', 'A2', 'A3']

I had tried list comprehension but it just returns an error "can only concatenate str (not "list") to str"

[alpha + val for alpha in df['Alpha'].str.split(",") for val in df['Val'].str.split(",")]

This kind of like a 1X1 matrix by a 1X3 matrix (but concatenating the strings) but I'm not sure how to achieve this using pandas.

Body:
using the data courtesy @challasandeep420 we can also do :

df['Result'] = (df['Val'].str[0].str.split(',').explode().str.strip()
                         .radd(df['Alpha']).groupby(level=0).agg(list))
print(df)

  Alpha           Val            Result
0     A     [1, 2, 3]      [A1, A2, A3]
1     B  [4, 5, 6, 7]  [B4, B5, B6, B7]


问:
Statically scheduling OOO processors
The LLVM MISched instruction scheduler uses declarative TableGen descriptions of the processor functional units, pipelines and latencies. Imagine trying to determine the equivalent of the coding guidelines from Intel's Optimization Reference Manual from those declarations.

Broadly speaking, what are the objectives/techniques for statically scheduling OOO processors? When would it schedule an instruction A before B and when would it schedule A after B for an OOO processor?

Superscalar processors can execute more than one instruction at a time. An in-order processor will only consider instructions in their original order. An out-of-order (OOO) processor can execute instructions out of order and then commit the results in order. Speculation doesn't matter for this question but I assume these processors are pipelined. Think A53 (in-order) and Haswell (OOO).

Which instruction an OOO processor will execute next is a scheduling decision made by the processor at run time. So this is usually called dynamic scheduling. Which instruction an in-order processor executes was decided by the compiler back when the program was compiled. Consequently this is usually called static scheduling.

However, compilers also statically target/schedule OOO processors. In both in-order and OOO cases, a compiler can look at a large window of instructions; a compiler has to deal with register pressure; and in both cases, a compiler wants to keep functional units busy. OOO processors typically can also rename registers, reducing register pressure.

Given that an OOO processor schedules instructions dynamically, what should the ahead of time compiler do to help this?

答:
You are generally correct but compile-time scheduling can still slightly improve execution speed. This happens because compiler can rearrange instructions in more optimal way to speed up decoding (older variants of x86 could decode multiple instructions in parallel only if sequence satisfies certain constraints) or to pack them more tightly in processor's instruction buffer. To cite from Robert Morgan's "Building an optimizing compiler":

```<code>The compiler should schedule the insns as if the processor were
not an out-of-order execution processor.  The more effective this
schedule is, the larger the size of the effective insns buffer.
</code>```

The wins are normally quite small in practice (few percent).

Title: Statically scheduling OOO processors

Body:
You are generally correct but compile-time scheduling can still slightly improve execution speed. This happens because compiler can rearrange instructions in more optimal way to speed up decoding (older variants of x86 could decode multiple instructions in parallel only if sequence satisfies certain constraints) or to pack them more tightly in processor's instruction buffer. To cite from Robert Morgan's "Building an optimizing compiler":

The compiler should schedule the insns as if the processor were
not an out-of-order execution processor.  The more effective this
schedule is, the larger the size of the effective insns buffer.

The wins are normally quite small in practice (few percent).


问:
Vue.js: Search through nested arrays
I have been working on a FAQ page that has categories and once you have selected a category, it shows questions users have asked. You can then select a question to display the answer. There are 7 categories and each has an array named "questionList" that has various amounts of questions. I am creating a search bar that will filter through ALL questions in each category and display the question and answer that matches the search. Right now the filtered list only displays the first categories questions....

Here is an example of how my data is setup

```<code>categoryList : [
           {
             category: 'Category Title',
             questionList: [
                      {
                         question: 'Question',
                         answer: '<p>copy goes here</p>'
                       }, ...
                     ]
            },
            {
               category: 'Next Title',
               questionList: [
                       {
                         question: 'Question',
                         answer: '<p>copy goes here</p>'
                       },
                     ]
             }, ...
</code>```

I was looking at another stackoverflow solution and I really could not figure out how to have it function with my multiple nested arrays. Here is the html:

```<code><div class="filtered" v-for="qa in filteredList">
     <div class="filter-container">
          <h3>{{ qa.question }}</h3>
          <div v-html="qa.answer"></div>
     </div>
</div>
</code>```

and my computed function:

```<code>filteredList() {
      for (i = 0; i < this.categoryList.length; i++) {

            var list =  this.categoryList[i];

            for (j = 0; j < list.questionList.length; j++ ) {

                    return list.questionList.filter(qa => {
                                 return qa.question.toLowerCase().includes(this.search.toLowerCase());
                        })
                   }
              }
          }
</code>```

I'm not sure if I am even close to the correct solution or waaaay off here... please help!

答:
You're returning abit too early, use filter then loop over the sub-items, though your HTML part is only looping over the main categories, you want two loops for that too.

```<code>const component = {
  template: `
  <div>
    <input v-model="search"/>

    <ul v-for="qa in filteredList">
      <li>
        {{qa.category}}
          <ul v-for="qa in qa.questionList">
            <li>
              {{qa.question}}:<br>
              <span v-html="qa.answer"></span>
             </li>
          </ul>
       </li>
    </ul>
  </div>
  `,
  computed: {
    filteredList() {
      return this.categoryList.filter(item => {
        for (const {question, answer} of item.questionList) {
          if (
            question.indexOf(this.search) > -1 ||
            answer.indexOf(this.search) > -1
          ) {
            return item
          }
        }
      })
    }
  },
  data() {
    return {
      search: '',
      categoryList: [
        {
          category: 'Category Title',
          questionList: [
            {
              question: 'Question',
              answer: '<p>copy goes here</p>',
            },
          ],
        },
        {
          category: 'Next Title',
          questionList: [
            {
              question: 'Question',
              answer: '<p>copy goes here</p>'
            }
          ]
        }
      ]
    }
  }
}
</code>```

Edit (filter questions):

Using bog standard for loops, create a new copy of the array, loop over and only push the new item if questionList contains matches.

```<code>filteredList() {
  const ret = []
  for (const item of this.categoryList) {
    const t = {
      ...item,
      questionList: []
    }
    for (const q of item.questionList) {
      if (
        q.question.indexOf(this.search) > -1 ||
        q.answer.indexOf(this.search) > -1
      ) {
        t.questionList.push(q)
      }
    }
    if (t.questionList.length) ret.push(t)
  }
  return ret
},
</code>```

Title: Vue.js: Search through nested arrays

Body:
I have been working on a FAQ page that has categories and once you have selected a category, it shows questions users have asked. You can then select a question to display the answer. There are 7 categories and each has an array named "questionList" that has various amounts of questions. I am creating a search bar that will filter through ALL questions in each category and display the question and answer that matches the search. Right now the filtered list only displays the first categories questions....

Here is an example of how my data is setup

categoryList : [
           {
             category: 'Category Title',
             questionList: [
                      {
                         question: 'Question',
                         answer: '
copy goes here
'
                       }, ...
                     ]
            },
            {
               category: 'Next Title',
               questionList: [
                       {
                         question: 'Question',
                         answer: '
copy goes here
'
                       },
                     ]
             }, ...

I was looking at another stackoverflow solution and I really could not figure out how to have it function with my multiple nested arrays. Here is the html:

{{ qa.question }}

and my computed function:

filteredList() {
      for (i = 0; i < this.categoryList.length; i++) {

            var list =  this.categoryList[i];

            for (j = 0; j < list.questionList.length; j++ ) {

                    return list.questionList.filter(qa => {
                                 return qa.question.toLowerCase().includes(this.search.toLowerCase());
                        })
                   }
              }
          }

I'm not sure if I am even close to the correct solution or waaaay off here... please help!

Body:
You're returning abit too early, use filter then loop over the sub-items, though your HTML part is only looping over the main categories, you want two loops for that too.

const component = {
  template: `
  <div>
    <input v-model="search"/>

    <ul v-for="qa in filteredList">
      <li>
        {{qa.category}}
          <ul v-for="qa in qa.questionList">
            <li>
              {{qa.question}}:<br>
              <span v-html="qa.answer"></span>
             </li>
          </ul>
       </li>
    </ul>
  </div>
  `,
  computed: {
    filteredList() {
      return this.categoryList.filter(item => {
        for (const {question, answer} of item.questionList) {
          if (
            question.indexOf(this.search) > -1 ||
            answer.indexOf(this.search) > -1
          ) {
            return item
          }
        }
      })
    }
  },
  data() {
    return {
      search: '',
      categoryList: [
        {
          category: 'Category Title',
          questionList: [
            {
              question: 'Question',
              answer: '<p>copy goes here</p>',
            },
          ],
        },
        {
          category: 'Next Title',
          questionList: [
            {
              question: 'Question',
              answer: '<p>copy goes here</p>'
            }
          ]
        }
      ]
    }
  }
}

Edit (filter questions):

Using bog standard for loops, create a new copy of the array, loop over and only push the new item if questionList contains matches.

filteredList() {
  const ret = []
  for (const item of this.categoryList) {
    const t = {
      ...item,
      questionList: []
    }
    for (const q of item.questionList) {
      if (
        q.question.indexOf(this.search) > -1 ||
        q.answer.indexOf(this.search) > -1
      ) {
        t.questionList.push(q)
      }
    }
    if (t.questionList.length) ret.push(t)
  }
  return ret
},


问:
Tools for Domain Specific Language/Functions
Our users can enter questions that get answered by students. Our users need a extensible, flexible way to define the correct answers to these questions (which are stored as a simple string).

I would like to expose a library of domain specific functions that users can call on to describe the correct answer. Eg:

```<code>exact_match("puppy") // means the correct answer is the string 'puppy'
</code>```

or

```<code>contains("yesterday") // means any answer with the word 'yesterday' is correct
</code>```

The naive implementation would involve eval'ing user supplied strings in a sandboxed runtime (like a javascript vm or ruby vm). But I'd like to go further and only allow specific functions to be called. Any other scripting would be discarded. Such that:

```<code>puts("foo"); contains("yesterday")
</code>```

would be illegal. Since we don't expose or allow puts().

How can I constrain the execution environment to only run a whitelist of functions? Or is there a different approach to build this kind of external-facing DSL instead of trying to constrain an existing language to a subset of functions?

答: I would check out MPS by JetBrains if I were you, its an open source DSL creation tool. I have never used it myself, but from everything I have seen on it, it's very intuitive; and all of their other products are incredibly powerful.</p>

Body:
Our users can enter questions that get answered by students. Our users need a extensible, flexible way to define the correct answers to these questions (which are stored as a simple string).

I would like to expose a library of domain specific functions that users can call on to describe the correct answer. Eg:

exact_match("puppy") // means the correct answer is the string 'puppy'

or

contains("yesterday") // means any answer with the word 'yesterday' is correct

The naive implementation would involve eval'ing user supplied strings in a sandboxed runtime (like a javascript vm or ruby vm). But I'd like to go further and only allow specific functions to be called. Any other scripting would be discarded. Such that:

puts("foo"); contains("yesterday")

would be illegal. Since we don't expose or allow puts().

How can I constrain the execution environment to only run a whitelist of functions? Or is there a different approach to build this kind of external-facing DSL instead of trying to constrain an existing language to a subset of functions?


问:
Maven - Sharing libraries between projects
I'm working on a multi-project, and right now I have a structure that resembles this (actually there are a couple of jar projects and a couple of war projects)

```<code>/myProj
 |_______projA (jar)
 |          |____pom.xml
 |          |____target/jar files
 |_______projB (war)
 |          |___pom.xml
 |          |___web-inf/lib/jarfiles
 |_______projEar
 |          |___pom.xml
 |___pom.xml
</code>```

What I want to achieve, is to make projA and projB to read their dependences from a common shared folder, instead of keeping their own copy.

Actually, I don't really care where they read them from at compile time, but when I package my EAR file, I want each jar/war to appear just once, hence reducing the EAR size.

I've tried declaring the dependencies on the parent pom, declaring the dependencies as  and some other things, but so far I haven't achieved this.

Is there an easy way to achieve this? Any simple maven plugin?

Thanks in advance.

答:
You should be able to do this by adding the JAR as a dependency to your EAR's pom.xml:

```<code><dependencies>
    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>myapp-web</artifactId>
        <version>1.0-SNAPSHOT</version>
        <type>war</type>
    </dependency>
    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>myapp-utils</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <type>jar</type>
    </dependency>
</dependencies>
</code>```

...and specifying the dependency as provided in your WARs' pom.xml:

```<code>    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>myapp-utils</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>
</code>```

If Maven/other tooling has already copied the JAR to your WEB-INF/lib directory, you may need to delete the file manually prior to rebuilding.

This should result in an EAR of the form:

```<code>META-INF/MANIFEST.MF
lib/myapp-utils-0.0.1-SNAPSHOT.jar
META-INF/application.xml
myapp-web.war
</code>```

Body:
I'm working on a multi-project, and right now I have a structure that resembles this (actually there are a couple of jar projects and a couple of war projects)

/myProj
 |_______projA (jar)
 |          |____pom.xml
 |          |____target/jar files
 |_______projB (war)
 |          |___pom.xml
 |          |___web-inf/lib/jarfiles
 |_______projEar
 |          |___pom.xml
 |___pom.xml

What I want to achieve, is to make projA and projB to read their dependences from a common shared folder, instead of keeping their own copy.

Actually, I don't really care where they read them from at compile time, but when I package my EAR file, I want each jar/war to appear just once, hence reducing the EAR size.

I've tried declaring the dependencies on the parent pom, declaring the dependencies as  and some other things, but so far I haven't achieved this.

Is there an easy way to achieve this? Any simple maven plugin?

Thanks in advance.

Body:
You should be able to do this by adding the JAR as a dependency to your EAR's pom.xml:

<dependencies>
    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>myapp-web</artifactId>
        <version>1.0-SNAPSHOT</version>
        <type>war</type>
    </dependency>
    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>myapp-utils</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <type>jar</type>
    </dependency>
</dependencies>

...and specifying the dependency as provided in your WARs' pom.xml:

    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>myapp-utils</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>

If Maven/other tooling has already copied the JAR to your WEB-INF/lib directory, you may need to delete the file manually prior to rebuilding.

This should result in an EAR of the form:

META-INF/MANIFEST.MF
lib/myapp-utils-0.0.1-SNAPSHOT.jar
META-INF/application.xml
myapp-web.war


问:
Why javascript code is not being loaded inside coldfusion?
I have a coldfusion file(.cfm) which calls another .cfm file where script tag is defined having alert function. When i run this file, it doesn't load javascript code. What is potential issue?

答: Test with <cfinclude template="/Features/lic/Features/Convictions/ActionPages/dsp_lic_sub_convictions.cfm">


问:
Sending explicit zeroes in protobuf3
In Protobuf3 zero is the default value for numeric types, and so they are filtered out when serialized.

I have an application where I need to send a value only when it has changed. For example, x was 1, now x is 0, send this value.

It isn't possible to send only the delta, eg -1, because some of these values are floats or doubles, and we do not want to accrue errors.

There are over 200 different variables in some classes I need to serialize, so solutions like "add a boolean to flag which fields have changed" are possible but not fun. Other suggestions that have a large amount of per-field work or processing are undesirable too.

Is there a simple mechanism to tell protobuf3 to explicitly keep a value even though it is the default value?

Possible solutions:

Send the entire class each time. The main downside here is some fields may have a lot of data.

Use a boolean "has changed" in the schema to indicate if a variable has changed, even if it is 0

Use a magic value. Terrible idea, but possible. Not going to do this.

答:
If you need to distinguish 0 and null then you can use proto3 wrapper types: https://developers.google.com/protocol-buffers/docs/reference/csharp-generated#wrapper_types
There are special wrapper types for such case: StringWrapper, Int32Wrapper and etc. All of the wrapper types that correspond to C# value types (Int32Wrapper, DoubleWrapper, BoolWrapper etc) are mapped to Nullable<T> where T is the corresponding non-nullable type.

Title: Sending explicit zeroes in protobuf3


问:
Error when importing mathjs in Angular 9 CLI webworker
I am currently trying add a webworker to my Angular 9 project using Angular CLI 9.1.7.
This webworker should run some calculations using mathjs 7.

However, importing mathjs into the webworker always results in the following error in the browser console.
If I don't import mathjs, the worker runs without a problem.

```<code>index.js:7 Uncaught ReferenceError: window is not defined
    at Object../node_modules/seed-random/index.js (index.js:7)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/function/probability/util/seededRNG.js (seededRNG.js:1)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/function/probability/pickRandom.js (pickRandom.js:1)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/factoriesAny.js (factoriesAny.js:1)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/entry/pureFunctionsAny.generated.js (pureFunctionsAny.generated.js:1)
    at __webpack_require__ (bootstrap:19)
</code>```

The referenced line is

```<code>var GLOBAL = typeof global === 'undefined' ? window : global;
</code>```

and is part of the seed-random library used in mathjs.
I know that window is typically undefined in a webworker, however global should be set as far as I understand.
In the webpack config that the angular-devkit uses internally, I found the follwing section:

```<code>{
  plugins: [new WorkerPlugin({
    globalObject: false,
    plugins: [getTypescriptWorkerPlugin(wco, workerTsConfigPath)],
  })],
}
</code>```

There, I already tried setting globalObject to self or this in my local node_modules folder, however this did not solve the problem.
I also don't see an option in the angular.json file to provide any additional configuration for the webworker to fix this problem, so I am unsure what to do to make this work.
In the mathjs documentation, I found an example of using it in a webworker, so I assume it should also be possible using the Angular CLI.

I created a GitHub repo with a minimal working example. If you run it with

```<code>npm install
npm start
</code>```

you can see the described error in the browser console.

So my question is: How can I use mathjs in an Angular CLI webworker?

答:
I opened an issue on the math.js GitHub where another workaround was proposed:
It seems to be sufficient to just change the import from

```<code>import { sqrt } from 'mathjs';
</code>```

to

```<code>import { sqrt } from 'mathjs/dist/math.js';
</code>```

to fix the webworker.

This workaround is fairly simple and seems to work. However, this problem might be solved in future versions of math.js. It might make sense to check the issue for updates on this.

Body:
I am currently trying add a webworker to my Angular 9 project using Angular CLI 9.1.7.
This webworker should run some calculations using mathjs 7.

However, importing mathjs into the webworker always results in the following error in the browser console.
If I don't import mathjs, the worker runs without a problem.

index.js:7 Uncaught ReferenceError: window is not defined
    at Object../node_modules/seed-random/index.js (index.js:7)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/function/probability/util/seededRNG.js (seededRNG.js:1)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/function/probability/pickRandom.js (pickRandom.js:1)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/factoriesAny.js (factoriesAny.js:1)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/mathjs/es/entry/pureFunctionsAny.generated.js (pureFunctionsAny.generated.js:1)
    at __webpack_require__ (bootstrap:19)

The referenced line is

var GLOBAL = typeof global === 'undefined' ? window : global;

and is part of the seed-random library used in mathjs.
I know that window is typically undefined in a webworker, however global should be set as far as I understand.
In the webpack config that the angular-devkit uses internally, I found the follwing section:

{
  plugins: [new WorkerPlugin({
    globalObject: false,
    plugins: [getTypescriptWorkerPlugin(wco, workerTsConfigPath)],
  })],
}

There, I already tried setting globalObject to self or this in my local node_modules folder, however this did not solve the problem.
I also don't see an option in the angular.json file to provide any additional configuration for the webworker to fix this problem, so I am unsure what to do to make this work.
In the mathjs documentation, I found an example of using it in a webworker, so I assume it should also be possible using the Angular CLI.

I created a GitHub repo with a minimal working example. If you run it with

npm install
npm start

you can see the described error in the browser console.

So my question is: How can I use mathjs in an Angular CLI webworker?

Body:
I opened an issue on the math.js GitHub where another workaround was proposed:
It seems to be sufficient to just change the import from

import { sqrt } from 'mathjs';

to

import { sqrt } from 'mathjs/dist/math.js';

to fix the webworker.

This workaround is fairly simple and seems to work. However, this problem might be solved in future versions of math.js. It might make sense to check the issue for updates on this.


问:
SwiftUI Timer.publish causing whole screen to refresh
GIF of Entire Screen Refreshing

I am currently learning combine and MVVM.  My problem is when I try to use a timer.publish, eventually I'm going to create a stop button, it causes the entire screen to refresh instead of the Text I have .onReceive.

I was hoping someone could provide me some insight on how I'm using publishers and observers incorrectly.

View:

```<code>import SwiftUI
import Combine

struct ApptCardView: View {

    @ObservedObject var apptCardVM: ApptCardViewModel
    @State var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
            Text("\(currentDate)")
                .onReceive(timer) { input in
                    self.currentDate = input
                   }
            Picker("Seizure Type", selection: $apptCardVM.typeIndex) {
            ForEach(0..<apptCardVM.typeChoice.count) {
                Text(self.apptCardVM.typeChoice[$0])
            }
        }.pickerStyle(SegmentedPickerStyle())

        }

    }
}
</code>```

View Model:

```<code>import Foundation
import Combine

class ApptCardViewModel: ObservableObject, Identifiable {

    @Published var appt: ApptEvent
    @Published var typeChoice = ["Quick", "Long", "FullService"]
    @Published var typeIndex: Int = 0

    private var cancellables = Set<AnyCancellable>()

    init(appt: ApptEvent) {
        self.appt = appt
    }

}
</code>```

答:
If you want to refresh only a part of body, then separate that part into dedicated subview, eg:</p>

```<code>struct ApptCardView: View {

    @ObservedObject var apptCardVM: ApptCardViewModel

    var body: some View {
        VStack {
            CurrentDateView()  // << here !!

            Picker("Seizure Type", selection: $apptCardVM.typeIndex) {
            ForEach(0..<apptCardVM.typeChoice.count) {
                Text(self.apptCardVM.typeChoice[$0])
            }
        }.pickerStyle(SegmentedPickerStyle())

        }

    }
}

struct CurrentDateView: View {
    @State private var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    var body: some View {
        Text("\(currentDate)")
            .onReceive(timer) { input in
                self.currentDate = input // << refresh only own body !!
        }
    }
}
</code>```

Body:
GIF of Entire Screen Refreshing

I am currently learning combine and MVVM.  My problem is when I try to use a timer.publish, eventually I'm going to create a stop button, it causes the entire screen to refresh instead of the Text I have .onReceive.

I was hoping someone could provide me some insight on how I'm using publishers and observers incorrectly.

View:

import SwiftUI
import Combine

struct ApptCardView: View {

    @ObservedObject var apptCardVM: ApptCardViewModel
    @State var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
            Text("\(currentDate)")
                .onReceive(timer) { input in
                    self.currentDate = input
                   }
            Picker("Seizure Type", selection: $apptCardVM.typeIndex) {
            ForEach(0..<apptCardVM.typeChoice.count) {
                Text(self.apptCardVM.typeChoice[$0])
            }
        }.pickerStyle(SegmentedPickerStyle())

        }

    }
}

View Model:

import Foundation
import Combine

class ApptCardViewModel: ObservableObject, Identifiable {

    @Published var appt: ApptEvent
    @Published var typeChoice = ["Quick", "Long", "FullService"]
    @Published var typeIndex: Int = 0

    private var cancellables = Set<AnyCancellable>()

    init(appt: ApptEvent) {
        self.appt = appt
    }

}

Body:
If you want to refresh only a part of body, then separate that part into dedicated subview, eg:

struct ApptCardView: View {

    @ObservedObject var apptCardVM: ApptCardViewModel

    var body: some View {
        VStack {
            CurrentDateView()  // << here !!

            Picker("Seizure Type", selection: $apptCardVM.typeIndex) {
            ForEach(0..<apptCardVM.typeChoice.count) {
                Text(self.apptCardVM.typeChoice[$0])
            }
        }.pickerStyle(SegmentedPickerStyle())

        }

    }
}

struct CurrentDateView: View {
    @State private var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    var body: some View {
        Text("\(currentDate)")
            .onReceive(timer) { input in
                self.currentDate = input // << refresh only own body !!
        }
    }
}


问:
State list of world with country-code
Where can I found the list of all the states of world with their country code (ISO2 or ISO3).

I have to insert all these states in my database. If the list is available in the .sql will be great.

I need state list of world with country-code not the country list.

Do you know where can I found?

Thanks in Advance.

答:
http://www.timdavis.com.au/data/

There is a link to a excel spreadsheet of all the country and state information.

Title: State list of world with country-code


问:
Evaluation order in ternary operator with increments
```<code>#define MAX(a,b) ((a)>(b) ? (a) : (b))
   int main(void) {
   int a=2;
   int b=3;

   int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
   printf("\na= %d", a);// a=3
   printf("\nb= %d", b);//b=5
   printf("\nc= %d", c);//c=4

   a=3;
   b=2;
   cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));

   printf("\na= %d", a); // a=5
   printf("\nb= %d", b); //b=3
   printf("\nc= %d", c); //c=4

return 0;
}
</code>```

I would like to know why c is not evaluating to 5.

It appears to me the evaluation order should be:

First both a and be get incremented in  (a++)>(b++)

If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to  (a++), so a
increments again.

The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.

Any idea?

答:
Let's consider for example this declaration

```<code>int c = MAX(a++,b++);
</code>```

after the macro substitution there will be

```<code>int c = (( a++) >( b++ ) ? (a++) : (b++));
</code>```

The variables a and b are initialized like

```<code>int a=2;
int b=3;
</code>```

As a is less than b then the third expression (b++) will be evaluated as a result of the conditional operator. In the first expression ( a++) >( b++ ) a and b were incremented. There is a sequence point after the evaluation of the first expression.

So a will be set to 3, b will be set to 4.

As it was already said the value of the conditional operator is the value of the third expression (b++) where there is used the post-increment. The value of the post-increment operator is the value of its operand before incrementing.

From the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix ++ operator is the value of the
  operand. As a side effect, the value of the operand object is
  incremented (that is, the value 1 of the appropriate type is added to
  it).

So the value of the conditional operator is 4. This value will be assigned to the variable c. But as a side effect the value of b will be incremented.

Thus after this declaration a will be equal to 3, b will be equal to 5 and c will be equal to 4.

For clarity this declaration

```<code>int c = (( a++) >( b++ ) ? (a++) : (b++));
</code>```

in fact can be rewritten in the logically equivalent way.

```<code>int result = a > b;
++a;
++b;

int c;

if ( result != 0 )
{
    c = a++;
}
else
{
    c = b++;
}
</code>```

Body:
#define MAX(a,b) ((a)>(b) ? (a) : (b))
   int main(void) {
   int a=2;
   int b=3;

   int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
   printf("\na= %d", a);// a=3
   printf("\nb= %d", b);//b=5
   printf("\nc= %d", c);//c=4

   a=3;
   b=2;
   cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));

   printf("\na= %d", a); // a=5
   printf("\nb= %d", b); //b=3
   printf("\nc= %d", c); //c=4

return 0;
}

I would like to know why c is not evaluating to 5.

It appears to me the evaluation order should be:

First both a and be get incremented in  (a++)>(b++)

If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to  (a++), so a
increments again.

The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.

Any idea?

Body:
Let's consider for example this declaration

int c = MAX(a++,b++);

after the macro substitution there will be

int c = (( a++) >( b++ ) ? (a++) : (b++));

The variables a and b are initialized like

int a=2;
int b=3;

As a is less than b then the third expression (b++) will be evaluated as a result of the conditional operator. In the first expression ( a++) >( b++ ) a and b were incremented. There is a sequence point after the evaluation of the first expression.

So a will be set to 3, b will be set to 4.

As it was already said the value of the conditional operator is the value of the third expression (b++) where there is used the post-increment. The value of the post-increment operator is the value of its operand before incrementing.

From the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix ++ operator is the value of the
  operand. As a side effect, the value of the operand object is
  incremented (that is, the value 1 of the appropriate type is added to
  it).

So the value of the conditional operator is 4. This value will be assigned to the variable c. But as a side effect the value of b will be incremented.

Thus after this declaration a will be equal to 3, b will be equal to 5 and c will be equal to 4.

For clarity this declaration

int c = (( a++) >( b++ ) ? (a++) : (b++));

in fact can be rewritten in the logically equivalent way.

int result = a > b;
++a;
++b;

int c;

if ( result != 0 )
{
    c = a++;
}
else
{
    c = b++;
}


问:
How can I create SQL table keys with items from looping through a list in Python
I have a list called headers of about 40-50 items, and I'm trying to make them all keys in a table. I'm trying to avoid typing them all out, here's what I have so far:

```<code>def createtable_db():
    cnx = mysql.connector.connect(user='x', password='x', host='x', database='data')

    mycursor = cnx.cursor()

    create_table = "CREATE TABLE IF NOT EXISTS players (id INT AUTO_INCREMENT PRIMARY KEY)"

    for h in headers:
        pop_table = "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

    mycursor.execute(create_table)
    mycursor.execute(pop_table)

    cnx.close()

createtable_db()
</code>```

This only adds the very last key, I tried adding a + to make this line:

```<code> pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"
</code>```

but that's also not working: it gives me a syntax error.

答:
```<code>pop_table = "ALTER TABLE players "
for h in headers:
    pop_table += "ADD COLUMN "+ h + " VARCHAR(255), "

#Replace the last , with a ;
pop_table.replace(pop_table[len(pop_table)-1], ';')
mycursor.execute(create_table)
mycursor.execute(pop_table, multi=True)
</code>```

Maybe if you did it like this? Sorry its been a while since I used mysql.connector. If I remember correctly, multi must be set to True if you intend to execute more than one command.

Body:
I have a list called headers of about 40-50 items, and I'm trying to make them all keys in a table. I'm trying to avoid typing them all out, here's what I have so far:

def createtable_db():
    cnx = mysql.connector.connect(user='x', password='x', host='x', database='data')

    mycursor = cnx.cursor()

    create_table = "CREATE TABLE IF NOT EXISTS players (id INT AUTO_INCREMENT PRIMARY KEY)"

    for h in headers:
        pop_table = "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

    mycursor.execute(create_table)
    mycursor.execute(pop_table)

    cnx.close()

createtable_db()

This only adds the very last key, I tried adding a + to make this line:

 pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

but that's also not working: it gives me a syntax error.

Body:
pop_table = "ALTER TABLE players "
for h in headers:
    pop_table += "ADD COLUMN "+ h + " VARCHAR(255), "

#Replace the last , with a ;
pop_table.replace(pop_table[len(pop_table)-1], ';')
mycursor.execute(create_table)
mycursor.execute(pop_table, multi=True)

Maybe if you did it like this? Sorry its been a while since I used mysql.connector. If I remember correctly, multi must be set to True if you intend to execute more than one command.


问:
Sharing update on linkedin doesn't scrape/pull page title and content
I am working on a website and we have a requirement for allowing our clients to share their pages on LinkedIn.

We have implemented a share button using AddThis which seems to work fine for LinkedIn, but manually sharing any of the pages that work fine with LinkedIn (via the Share Update functionality of our accounts) doesn't seem to work as expected.

When manually sharing a link, the link to the page is properly generated, however the title and descriptive text of the page (we're talking about news articles) are not filled all of the time.

It seems that most of the time we are getting the 404 page's title and content, and sometimes just the 404 page's title and the targeted page's content.

Has anyone else encountered this issue? If so, could you tell me where the information is pulled from and how?

答:
To prepopulate a preview of your site's title, image, etc., you'll need to use og: tags, for instance...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

You would insert these into the  block of your HTML.

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

You can verify that you implemented correctly by using the LinkedIn Post Inspector on your website's URL.

Body:
To prepopulate a preview of your site's title, image, etc., you'll need to use og: tags, for instance...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

You would insert these into the <head> block of your HTML.

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

You can verify that you implemented correctly by using the LinkedIn Post Inspector on your website's URL.


问:
Beautifulsoup + HTML...how to ignore a few h3 classes
I got the following code:

```<code>from bs4 import BeautifulSoup
import requests
import re

source = requests.get('https://tienda.mimo.com.ar/mimo/junior/ropa-para-ninas.html').text

soup = BeautifulSoup(source, 'lxml')

for name_product, old_price, special_price in zip(soup.select('h3', class_='titprod'),
                                                  soup.select('span[id^="old-price"]'),
                                                  soup.select('span[id^="product-price"]')):
    print(f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_price.text.strip()}')
</code>```

that outputs:

Name: Para acceder a la promoción seleccione el banco y la tarjeta de crédito que corresponda |  Old price = $ 295 | Discounted price = $ 236
Name: ¡Gracias por suscribirte al newsletter! |  Old price = $ 990 | Discounted price = $ 743
Name: Elegí por talle |  Old price = $ 2.300 | Discounted price = $ 1.725
Name: TAPABOCAS |  Old price = $ 1.550 | Discounted price = $ 1.163
Name: REMERA JR TOWN |  Old price = $ 2.990 | Discounted price = $ 2.243
Name: CAMISOLA NENA DELFI |  Old price = $ 1.990 | Discounted price = $ 1.493```

As you can see instead of taking the proper Product's names. Its actually taking what it says on the header on the very first two lines (Name: Para acceder a la promoción seleccione el banco y la tarjeta de crédito que corresponda...... ) , which are using the same css_selector (titprod). Don't know how to get deep into the LI class (rounded black square) to get to the proper name of the product (rounded red square).
Due to this the list is misplaced, causing the prices to not correspond to the name of the product on each line.

答:
I had to change

```<code>soup.select('h3', class_='titprod'),
</code>```

for

```<code>soup.select('h3.titprod')
</code>```

as @AndrejKessely suggested on the comments and it works perfectly

Body:
I got the following code:

from bs4 import BeautifulSoup
import requests
import re

source = requests.get('https://tienda.mimo.com.ar/mimo/junior/ropa-para-ninas.html').text

soup = BeautifulSoup(source, 'lxml')

for name_product, old_price, special_price in zip(soup.select('h3', class_='titprod'),
                                                  soup.select('span[id^="old-price"]'),
                                                  soup.select('span[id^="product-price"]')):
    print(f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_price.text.strip()}')

that outputs:

Name: Para acceder a la promoción seleccione el banco y la tarjeta de crédito que corresponda |  Old price = $ 295 | Discounted price = $ 236
Name: ¡Gracias por suscribirte al newsletter! |  Old price = $ 990 | Discounted price = $ 743
Name: Elegí por talle |  Old price = $ 2.300 | Discounted price = $ 1.725
Name: TAPABOCAS |  Old price = $ 1.550 | Discounted price = $ 1.163
Name: REMERA JR TOWN |  Old price = $ 2.990 | Discounted price = $ 2.243
Name: CAMISOLA NENA DELFI |  Old price = $ 1.990 | Discounted price = $ 1.493

As you can see instead of taking the proper Product's names. Its actually taking what it says on the header on the very first two lines (Name: Para acceder a la promoción seleccione el banco y la tarjeta de crédito que corresponda...... ) , which are using the same css_selector (titprod). Don't know how to get deep into the LI class (rounded black square) to get to the proper name of the product (rounded red square).
Due to this the list is misplaced, causing the prices to not correspond to the name of the product on each line.

Body:
I had to change

soup.select('h3', class_='titprod'),

for

soup.select('h3.titprod')

as @AndrejKessely suggested on the comments and it works perfectly


问:
check permissions of directories in python
i want a python program that given a directory, it will return all directories within that directory that have 775 (rwxrwxr-x) permissions

thanks!

答:
You can check 775 permission for files and directories using below command</p>

```<code>path="location of file or directory"
if (oct(os.stat(path).st_mode)[-3:]=="775"):
    print(path)
</code>```

OwnerDisplayName: donge

LastEditorDisplayName: vartec

ContentLicense: CC BY-SA 2.5

Body:
You can check 775 permission for files and directories using below command

path="location of file or directory"
if (oct(os.stat(path).st_mode)[-3:]=="775"):
    print(path)


问:
unable to run librdkafka=1.3.0 over docker
I was trying to run librdkafka version 1.3.0 from alpine distribution over my docker container using this:

```<code>FROM golang:1.13.6-alpine3.10 as base

RUN apk add --no-cache --update librdkafka=1.3.0 librdkafka-dev=1.3.0 --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/community
</code>```

but got this error while building image:

```<code>librdkafka-1.4.2-r0:
    breaks: world[librdkafka=1.3.0]
    satisfies: librdkafka-dev-1.4.2-r0[librdkafka=1.4.2-r0]
  librdkafka-dev-1.4.2-r0:
    breaks: world[librdkafka-dev=1.3.0]
</code>```

Can someone tell me what might be possibly wrong here?

答:
The librdkafka package has been upgraded to 1.4.2.

In Alpine repositories, as opposed to Ubuntu for example, old package versions are not kept. This is mostly done for security reasons, AFAICT. When a package is upgraded, the old version is gone for good. This has the unfortunate side effect of breaking images that depend on specific package versions.

The currently available librdkafka 1.X versions on Alpine repositories are 1.4.2 (edge, 3.12), 1.2.2 (3.11), and 1.0.1 (3.10).

If you must use this exact version, you could try building it from source, using the 1.3.0 tag.

Body:
I was trying to run librdkafka version 1.3.0 from alpine distribution over my docker container using this:

FROM golang:1.13.6-alpine3.10 as base

RUN apk add --no-cache --update librdkafka=1.3.0 librdkafka-dev=1.3.0 --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/community

but got this error while building image:

librdkafka-1.4.2-r0:
    breaks: world[librdkafka=1.3.0]
    satisfies: librdkafka-dev-1.4.2-r0[librdkafka=1.4.2-r0]
  librdkafka-dev-1.4.2-r0:
    breaks: world[librdkafka-dev=1.3.0]

Can someone tell me what might be possibly wrong here?


问:
Aggregate Two Variables by One Date
I have the following dataset I am working with:

```<code>     day descent_cd
   <int> <chr>
 1    26 B
 2    19 W
 3    19 B
 4    16 B
 5     1 W
 6     2 W
 7     2 B
 8     2 B
 9     3 W
10     3 W
# … with 1,283 more rows
</code>```

In short: the "day" variable is the day of the month. "Descent_cd" is race (black or white).

I am trying to organize it so that I get a column for "B" and a column for "W" both sorted by total arrest made that day ... meaning: counting all the "B"s for day "1" and the same for "W" and then so on and so forth through the rest of the month.

I ultimately want to do this as a geom_ridge graph.

答:
Is this what you are looking for?</p>

```<code>library(tidyverse)
#sample data
df <- tibble::tribble(
  ~day, ~descent_cd,
    26L,      "B",
   19L,         "W",
   19L,         "B",
   16L,         "B",
    1L,         "W",
    2L,         "W",
    2L,         "B",
    2L,         "B",
    3L,         "W",
    3L,         "W"
  )

df %>%
  group_by(day, descent_cd) %>%
  summarise(total_arrest = n()) %>% #calculate number of arrests per day per descent_cd
  pivot_wider(names_from = descent_cd, values_from = total_arrest) %>% #create columns W and B
  mutate(W = if_else(is.na(W),as.integer(0),W), #replace NAs with 0 (meaning 0 arrests that day)
         B = if_else(is.na(B),as.integer(0),B)) %>%
  arrange(desc(wt = W+B)) #arrange df in descending order of total arrests per day

# A tibble: 6 x 3
# Groups:   day [6]
    day     W     B
  <int> <int> <int>
1     2     1     2
2     3     2     0
3    19     1     1
4     1     1     0
5    16     0     1
6    26     0     1

</code>```

Title: Aggregate Two Variables by One Date

Body:
I have the following dataset I am working with:

     day descent_cd
   <int> <chr>
 1    26 B
 2    19 W
 3    19 B
 4    16 B
 5     1 W
 6     2 W
 7     2 B
 8     2 B
 9     3 W
10     3 W
# … with 1,283 more rows

In short: the "day" variable is the day of the month. "Descent_cd" is race (black or white).

I am trying to organize it so that I get a column for "B" and a column for "W" both sorted by total arrest made that day ... meaning: counting all the "B"s for day "1" and the same for "W" and then so on and so forth through the rest of the month.

I ultimately want to do this as a geom_ridge graph.

Body:
Is this what you are looking for?

library(tidyverse)
#sample data
df <- tibble::tribble(
  ~day, ~descent_cd,
    26L,      "B",
   19L,         "W",
   19L,         "B",
   16L,         "B",
    1L,         "W",
    2L,         "W",
    2L,         "B",
    2L,         "B",
    3L,         "W",
    3L,         "W"
  )

df %>%
  group_by(day, descent_cd) %>%
  summarise(total_arrest = n()) %>% #calculate number of arrests per day per descent_cd
  pivot_wider(names_from = descent_cd, values_from = total_arrest) %>% #create columns W and B
  mutate(W = if_else(is.na(W),as.integer(0),W), #replace NAs with 0 (meaning 0 arrests that day)
         B = if_else(is.na(B),as.integer(0),B)) %>%
  arrange(desc(wt = W+B)) #arrange df in descending order of total arrests per day

# A tibble: 6 x 3
# Groups:   day [6]
    day     W     B
  <int> <int> <int>
1     2     1     2
2     3     2     0
3    19     1     1
4     1     1     0
5    16     0     1
6    26     0     1


问:
Open a new tab with javascript but stay on current tab
Is it possible to open a new tab in Firefox (in background) using window.open("http://www.google.com") function, and remain the current tab?

Thanks for any help

答:
Whether or not to focus a new tab when it is opened is a browser setting and not something that you can control.

Opening links in a new tab at all (rather than a separate window) is a browser setting too, so you're facing an uphill battle with this one.

Basically, leave it up to the user to decide how they want to open links.


问:
Changing colors of chart elements in r-highcharter
I have line chart with 25 lines, but want to color only 3 of them and others make grey, how can I do it?</p>

答:
You can use Highcharter's hc_chart function to include chart.events.load event in which you can fire custom JavaScript code. Use JS("") function to inject JavaScript code into R.
In that JavaScript code, you can loop through all series and update their colors using series.update() method.

I did exactly the same today here: How to change the color of marker-points dynamically based on y-position
but instead of series, I changed the markers' color.

API Reference: https://api.highcharts.com/highcharts/chart.events.load
https://api.highcharts.com/class-reference/Highcharts.Series#update

Here is a JavaScript demo showing it: https://jsfiddle.net/BlackLabel/cyhd5Ln2/

```<code>var series = [];

for (let i = 0; i < 15; i++) {
    series.push({
        data: [5 + i, 6 + i, 3 + i, 4 + i]
    });
}

Highcharts.chart('container', {

    chart: {
        events: {
            load: function () {
                this.series.forEach(function (series, i) {
                    if (i < 3) {
                        series.update({
                            color: 'red'
                        }, false);
                    } else {
                        series.update({
                            color: 'grey'
                        }, false);
                    }
                });
                this.redraw();
            }
        }
    },

  series: series

});
</code>```

Instead of updating the chart 15 times (which is a performance killing when you have more series), I updated with redraw flag: false and after the for loop I did chart.redraw() just once.

Body:
You can use Highcharter's hc_chart function to include chart.events.load event in which you can fire custom JavaScript code. Use JS("") function to inject JavaScript code into R.
In that JavaScript code, you can loop through all series and update their colors using series.update() method.

I did exactly the same today here: How to change the color of marker-points dynamically based on y-position
but instead of series, I changed the markers' color.

API Reference: https://api.highcharts.com/highcharts/chart.events.load
https://api.highcharts.com/class-reference/Highcharts.Series#update

Here is a JavaScript demo showing it: https://jsfiddle.net/BlackLabel/cyhd5Ln2/

var series = [];

for (let i = 0; i < 15; i++) {
    series.push({
        data: [5 + i, 6 + i, 3 + i, 4 + i]
    });
}

Highcharts.chart('container', {

    chart: {
        events: {
            load: function () {
                this.series.forEach(function (series, i) {
                    if (i < 3) {
                        series.update({
                            color: 'red'
                        }, false);
                    } else {
                        series.update({
                            color: 'grey'
                        }, false);
                    }
                });
                this.redraw();
            }
        }
    },

  series: series

});

Instead of updating the chart 15 times (which is a performance killing when you have more series), I updated with redraw flag: false and after the for loop I did chart.redraw() just once.


问:
Error: ENOENT, no such file or directory - fs.createReadStream that is piped into a fs.createWriteStream
Below is my code where I am trying to use fs.createReadStream that is piped into a fs.createWriteStream. Its working for one hit. But if I run the same code using concurrent hits getting error as

Error: ENOENT, no such file or directory

```<code>var fileReadStream = fs.createReadStream("test.png", {encoding: "utf16le"});
var fileWriteStream = fs.createWriteStream("test1.png", {encoding: "utf16le"});
fileReadStream.pipe(fileWriteStream);
fileReadStream.on('end', function () {
});
fileWriteStream.on('close', function () {
    fileReadStream.on('finish', function () {
        fs.unlink(test1.png);
    })

})
</code>```

I am not that good in filesystem api's. Can someone help me what I am doing wrong here.

答:
Add __dirname + '/test.png' that fixed my error</p>

```<code> var fileReadStream = fs.createReadStream(__dirname + <path to image From current directory>, {encoding: "utf16le"});
var fileWriteStream = fs.createWriteStream(__dirname + <path to image From current directory>, {encoding: "utf16le"});
</code>```

Body:
Below is my code where I am trying to use fs.createReadStream that is piped into a fs.createWriteStream. Its working for one hit. But if I run the same code using concurrent hits getting error as

Error: ENOENT, no such file or directory

var fileReadStream = fs.createReadStream("test.png", {encoding: "utf16le"});
var fileWriteStream = fs.createWriteStream("test1.png", {encoding: "utf16le"});
fileReadStream.pipe(fileWriteStream);
fileReadStream.on('end', function () {
});
fileWriteStream.on('close', function () {
    fileReadStream.on('finish', function () {
        fs.unlink(test1.png);
    })

})

I am not that good in filesystem api's. Can someone help me what I am doing wrong here.

Body:
Add __dirname + '/test.png' that fixed my error

 var fileReadStream = fs.createReadStream(__dirname + <path to image From current directory>, {encoding: "utf16le"});
var fileWriteStream = fs.createWriteStream(__dirname + <path to image From current directory>, {encoding: "utf16le"});


答:
The problem is that you are using select() method wrong way. To select all
 with class=titprod, you need to write soup.select('h3.titprod').

The class_= parameter belongs to .find() and .find_all() functions (that don't take CSS selectors).

Link to .find_all() in the bs4 documentation.

Examples of CSS selectors from the bs4 documentation.

Title: Beautifulsoup + HTML...how to ignore a few h3 classes

Body:
The problem is that you are using select() method wrong way. To select all <h3> with class=titprod, you need to write soup.select('h3.titprod').

The class_= parameter belongs to .find() and .find_all() functions (that don't take CSS selectors).

Link to .find_all() in the bs4 documentation.

Examples of CSS selectors from the bs4 documentation.


问:
Can you recommend a couple of really good AS3 and MXML editors for Mac?
I've just switched from Windows to Mac and need to find a few tools to replace those that were Windows-only.  I'm most familiar with FlashDevelop, which I've used for years, but it is Windows only.  SEPY seems to have been abandoned, FlashIDE's editor seems weak, and I don't want to purchase FDT or FlexBuilder right now.

I would like an editor that is as good as FlashDevelop at auto-completion and syntax highlight for AS3 and MXML, is highly customizable, and can thus be configured to call external scripts and applications, such as ant, javac, mxmlc, and python with a custom button or hotkey.  Also, it would be great if it is lightweight and isn't too pushy about using it's own project folder/management like Eclipse/FlexBuilder/FDT.  I often only need to build a single AS3 file or MXML file and don't like the project setup time or having my own folders littered with project metadata files.

Can you recommend a couple of really good AS3 and MXML editors for Mac?

答:
Textmate is your guy. Super lightweight, infinitely customizable with loads of lovely plug-ins and "bundles" (syntax, auto-complete, snippets, macros, commands). There's an AS3 bundle as well that adds ant, mxmlc, etc. It's also really fun to make custom color-highlighting for. It's not for everyone–it's definitely very lightweight (don't expect an IDE), but if you work with it for awhile, you'll see why it's one of mac-user's favorites.

http://macromates.com/

Edit:

Coda is a sexy little app by Panic (makers of Transmit FTP, the de-facto ftp program for Mac) that wraps css editors, text editors, a terminal window, FTP, and more into one tab-paneled application. I personally found it to be too stripped down in each department, but it does make a great application overall if it suits your needs. I know a few programmers and project managers who use it and love it.

http://www.panic.com/coda/

Also, Xcode (the free Mac development IDE) can be very nicely configured to work with AS3. I've been developing with it in Objective-C recently and the code-completion and hinting is brilliant. If you can get something like the following rocking with AS3, it could be pretty badass.

http://blog.joshbuhler.com/xcodeflex/

and

http://opencode.forabettertoday.org/?p=3

Other than that, your options are pretty limited until FlashDevelop comes to Mac. I know that using Flash's editor sure as heck isn't an option! They might as well not include it in the next Flash! ;)

OwnerDisplayName: TypeOneError

LastEditorDisplayName: TypeOneError


问:
SQL where clause with case statement
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

```<code>AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END
</code>```

I'm not sure how to process the -1 to say select all users

Thanks

答:
you can change the clause like this to return all users...

```<code>AND ( @user = -1
    OR usertable.userid = @user
)
</code>```

No need of case statement this way...

Title: SQL where clause with case statement

Body:
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END

I'm not sure how to process the -1 to say select all users

Thanks

Body:
you can change the clause like this to return all users...

AND ( @user = -1
    OR usertable.userid = @user
)

No need of case statement this way...