问:
ANDROID: email client receiver email id empty in android-parse
I'm using android- parse server in app.  below is parse db screenshot of email column .
the email column is after the hidden password column in database .

my problem is

when i retrieve email ids to email client,
email is null even if the email column has emails .

note : in the app in another place (another table) i'm pulling email ids to email client in same manner, but there mail is showing well .. only here the problem occurs.

if anyone knows please help ?

this is email column in parse database

```<code> try{
                        JSONObject jsonObject = parseObjectToJson(object);
                        Log.d("Object", jsonObject.toString());
                        Log.d("Email", "+" + object.get("email"));
                        personNumber = jsonObject.getString("telephone");
                        personEmail = jsonObject.getString("email");
                    }catch (JSONException je){

                    }catch (ParseException pe){

                    }
</code>```

this is  email button

```<code>  emailPerson = (Button)findViewById(R.id.individualEmail);
            emailPerson.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setData(Uri.parse("mailto:"));
                    i.setType("plain/text");
                    i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {personEmail});
                    startActivity(i);
                }
            });
            if(personEmail==null || personEmail.equals("")  || personEmail.equals(" ")){
                emailPerson.setClickable(false);
                emailPerson.setEnabled(false);
                emailPerson.setVisibility(View.GONE);
            }
            else{
                emailPerson.setEnabled(true);
                emailPerson.setClickable(true);
                emailPerson.setVisibility(View.VISIBLE);
            }
</code>```

here it is working fine but this is a different table in same database . >in this table there is no hidden password field

```<code>try{
                            corporateEmail = jsonObject.getString("email");
                            if(corporateEmail == null || corporateEmail.equals("")){
                                emailCorporate.setVisibility(View.GONE);
                                emailCorporate.setEnabled(false);
                                emailCorporate.setClickable(false);
                            }
</code>```

```<code>emailCorporate = (Button) findViewById(R.id.corporateEmail);
        emailCorporate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setData(Uri.parse("mailto:"));
                i.setType("plain/text");
                i.putExtra(Intent.EXTRA_EMAIL, new String[] {corporateEmail});
                startActivity(i);
            }
        });
</code>```

```<code> private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException, com.parse.ParseException {
        JSONObject jsonObject = new JSONObject();
        parseObject.fetchIfNeeded();
        Set<String> keys = parseObject.keySet();
        for (String key : keys) {
            Object objectValue = parseObject.get(key);
            if (objectValue instanceof ParseObject) {
                jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));
            } else if (objectValue instanceof ParseRelation) {
            } else {
                jsonObject.put(key, objectValue.toString());
            }
        }
        return jsonObject;
    }
</code>```

答: if jsonObject is not null check to see if the parse database you are pulling your data from has the the "email" tag</p>

Body:
I'm using android- parse server in app.  below is parse db screenshot of email column .
the email column is after the hidden password column in database .

my problem is

when i retrieve email ids to email client,
email is null even if the email column has emails .

note : in the app in another place (another table) i'm pulling email ids to email client in same manner, but there mail is showing well .. only here the problem occurs.

if anyone knows please help ?

this is email column in parse database

 try{
                        JSONObject jsonObject = parseObjectToJson(object);
                        Log.d("Object", jsonObject.toString());
                        Log.d("Email", "+" + object.get("email"));
                        personNumber = jsonObject.getString("telephone");
                        personEmail = jsonObject.getString("email");
                    }catch (JSONException je){

                    }catch (ParseException pe){

                    }

this is  email button

  emailPerson = (Button)findViewById(R.id.individualEmail);
            emailPerson.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setData(Uri.parse("mailto:"));
                    i.setType("plain/text");
                    i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {personEmail});
                    startActivity(i);
                }
            });
            if(personEmail==null || personEmail.equals("")  || personEmail.equals(" ")){
                emailPerson.setClickable(false);
                emailPerson.setEnabled(false);
                emailPerson.setVisibility(View.GONE);
            }
            else{
                emailPerson.setEnabled(true);
                emailPerson.setClickable(true);
                emailPerson.setVisibility(View.VISIBLE);
            }

here it is working fine but this is a different table in same database . >in this table there is no hidden password field

try{
                            corporateEmail = jsonObject.getString("email");
                            if(corporateEmail == null || corporateEmail.equals("")){
                                emailCorporate.setVisibility(View.GONE);
                                emailCorporate.setEnabled(false);
                                emailCorporate.setClickable(false);
                            }

emailCorporate = (Button) findViewById(R.id.corporateEmail);
        emailCorporate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setData(Uri.parse("mailto:"));
                i.setType("plain/text");
                i.putExtra(Intent.EXTRA_EMAIL, new String[] {corporateEmail});
                startActivity(i);
            }
        });

 private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException, com.parse.ParseException {
        JSONObject jsonObject = new JSONObject();
        parseObject.fetchIfNeeded();
        Set<String> keys = parseObject.keySet();
        for (String key : keys) {
            Object objectValue = parseObject.get(key);
            if (objectValue instanceof ParseObject) {
                jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));
            } else if (objectValue instanceof ParseRelation) {
            } else {
                jsonObject.put(key, objectValue.toString());
            }
        }
        return jsonObject;
    }


来源: stackexchange

问:
Eclipse is freezing itself before getting started
I've been trying to open Eclipse to start my work today, and it freezes everytime during load.

My Eclipse is Helios. Someone told me I should remove a file called .lock from .metadata folder, but still didn't work.

Does anyone have any idea of how do I "melt" this thing up?

ps: I opened it yesterday with no problems.

答:
Start it with the -clean option.

It should take a bit longer (depends on your eclipse configuration and workspace, but if nothing is really broken, it will get it to work).

ContentLicense: CC BY-SA 2.5


问:
SQL query is very slow
I have a query that is updating views and likes for posts for the last 24 hours, but it is very slow. For around 3000 posts it takes more than 15 seconds to complete, which is a big problem since other queries can't be executed during that period.

```<code>$update_query = mysqli_query($database, "UPDATE post SET
                likes_last_day = (SELECT COUNT(post_like_id) FROM post_like WHERE post.post_id = post_like.post_id AND post_like.date > ('$current_date' - INTERVAL 1 DAY)),
                views_last_day = (SELECT COUNT(post_view_id) FROM post_view WHERE post.post_id = post_view.post_id AND post_view.date > ('$current_date' - INTERVAL 1 DAY))");
</code>```

Is there a way to optimize this query to execute faster?

答: If performance is still an issue after adding indexes, you might think about executing this in a stored procedure, so db would reuse execution plan rather than building it for every ad hoc query. </p>

ContentLicense: CC BY-SA 3.0

Title: SQL query is very slow

Body:
I have a query that is updating views and likes for posts for the last 24 hours, but it is very slow. For around 3000 posts it takes more than 15 seconds to complete, which is a big problem since other queries can't be executed during that period.

$update_query = mysqli_query($database, "UPDATE post SET
                likes_last_day = (SELECT COUNT(post_like_id) FROM post_like WHERE post.post_id = post_like.post_id AND post_like.date > ('$current_date' - INTERVAL 1 DAY)),
                views_last_day = (SELECT COUNT(post_view_id) FROM post_view WHERE post.post_id = post_view.post_id AND post_view.date > ('$current_date' - INTERVAL 1 DAY))");

Is there a way to optimize this query to execute faster?


问:
Why isn't my range regex syntax working?
I'm using Ruby 2.4.  I want to say match a string that contains between 3 and 4 consecutive numbers.  But my braces syntax isn't working

```<code>2.4.0 :034 > data = "1234"
 => "1234"
2.4.0 :035 > data =~ /\d{3, 4}/
 => nil
</code>```

What's the ocrrect way to say this?

答:
Remove the space inside the limiting quantifier:

```<code>data =~ /\d{3,4}/
</code>```

If you want to match the entire string consisting of just 3 to 4 digits, use

```<code>data =~ /\A\d{3,4}\z/
</code>```

Details:

\A - start of string

\d{3,4} - 3 to 4 digits

\z - end of string.

See the Rubular demo.

Body:
I'm using Ruby 2.4.  I want to say match a string that contains between 3 and 4 consecutive numbers.  But my braces syntax isn't working

2.4.0 :034 > data = "1234"
 => "1234"
2.4.0 :035 > data =~ /\d{3, 4}/
 => nil

What's the ocrrect way to say this?

Body:
Remove the space inside the limiting quantifier:

data =~ /\d{3,4}/

If you want to match the entire string consisting of just 3 to 4 digits, use

data =~ /\A\d{3,4}\z/

Details:

\A - start of string

\d{3,4} - 3 to 4 digits

\z - end of string.

See the Rubular demo.


问:
Formatting all columns using mutate_all in dplyr
I'm looking at formatting a table using scales::dollar within mutate_all.

Desired results

The desired results can be obtained with use of the sapply:

```<code>>> sapply(mtcars, scales::dollar)
      mpg      cyl  disp      hp     drat    wt      qsec     vs   am   gear carb
 [1,] "$21.00" "$6" "$160.00" "$110" "$3.90" "$2.62" "$16.46" "$0" "$1" "$4" "$4"
 [2,] "$21.00" "$6" "$160.00" "$110" "$3.90" "$2.88" "$17.02" "$0" "$1" "$4" "$4"
 [3,] "$22.80" "$4" "$108.00" "$93"  "$3.85" "$2.32" "$18.61" "$1" "$1" "$4" "$1"
 [4,] "$21.40" "$6" "$258.00" "$110" "$3.08" "$3.22" "$19.44" "$1" "$0" "$3" "$1"
</code>```

Challenge

Attempt to achieve the same results via dplyr pipeline and scales::dollar:

```<code>mtcars %>% mutate_all(funs(scales::dollar(.)))
</code>```

fails:

```<code>Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) :
  values must be length 1,
 but FUN(X[[1]]) result is length 3
</code>```

Further exploration

A primitive workaround can be attempted:

```<code>mtcars %>% mutate_each(funs(as.character(paste0("$", .))))
</code>```

results:

```<code>>> mtcars %>% mutate_each(funs(as.character(paste0("$", .))))
     mpg cyl   disp   hp  drat     wt   qsec vs am gear carb
1    $21  $6   $160 $110  $3.9  $2.62 $16.46 $0 $1   $4   $4
2    $21  $6   $160 $110  $3.9 $2.875 $17.02 $0 $1   $4   $4
3  $22.8  $4   $108  $93 $3.85  $2.32 $18.61 $1 $1   $4   $1
</code>```

Following a similar discussion, the approach could be easily developed further to create the desired currency format, but this is not the point.

Question

Why scales::dollar(.) fails when applied within mutate_all (or mutate_each)? When
applied to vector elements it works as expected, shouldn't this behaviour be replicated along observations available in a column when passed within mutate_all / mutate_each:

```<code>>> scales::dollar(c(1, 1e4))
[1] "$1"      "$10,000"
</code>```

答:
We need to wrap with as.character as it seems to be a bug when we use package::function in the funs.  It is documented here

```<code>mtcars %>%
     mutate_each(funs(as.character(scales::dollar(.))))
</code>```

Besides, the function mutate_each is getting deprecated based on the blog link @Frank shared, so we can use mutate_at

```<code>mtcars %>%
       mutate_at(names(.), funs(as.character(scales::dollar(.))))
</code>```

The remedy would be to load the package and then call without the ::

```<code>library(scales)
mtcars %>%
    mutate_at(names(.), funs(dollar(.)))
</code>```

Or

```<code>mtcars %>%
        mutate_at(names(.), dollar)
</code>```

Body:
I'm looking at formatting a table using scales::dollar within mutate_all.

Desired results

The desired results can be obtained with use of the sapply:

>> sapply(mtcars, scales::dollar)
      mpg      cyl  disp      hp     drat    wt      qsec     vs   am   gear carb
 [1,] "$21.00" "$6" "$160.00" "$110" "$3.90" "$2.62" "$16.46" "$0" "$1" "$4" "$4"
 [2,] "$21.00" "$6" "$160.00" "$110" "$3.90" "$2.88" "$17.02" "$0" "$1" "$4" "$4"
 [3,] "$22.80" "$4" "$108.00" "$93"  "$3.85" "$2.32" "$18.61" "$1" "$1" "$4" "$1"
 [4,] "$21.40" "$6" "$258.00" "$110" "$3.08" "$3.22" "$19.44" "$1" "$0" "$3" "$1"

Challenge

Attempt to achieve the same results via dplyr pipeline and scales::dollar:

mtcars %>% mutate_all(funs(scales::dollar(.)))

fails:

Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) :
  values must be length 1,
 but FUN(X[[1]]) result is length 3

Further exploration

A primitive workaround can be attempted:

mtcars %>% mutate_each(funs(as.character(paste0("$", .))))

results:

>> mtcars %>% mutate_each(funs(as.character(paste0("$", .))))
     mpg cyl   disp   hp  drat     wt   qsec vs am gear carb
1    $21  $6   $160 $110  $3.9  $2.62 $16.46 $0 $1   $4   $4
2    $21  $6   $160 $110  $3.9 $2.875 $17.02 $0 $1   $4   $4
3  $22.8  $4   $108  $93 $3.85  $2.32 $18.61 $1 $1   $4   $1

Following a similar discussion, the approach could be easily developed further to create the desired currency format, but this is not the point.

Question

Why scales::dollar(.) fails when applied within mutate_all (or mutate_each)? When
applied to vector elements it works as expected, shouldn't this behaviour be replicated along observations available in a column when passed within mutate_all / mutate_each:

>> scales::dollar(c(1, 1e4))
[1] "$1"      "$10,000"

Body:
We need to wrap with as.character as it seems to be a bug when we use package::function in the funs.  It is documented here

mtcars %>%
     mutate_each(funs(as.character(scales::dollar(.))))

Besides, the function mutate_each is getting deprecated based on the blog link @Frank shared, so we can use mutate_at

mtcars %>%
       mutate_at(names(.), funs(as.character(scales::dollar(.))))

The remedy would be to load the package and then call without the ::

library(scales)
mtcars %>%
    mutate_at(names(.), funs(dollar(.)))

Or

mtcars %>%
        mutate_at(names(.), dollar)


问:
detect/set immutable on a file in Ruby
I am in need of a ruby way to detect if immutable is set on a file. If it is I need to remove it. Make my change to the file and then return it to immutability. I have looked at File and Fileutils,  I have searched but all I can find with immutable and ruby is how to make ruby objects and threads immutable, which is of course a different thing then what I am looking for. I am trying to avoid using the shell, I want to stick to ruby code if at all possible. I am imagining code something like this:</p>

```<code>file_name = '/boot/grub2/grub.cfg'
was_immutable = false
if File.immutable?(file_name)
    FileUtils.chattr '-i', file_name
    was_immutable = true
end
#my changes
if was_immutable
    FileUtils.chattr '+i', file_name
end
</code>```

答:
This might seem like an over-simplification, but you can probably see where it is going:

```<code>file_name = '/boot/grub2/grub.cfg'
a = %x[lsattr #{file_name}].chomp
puts a if a[/i/]
</code>```

Ok, so based on the link in the comments below, here is what I could come up with as a ruby version (if a guru around, happy to see how this should look):

```<code>#!/usr/bin/env ruby

require 'fcntl'

FS_IOC_GETFLAGS = 0x80086601
EXT3_IMMUTABLE_FL = 0x00000010
$count = 0

def check(filename)
    fd = IO.sysopen(filename, Fcntl::O_RDONLY)
    f = IO.new(fd)
    a = [0].pack("L_")
    f.ioctl(FS_IOC_GETFLAGS, a)

    unless a.unpack('L_')[0] & EXT3_IMMUTABLE_FL == 0
        puts "#{filename} is immutable :- a[0] = #{a[0].to_s}"
        $count += 1
    end

    f.close
end

ARGV.each do |arg|
    Dir[arg + '/*'].each do |item|
        check(item) if File.file?(item)
    end
end

exit(1) unless $count == 0
</code>```

Title: detect/set immutable on a file in Ruby

Body:
I am in need of a ruby way to detect if immutable is set on a file. If it is I need to remove it. Make my change to the file and then return it to immutability. I have looked at File and Fileutils,  I have searched but all I can find with immutable and ruby is how to make ruby objects and threads immutable, which is of course a different thing then what I am looking for. I am trying to avoid using the shell, I want to stick to ruby code if at all possible. I am imagining code something like this:

file_name = '/boot/grub2/grub.cfg'
was_immutable = false
if File.immutable?(file_name)
    FileUtils.chattr '-i', file_name
    was_immutable = true
end
#my changes
if was_immutable
    FileUtils.chattr '+i', file_name
end

Body:
This might seem like an over-simplification, but you can probably see where it is going:

file_name = '/boot/grub2/grub.cfg'
a = %x[lsattr #{file_name}].chomp
puts a if a[/i/]

Ok, so based on the link in the comments below, here is what I could come up with as a ruby version (if a guru around, happy to see how this should look):

#!/usr/bin/env ruby

require 'fcntl'

FS_IOC_GETFLAGS = 0x80086601
EXT3_IMMUTABLE_FL = 0x00000010
$count = 0

def check(filename)
    fd = IO.sysopen(filename, Fcntl::O_RDONLY)
    f = IO.new(fd)
    a = [0].pack("L_")
    f.ioctl(FS_IOC_GETFLAGS, a)

    unless a.unpack('L_')[0] & EXT3_IMMUTABLE_FL == 0
        puts "#{filename} is immutable :- a[0] = #{a[0].to_s}"
        $count += 1
    end

    f.close
end

ARGV.each do |arg|
    Dir[arg + '/*'].each do |item|
        check(item) if File.file?(item)
    end
end

exit(1) unless $count == 0


问:
linq2sql, repository pattern - how to query data from two or more tables?
I use Repository pattern (and linq2sql as data access) and have, for example, ProductsRep and CustomersRep.

In very simple scenario db has two tables -  Produsts (ProductID, CustomerID, ProductName, Date) and  Customer (CustomerID, FirstName, LastName).

Each repository provide methods to create, update, delete and get specific model object, and, may be, some filters.

But if I want to query all customers that buy specific product by product name, I have to get ProductID of this product using ProductsRep and then get all customers that buy product with this id using CustomersRep.

Am I right? This is actually two sql requests that l2s must generate, is it possible to do only one request?

And, in general, if we want to query data using multiple tables with relationships and repository pattern, how to do this by reduce amount of queries to minimum?

Thanks.

答:
```<code>var customers = from cust in CustomersRep
                join prod in ProductsRep on prod.CustomerID equals cust.CustomerID
                where prod.ProductName == yourInput
                select cust;
</code>```

You can write a query, similar to you would in SQL (essentially). In the above yourInput is the variable that holds the product name you're interested in.

This should give you a single DB query request, so long as ProductsRep and CustomersRep are in the same DB.

Body:
var customers = from cust in CustomersRep
                join prod in ProductsRep on prod.CustomerID equals cust.CustomerID
                where prod.ProductName == yourInput
                select cust;

You can write a query, similar to you would in SQL (essentially). In the above yourInput is the variable that holds the product name you're interested in.

This should give you a single DB query request, so long as ProductsRep and CustomersRep are in the same DB.


问:
Citrus Framework - Can a variable be assigned from a response?
I'm trying to test the following two REST calls:

Request 1

```<code>GET getLatestVersion
Response: {"version": 10}
</code>```

Request 2

```<code>POST getVersionData (body={"version": 10})
Response: {"version": 10, data: [...]}
</code>```

Is it possible to assign the "version" from Request 1 to a variable to use in Request 2 within the same test?

```<code>@CitrusTest(name = "SimpleIT.getVersionTest")
public void getVersionTest() {
    // Request 1
    http()
            .client("restClient")
            .send()
            .get("/getLatestVersion")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            // Can the version be assigned to a variable here?
            .payload("{\"version\":10}");

    // Request 2
    http()
            .client("restClient")
            .send()
            .post("/getVersionData")
            // Idealy this would be a Citrus variable from the previous response
            .payload("{\"version\":10}")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            .payload("\"version\": 10, data: [...]");
}
</code>```

答:
One approach that works is to extract the value from the TestContext and assign it as a variable

```<code>@CitrusTest(name = "SimpleIT.getVersionTest")
@Test
public void getVersionTest(@CitrusResource TestContext context) {

    http(httpActionBuilder -> httpActionBuilder
        .client("restClient")
        .send()
        .get("/getLatestVersion")
        .name("request1")
        .accept("application/json")
    );

    http(httpActionBuilder -> httpActionBuilder
        .client("restClient")
        .receive()
        .response(HttpStatus.OK)
        .messageType(MessageType.JSON)
        .payload("{\"version\":\"@greaterThan(0)@\"}")
    );

    // This extracts the version and assigns it as a variable
    groovy(action -> action.script(new ClassPathResource("addVariable.groovy")));

    http(httpActionBuilder -> httpActionBuilder
            .client("restClient")
            .send()
            .post("/getVersionData")
            .payload("{\"version\":${versionId}}")
            .accept("application/json")
    );

    http(httpActionBuilder -> httpActionBuilder
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
    );
}
</code>```

addVariable.groovy

This extracts the variable from the response and adds it to the TestContext.

```<code>import com.consol.citrus.message.Message
import groovy.json.JsonSlurper

Message message = context.getMessageStore().getMessage("receive(restClient)");

def jsonSlurper = new JsonSlurper();
def payload = jsonSlurper.parseText((String) message.getPayload())

// Set the version as a variable in the TestContext
context.getVariables().put("versionId", payload.version)
</code>```

Questions

Is there a neater way to do this?

Is there a way to name the messages within the MessageStore?

Body:
I'm trying to test the following two REST calls:

Request 1

GET getLatestVersion
Response: {"version": 10}

Request 2

POST getVersionData (body={"version": 10})
Response: {"version": 10, data: [...]}

Is it possible to assign the "version" from Request 1 to a variable to use in Request 2 within the same test?

@CitrusTest(name = "SimpleIT.getVersionTest")
public void getVersionTest() {
    // Request 1
    http()
            .client("restClient")
            .send()
            .get("/getLatestVersion")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            // Can the version be assigned to a variable here?
            .payload("{\"version\":10}");

    // Request 2
    http()
            .client("restClient")
            .send()
            .post("/getVersionData")
            // Idealy this would be a Citrus variable from the previous response
            .payload("{\"version\":10}")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            .payload("\"version\": 10, data: [...]");
}

Body:
One approach that works is to extract the value from the TestContext and assign it as a variable

@CitrusTest(name = "SimpleIT.getVersionTest")
@Test
public void getVersionTest(@CitrusResource TestContext context) {

    http(httpActionBuilder -> httpActionBuilder
        .client("restClient")
        .send()
        .get("/getLatestVersion")
        .name("request1")
        .accept("application/json")
    );

    http(httpActionBuilder -> httpActionBuilder
        .client("restClient")
        .receive()
        .response(HttpStatus.OK)
        .messageType(MessageType.JSON)
        .payload("{\"version\":\"@greaterThan(0)@\"}")
    );

    // This extracts the version and assigns it as a variable
    groovy(action -> action.script(new ClassPathResource("addVariable.groovy")));

    http(httpActionBuilder -> httpActionBuilder
            .client("restClient")
            .send()
            .post("/getVersionData")
            .payload("{\"version\":${versionId}}")
            .accept("application/json")
    );

    http(httpActionBuilder -> httpActionBuilder
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
    );
}

addVariable.groovy

This extracts the variable from the response and adds it to the TestContext.

import com.consol.citrus.message.Message
import groovy.json.JsonSlurper

Message message = context.getMessageStore().getMessage("receive(restClient)");

def jsonSlurper = new JsonSlurper();
def payload = jsonSlurper.parseText((String) message.getPayload())

// Set the version as a variable in the TestContext
context.getVariables().put("versionId", payload.version)

Questions

Is there a neater way to do this?

Is there a way to name the messages within the MessageStore?


问:
How do I write a bin/script for these bash and ruby commands?
I am constantly writing these commands in terminal but I don't know how to write a script for it. What can I do? These are the commands I would write in succession in both bash and irb:

```<code># in bash
docker exec -it <some_container> bash
irb

# now everything below is a ruby command
require 'bundler'
Bundler.require

required_load_path = File.expand_path(".")
$LOAD_PATH.unshift(required_load_path) unless $LOAD_PATH.include?(required_load_path)

Dir['config/*.rb'].each { |file| load file }

ENV["RAILS_ENV"] = 'development'
...
</code>```

I have a ruby project with a bin folder. What script can I write that would automate all of this? I'm currently having trouble because when I run the docker exec part... the irb part isn't run next for some reason.

答:
If you just want to execute the ruby script on Docker, one alternative is to create a ruby file with the commands you want:

```<code># rubyscript.rb
puts 'hello'
# ...
</code>```

And call it with docker exec:

```<code>docker exec -it <imagename> ruby rubyscript.rb
</code>```

However if you want to run something and stay in REPL to execute more stuff, you could for example call pry inside the script:

```<code># rubyscript.rb
puts 'hello'
# ...
require 'pry'
pry
</code>```

This will execute your stuff and stay within pry, executed on the Docker container.

Body:
I am constantly writing these commands in terminal but I don't know how to write a script for it. What can I do? These are the commands I would write in succession in both bash and irb:

# in bash
docker exec -it <some_container> bash
irb

# now everything below is a ruby command
require 'bundler'
Bundler.require

required_load_path = File.expand_path(".")
$LOAD_PATH.unshift(required_load_path) unless $LOAD_PATH.include?(required_load_path)

Dir['config/*.rb'].each { |file| load file }

ENV["RAILS_ENV"] = 'development'
...

I have a ruby project with a bin folder. What script can I write that would automate all of this? I'm currently having trouble because when I run the docker exec part... the irb part isn't run next for some reason.

Body:
If you just want to execute the ruby script on Docker, one alternative is to create a ruby file with the commands you want:

# rubyscript.rb
puts 'hello'
# ...

And call it with docker exec:

docker exec -it <imagename> ruby rubyscript.rb

However if you want to run something and stay in REPL to execute more stuff, you could for example call pry inside the script:

# rubyscript.rb
puts 'hello'
# ...
require 'pry'
pry

This will execute your stuff and stay within pry, executed on the Docker container.


问:
Countdown timer, not displaying time
I currently have a countdown timer that resets every 24 hours but for some now it displays "NaN" instead of the time. I have a feeling it may be to do with the variables ?

Can someone please help me rectify what the issue may be ?

```<code>// Set the date we're counting down to
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var today = new Date();
var day = today.getDate();
var month = today.getMonth() ;
var year = today.getFullYear();
//alert(year); You can check the year from here
var countDownDate = new Date( monthNames[month] + day + "2017 24:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

// Get todays date and time
var now = new Date().getTime();

// Find the distance between now an the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

if(hours < 10){
var hours = "0" + hours;

}
if(minutes<10){
var minutes = "0" + minutes;

}
if(seconds <10){
var seconds = "0" + seconds;
}

// Output the result in an element with id="demo"
document.getElementById("H_one").innerHTML = hours ;
document.getElementById("M_one").innerHTML = minutes;
document.getElementById("s_one").innerHTML = seconds ;

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</code>```

答:
```<code>var countDownDate = new Date( monthNames[month] + " " + day + " " + "2017 24:00:00").getTime();
</code>```

You forgot to add spaces.

Title: Countdown timer, not displaying time

Body:
I currently have a countdown timer that resets every 24 hours but for some now it displays "NaN" instead of the time. I have a feeling it may be to do with the variables ?

Can someone please help me rectify what the issue may be ?

// Set the date we're counting down to
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var today = new Date();
var day = today.getDate();
var month = today.getMonth() ;
var year = today.getFullYear();
//alert(year); You can check the year from here
var countDownDate = new Date( monthNames[month] + day + "2017 24:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

// Get todays date and time
var now = new Date().getTime();

// Find the distance between now an the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

if(hours < 10){
var hours = "0" + hours;

}
if(minutes<10){
var minutes = "0" + minutes;

}
if(seconds <10){
var seconds = "0" + seconds;
}

// Output the result in an element with id="demo"
document.getElementById("H_one").innerHTML = hours ;
document.getElementById("M_one").innerHTML = minutes;
document.getElementById("s_one").innerHTML = seconds ;

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);

Body:
var countDownDate = new Date( monthNames[month] + " " + day + " " + "2017 24:00:00").getTime();

You forgot to add spaces.


问:
io.imread reading some .tif files but not others
I am trying to understand an error with a script. I inherited the script from a colleague and I'm trying to get it to work on my machine. I am running it in Python3.3.5 and if preforms some measurement functions on .tif files. These are the list of modules I call

```<code>import matplotlib, copy, skimage, mahotas, os, tifffile
from skimage import io, filter, morphology, draw
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
</code>```

The script breaks and throws an error at the line calling the io.imread function on my desire .tif files.

```<code>‘OSError: cannot identify image file’
</code>```

However, when I change the script to open a different tif image file path, it works.  I have not included my code, because it seems that this is an issue with my python setup? I get more errors when I try to run this with Python27. It might be incompatibilities with the modules I’m using?
Does anyone have any clues for what might cause io.imread to work on some image files but not others?
The only difference I can think of between the image files is size.

答:
I figured it out. The skimage function works for 8-bit image files, whereas my files where 16-bit.
Changing the image object from

```<code>io.imread()
</code>```

to the tifffile function

```<code>tiff.imread()
</code>```

allowed all of my 16-bit images to be processed. A beginner's mistake, but it took me a bit to remember those differences between the library functions.

Body:
I am trying to understand an error with a script. I inherited the script from a colleague and I'm trying to get it to work on my machine. I am running it in Python3.3.5 and if preforms some measurement functions on .tif files. These are the list of modules I call

import matplotlib, copy, skimage, mahotas, os, tifffile
from skimage import io, filter, morphology, draw
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

The script breaks and throws an error at the line calling the io.imread function on my desire .tif files.

‘OSError: cannot identify image file’

However, when I change the script to open a different tif image file path, it works.  I have not included my code, because it seems that this is an issue with my python setup? I get more errors when I try to run this with Python27. It might be incompatibilities with the modules I’m using?
Does anyone have any clues for what might cause io.imread to work on some image files but not others?
The only difference I can think of between the image files is size.

Body:
I figured it out. The skimage function works for 8-bit image files, whereas my files where 16-bit.
Changing the image object from

io.imread()

to the tifffile function

tiff.imread()

allowed all of my 16-bit images to be processed. A beginner's mistake, but it took me a bit to remember those differences between the library functions.


问:
What is the HTTP_X_CLIENT_DATA in the $_SERVER array?
I see an element in the $_SERVER array called HTTP_X_CLIENT_DATA - $_SERVER['HTTP_X_CLIENT_DATA'], and its value looks like some kind of base64-encoded string. What is this element used for?

Here is an example value, which I tried decoding but seems to be also encrypted?

CJa2yQEIprbJAQjBtskBCPqcygEIqZ3KAQ==

答:
It appears to be both uncommon and non-standard. Here's a List of HTTP Header Fields.

If you provide the URL that served it, we might able to help you further.


问:
How to move text around when using turtle.write in Python?
I am trying to solve Exercise 9 from Chapter 5 of 'Think Python' ( version: http://openbookproject.net/thinkcs/python/english3e/conditionals.html ). It involves moving text from turtle.write around so it doesn't overlap with the barchart when the values are negative. I have tried using triple quotation marks """like this""" in order to add an extra row before the text, but the extra row goes in the wrong place. Please help?</p>

```<code>import turtle
wn=turtle.Screen()
wn.bgcolor("lightgreen")
wn.title("Barcharts FTW")
pen=turtle.Turtle()
pen.hideturtle()
pen.color("blue","red")
pen.pensize(2)
pen.penup()
pen.goto(-300,-100)

def draw_bar (t,height):
    t.pendown()
    t.begin_fill()
    t.lt(90)
    t.fd(height)
    t.write("   " + str(height))
    t.rt(90)
    t.fd(40)
    t.rt(90)
    t.fd(height)
    t.end_fill()
    t.lt(90)
    t.penup()
    t.fd(10)

xs = [48, 117, 200, 240, -160, 260, 220]
for v in xs:
    draw_bar(pen,v)

wn.mainloop()
</code>```

答:
Note the if height < 0 part, which checks if the bar height is negative. In that case, the turtle moves back (tur_pen.forward(-15)) so that when it writes the value the text is not overlapping the bar.

```<code># Modified turtle pie chart II
# By Dave Zabel  3/29/2017 - 3/31/2017
# Import turtle and random modules
import turtle
import random

values = random.sample(range(-250, 250), 15)  # Initiate a list of 15 random values

def draw_bar(tur_pen, height):
    """Get turtle to draw one bar of height"""
    tur_pen.begin_fill()  # Begins color fill
    tur_pen.left(90)  # Starts a bar whose height is a value from the variable "values"
    tur_pen.forward(height)
    tur_pen.penup()  # Sequence checks for negative value so as to print value UNDER the line
    if height < 0:
        tur_pen.forward(-15)
    tur_pen.write('    ' + str(height))  # Prints the value of the bar height
    if height < 0:
        tur_pen.forward(15)
    tur_pen.pendown()  # Continues to complete one bar
    tur_pen.right(90)
    tur_pen.forward(40)
    tur_pen.right(90)
    tur_pen.forward(height)
    tur_pen.left(90)
    tur_pen.end_fill()  # Stops the fill process
    tur_pen.penup()  # Has the pen skip between bars
    tur_pen.forward(10)
    tur_pen.pendown()

bar_screen = turtle.Screen()  # Sets the attributes of the screen
bar_screen.title('Bar Graph')
bar_screen.bgcolor('light green')

bar = turtle.Turtle()  # Sets the attributes of the pen
bar.pensize(3)
bar.speed(5)
bar.penup()
bar.goto(-360, 0)
bar.pendown()
fill_color = ''  # Changes the fill color by height
for v in values:
    if v >= 200:
        fill_color = 'green'
    elif v >= 100 < 200:
        fill_color = 'yellow'
    elif v > 0 < 100:
        fill_color = 'gray'
    elif v < 0:
        fill_color = 'red'
    bar.color('blue', fill_color)
    draw_bar(bar, v)  # Starts the process

bar_screen.mainloop()  # Holds the screen open until the user closes it
</code>```

Body:
I am trying to solve Exercise 9 from Chapter 5 of 'Think Python' ( version: http://openbookproject.net/thinkcs/python/english3e/conditionals.html ). It involves moving text from turtle.write around so it doesn't overlap with the barchart when the values are negative. I have tried using triple quotation marks """like this""" in order to add an extra row before the text, but the extra row goes in the wrong place. Please help?

import turtle
wn=turtle.Screen()
wn.bgcolor("lightgreen")
wn.title("Barcharts FTW")
pen=turtle.Turtle()
pen.hideturtle()
pen.color("blue","red")
pen.pensize(2)
pen.penup()
pen.goto(-300,-100)

def draw_bar (t,height):
    t.pendown()
    t.begin_fill()
    t.lt(90)
    t.fd(height)
    t.write("   " + str(height))
    t.rt(90)
    t.fd(40)
    t.rt(90)
    t.fd(height)
    t.end_fill()
    t.lt(90)
    t.penup()
    t.fd(10)

xs = [48, 117, 200, 240, -160, 260, 220]
for v in xs:
    draw_bar(pen,v)

wn.mainloop()

Body:
Note the if height < 0 part, which checks if the bar height is negative. In that case, the turtle moves back (tur_pen.forward(-15)) so that when it writes the value the text is not overlapping the bar.

# Modified turtle pie chart II
# By Dave Zabel  3/29/2017 - 3/31/2017
# Import turtle and random modules
import turtle
import random

values = random.sample(range(-250, 250), 15)  # Initiate a list of 15 random values

def draw_bar(tur_pen, height):
    """Get turtle to draw one bar of height"""
    tur_pen.begin_fill()  # Begins color fill
    tur_pen.left(90)  # Starts a bar whose height is a value from the variable "values"
    tur_pen.forward(height)
    tur_pen.penup()  # Sequence checks for negative value so as to print value UNDER the line
    if height < 0:
        tur_pen.forward(-15)
    tur_pen.write('    ' + str(height))  # Prints the value of the bar height
    if height < 0:
        tur_pen.forward(15)
    tur_pen.pendown()  # Continues to complete one bar
    tur_pen.right(90)
    tur_pen.forward(40)
    tur_pen.right(90)
    tur_pen.forward(height)
    tur_pen.left(90)
    tur_pen.end_fill()  # Stops the fill process
    tur_pen.penup()  # Has the pen skip between bars
    tur_pen.forward(10)
    tur_pen.pendown()

bar_screen = turtle.Screen()  # Sets the attributes of the screen
bar_screen.title('Bar Graph')
bar_screen.bgcolor('light green')

bar = turtle.Turtle()  # Sets the attributes of the pen
bar.pensize(3)
bar.speed(5)
bar.penup()
bar.goto(-360, 0)
bar.pendown()
fill_color = ''  # Changes the fill color by height
for v in values:
    if v >= 200:
        fill_color = 'green'
    elif v >= 100 < 200:
        fill_color = 'yellow'
    elif v > 0 < 100:
        fill_color = 'gray'
    elif v < 0:
        fill_color = 'red'
    bar.color('blue', fill_color)
    draw_bar(bar, v)  # Starts the process

bar_screen.mainloop()  # Holds the screen open until the user closes it


问:
Par Paragraph Formatter - How to use it in the Windows Command Line
There is a very smart and useful paragraph formatter par (par website). I have used it with Vim and it works great. I would like to use it in Windows command line. (I am using Windows 7). But I get the par error: bad argument error. How can I use par in the windows command prompt. I already have it in my path, so it does find it and also gives me help content. But I can't figure out why it errors out, when I pass a long text stream to it.

(Since, there is a par.exe on the developers website. I am pretty sure that it is meant to work on Windows.)

What I have tried is:

```<code>par w30 "This is a long long paragraph. Please shorten it to 30 characters per line. But it does not work."
par 30j "This is a long long paragraph. Please shorten it to 30 characters per line and also justify the text. But it does not work."
</code>```

I have used it successfully with Vim and it works great. Please help.

答:
I believe input must be piped into the tool, not passed as an argument. So for your examples, try this:</p>

```<code>echo This is a long long paragraph. Please shorten it to 30 characters per line. But it does not work.| par w30
echo This is a long long paragraph. Please shorten it to 30 characters per line and also justify the text. But it does not work.| par 30j
</code>```

Body:
There is a very smart and useful paragraph formatter par (par website). I have used it with Vim and it works great. I would like to use it in Windows command line. (I am using Windows 7). But I get the par error: bad argument error. How can I use par in the windows command prompt. I already have it in my path, so it does find it and also gives me help content. But I can't figure out why it errors out, when I pass a long text stream to it.

(Since, there is a par.exe on the developers website. I am pretty sure that it is meant to work on Windows.)

What I have tried is:

par w30 "This is a long long paragraph. Please shorten it to 30 characters per line. But it does not work."
par 30j "This is a long long paragraph. Please shorten it to 30 characters per line and also justify the text. But it does not work."

I have used it successfully with Vim and it works great. Please help.

Body:
I believe input must be piped into the tool, not passed as an argument. So for your examples, try this:

echo This is a long long paragraph. Please shorten it to 30 characters per line. But it does not work.| par w30
echo This is a long long paragraph. Please shorten it to 30 characters per line and also justify the text. But it does not work.| par 30j


问:
How can I programmatically find Swift's version?
I know I can find the version of Swift I'm running right now reverting to a Terminal and typing:

```<code>xcrun swift --version
Swift version 1.1 (swift-600.0.57.4)
Target: x86_64-apple-darwin13.4.0
</code>```

Also, I've been reading about the Preprocessor Macros in Swift, but no luck finding a Swift version constant.

As Swift 1.2 approaches it will be nice to flag old code that only runs on Swift 1.1 (Xcode up to 6.2) or new code that needs Xcode 6.3 (Swift 1.2)

Note: I can also use system() to do something like:

```<code>system("xcrun swift --version | grep version > somefile.txt")
</code>```

Then open somefile.txt, but rather prefer some simpler solution

答:
Swift 3.1 extends the @available attribute to support specifying Swift version numbers in addition to its existing platform versions.

```<code>// Swift 3.1

@available(swift 3.1)
func intVersion(number: Double) -> Int? {
  return Int(exactly: number)
}

@available(swift, introduced: 3.0, obsoleted: 3.1)
func intVersion(number: Double) -> Int {
  return Int(number)
}
</code>```

Body:
I know I can find the version of Swift I'm running right now reverting to a Terminal and typing:

xcrun swift --version
Swift version 1.1 (swift-600.0.57.4)
Target: x86_64-apple-darwin13.4.0

Also, I've been reading about the Preprocessor Macros in Swift, but no luck finding a Swift version constant.

As Swift 1.2 approaches it will be nice to flag old code that only runs on Swift 1.1 (Xcode up to 6.2) or new code that needs Xcode 6.3 (Swift 1.2)

Note: I can also use system() to do something like:

system("xcrun swift --version | grep version > somefile.txt")

Then open somefile.txt, but rather prefer some simpler solution

Body:
Swift 3.1 extends the @available attribute to support specifying Swift version numbers in addition to its existing platform versions.

// Swift 3.1

@available(swift 3.1)
func intVersion(number: Double) -> Int? {
  return Int(exactly: number)
}

@available(swift, introduced: 3.0, obsoleted: 3.1)
func intVersion(number: Double) -> Int {
  return Int(number)
}


问:
adding an input value and submitting the form on load
I have the following form:

```<code><form action="http://example.co.uk/order" method="post" id="voucher" class="AVAST_PAM_nonloginform">
  <fieldset>
    <h4>Vouchers</h4>
    <input type="text" class="discount_name form-control" id="discount_name" name="discount_name" value="">
    <input type="hidden" name="submitDiscount">
    <button type="submit" name="submitAddDiscount" class="button btn btn-default button-small"><span>OK</span></button>
  </fieldset>
</form>
</code>```

and am using the following script:

```<code><script>
window.onload = function(){
document.getElementById(\"discount_name\").value = \"50681\";
}
</script>
</code>```

to populate the input. I then use:

```<code><script>
window.onload = function(){
document.forms['voucher'].submit();
}
</script>
</code>```

to activate the submit.

However, use the second script, it stops the "50681" from being inputted into the text box (instead submits a blank input).

Originally I had the code as :

```<code>  <script>
    window.onload = function(){
    document.getElementById(\"discount_name\").value = \"50681\";
document.forms['voucher'].submit();
    }
    </script>
</code>```

(I split it up thinking it may be a timing issue).

Any ideas?

p.s. the reason for the backslash's is due to it currently being run under php until I can get it working

答:
The issue seems to be with (\"discount_name\").value = \"50681\"; & document.forms['voucher'].submit();

In either of the case you can avoid \ & for form you need to target by the index number. Assuming there is only one form present , so passing 0 in index

```<code> window.onload = function(){
    document.getElementById("discount_name").value = "50681";
    document.forms[0].submit();
    }
</code>```

Note: In the demo I have changed the action url to https else it will prohibit to make call from jsfiddle. In your case you can still keep http in code

DEMO USING ID

Body:
I have the following form:

<form action="http://example.co.uk/order" method="post" id="voucher" class="AVAST_PAM_nonloginform">
  <fieldset>

Vouchers

    <input type="text" class="discount_name form-control" id="discount_name" name="discount_name" value="">
    <input type="hidden" name="submitDiscount">
    <button type="submit" name="submitAddDiscount" class="button btn btn-default button-small">OK</button>
  </fieldset>
</form>

and am using the following script:

to populate the input. I then use:

to activate the submit.

However, use the second script, it stops the "50681" from being inputted into the text box (instead submits a blank input).

Originally I had the code as :

(I split it up thinking it may be a timing issue).

Any ideas?

p.s. the reason for the backslash's is due to it currently being run under php until I can get it working

Body:
The issue seems to be with (\"discount_name\").value = \"50681\"; & document.forms['voucher'].submit();

In either of the case you can avoid \ & for form you need to target by the index number. Assuming there is only one form present , so passing 0 in index

 window.onload = function(){
    document.getElementById("discount_name").value = "50681";
    document.forms[0].submit();
    }

Note: In the demo I have changed the action url to https else it will prohibit to make call from jsfiddle. In your case you can still keep http in code

DEMO USING ID


问:
Power BI: Assign measure value to calculate column
assign measure value to calculated column

I have created two tables:

User can see green field as slicer in sheet and on select, i have created measure in id_indicator table,

Measure will take one value, that user selects from slicer

Measure 5 = if(COUNTROWS('Input_Threshold') = 1, sum('Input_Threshold'[Green]), BLANK())

I want to assign ([measure 5]  * [by_hour]) to field calculated but it is not working, giving black (I tried calculated = [measure 5] but still not working)
Is it possibe to assign measure value to calculated column?

Below it says measure5 has value 60

But while at assigning column values it takes blank value as 'else' part says.

答:
Of course it is possible to assign measure to the calculated column.
The measure in such a case will be evaluated in row context applicable for every row of this calculated column.

The measure however needs to be accessible. Therefore it must be defined in table to which you are adding calculated column, or defined in the table accessible through a relationship.

Create simple example:

```<code>TestMeasure = 7
CalculatedColumn = 7 * id_indicator
</code>```

Edit (after OP updated question):

Calculated objects (calc tables and calc columns) are not affected by slicers. Calculated objects are static therefore you cannot alter calculated object results through slicers.

Body:
Of course it is possible to assign measure to the calculated column.
The measure in such a case will be evaluated in row context applicable for every row of this calculated column.

The measure however needs to be accessible. Therefore it must be defined in table to which you are adding calculated column, or defined in the table accessible through a relationship.

Create simple example:

TestMeasure = 7
CalculatedColumn = 7 * id_indicator

Edit (after OP updated question):

Calculated objects (calc tables and calc columns) are not affected by slicers. Calculated objects are static therefore you cannot alter calculated object results through slicers.


问:
Memory taken by a program variable
I was asked this in an interview recently:
If I have a program, that is platform independent (say a program in java or python) and it has a variable a that stores a positive integer, then the memory taken by the variable is different in different OS?

I personally think it is dependent on how an OS implements memory management and the OS architecture but still needed to be sure.

答:
If you have a program where the size of an integer varies, it is not likely to be platform independent.

the memory taken by the variable is different in different OS?

It might be different, depending upon the language implementation.

Title: Memory taken by a program variable


问:
How to separate array processing into goroutines?
I have a slice of 30'000 strings. How do I separate processing this slice into, say, 10 goroutines that would take 3000 strings from the slice, extract some data from them and push into a new slice?

So, in the end, I will have 10 slices with 3000 processed results in each. What's the pattern to handle this problem?

I have had a look at this article, but not sure which of these patterns applies to my case.

答:
Using a channel, read the elements from the slice, use a Fan out to distribute load and pass messages. Then, process the strings in goroutines and collect the results back (fan in ) in a single goroutine to avoid mutexes.

You may want to set the number of Max concurrent concurrent goroutines.

Keep in mind that slices are not thread safe when writing to them.

Useful info:

https://blog.golang.org/pipelines
  https://talks.golang.org/2012/concurrency.slide#1
  https://blog.golang.org/advanced-go-concurrency-patterns
  https://talks.golang.org/2013/advconc.slide#1


问:
How to play mp3 file in swift3?
I have started to learn ios development and am stuck in one place. My code to play mp3 file is

```<code>var bombSoundEffect: AVAudioPlayer!
let path = Bundle.main.path(forResource: "faded", ofType:"mp3")!
let url = NSURL(fileURLWithPath: path)

 do {
        let sound = try AVAudioPlayer(contentsOf: (url as NSURL) as URL)
        bombSoundEffect.play()

    } catch {
        print("couldn't load file :(")
    }
    if bombSoundEffect != nil {
        bombSoundEffect.stop()
        bombSoundEffect = nil
        }
</code>```

However, when I click on the button, my file doesn't play. The song is playing perfectly normally.

答:
There's lots wrong with your code, but it's a sunny day, so try something like this…</p>

```<code>func playSound() {
    guard let url = Bundle.main.url(forResource: "faded", withExtension: "mp3") else { return }

    let bombSoundEffect = try? AVAudioPlayer(contentsOf: url)
    bombSoundEffect?.play()
}
</code>```

Title: How to play mp3 file in swift3?

Body:
I have started to learn ios development and am stuck in one place. My code to play mp3 file is

var bombSoundEffect: AVAudioPlayer!
let path = Bundle.main.path(forResource: "faded", ofType:"mp3")!
let url = NSURL(fileURLWithPath: path)

 do {
        let sound = try AVAudioPlayer(contentsOf: (url as NSURL) as URL)
        bombSoundEffect.play()

    } catch {
        print("couldn't load file :(")
    }
    if bombSoundEffect != nil {
        bombSoundEffect.stop()
        bombSoundEffect = nil
        }

However, when I click on the button, my file doesn't play. The song is playing perfectly normally.

Body:
There's lots wrong with your code, but it's a sunny day, so try something like this…

func playSound() {
    guard let url = Bundle.main.url(forResource: "faded", withExtension: "mp3") else { return }

    let bombSoundEffect = try? AVAudioPlayer(contentsOf: url)
    bombSoundEffect?.play()
}


问:
Why does my application close when a random character is pressed?
I have this console application, It's very basic as you can see and im trying to make it to where when it says

Console.WriteLine("Would you like to go back to the main menu? Y/N");

And lets say i dont press either Y or N.. But instead lets say F the application just closes.. How come?
And what methods should I use to resolve this issue?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Game
{
    class Program
    {
        static void Main(string[] args)
        {
            startMenu();

        }

        public static void startMenu()
        {
            Console.WriteLine("======= Welcome To The Player Registry =======");
            Console.WriteLine("1. Name");
            Console.WriteLine("2. Age");
            Console.WriteLine("3. City");

            try
            {
                int value = Convert.ToInt32(Console.ReadLine());
                int answer = value;
                switch (answer)
                {
                    case 1:
                        Console.Clear();
                        Console.WriteLine("======= Player Names=======");
                        Console.WriteLine("Jonsson, Adam");
                        Console.WriteLine("Jetsson, Carl");
                        Console.WriteLine("Jimmy, Golf");
                        Console.WriteLine("Ali, Mohammed");
                        Console.WriteLine();

                        Console.WriteLine("Would you like to go back to the main menu? Y/N");
                        string choice = Console.ReadLine();
                        if (choice.Equals("Y", StringComparison.OrdinalIgnoreCase) || choice.Equals("y", StringComparison.OrdinalIgnoreCase))
                        {
                            Console.Clear();
                            startMeny();
                        }
                        if (choice.Equals("N", StringComparison.OrdinalIgnoreCase) || choice.Equals("n", StringComparison.OrdinalIgnoreCase))
                        {
                            Console.Clear();
                            Console.WriteLine("Okay.. Bye!");
                            Console.ReadKey();
                        }
                        break;

                    case 2:
                        Console.WriteLine("Look it works!");
                        break;
                    default:
                        Console.WriteLine("What?..");
                        return;

                }
            }
            catch
            {

            }
        }
    }
}
</code>```

答:
The console app is closing because it will only run until it has nothing more to do. A good way to avoid closing the program is to give the user the option to do something else.

These all need more code to match your project, but here is just a quick idea:

you could create a few methods to help you out:

```<code> public static string BackToMainMenu()
    {
        Console.WriteLine("Would you like to go back to the main menu? Y/N");
        return Console.ReadLine(); ///returns the user's choice in a string variable
    }

 public static void CheckChoice(string choice)
    {
        if (choice == "y")
        {
            ///back at menu stuff goes here
        }

        if (choice == "n")
        {
            ///whatever you want to do on "n"
        }

        ///if user types anything other than y or n (could also use 'else')
        if (choice != "n" && choice != "y")
        {
            Console.WriteLine("Incorrect Input");

            ///Ask user if they want to go back to menu (again)
            ///check their choice
            CheckChoice(BackToMainMenu());
        }
    }
</code>```

replace what you have under case 1 with:

```<code>   case 1:
                    Console.Clear();
                    Console.WriteLine("======= Player Names=======");
                    Console.WriteLine("Jonsson, Adam");
                    Console.WriteLine("Jetsson, Carl");
                    Console.WriteLine("Jimmy, Golf");
                    Console.WriteLine("Ali, Mohammed");
                    Console.WriteLine();

                    ///ask "back to menu?" and check choice
                    CheckChoice(BackToMainMenu());
</code>```

Body:
I have this console application, It's very basic as you can see and im trying to make it to where when it says

Console.WriteLine("Would you like to go back to the main menu? Y/N");

And lets say i dont press either Y or N.. But instead lets say F the application just closes.. How come?
And what methods should I use to resolve this issue?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Game
{
    class Program
    {
        static void Main(string[] args)
        {
            startMenu();

        }

        public static void startMenu()
        {
            Console.WriteLine("======= Welcome To The Player Registry =======");
            Console.WriteLine("1. Name");
            Console.WriteLine("2. Age");
            Console.WriteLine("3. City");

            try
            {
                int value = Convert.ToInt32(Console.ReadLine());
                int answer = value;
                switch (answer)
                {
                    case 1:
                        Console.Clear();
                        Console.WriteLine("======= Player Names=======");
                        Console.WriteLine("Jonsson, Adam");
                        Console.WriteLine("Jetsson, Carl");
                        Console.WriteLine("Jimmy, Golf");
                        Console.WriteLine("Ali, Mohammed");
                        Console.WriteLine();

                        Console.WriteLine("Would you like to go back to the main menu? Y/N");
                        string choice = Console.ReadLine();
                        if (choice.Equals("Y", StringComparison.OrdinalIgnoreCase) || choice.Equals("y", StringComparison.OrdinalIgnoreCase))
                        {
                            Console.Clear();
                            startMeny();
                        }
                        if (choice.Equals("N", StringComparison.OrdinalIgnoreCase) || choice.Equals("n", StringComparison.OrdinalIgnoreCase))
                        {
                            Console.Clear();
                            Console.WriteLine("Okay.. Bye!");
                            Console.ReadKey();
                        }
                        break;

                    case 2:
                        Console.WriteLine("Look it works!");
                        break;
                    default:
                        Console.WriteLine("What?..");
                        return;

                }
            }
            catch
            {

            }
        }
    }
}

Body:
The console app is closing because it will only run until it has nothing more to do. A good way to avoid closing the program is to give the user the option to do something else.

These all need more code to match your project, but here is just a quick idea:

you could create a few methods to help you out:

 public static string BackToMainMenu()
    {
        Console.WriteLine("Would you like to go back to the main menu? Y/N");
        return Console.ReadLine(); ///returns the user's choice in a string variable
    }

 public static void CheckChoice(string choice)
    {
        if (choice == "y")
        {
            ///back at menu stuff goes here
        }

        if (choice == "n")
        {
            ///whatever you want to do on "n"
        }

        ///if user types anything other than y or n (could also use 'else')
        if (choice != "n" && choice != "y")
        {
            Console.WriteLine("Incorrect Input");

            ///Ask user if they want to go back to menu (again)
            ///check their choice
            CheckChoice(BackToMainMenu());
        }
    }

replace what you have under case 1 with:

   case 1:
                    Console.Clear();
                    Console.WriteLine("======= Player Names=======");
                    Console.WriteLine("Jonsson, Adam");
                    Console.WriteLine("Jetsson, Carl");
                    Console.WriteLine("Jimmy, Golf");
                    Console.WriteLine("Ali, Mohammed");
                    Console.WriteLine();

                    ///ask "back to menu?" and check choice
                    CheckChoice(BackToMainMenu());


问:
angular controller by module blank page
hello i have a problem with angular im benninger to this framework but i have some knowledge about it . Yesterday i faced a problem when i wanted to change controller from a global function(in this case all is OK) to controller by module i recive blank page here is my code

```<code>angular.module('myApp', ['ngRoute', 'membersService']).config(
['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
    $routeProvider.when('/home', {
        templateUrl: 'partials/home.html',
        controller: MembersCtrl
    }).otherwise({
        redirectTo: '/home'
    });
}]);
</code>```

```<code>var myApp = angular.module('myApp');
myApp.controller('MembersCtrl',['$scope','$http', 'MembersSrv',function ($scope, $http, MembersSrv) {

$scope.refresh = function () {
    return MembersSrv.getAllPersons().then(function (data) {
        $scope.persons = data.data;
    });
};

$scope.clearMessages = function () {
    $scope.successMessages = '';
    $scope.errorMessages = '';
    $scope.errors = {};
};

$scope.reset = function () {
    if ($scope.regForm) {
        $scope.regForm.$setPristine();
    }
    $scope.newPerson = {name: "", lname: "", phoneNumber: ""};
    $scope.clearMessages();
};

$scope.register = function () {
    $scope.clearMessages();

    MembersSrv.save($scope.newPerson, function (data) {
        $scope.refresh();
        $scope.reset();
        $scope.successMessages = ['Member Registered'];
    }, function (result) {
        if ((result.status == 409) || (result.status == 400)) {
            $scope.errors = result.data;
        } else {
            $scope.errorMessages = ['Unknown  server error'];
        }
    });
};

$scope.refresh();
$scope.reset();
$scope.orderBy = 'name';
}]);
</code>```

```<code>angular.module('membersService', []).service('MembersSrv', [
'$http', function ($http) {
    this.getAllPersons = function () {
        var url = "http://localhost:8080/gadziksy-web/rest/person";
        var req = {
            method: 'GET',
            url: url,
        };
        return $http(req);
    }
    }]);
</code>```

<!DOCTYPE html>

    <title>myApp</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <meta name="format-detection" content="telephone=no"/>
    <link rel="stylesheet" href="css/screen.css" type="text/css"/>

```
</div>
</div>
</p>

<hr>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<div ng-controller="MembersCtrl">
    <h1 align="center">International Bank Application</h1>
    <div>
        <p>You have successfully connected to the Application.</p>
    </div>
    <form name="regForm" ng-submit="register()">
        <h2>Member Registration</h2>
        <fieldset>
            <legend>Register a member:</legend>
            <div>
                <label for="name">Name:</label>
                <input type="text" name="name" id="name" ng-model="newPerson.name" placeholder="Your Name" required
                       autofocus/>
            </div>
            <div>
                <label for="lname">Lname:</label>
                <input type="text" name="lname" id="lname" ng-model="newPerson.lname" placeholder="Your Lastname"
                       required/>
            </div>
            <div>
                <label for="dob">Date</label>
                <input type="date" name="dob" id="dob" ng-model="newPerson.dob" placeholder="Your Date" required/>
            </div>

            <ul ng-hide="!successMessages" class="success">
                <li ng-repeat="message in successMessages">{{message}}</li>
            </ul>

            <ul ng-hide="!errorMessages" class="error">
                <li ng-repeat="message in errorMessages">{{message}}</li>
            </ul>

            <div>
                <input type="submit" ng-disabled="regForm.$invalid" id="register" value="Register"/>
                <input type="button" ng-click="reset()" name="cancel"
                       id="cancel" value="Cancel"/>
            </div>
        </fieldset>
    </form>
    <h2>Persons</h2>
    <em ng-show="persons.length == 0">No registered members.</em>
    <table ng-hide="persons.length == 0" class="simpletablestyle">
        <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Lname</th>
            <th>Date</th>
            <th>REST URL</th>
        </tr>
        </thead>
        <tr ng-repeat="person in persons | orderBy:orderBy">
            <td>{{person.id}}</td>
            <td>{{person.name}}</td>
            <td>{{person.lname}}</td>
            <td>{{person.dob}}</td>
            <td>details-{{person.id}}
            </td>
    </table>
    <div>
        REST URL for all members: /rest/members
    </div>
    <div>
        <input type="button" ng-click="refresh()" name="refresh"
               id="refresh" value="Refresh"/>
    </div>
</div></code>```

答: Change controller: MembersCtrl to controller: 'MembersCtrl' in $routeProvider config

Title: angular controller by module blank page

Body:
hello i have a problem with angular im benninger to this framework but i have some knowledge about it . Yesterday i faced a problem when i wanted to change controller from a global function(in this case all is OK) to controller by module i recive blank page here is my code

angular.module('myApp', ['ngRoute', 'membersService']).config(
['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
    $routeProvider.when('/home', {
        templateUrl: 'partials/home.html',
        controller: MembersCtrl
    }).otherwise({
        redirectTo: '/home'
    });
}]);

var myApp = angular.module('myApp');
myApp.controller('MembersCtrl',['$scope','$http', 'MembersSrv',function ($scope, $http, MembersSrv) {

$scope.refresh = function () {
    return MembersSrv.getAllPersons().then(function (data) {
        $scope.persons = data.data;
    });
};

$scope.clearMessages = function () {
    $scope.successMessages = '';
    $scope.errorMessages = '';
    $scope.errors = {};
};

$scope.reset = function () {
    if ($scope.regForm) {
        $scope.regForm.$setPristine();
    }
    $scope.newPerson = {name: "", lname: "", phoneNumber: ""};
    $scope.clearMessages();
};

$scope.register = function () {
    $scope.clearMessages();

    MembersSrv.save($scope.newPerson, function (data) {
        $scope.refresh();
        $scope.reset();
        $scope.successMessages = ['Member Registered'];
    }, function (result) {
        if ((result.status == 409) || (result.status == 400)) {
            $scope.errors = result.data;
        } else {
            $scope.errorMessages = ['Unknown  server error'];
        }
    });
};

$scope.refresh();
$scope.reset();
$scope.orderBy = 'name';
}]);

angular.module('membersService', []).service('MembersSrv', [
'$http', function ($http) {
    this.getAllPersons = function () {
        var url = "http://localhost:8080/gadziksy-web/rest/person";
        var req = {
            method: 'GET',
            url: url,
        };
        return $http(req);
    }
    }]);

<!DOCTYPE html>

    <title>myApp</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <meta name="format-detection" content="telephone=no"/>
    <link rel="stylesheet" href="css/screen.css" type="text/css"/>

<?xml version="1.0" encoding="UTF-8"?>

International Bank Application

You have successfully connected to the Application.

    <form name="regForm" ng-submit="register()">

Member Registration

        <fieldset>
            <legend>Register a member:</legend>

                Name:
                <input type="text" name="name" id="name" ng-model="newPerson.name" placeholder="Your Name" required
                       autofocus/>

                Lname:
                <input type="text" name="lname" id="lname" ng-model="newPerson.lname" placeholder="Your Lastname"
                       required/>

                Date
                <input type="date" name="dob" id="dob" ng-model="newPerson.dob" placeholder="Your Date" required/>

{{message}}

{{message}}

                <input type="submit" ng-disabled="regForm.$invalid" id="register" value="Register"/>
                <input type="button" ng-click="reset()" name="cancel"
                       id="cancel" value="Cancel"/>

        </fieldset>
    </form>

Persons

    No registered members.

            Id
            Name
            Lname
            Date
            REST URL

            {{person.id}}
            {{person.name}}
            {{person.lname}}
            {{person.dob}}
            details-{{person.id}}

        REST URL for all members: /rest/members

        <input type="button" ng-click="refresh()" name="refresh"
               id="refresh" value="Refresh"/>


问:
Double versus float
I have a constant for pi in my code:

const float PI = acos(-1);

Would it be better to declare it as a double?  An answer to another question on this site said floating point operations aren't exactly precise, and I'd like the constant to be accurate.

答:
As this site says, there are three overloaded versions of acos function.

Therefore the call acos(-1) is ambiguous.

Having said that, you should declare PI as long double to avoid any loss of precision, by using

```<code>   const long double PI = acos(-1.0L);
</code>```

Title: Double versus float

Body:
As this site says, there are three overloaded versions of acos function.

Therefore the call acos(-1) is ambiguous.

Having said that, you should declare PI as long double to avoid any loss of precision, by using

   const long double PI = acos(-1.0L);


问:
Extracting values from listbox
I created a UserForm in VBA with 2 ListBoxes.

What I want to do is extract values from the right ListBox (and keep them in temp) and delete every row in another sheet which contains these names.

Writing a code to delete rows is not an issues. I have no clue how to use these selected items in another VBA module. Any ideas?

答:
This code solved my issue</p>

```<code>Private Sub delete_button_Click()

On Error Resume Next

Dim custom_range(1 To 5) As Range

Set custom_range(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set custom_range(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells
Set custom_range(3) = ActiveWorkbook.Sheets("Costs").Columns(2).Cells
Set custom_range(4) = ActiveWorkbook.Sheets("Revenue").Columns(2).Cells
Set custom_range(5) = ActiveWorkbook.Sheets("FS").Columns(2).Cells

For i = 0 To ListBox_selected_countries.ListCount - 1
    country_to_delete = ListBox_selected_countries.List(i)

    For j = 1 To 5
    Set active_range = custom_range(j)
        For Each c In active_range
            If c.Value = country_to_delete Then
                c.EntireRow.delete
            End If
        Next c
    Next j

Next i

End Sub
</code>```

Title: Extracting values from listbox

Body:
This code solved my issue

Private Sub delete_button_Click()

On Error Resume Next

Dim custom_range(1 To 5) As Range

Set custom_range(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set custom_range(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells
Set custom_range(3) = ActiveWorkbook.Sheets("Costs").Columns(2).Cells
Set custom_range(4) = ActiveWorkbook.Sheets("Revenue").Columns(2).Cells
Set custom_range(5) = ActiveWorkbook.Sheets("FS").Columns(2).Cells

For i = 0 To ListBox_selected_countries.ListCount - 1
    country_to_delete = ListBox_selected_countries.List(i)

    For j = 1 To 5
    Set active_range = custom_range(j)
        For Each c In active_range
            If c.Value = country_to_delete Then
                c.EntireRow.delete
            End If
        Next c
    Next j

Next i

End Sub


问:
Send notification to android devices within a radius using Azure Notification Hub
I am building a prototyping using Azure Functions and Notification Hub.

Within my function I want a select a bunch of devices based on a geo spatial query and send a notification to these resulted devices.

I have notifications working with Firebase and Android but how can I target a random group of devices based on a query result?

```<code>#r "Microsoft.Azure.NotificationHubs"
#load "location.csx"

using System;
using System.Net;
using Microsoft.Azure.NotificationHubs;

public static async Task Run(LocationInfo message, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"Sending GCM notification of a new user");
    string gcmNotificationPayload = "{\"data\": {\"message\": \"test message")\" }}";
    log.Info($"{gcmNotificationPayload}");
    await notification.AddAsync(new GcmNotification(gcmNotificationPayload));
}
</code>```

答:
Your solution will depend on what you're trying to achieve. You didn't give much details about what kind of scenarios you're targeting.

But in general, without knowing what specifically you're looking for, you may find the following examples useful:

Geo-fenced push notifications with Azure Notification Hubs and Bing Spatial Data

Location based Push Notifications with Windows Azure Notification Hubs

You might also benefit from learning about Routing and tag expressions in Notification Hubs.

Body:
I am building a prototyping using Azure Functions and Notification Hub.

Within my function I want a select a bunch of devices based on a geo spatial query and send a notification to these resulted devices.

I have notifications working with Firebase and Android but how can I target a random group of devices based on a query result?

#r "Microsoft.Azure.NotificationHubs"
#load "location.csx"

using System;
using System.Net;
using Microsoft.Azure.NotificationHubs;

public static async Task Run(LocationInfo message, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"Sending GCM notification of a new user");
    string gcmNotificationPayload = "{\"data\": {\"message\": \"test message")\" }}";
    log.Info($"{gcmNotificationPayload}");
    await notification.AddAsync(new GcmNotification(gcmNotificationPayload));
}


问:
Onclick an element, sliding toggle of div
I am trying to do an accordian style opening/closing of div using jquery. But for some reason the next() in jquery doesn't seem to be working. I want when a title is clicked, all other div should be closed except the clicked one.

Html code --

```<code><div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
</code>```

Demo -- https://jsfiddle.net/v3hc19np/1/

Any help is highly appreciated.

答:
Solution:

Your div was not nested correctly, thus the next('div') could not be found. Here's how it should be:

```<code><div class="office-row">
  <h3 class="office-title">Title</h3>
  <div class="office">sadasd</div>
</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
  <div class="office">sadasd</div>
</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
  <div class="office">sadasd</div>
</div>
</code>```

Demo:
https://jsfiddle.net/v3hc19np/5/

Body:
I am trying to do an accordian style opening/closing of div using jquery. But for some reason the next() in jquery doesn't seem to be working. I want when a title is clicked, all other div should be closed except the clicked one.

Html code --

Title

sadasd

Title

sadasd

Title

Demo -- https://jsfiddle.net/v3hc19np/1/

Any help is highly appreciated.

Body:
Solution:

Your div was not nested correctly, thus the next('div') could not be found. Here's how it should be:

<div class="office-row">
  <h3 class="office-title">Title</h3>
  <div class="office">sadasd</div>
</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
  <div class="office">sadasd</div>
</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
  <div class="office">sadasd</div>
</div>

Demo:
https://jsfiddle.net/v3hc19np/5/


问:
Auto-generation of .NET unit tests
Is there such a thing as unit test generation? If so...

...does it work well?

...What are the auto generation solutions that are available for .NET?

...are there examples of using a technology like this?

...is this only good for certain types of applications, or could it be used to replace all manually written unit testing?

答:
Updated for 2017:

Unit Test Boilerplate Generator works for VS 2015-2017 and is being maintained. Seems to work as advertised.

OwnerDisplayName: Phobis

Title: Auto-generation of .NET unit tests


问:
Flex: Panel container loses borderSkin (embedded swf) when scrollbars appear
I've been asking around and googling like crazy, but can't figure this one out.
I have a panel in a flex-AIR app with a borderSkin - an @Embed swf symbol. Everything looks good till the panel has enough children added to merit a scrollbar, at which point the borderSkin disappears, leaving only the default background color. Remove the children and the borderskin comes back. The swf symbol uses scale9 grids.

What am I doing wrong? Any ideas?
Thanks in advance, Jeremy

答:
I did find the answer from a friend.
Apparently, the panel's background color disappears automatically when a custom borderskin is applied. However, when scrollbars are used, that background reappears - white being the default color - and fills the entire panel. Setting the panel's background alpha to 0 solves the problem.</p>


问:
Is it dangerous to create pure virtual function of a virtual function?
Let us suppose that we have an abstract class NonEditableSuperBase from which we create another abstract class MyBase.

The first class NonEditableSuperBase has a virtual function (non pure virtual). However, I want to force that if someone creates a class that derives from MyBase, he/she must provide an implementation to the mentioned function.

Hence, my idea is to define the function as pure virtual in MyBase.

My question: Is it a bad idea given that it was just virtual in NonEditableSuperBase?

Example:

```<code>//NonEditableSuperBase.h
class NonEditableSuperBase
{
  ...
  public:
    virtual int someMethod(); //It has an implementation, suppose {return 42;}
};

//MyBase.h
class MyBase: public NonEditableSuperBase
{
  public:
     explicit MyBase();
     virtual ~MyBase() = default;
     virtual int someMethod() = 0;  //I make it pure virtual
};

//MyBase.cpp
MyBase::MyBase() : NonEditableSuperBase() { }

//Now someone creates a derived class from MyBase.
class SuperDerived : public MyBase
{
  public:
    explicit SuperDerived();
    int someMethod(); //The user must create an implementation of the function
};
</code>```

Update:
As an example, in my case I want to create some derived classes from the QAbstractTableModel class of the Qt framework. To reuse some code I want to create an intermediate abstract class.

```<code>QAbstractTableModel <- MyAbstractModel <- MyModelA (or MyModelB ... etc).
</code>```

However, I want to ensure that the models (MyModelA, MyModelB) re-implement some of the virtual functions of QAbstractTableModel (like the ::index() function) because some of the additional methods of MyAbstractModel requires specific implementations of the primer functions.

答:
[I'm assuming that the intent was for MyBase to publicly derive from NonEditableSuperBase, which is not what the code sample in the question actually does.]

It doesn't seem inherently dangerous, but consider that a class like SuperDerived that derives from MyBase could explicitly choose to use the NonEditableSuperBase implementation.

```<code>class SuperDerived : public MyBase {
  public:
    using NonEditableSuperBase::someMethod;
    // Or, explicitly:
    // int someMethod() override { return NonEditableSuperBase::someMethod(); }
};
</code>```

This satisfies the pure-virtual requirement imposed by MyBase but acts exactly as if MyBase didn't have that requirement.  You've made the author of SuperDerived do something, but you haven't actually prevented them from using the ultimate base class's implementation.

Body:
Let us suppose that we have an abstract class NonEditableSuperBase from which we create another abstract class MyBase.

The first class NonEditableSuperBase has a virtual function (non pure virtual). However, I want to force that if someone creates a class that derives from MyBase, he/she must provide an implementation to the mentioned function.

Hence, my idea is to define the function as pure virtual in MyBase.

My question: Is it a bad idea given that it was just virtual in NonEditableSuperBase?

Example:

//NonEditableSuperBase.h
class NonEditableSuperBase
{
  ...
  public:
    virtual int someMethod(); //It has an implementation, suppose {return 42;}
};

//MyBase.h
class MyBase: public NonEditableSuperBase
{
  public:
     explicit MyBase();
     virtual ~MyBase() = default;
     virtual int someMethod() = 0;  //I make it pure virtual
};

//MyBase.cpp
MyBase::MyBase() : NonEditableSuperBase() { }

//Now someone creates a derived class from MyBase.
class SuperDerived : public MyBase
{
  public:
    explicit SuperDerived();
    int someMethod(); //The user must create an implementation of the function
};

Update:
As an example, in my case I want to create some derived classes from the QAbstractTableModel class of the Qt framework. To reuse some code I want to create an intermediate abstract class.

QAbstractTableModel <- MyAbstractModel <- MyModelA (or MyModelB ... etc).

However, I want to ensure that the models (MyModelA, MyModelB) re-implement some of the virtual functions of QAbstractTableModel (like the ::index() function) because some of the additional methods of MyAbstractModel requires specific implementations of the primer functions.

Body:
[I'm assuming that the intent was for MyBase to publicly derive from NonEditableSuperBase, which is not what the code sample in the question actually does.]

It doesn't seem inherently dangerous, but consider that a class like SuperDerived that derives from MyBase could explicitly choose to use the NonEditableSuperBase implementation.

class SuperDerived : public MyBase {
  public:
    using NonEditableSuperBase::someMethod;
    // Or, explicitly:
    // int someMethod() override { return NonEditableSuperBase::someMethod(); }
};

This satisfies the pure-virtual requirement imposed by MyBase but acts exactly as if MyBase didn't have that requirement.  You've made the author of SuperDerived do something, but you haven't actually prevented them from using the ultimate base class's implementation.


问:
Matching multiple patterns
I want to see, if "001" or "100" or "000" occurs in a string of 4 characters of 0 and 1. For example, a 4 character string could be like "1100" or "0010" or "1001" or "1111". How do I match many strings in a string with a single command?

I know grep could be used for pattern matching, but using grep, I can check only one string at a time. I want to know if multiple strings can be used with some other command or with grep itself.

答:
You can also use the %like% operator from data.table library.

```<code>library(data.table)

# input
  x <- c("1100", "0010", "1001", "1111")
  pattern <- "001|100|000"

# check for pattern
  x %like% pattern

> [1]  TRUE  TRUE  TRUE FALSE
</code>```

ContentLicense: CC BY-SA 4.0

Title: Matching multiple patterns

Body:
You can also use the %like% operator from data.table library.

library(data.table)

# input
  x <- c("1100", "0010", "1001", "1111")
  pattern <- "001|100|000"

# check for pattern
  x %like% pattern

> [1]  TRUE  TRUE  TRUE FALSE


问:
EXT JS: How to hide the fourth tab of the item based on some if condition?
I am new to ext js and I am trying to hide the fourth tab on my screen based on certain entity condition. As, I have coded I am able to disable
(blur) the 4th Setting tab, but the hidden or hide() function is failing.

Basically, I want to hide the fourth tab in items Payment.PaymentSettingsCfg on certain condition.
Any help would really appreciate, thanks in advance.

var bsdataloded = false;
Payment.PaymentSettingsCfg = {
  id: 'PaymentSettingsPanel',
  title: getMsg('PaymentAdmin', 'PaymentSettingsHeader'),
  xtype: 'PaymentSettingsPanels',
  listeners: {
    activate: function() {
      if (!bsdataloded) {
        this.loadSettings();
        bsdataloded = true;

      }
    }
  }

}
var hidePaymentSettingcfg = false;
debugger;
if (Payment.EntitySettings &&
  Payment.EntSettings["EntSITE|Payment_SWitch"] === "Y") {
  Payment.PaymentSettingsCfg.disabled = true; //working
  // Payment.PaymentSettingsCfg.hidden  = true;// not working, even hide() not working
  hidePaymentSettingcfg = true;

}
init: function() {
  Ext.QuickTips.init();
  Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
    expires: null
  }));

  app = new Payment.admin.AppContainer({
    id: 'main-panel',
    title: Payment.getMsg('PaymentAdmin', 'PaymentConfHeader'),
    el: 'bodydiv',
    border: true,
    layout: 'fit',
    defaults: {
      border: false
    },
    items: [{
      xtype: 'tabpanel',
      activeTab: 0,
      width: 500,
      deferredRender: false,
      hidden: false,
      defaults: {
        border: false
      },
      items: [
        Payment.PaymentItemCfg,
        Payment.PaymentPeriodCfg,
        Payment.PaymentTypeCfg,
        Payment.PaymentSettingsCfg
      ]
    }]
  });
  app.render();
}

};
}();```

答:
Added the logic to the listeners and it worked.

listeners : {
    afterrender : function(){

```<code>var testTab = this.getTabEl(3);
if (Payment.EntSettings["EntSITE|Payment_SWitch"] === "Y") {
    testTab.hide();
}

}
</code>```

}

Body:
Added the logic to the listeners and it worked.

listeners : {
    afterrender : function(){

var testTab = this.getTabEl(3);
if (Payment.EntSettings["EntSITE|Payment_SWitch"] === "Y") {
    testTab.hide();
}

}

}


问:
Citrus Framework - Can a variable be assigned from a response?
I'm trying to test the following two REST calls:

Request 1

```<code>GET getLatestVersion
Response: {"version": 10}
</code>```

Request 2

```<code>POST getVersionData (body={"version": 10})
Response: {"version": 10, data: [...]}
</code>```

Is it possible to assign the "version" from Request 1 to a variable to use in Request 2 within the same test?

```<code>@CitrusTest(name = "SimpleIT.getVersionTest")
public void getVersionTest() {
    // Request 1
    http()
            .client("restClient")
            .send()
            .get("/getLatestVersion")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            // Can the version be assigned to a variable here?
            .payload("{\"version\":10}");

    // Request 2
    http()
            .client("restClient")
            .send()
            .post("/getVersionData")
            // Idealy this would be a Citrus variable from the previous response
            .payload("{\"version\":10}")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            .payload("\"version\": 10, data: [...]");
}
</code>```

答:
You can use JsonPath expressions:

```<code>http()
    .client("restClient")
    .receive()
    .response(HttpStatus.OK)
    .messageType(MessageType.JSON)
    .extractFromPayload("$.version", "apiVersion")
    .payload("{\"version\":\"@ignore@\"}");
</code>```

Or you can use the create variable matcher in payload:

```<code>http()
    .client("restClient")
    .receive()
    .response(HttpStatus.OK)
    .messageType(MessageType.JSON)
    .payload("{\"version\":\"@variable('apiVersion')@\"}");
</code>```

Both options will create a new test variable apiVersion that you can reference with ${apiVersion} in further test actions.

Body:
I'm trying to test the following two REST calls:

Request 1

GET getLatestVersion
Response: {"version": 10}

Request 2

POST getVersionData (body={"version": 10})
Response: {"version": 10, data: [...]}

Is it possible to assign the "version" from Request 1 to a variable to use in Request 2 within the same test?

@CitrusTest(name = "SimpleIT.getVersionTest")
public void getVersionTest() {
    // Request 1
    http()
            .client("restClient")
            .send()
            .get("/getLatestVersion")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            // Can the version be assigned to a variable here?
            .payload("{\"version\":10}");

    // Request 2
    http()
            .client("restClient")
            .send()
            .post("/getVersionData")
            // Idealy this would be a Citrus variable from the previous response
            .payload("{\"version\":10}")
            .accept("application/json");

    http()
            .client("restClient")
            .receive()
            .response(HttpStatus.OK)
            .messageType(MessageType.JSON)
            .payload("\"version\": 10, data: [...]");
}

Body:
You can use JsonPath expressions:

http()
    .client("restClient")
    .receive()
    .response(HttpStatus.OK)
    .messageType(MessageType.JSON)
    .extractFromPayload("$.version", "apiVersion")
    .payload("{\"version\":\"@ignore@\"}");

Or you can use the create variable matcher in payload:

http()
    .client("restClient")
    .receive()
    .response(HttpStatus.OK)
    .messageType(MessageType.JSON)
    .payload("{\"version\":\"@variable('apiVersion')@\"}");

Both options will create a new test variable apiVersion that you can reference with ${apiVersion} in further test actions.


问:
php & mysql: Proper handling of all types of queries
I would like to make one universal function for database queries.
The function I have below works perfectly for SELECT queries.
However I would like to have it working properly for INSERT, UPDATE,
DROP and other queries not returning anything. Can someone tell me
why using mysqli_fetch_all for such queries prints warning? How
to properly handle it? How to obtain status of such queries?</p>

```<code>function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        print("ERROR\nFAILED_TO_QUERY\n");
        return;
    }

    // Obtain results
    $rows = mysqli_fetch_all($result, MYSQL_ASSOC);
    if(!$rows) {
        print("OK\n0\n0\n");
        return;
    }

    // Print result array keys
    $keys = array_keys($rows[0]);
    print("OK\n" . count($keys) . "\n");
    foreach($keys as $key)
        print($key . "\n");

    // Print result rows
    print(count($rows) . "\n");
    foreach($rows as $row)
        foreach($row as $value)
            print($value . "\n");
}
</code>```

答:
From the manual:

mysqli_query

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

So, when you do a data modification query (INSERT for example), you get boolean value. When you try to pass it as argument for mysqli_fetch_all() you get an error, because this function expects an instance of mysqli_result class.

Body:
I would like to make one universal function for database queries.
The function I have below works perfectly for SELECT queries.
However I would like to have it working properly for INSERT, UPDATE,
DROP and other queries not returning anything. Can someone tell me
why using mysqli_fetch_all for such queries prints warning? How
to properly handle it? How to obtain status of such queries?

function cms_query($sql_query)
{
    // Object returned by mysqli_connect
    global $cms_db;

    // Perform query
    $result = mysqli_query($cms_db, $sql_query);
    if(!$result) {
        print("ERROR\nFAILED_TO_QUERY\n");
        return;
    }

    // Obtain results
    $rows = mysqli_fetch_all($result, MYSQL_ASSOC);
    if(!$rows) {
        print("OK\n0\n0\n");
        return;
    }

    // Print result array keys
    $keys = array_keys($rows[0]);
    print("OK\n" . count($keys) . "\n");
    foreach($keys as $key)
        print($key . "\n");

    // Print result rows
    print(count($rows) . "\n");
    foreach($rows as $row)
        foreach($row as $value)
            print($value . "\n");
}