问:
echo user information on a product not working in codeigniter
I have been trying to echo user information on a product but its not working. I used to try it with this join function in my model :

```<code> public function getdata()
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->join('products','products.user_id = users.user_id');
        $query = $this->db->get();
        if($query->num_rows()>0)
        {
           return $query->result_array();
        }
    }
</code>```

It didn't work properly because it echoed for example all the usernames from the database when I tried to echo a username that belongs to the same user_id.

Now I tried to do it like this:

This is my Controller function (AlleCadeausController):

```<code>public function index()
{
     /** Laad de models **/
    $this->load->model('Product_model');
    $selectProducts = $this->Product_model->selectProducts();
    foreach ($selectProducts as $key => $product)
    {
        # first name
        $user = $this->Product_model->get_user_name($product['user_id']);
        #append both NEW VALUES to same array
        $data[$key]['voornaam'] = $user[0]['voornaam'];
    }
     /** Make $data **/
    $data['products'] = $this->Product_model->selectProducts();
     /** Laad de allecadeaus view en geef $data mee **/
    $this->load->view('allecadeaus', $data);
}
</code>```

My model functions in my Prduct_model.php file:

```<code>public function selectProducts()
{
    $query= $this->db->query("SELECT * FROM products");
    $result = $query->result_array();
    return $result;
}

function get_user_name($name)
{
    $query= $this->db->query("SELECT voornaam FROM users WHERE user_id = $name ");
    $result = $query->result_array();
    return $result;
}
</code>```

And this is how I tried to echo the user information in the product foreach loop in the view:

```<code><?php foreach($products as $product) : ?>
    <a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">
        <div class="main-products">
            <img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">
            <div class="product_naam"><?php echo $product["product_naam"]; ?></div>
            <div class="ophaal_plaats"><?php  echo $product["ophaal_plaats"]; ?></div>
        </div>
    </a>
    <div class="aangeboden_door">
        <p>
            <tr>
                <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
                <td><?php echo $product['voornaam'];?></td>
            </tr>
        </p>
    </div>
<?php endforeach; ?>
</code>```

at this line :

<?php echo $product['voornaam'];?>	I try to echo the first
  name of the user of the product but its not working.
      The PHP error that I'm receiving is: undefined index: voornaam , line: 55 which is this line: <?php echo
  $product['voornaam'];?>

Database information of both tables products and users:

```<code>Table 1 : products:

product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id

table 2 : users:

user_id
email
voornaam
achternaam
beschrijving
profiel_foto
</code>```

答:
You can use the active records instead of create multiple function:

Your controller:

```<code>public function index()
{
    $data = array();
    $this->load->model('product_model');
    $data['products'] = $this->product_model->selectProducts();
    $this->load->view('allecadeaus', $data);
}
</code>```

Your view:

Your view:

```<code><?php foreach($products as $product) : ?>
<a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">
  <div class="main-products">
    <img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">
    <div class="product_naam"><?php echo $product["product_naam"]; ?></div>
    <div class="ophaal_plaats"><?php  echo $product["ophaal_plaats"]; ?></div>
  </div>
</a>
<div class="aangeboden_door">
  <p>
    <tr>
      <?php
          //Here is the active record query which is getting the 'voorname' and other data
          $userarray = $this->db->get_where('users', array('user_id'=>$product["user_id"]))->row_array();
          // you can print_r($userarray); for see the array you get
      ?>
      <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
      <td><?php echo $userarray['voornaam'];?></td>
    </tr>
  </p>
</div>
<?php endforeach; ?>
</code>```

Body:
I have been trying to echo user information on a product but its not working. I used to try it with this join function in my model :

 public function getdata()
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->join('products','products.user_id = users.user_id');
        $query = $this->db->get();
        if($query->num_rows()>0)
        {
           return $query->result_array();
        }
    }

It didn't work properly because it echoed for example all the usernames from the database when I tried to echo a username that belongs to the same user_id.

Now I tried to do it like this:

This is my Controller function (AlleCadeausController):

public function index()
{
     /** Laad de models **/
    $this->load->model('Product_model');
    $selectProducts = $this->Product_model->selectProducts();
    foreach ($selectProducts as $key => $product)
    {
        # first name
        $user = $this->Product_model->get_user_name($product['user_id']);
        #append both NEW VALUES to same array
        $data[$key]['voornaam'] = $user[0]['voornaam'];
    }
     /** Make $data **/
    $data['products'] = $this->Product_model->selectProducts();
     /** Laad de allecadeaus view en geef $data mee **/
    $this->load->view('allecadeaus', $data);
}

My model functions in my Prduct_model.php file:

public function selectProducts()
{
    $query= $this->db->query("SELECT * FROM products");
    $result = $query->result_array();
    return $result;
}

function get_user_name($name)
{
    $query= $this->db->query("SELECT voornaam FROM users WHERE user_id = $name ");
    $result = $query->result_array();
    return $result;
}

And this is how I tried to echo the user information in the product foreach loop in the view:

<?php foreach($products as $product) : ?>
    <a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">

            <img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">

<?php echo $product["product_naam"]; ?>

<?php  echo $product["ophaal_plaats"]; ?>

                <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
                <?php echo $product['voornaam'];?>

<?php endforeach; ?>

at this line :

<?php echo $product['voornaam'];?>	I try to echo the first
  name of the user of the product but its not working.
      The PHP error that I'm receiving is: undefined index: voornaam , line: 55 which is this line: <?php echo
  $product['voornaam'];?>

Database information of both tables products and users:

Table 1 : products:

product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id

table 2 : users:

user_id
email
voornaam
achternaam
beschrijving
profiel_foto

Body:
You can use the active records instead of create multiple function:

Your controller:

public function index()
{
    $data = array();
    $this->load->model('product_model');
    $data['products'] = $this->product_model->selectProducts();
    $this->load->view('allecadeaus', $data);
}

Your view:

Your view:

<?php foreach($products as $product) : ?>
<a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">
  <div class="main-products">
    <img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">
    <div class="product_naam"><?php echo $product["product_naam"]; ?></div>
    <div class="ophaal_plaats"><?php  echo $product["ophaal_plaats"]; ?></div>
  </div>
</a>
<div class="aangeboden_door">
  <p>
    <tr>
      <?php
          //Here is the active record query which is getting the 'voorname' and other data
          $userarray = $this->db->get_where('users', array('user_id'=>$product["user_id"]))->row_array();
          // you can print_r($userarray); for see the array you get
      ?>
      <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
      <td><?php echo $userarray['voornaam'];?></td>
    </tr>
  </p>
</div>
<?php endforeach; ?>


来源: stackexchange

问:
Eloquent model events not firing when using relations
I have a typical event hook for soft deleting children:

```<code>public static function boot()
{
    parent::boot();
    static::deleted(function($model1)
    {
        $model1->hasmanyrelation()->delete();
    });
}
</code>```

and

```<code>public function hasmanyrelation()
{
    return $this->hasMany('Model2');
}
</code>```

Now when I use:

```<code>$model0->model1->each(function($model1){$model1->delete();});
</code>```

things work as expected and model2 children of model 1 get (soft) deleted. But when I use:

```<code>$model0->model1()->delete();
</code>```

then all related model1 records get deleted but model2 and all its records remain untouched. What is wrong with the latter, simpler syntax that it deletes model1 records but skips its model events??

答:
refactor this :

```<code>$model1->hasmanyrelation()->delete();
</code>```

to

```<code>$models = $model1->hasmanyrelation;
foreach($models as $model){
    $model->delete()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a typical event hook for soft deleting children:

public static function boot()
{
    parent::boot();
    static::deleted(function($model1)
    {
        $model1->hasmanyrelation()->delete();
    });
}

and

public function hasmanyrelation()
{
    return $this->hasMany('Model2');
}

Now when I use:

$model0->model1->each(function($model1){$model1->delete();});

things work as expected and model2 children of model 1 get (soft) deleted. But when I use:

$model0->model1()->delete();

then all related model1 records get deleted but model2 and all its records remain untouched. What is wrong with the latter, simpler syntax that it deletes model1 records but skips its model events??

Body:
refactor this :

$model1->hasmanyrelation()->delete();

to

$models = $model1->hasmanyrelation;
foreach($models as $model){
    $model->delete()
}


问:
is it possible to use twice ifPresent each one checking different return or bifurcate map
Context: I have chained objects generated by wsdl2java. There is an already created method that call the soap web services, receives the xml and unmarshalling it in cascaded objects.

Desire: I want to get two different objects which lies in different hierarchy nodes. From mapping perspective they are hold "far" from one another but from business perspective they are a "couple".

This is currently working:

```<code>Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()));

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));
</code>```

What I am trying is something like (pseudo-explanation):

```<code>Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()))
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));
</code>```

I understand that this doesn't work because I can have only one terminate clausure and ifPresent appears twice.

From dummy viewpoint, my question could be also: is it possible to fork/bifurcate/divide map in two different direction in same lambda expression?

*** Based on Eugene suggestion I did successfully

```<code>Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode)
        .ifPresent(o -> {
            System.out.println(o.getValue().getValue());
            System.out.println(o.getBeschrijving().getValue());
        });
</code>```

I changed from myMethod to System.out.println so no confusion is caused (I don't care about myMethod in this context. It could be anyother method of any instanced object).

Althought it works and it sounds a good progress compared to original one (instead of two lambda sentences there are only one), I see some problem: "o.getValue().getValue()" and  "o.getBeschrijving().getValue()" are null unsafety, aren't they?

答:
You can catch your result like that:

```<code>Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode)
    .map(CodeOndernemingOfVestigingType::getValue)
    .map(o -> {
        myMethod("onderneming_type", o.getValue());
        return o.getBeschrijving();
    })
    .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));
</code>```

Take a notice, that multiline lambdas are bad and hard to read, so you can extract it into private method.

EDIT
You want to branch your Optional. Is not possible and you should do:

```<code>Optional<Code> op = Optional.ofNullable(onderneming.getOndernemingOfVestiging())
    .map(OndernemingOfVestigingType::getCode)

op.map(CodeOndernemingOfVestigingType::getValue)
    .ifPresent(o -> myMethod("onderneming_type", o.getValue()));

op.map(CodeOndernemingOfVestigingType::getBeschrijving)
    .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));
</code>```

It should be more readable than do some hacks.

Body:
Context: I have chained objects generated by wsdl2java. There is an already created method that call the soap web services, receives the xml and unmarshalling it in cascaded objects.

Desire: I want to get two different objects which lies in different hierarchy nodes. From mapping perspective they are hold "far" from one another but from business perspective they are a "couple".

This is currently working:

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()));

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

What I am trying is something like (pseudo-explanation):

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()))
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

I understand that this doesn't work because I can have only one terminate clausure and ifPresent appears twice.

From dummy viewpoint, my question could be also: is it possible to fork/bifurcate/divide map in two different direction in same lambda expression?

*** Based on Eugene suggestion I did successfully

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode)
        .ifPresent(o -> {
            System.out.println(o.getValue().getValue());
            System.out.println(o.getBeschrijving().getValue());
        });

I changed from myMethod to System.out.println so no confusion is caused (I don't care about myMethod in this context. It could be anyother method of any instanced object).

Althought it works and it sounds a good progress compared to original one (instead of two lambda sentences there are only one), I see some problem: "o.getValue().getValue()" and  "o.getBeschrijving().getValue()" are null unsafety, aren't they?

Body:
You can catch your result like that:

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode)
    .map(CodeOndernemingOfVestigingType::getValue)
    .map(o -> {
        myMethod("onderneming_type", o.getValue());
        return o.getBeschrijving();
    })
    .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

Take a notice, that multiline lambdas are bad and hard to read, so you can extract it into private method.

EDIT
You want to branch your Optional. Is not possible and you should do:

Optional<Code> op = Optional.ofNullable(onderneming.getOndernemingOfVestiging())
    .map(OndernemingOfVestigingType::getCode)

op.map(CodeOndernemingOfVestigingType::getValue)
    .ifPresent(o -> myMethod("onderneming_type", o.getValue()));

op.map(CodeOndernemingOfVestigingType::getBeschrijving)
    .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

It should be more readable than do some hacks.


问:
Conflict libraries lodash.js and underscore.js
My project uses the lodash.js library. Off I need to add my project to another project that uses the underscore.js library.
This puts me in conflict errors between these two libraries.

I tried writing this, but it does not change anything:

```<code><script src="/web/externals/underscore/underscore.js"></script>
<script src="/web/externals/lodash/lodash.js"></script>

<script>
    window.lodash = _.noConflict();
    window.underscore = _.noConflict();
</script>

<app-root></app-root>
<script type="text/javascript" src="/etc/inline.bundle.js"></script>
<script type="text/javascript" src="/etc/polyfills.bundle.js"></script>
</code>```

//////////EDIT////////

```<code><script src="/web/externals/underscore/underscore.js"></script>
<script src="/web/externals/lodash/lodash.js"></script>

<script>
    var lodash = _.noConflict()
</script>

<app-root></app-root>
<script type="text/javascript" src="/etc/chat/inline.bundle.js"></script>
<script type="text/javascript" src="/etc/chat/polyfills.bundle.js"></script>
</code>```

答:
You only need to call noConflict once, and you don't need to alter the window object either (though you can it is completely unnecessary). Copy the below code, put it in an HTML file, load it in your favorite browser and check the console. You will see it works without any conflicts

```<code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
<script>
    var __ = _.noConflict();
</script>

<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
  var string = 'test';
  var array = ['1', '2', '3'];

  //starts with is a lodash function
  console.log(__.startsWith(string, 't'));

  //shuffle is an underscore function
  console.log(_.shuffle(array));
</script>
</code>```

You can name the lodash variable whatever you want, and keep underscore as _

If you'd rather keep lodash as _ and rename underscore just swap the load order of the 2 scripts

```<code> <script src="http://underscorejs.org/underscore-min.js"></script>
<script>
    var __ = _.noConflict();
</script>

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
<script>
  var string = 'test';
  var array = ['1', '2', '3'];

  console.log(_.startsWith(string, 't'));
  console.log(__.shuffle(array));
</script>
</code>```

If this doesn't work for you then there is something else wrong and you need to post more code.

Body:
My project uses the lodash.js library. Off I need to add my project to another project that uses the underscore.js library.
This puts me in conflict errors between these two libraries.

I tried writing this, but it does not change anything:

<app-root></app-root>

//////////EDIT////////

<app-root></app-root>

Body:
You only need to call noConflict once, and you don't need to alter the window object either (though you can it is completely unnecessary). Copy the below code, put it in an HTML file, load it in your favorite browser and check the console. You will see it works without any conflicts

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
<script>
    var __ = _.noConflict();
</script>

<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
  var string = 'test';
  var array = ['1', '2', '3'];

  //starts with is a lodash function
  console.log(__.startsWith(string, 't'));

  //shuffle is an underscore function
  console.log(_.shuffle(array));
</script>

You can name the lodash variable whatever you want, and keep underscore as _

If you'd rather keep lodash as _ and rename underscore just swap the load order of the 2 scripts

 <script src="http://underscorejs.org/underscore-min.js"></script>
<script>
    var __ = _.noConflict();
</script>

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
<script>
  var string = 'test';
  var array = ['1', '2', '3'];

  console.log(_.startsWith(string, 't'));
  console.log(__.shuffle(array));
</script>

If this doesn't work for you then there is something else wrong and you need to post more code.


问:
Wordress index page redirects to another page
I have change the directory of my wordpress project from

/root/demoweb/web to /root

but index page still redirecting to old one.

I have changed the .htaccess configurations and settings/ general admin settings also.

what should i do ?

答:
This is the queries I usually perform (of course replace the value old_url and new_url by yours):

```<code>UPDATE wp_options SET option_value = replace(option_value, 'old_url', 'new_url') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'old_url', 'new_url');

UPDATE wp_posts SET post_content = replace(post_content, 'old_url', 'new_url');

UPDATE wp_postmeta SET meta_value = replace(meta_value, 'old_url', 'new_url');
</code>```

Then checking if there is a redirect in .htaccess.

Then accessing the admin URL by going to my new_url/wp-admin/ and regenerating the permalinks (Settings > Permalinks, and click save changes).

Last one: clean your cache if you got a caching plugin or server-module.

Body:
This is the queries I usually perform (of course replace the value old_url and new_url by yours):

UPDATE wp_options SET option_value = replace(option_value, 'old_url', 'new_url') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'old_url', 'new_url');

UPDATE wp_posts SET post_content = replace(post_content, 'old_url', 'new_url');

UPDATE wp_postmeta SET meta_value = replace(meta_value, 'old_url', 'new_url');

Then checking if there is a redirect in .htaccess.

Then accessing the admin URL by going to my new_url/wp-admin/ and regenerating the permalinks (Settings > Permalinks, and click save changes).

Last one: clean your cache if you got a caching plugin or server-module.


问:
Rails - Using true and false
I have the following in my controller:

```<code>if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end
</code>```

Then later in create.je.erb do:

```<code><% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>
</code>```

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

答:
Rails.logger.info false incorrectly outputs nothing (see my answer to your other question), so I think that's hiding whatever your real problem is.

ERB <%= something %> implicitly calls something.to_s, but false.to_s == 'false', so the most likely explanation for what you're seeing is that @archived_new_status is somehow not getting set at all, or not getting passed to the view template.

ContentLicense: CC BY-SA 2.5

Title: Rails - Using true and false

Body:
I have the following in my controller:

if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end

Then later in create.je.erb do:

<% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?


问:
rm -f fails for missing files when using "bash -e" as shell in GNU Make 4
I have a Makefile that looks as follows:

```<code>.ONESHELL:
SHELL = /bin/bash
.SHELLFLAGS = -e

clean:
    rm -f foo

.PHONY: clean
</code>```

foo doesn't exist. When I run this on Debian, GNU Make 4.1 I get this error:

```<code>rm -f foo
/bin/bash: rm -f foo: No such file or directory
Makefile:6: recipe for target 'clean' failed
make: *** [clean] Error 1
</code>```

When I run it on macOS, GNU Make 3.81 it works as expected. It makes no difference if I write -rm -f instead of rm -f.

Why do I get the error? Running bash -e -c "rm -f foo" ; echo $? in a shell prints 0 on both systems.

Am I missing something?

答:
That is an invalid setting for .SHELLFLAGS.  It will result in this being invoked:

```<code>/bin/sh -e 'rm -f foo'
</code>```

which is not a valid command line; it's telling the shell to run a program named, literally, rm -f foo which is obviously wrong.  You have to be sure you add the -c option as well, and since many shells only allow options in the first argument, you'll need:

```<code>.SHELLFLAGS = -ec
</code>```

This is documented in the GNU make manual.

The reason it "works" in the older GNU make 3.81 is that this version doesn't support the .SHELLFLAGS option at all, so that line is just ignored.

Body:
I have a Makefile that looks as follows:

.ONESHELL:
SHELL = /bin/bash
.SHELLFLAGS = -e

clean:
    rm -f foo

.PHONY: clean

foo doesn't exist. When I run this on Debian, GNU Make 4.1 I get this error:

rm -f foo
/bin/bash: rm -f foo: No such file or directory
Makefile:6: recipe for target 'clean' failed
make: *** [clean] Error 1

When I run it on macOS, GNU Make 3.81 it works as expected. It makes no difference if I write -rm -f instead of rm -f.

Why do I get the error? Running bash -e -c "rm -f foo" ; echo $? in a shell prints 0 on both systems.

Am I missing something?

Body:
That is an invalid setting for .SHELLFLAGS.  It will result in this being invoked:

/bin/sh -e 'rm -f foo'

which is not a valid command line; it's telling the shell to run a program named, literally, rm -f foo which is obviously wrong.  You have to be sure you add the -c option as well, and since many shells only allow options in the first argument, you'll need:

.SHELLFLAGS = -ec

This is documented in the GNU make manual.

The reason it "works" in the older GNU make 3.81 is that this version doesn't support the .SHELLFLAGS option at all, so that line is just ignored.


问:
How to create a number menu in python
i need a simple python code which makes a number menu, that doesn't take up many lines

```<code>    print ("Pick an option")
    menu =0
    Menu = input("""
    1. Check Password
    2. Generate Password
    3. Quit
    """)
    if (menu) == 1:
        Password = input("Please enter the password you want to check")
        points =0
</code>```

i tried this but it did not work how i thought it would. i thought this code would work as i have tried it before and it worked but i must have made a mistake in this one.

anyone have any suggestions?

thanks

this is my full code:

```<code>    print ("Pick an option")
    menu =0
    Menu = input("""
    1. Check Password
    2. Generate Password
    3. Quit
    """)
        if (menu) == 1:
        Password = input("Please enter the password you want to check")
        points =0
        smybols = ['!','%','^','&','*','(',')','-','_','=','+',]
        querty =
      ["qwertyuiop","QWERTYUIOP","asdfghjl","ASDFGHJKL","zxcvbnm","ZXCVBNM"]
if len(password) >24:
    print ('password is too long It must be between 8 and 24 characters')
elif len(password) <8:
    print ('password is too short It must be between 8 and 24 characters')
elif len(password) >=8 and len(password) <= 24:
    print ('password ok\n')
</code>```

答:
There are some fundamental flaws with your code that tells us you are not sure what the difference between types are (str vs int), or what some functions actually do (input()). These need to be corrected before you progress any further with your program.

Lets take a look at what your code currently does:

```<code>print ("Pick an option") # prints a message
menu = 0 # initializes a variable (menu) of type int to 0
Menu = input("""    # prints a message to receive input for variable (Menu) of type str
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1:  # conditional check against (menu) to int of 1
    ...
</code>```

Now stop here and look a little closer:

menu = 0 this sets a variable called menu equal to 0; the variable has a lowercase m and is of type int since you initialized it with an int.

Menu = input(...) this sets a variable called Menu equal to a str received from input(). So if you input 1, then what happens is a str is returned such that Menu = '1'. Notice that the variable has an uppercase M unlike menu before it; also note the ' ' around the 1. That means this is a str.

if (menu) == 1:... this checks the lower case'd menu against 1. Well you initialized menu = 0 and then you never touch the lower case'd menu again, so when you get to this it is still 0. So of course this will fail.

Given all that, here is what you can do to fix your code:

```<code>menu = 0
menu = int(input("Pick an option:\n"
                 "1. Check Password\n"
                 "2. Generate Password\n"
                 "3. Quit\n\n"
                 "Option Selected: ")
if (menu) == 1:
    ....
</code>```

Title: How to create a number menu in python

Body:
i need a simple python code which makes a number menu, that doesn't take up many lines

    print ("Pick an option")
    menu =0
    Menu = input("""
    1. Check Password
    2. Generate Password
    3. Quit
    """)
    if (menu) == 1:
        Password = input("Please enter the password you want to check")
        points =0

i tried this but it did not work how i thought it would. i thought this code would work as i have tried it before and it worked but i must have made a mistake in this one.

anyone have any suggestions?

thanks

this is my full code:

    print ("Pick an option")
    menu =0
    Menu = input("""
    1. Check Password
    2. Generate Password
    3. Quit
    """)
        if (menu) == 1:
        Password = input("Please enter the password you want to check")
        points =0
        smybols = ['!','%','^','&','*','(',')','-','_','=','+',]
        querty =
      ["qwertyuiop","QWERTYUIOP","asdfghjl","ASDFGHJKL","zxcvbnm","ZXCVBNM"]
if len(password) >24:
    print ('password is too long It must be between 8 and 24 characters')
elif len(password) <8:
    print ('password is too short It must be between 8 and 24 characters')
elif len(password) >=8 and len(password) <= 24:
    print ('password ok\n')

Body:
There are some fundamental flaws with your code that tells us you are not sure what the difference between types are (str vs int), or what some functions actually do (input()). These need to be corrected before you progress any further with your program.

Lets take a look at what your code currently does:

print ("Pick an option") # prints a message
menu = 0 # initializes a variable (menu) of type int to 0
Menu = input("""    # prints a message to receive input for variable (Menu) of type str
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1:  # conditional check against (menu) to int of 1
    ...

Now stop here and look a little closer:

menu = 0 this sets a variable called menu equal to 0; the variable has a lowercase m and is of type int since you initialized it with an int.

Menu = input(...) this sets a variable called Menu equal to a str received from input(). So if you input 1, then what happens is a str is returned such that Menu = '1'. Notice that the variable has an uppercase M unlike menu before it; also note the ' ' around the 1. That means this is a str.

if (menu) == 1:... this checks the lower case'd menu against 1. Well you initialized menu = 0 and then you never touch the lower case'd menu again, so when you get to this it is still 0. So of course this will fail.

Given all that, here is what you can do to fix your code:

menu = 0
menu = int(input("Pick an option:\n"
                 "1. Check Password\n"
                 "2. Generate Password\n"
                 "3. Quit\n\n"
                 "Option Selected: ")
if (menu) == 1:
    ....


问:
Why trim is not working?
I am trying to trim leading whitespaces from the string and I do not know what is wrong with my approach, any suggestions would be appreciated ?

Code:

this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();

am reading poNumber from csv file as "     IG078565 and IG083060 " and output also am getting same value with same whitespaces, not sure why ?

Updated

Adding complete method for better context:

```<code>public BillingDTO(String currency, String migrationId, String chargeId, String priceId, String poNumber, String otc,
            String billingClassId, String laborOnly) {
        super();
        this.currency = currency.equals("") ? currency : currency.trim();
        this.migrationId = migrationId.equals("") ? migrationId : migrationId.trim();
        this.chargeId = chargeId.equals("") ? chargeId : chargeId.trim();
        this.priceId = priceId.equals("") ? priceId : priceId.trim();
        this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
            //poNumber.trim();
        //System.out.println("poNumber:"+this.poNumber.trim());
        //this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
        this.otc = otc.equals("") ? otc : otc.trim();
        this.billingClassId = billingClassId.equals("") ? billingClassId : billingClassId.trim();
        this.laborOnly = laborOnly.equals("") ? "N" : laborOnly;
    }
</code>```

Thanks.

答: Are you sure you're reading the right variable for your output? You have 'poNumber', which is the original untrimmed string, and 'this.poNumber', which would get the trimmed string.</p>

Title: Why trim is not working?

Body:
I am trying to trim leading whitespaces from the string and I do not know what is wrong with my approach, any suggestions would be appreciated ?

Code:

this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();

am reading poNumber from csv file as "     IG078565 and IG083060 " and output also am getting same value with same whitespaces, not sure why ?

Updated

Adding complete method for better context:

public BillingDTO(String currency, String migrationId, String chargeId, String priceId, String poNumber, String otc,
            String billingClassId, String laborOnly) {
        super();
        this.currency = currency.equals("") ? currency : currency.trim();
        this.migrationId = migrationId.equals("") ? migrationId : migrationId.trim();
        this.chargeId = chargeId.equals("") ? chargeId : chargeId.trim();
        this.priceId = priceId.equals("") ? priceId : priceId.trim();
        this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
            //poNumber.trim();
        //System.out.println("poNumber:"+this.poNumber.trim());
        //this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
        this.otc = otc.equals("") ? otc : otc.trim();
        this.billingClassId = billingClassId.equals("") ? billingClassId : billingClassId.trim();
        this.laborOnly = laborOnly.equals("") ? "N" : laborOnly;
    }

Thanks.


问:
Autocomplete with Token field in Angular 4
can anyone please tell me how add a autocomplete with token field in angular 4.

I want something below like this.

http://sliptree.github.io/bootstrap-tokenfield/

Thanks

答:
Try below links will helps to achieve

https://github.com/lw0110/quick-editor

https://www.npmjs.com/package/ngx-chips

https://www.npmjs.com/package/angular2-tag-input

ContentLicense: CC BY-SA 4.0


问:
Multiple Choice Quiz using Python loops
I am having issues understanding loops in python. Also I am having problems understanding how to add loops to my Python Quiz assignment. Can someone please give me guidance on this issue of mine. Below is my current code on my python multiple choice quiz.</p>

```<code>from datetime import datetime
now = datetime.now()

# showing the current date you're taking the quiz
print("Today's Date is:")
print('%s/%s/%s' % (now.month, now.day, now.year))

print("")

#this will print out my welcome statement and ask you for your name
print('Hello welcome to my Quiz, what is your name?')

#definied the variable username so that the user could type in their name
usersname = input()
print ("")
print('It is nice to meet you, ' + usersname)

print("")
level = input ('Please select a difficulty (easy, medium, or hard): ')

print("")#I just used this to add some space between my lines
print("")#I just used this to add some space between my lines

#these are my questions

easy_questions= ["What is 20 + 2 __1__", "What is the capital of Georgia__2__","If john has $4 and buys a candy bar for $3.50, how much money does he have left over__3__","What is the name of the NBA basketball team in Georgia__4__","What is the name of the NFL team in Georgia__5__","How many toys do I have if I sell 3, but had 8 toys originally__6__","How many Bad Boy movies are there__7__","How many Fast Furious movies are there__8__","What is 10 * 5 __9__","What city does the UGA team play in__10__"]

medium_questions= ["What is 20 + 2 __1__", "What is the capital of Georgia__2__","If john has $4 and buys a candy bar for $3.50, how much money does he have left over__3__","What is the name of the NBA basketball team in Georgia__4__","What is the name of the NFL team in Georgia__5__","How many toys do I have if I sell 3, but had 8 toys originally__6__","How many Bad Boy movies are there__7__","How many Fast Furious movies are there__8__","What is 10 * 5 __9__","What city does the UGA team play in__10__"]

hard_questions= ["What is 20 + 2 __1__", "What is the capital of Georgia__2__","If john has $4 and buys a candy bar for $3.50, how much money does he have left over__3__","What is the name of the NBA basketball team in Georgia__4__","What is the name of the NFL team in Georgia__5__","How many toys do I have if I sell 3, but had 8 toys originally__6__","How many Bad Boy movies are there__7__","How many Fast Furious movies are there__8__","What is 10 * 5 __9__","What city does the UGA team play in__10__"]
</code>```

答:
Loops are very elementary (in any language), so I would highly recommend you read up on them. Here is a useful link: https://www.tutorialspoint.com/python3/python_loops.htm

You could do something like this:

```<code>for question in easy_questions:
    answer = input(question)
    check_if_answer_is_correct(answer)
</code>```

Title: Multiple Choice Quiz using Python loops

Body:
I am having issues understanding loops in python. Also I am having problems understanding how to add loops to my Python Quiz assignment. Can someone please give me guidance on this issue of mine. Below is my current code on my python multiple choice quiz.

from datetime import datetime
now = datetime.now()

# showing the current date you're taking the quiz
print("Today's Date is:")
print('%s/%s/%s' % (now.month, now.day, now.year))

print("")

#this will print out my welcome statement and ask you for your name
print('Hello welcome to my Quiz, what is your name?')

#definied the variable username so that the user could type in their name
usersname = input()
print ("")
print('It is nice to meet you, ' + usersname)

print("")
level = input ('Please select a difficulty (easy, medium, or hard): ')

print("")#I just used this to add some space between my lines
print("")#I just used this to add some space between my lines

#these are my questions

easy_questions= ["What is 20 + 2 __1__", "What is the capital of Georgia__2__","If john has $4 and buys a candy bar for $3.50, how much money does he have left over__3__","What is the name of the NBA basketball team in Georgia__4__","What is the name of the NFL team in Georgia__5__","How many toys do I have if I sell 3, but had 8 toys originally__6__","How many Bad Boy movies are there__7__","How many Fast Furious movies are there__8__","What is 10 * 5 __9__","What city does the UGA team play in__10__"]

medium_questions= ["What is 20 + 2 __1__", "What is the capital of Georgia__2__","If john has $4 and buys a candy bar for $3.50, how much money does he have left over__3__","What is the name of the NBA basketball team in Georgia__4__","What is the name of the NFL team in Georgia__5__","How many toys do I have if I sell 3, but had 8 toys originally__6__","How many Bad Boy movies are there__7__","How many Fast Furious movies are there__8__","What is 10 * 5 __9__","What city does the UGA team play in__10__"]

hard_questions= ["What is 20 + 2 __1__", "What is the capital of Georgia__2__","If john has $4 and buys a candy bar for $3.50, how much money does he have left over__3__","What is the name of the NBA basketball team in Georgia__4__","What is the name of the NFL team in Georgia__5__","How many toys do I have if I sell 3, but had 8 toys originally__6__","How many Bad Boy movies are there__7__","How many Fast Furious movies are there__8__","What is 10 * 5 __9__","What city does the UGA team play in__10__"]

Body:
Loops are very elementary (in any language), so I would highly recommend you read up on them. Here is a useful link: https://www.tutorialspoint.com/python3/python_loops.htm

You could do something like this:

for question in easy_questions:
    answer = input(question)
    check_if_answer_is_correct(answer)


问:
Fullcalendar + Private google calendar
I m using full calendar for a web app project and I sync it with google calendar of my client, but for the moment only public calendar.

Is there any way to sync with a private calendar ?

Note : We use 0auth to identify and sync with Google account.

Thanks

答: I have tried in the backend with php, use the google php client library to get the events and then put it into fullcalendar. This way, it works.</p>

Title: Fullcalendar + Private google calendar


问:
asyncfileupload show image after upload without refreshing the page
I have been cracking at this for a while now with no luck.

Using asyncfileupload control to upload a file and display the image. The uploading works fine and image is displayed if I reload/refresh the page.

But need to know how I can do this without reloading/refreshing the page.

After reading online posts, I see a recommendation to use scriptmanager but this doesn't work for me:

```<code>    protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {

          .
          .
          .
          .

        ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert",
        "window.parent.document.getElementById('" + img_ProfilePic.ClientID + "').src='" + "http://www.site.com/default.jpg" + "');",
        true);
</code>```

}

Thank you,
Behrouz

答:
After a few days, that's right, few day of debugging, I found this is a bug:

http://ajaxcontroltoolkit.codeplex.com/workitem/26761

I hope this will save other people some time.

Body:
I have been cracking at this for a while now with no luck.

Using asyncfileupload control to upload a file and display the image. The uploading works fine and image is displayed if I reload/refresh the page.

But need to know how I can do this without reloading/refreshing the page.

After reading online posts, I see a recommendation to use scriptmanager but this doesn't work for me:

    protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {

          .
          .
          .
          .

        ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert",
        "window.parent.document.getElementById('" + img_ProfilePic.ClientID + "').src='" + "http://www.site.com/default.jpg" + "');",
        true);

}

Thank you,
Behrouz


问:
design database in star model
I have following tables in my database (this is only a single part).

C_location table - hold information about locations (about 500 row)

C_ProjectStatus table - hold information about ProjectStatus (about 5 rows)

Project table - hold information about projects (about 1 mln rows)

ProjectLocation - the list of location that the project is implemented (about 10mln rows, each project has about 10 locations)

ProjectLocationParticipant - hold the information about the Participants in each location (about 5 participant for each location about 50 mln rows).

In general this is not the whole DB, I have also other "one to many" relations for Project, ProjectLocaion, etc. For example each Project has many implementers (ProjectImplementers table with FK to project) and ProjectImplementer can have its own "one to many" relation table with FK to ProjectImplementer table. So I have 3 kind of tables

Main entity or root - the Project table

lookup table - C_ProjectStatus and C_Location

Sub-entity table - All the child tables for project table, like ProjectLocation, ProjectLocationParticipant, etc.

This is my database structure.

```<code>CREATE TABLE C_Location (
LocationID INT PRIMARY KEY CLUSTERED IDENTITY,
Name NVARCHAR(50)
)
GO
CREATE TABLE C_ProjectStatus (
ProjectStatusID INT IDENTITY PRIMARY KEY,
Name NVARCHAR(50)
)
CREATE TABLE Project (
ProjectID INT IDENTITY PRIMARY KEY,
Title NVARCHAR(50),
StartDate DATETIME,
ProjectStatusID INT FOREIGN KEY REFERENCES dbo.C_ProjectStatus(ProjectStatusID)
)
GO
CREATE TABLE ProjectLocation (
PojectLocationID INT IDENTITY PRIMARY KEY,
ProjectID INT FOREIGN KEY REFERENCES dbo.Project(ProjectID),
LocationID INT FOREIGN KEY REFERENCES dbo.C_Location(LocationID)
)
GO
CREATE TABLE PorjectLocationParticipant (
ProjectLocationParticipantID INT PRIMARY KEY IDENTITY,
ProjectLocationID INT FOREIGN KEY REFERENCES dbo.ProjectLocation(PojectLocationID),
ParticipantFirstName NVARCHAR(50),
ParticipantLastName NVARCHAR(50)
)
</code>```

I am very new in data warehouse so I need help to convert this structure to star schema.

答: create a table with all measures-called as fact table. In your case it would be all the primary keys of the existing tables into one table and establish foreign key relationships with them. The existing tables would be your dimensions. If projectlocation and project table form a parent child relationship and its the norm through out, by leaving the tables as they are now with an addition of fact table creates a snowflake schema. If you are looking only for a star schema, combine project and project location tables into one table(which becomes one dimension), and likewise for all tables. This way each dimension holds only data related to one entity of your data warehouse. </p>

Title: design database in star model

Body:
I have following tables in my database (this is only a single part).

C_location table - hold information about locations (about 500 row)

C_ProjectStatus table - hold information about ProjectStatus (about 5 rows)

Project table - hold information about projects (about 1 mln rows)

ProjectLocation - the list of location that the project is implemented (about 10mln rows, each project has about 10 locations)

ProjectLocationParticipant - hold the information about the Participants in each location (about 5 participant for each location about 50 mln rows).

In general this is not the whole DB, I have also other "one to many" relations for Project, ProjectLocaion, etc. For example each Project has many implementers (ProjectImplementers table with FK to project) and ProjectImplementer can have its own "one to many" relation table with FK to ProjectImplementer table. So I have 3 kind of tables

Main entity or root - the Project table

lookup table - C_ProjectStatus and C_Location

Sub-entity table - All the child tables for project table, like ProjectLocation, ProjectLocationParticipant, etc.

This is my database structure.

CREATE TABLE C_Location (
LocationID INT PRIMARY KEY CLUSTERED IDENTITY,
Name NVARCHAR(50)
)
GO
CREATE TABLE C_ProjectStatus (
ProjectStatusID INT IDENTITY PRIMARY KEY,
Name NVARCHAR(50)
)
CREATE TABLE Project (
ProjectID INT IDENTITY PRIMARY KEY,
Title NVARCHAR(50),
StartDate DATETIME,
ProjectStatusID INT FOREIGN KEY REFERENCES dbo.C_ProjectStatus(ProjectStatusID)
)
GO
CREATE TABLE ProjectLocation (
PojectLocationID INT IDENTITY PRIMARY KEY,
ProjectID INT FOREIGN KEY REFERENCES dbo.Project(ProjectID),
LocationID INT FOREIGN KEY REFERENCES dbo.C_Location(LocationID)
)
GO
CREATE TABLE PorjectLocationParticipant (
ProjectLocationParticipantID INT PRIMARY KEY IDENTITY,
ProjectLocationID INT FOREIGN KEY REFERENCES dbo.ProjectLocation(PojectLocationID),
ParticipantFirstName NVARCHAR(50),
ParticipantLastName NVARCHAR(50)
)

I am very new in data warehouse so I need help to convert this structure to star schema.


问:
how to set an onclick listener for an imagebutton in an alertdialog
I have a layout with an ImageButton that is inflated in an AlertDialog, where/how should I set an onClick listener?

Here's the code I tried using:

```<code>    ImageButton ib = (ImageButton) findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });
</code>```

答:
Try to this in your code.

```<code>public void showAlertDialogButtonClicked(View view) {

    // create an alert builder
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Name");

    // set the custom layout
    final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
    builder.setView(customLayout);

    // add a button
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // send data from the AlertDialog to the Activity
            EditText editText = customLayout.findViewById(R.id.editText);
            sendDialogDataToActivity(editText.getText().toString());
        }
    });

    // create and show the alert dialog
    AlertDialog dialog = builder.create();
    dialog.show();
}
</code>```

Use this method from

```<code>  <Button android:layout_width="match_parent"
android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked"/>
</code>```

Body:
I have a layout with an ImageButton that is inflated in an AlertDialog, where/how should I set an onClick listener?

Here's the code I tried using:

    ImageButton ib = (ImageButton) findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });

Body:
Try to this in your code.

public void showAlertDialogButtonClicked(View view) {

    // create an alert builder
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Name");

    // set the custom layout
    final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
    builder.setView(customLayout);

    // add a button
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // send data from the AlertDialog to the Activity
            EditText editText = customLayout.findViewById(R.id.editText);
            sendDialogDataToActivity(editText.getText().toString());
        }
    });

    // create and show the alert dialog
    AlertDialog dialog = builder.create();
    dialog.show();
}

Use this method from

  <Button android:layout_width="match_parent"
android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked"/>


问:
AAR libs no longer created in the output folder with Android Studio 3.0
I have some lib modules in my Android project. Before updating Android Studio to the new 3.0 version and so the Gradle plugin to the 3.0.0 one, I was able to find the AAR file of my libs into the builder/output folder after building the project.

It seems that the AAR libs are no longer produced in this new version.

Is there any alternative way to get them again?

答:
In my case, where I am building with Jenkins and I want to have both the apk and aar in my artifacts I could achieve this by adding :[module_name]:bundleRelease to the targets.

So if your module name is test:

```<code>:app:assembleRelease :test:bundleRelease
</code>```

Body:
In my case, where I am building with Jenkins and I want to have both the apk and aar in my artifacts I could achieve this by adding :[module_name]:bundleRelease to the targets.

So if your module name is test:

:app:assembleRelease :test:bundleRelease


问:
Access data outside for loop
I have a main class and a UI class.

Let me do some explaining first. What i am doing currently, is processing some jar files to find all of the classname inside them (to use later with reflection)

In main, i do things and process data and in the UI there is a JTabbedPane that loads a JFrame when a plugin is correctly loaded (To do so, I share the UI class from main and then invoke it).

Now, to make this dynamic, i made a nice for loop that loops through all jars and gets all the classnames.

Question is, how do i access those strings found in the for loop externally?

EDIT
A commenter pointed out that I could just declare the strings outside the for loop, problem is I have no clue on how many jars i will load and for the sake of user convenience, I'd like to keep the main program as it is (so no updates, just plugin updates that can be handled inside the jar itself at runtime)

Sorry if this is dumb.

答:
As people in the comments said your best choice would be to declare a list of String outside the loop:

```<code>List<String> classnames = new ArrayList<String>();
for(String classname : jar) {
    classnames.add(classname);
}
</code>```

Something like this.

Title: Access data outside for loop

Body:
As people in the comments said your best choice would be to declare a list of String outside the loop:

List<String> classnames = new ArrayList<String>();
for(String classname : jar) {
    classnames.add(classname);
}

Something like this.


问:
Add an X to the end of a div with pure CSS?
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag">category 2</span>
<span class="categoryTag">category 3</span></code>```

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

答:
In my opinion, the text X in the style will be affected by the font used on the website. So it's better to use this alternative

.categoryTag {
  display: inline-block;
  background-color: #eaeaea;
  border-radius: 4px;
  position: relative;
  padding: 6px;
  padding-right: 25px;
  font-size: 12px;
  cursor: pointer;
  margin: 4px;
}

.categoryTag::after,
.categoryTag::before {
  content: '';
  height: 13px; /* tweak this change the size of the X */
  top:50%;
  width: 2px; /* tweak this change the thickness of the X */
  background: #000; /* change this change the color of the X */
  -webkit-transform:translate(-50%,-50%) rotate(45deg);
  -ms-transform:translate(-50%,-50%) rotate(45deg);
  -o-transform:translate(-50%,-50%) rotate(45deg);
  transform:translate(-50%,-50%) rotate(45deg);
  position: absolute;
  right: 13px;
  transition: all ease-in-out 0.3s;
}
.categoryTag::before {
    transform: translate(-50%,-50%) rotate(-45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag medium">category 2</span>
<span class="categoryTag large">category 3</span></code>```

With some small transition -

.categoryTag {
  display: inline-block;
  background-color: #eaeaea;
  border-radius: 4px;
  position: relative;
  padding: 6px;
  padding-right: 25px;
  font-size: 12px;
  cursor: pointer;
  margin: 4px;
}

.categoryTag::after,
.categoryTag::before {
  content: '';
  height: 8px; /* tweak this change the size of the X */
  top:50%;
  width: 1px; /* tweak this change the thickness of the X */
  background: #000; /* change this change the color of the X */
  -webkit-transform:translate(-50%,-50%) rotate(45deg);
  -ms-transform:translate(-50%,-50%) rotate(45deg);
  -o-transform:translate(-50%,-50%) rotate(45deg);
  transform:translate(-50%,-50%) rotate(45deg);
  position: absolute;
  right: 14px;
  transition: all ease-in-out 0.3s;
}
.categoryTag.two:before,.categoryTag.two:after{
  -webkit-transform:translate(-50%,-50%) rotate(89deg);;
  -ms-transform:translate(-50%,-50%) rotate(89deg);;
  -o-transform:translate(-50%,-50%) rotate(89deg);
  transform:translate(-50%,-50%) rotate(89deg);
}
.categoryTag::before {
  transform: translate(-50%,-50%) rotate(-45deg);
}
.categoryTag:hover:before,.categoryTag:hover:after{
  height: 13px;
  width: 2px;
  right: 13px;
}
.categoryTag.two:hover:after{
  height: 13px;
  -webkit-transform:translate(-50%,-50%) rotate(45deg);
  -ms-transform:translate(-50%,-50%) rotate(45deg);
  -o-transform:translate(-50%,-50%) rotate(45deg);
  transform:translate(-50%,-50%) rotate(45deg);
}

.categoryTag.two:hover:before {
  -webkit-transform:translate(-50%,-50%) rotate(-45deg);
  -ms-transform:translate(-50%,-50%) rotate(-45deg);
  -o-transform:translate(-50%,-50%) rotate(-45deg);
  transform:translate(-50%,-50%) rotate(-45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag two">category 2</span></code>```

I hope this was helpful for you.

Body:
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

category 1
category 2
category 3

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

Body:
In my opinion, the text X in the style will be affected by the font used on the website. So it's better to use this alternative

.categoryTag {
  display: inline-block;
  background-color: #eaeaea;
  border-radius: 4px;
  position: relative;
  padding: 6px;
  padding-right: 25px;
  font-size: 12px;
  cursor: pointer;
  margin: 4px;
}

.categoryTag::after,
.categoryTag::before {
  content: '';
  height: 13px; /* tweak this change the size of the X */
  top:50%;
  width: 2px; /* tweak this change the thickness of the X */
  background: #000; /* change this change the color of the X */
  -webkit-transform:translate(-50%,-50%) rotate(45deg);
  -ms-transform:translate(-50%,-50%) rotate(45deg);
  -o-transform:translate(-50%,-50%) rotate(45deg);
  transform:translate(-50%,-50%) rotate(45deg);
  position: absolute;
  right: 13px;
  transition: all ease-in-out 0.3s;
}
.categoryTag::before {
    transform: translate(-50%,-50%) rotate(-45deg);
}

<span class="categoryTag">category 1</span>
<span class="categoryTag medium">category 2</span>
<span class="categoryTag large">category 3</span>

With some small transition -

.categoryTag {
  display: inline-block;
  background-color: #eaeaea;
  border-radius: 4px;
  position: relative;
  padding: 6px;
  padding-right: 25px;
  font-size: 12px;
  cursor: pointer;
  margin: 4px;
}

.categoryTag::after,
.categoryTag::before {
  content: '';
  height: 8px; /* tweak this change the size of the X */
  top:50%;
  width: 1px; /* tweak this change the thickness of the X */
  background: #000; /* change this change the color of the X */
  -webkit-transform:translate(-50%,-50%) rotate(45deg);
  -ms-transform:translate(-50%,-50%) rotate(45deg);
  -o-transform:translate(-50%,-50%) rotate(45deg);
  transform:translate(-50%,-50%) rotate(45deg);
  position: absolute;
  right: 14px;
  transition: all ease-in-out 0.3s;
}
.categoryTag.two:before,.categoryTag.two:after{
  -webkit-transform:translate(-50%,-50%) rotate(89deg);;
  -ms-transform:translate(-50%,-50%) rotate(89deg);;
  -o-transform:translate(-50%,-50%) rotate(89deg);
  transform:translate(-50%,-50%) rotate(89deg);
}
.categoryTag::before {
  transform: translate(-50%,-50%) rotate(-45deg);
}
.categoryTag:hover:before,.categoryTag:hover:after{
  height: 13px;
  width: 2px;
  right: 13px;
}
.categoryTag.two:hover:after{
  height: 13px;
  -webkit-transform:translate(-50%,-50%) rotate(45deg);
  -ms-transform:translate(-50%,-50%) rotate(45deg);
  -o-transform:translate(-50%,-50%) rotate(45deg);
  transform:translate(-50%,-50%) rotate(45deg);
}

.categoryTag.two:hover:before {
  -webkit-transform:translate(-50%,-50%) rotate(-45deg);
  -ms-transform:translate(-50%,-50%) rotate(-45deg);
  -o-transform:translate(-50%,-50%) rotate(-45deg);
  transform:translate(-50%,-50%) rotate(-45deg);
}

<span class="categoryTag">category 1</span>
<span class="categoryTag two">category 2</span>

I hope this was helpful for you.


问:
Java Engine Script which support Compilable
In continuing my question, Java uses Beanshell as script engine,
while BeanShell Engine Script Compilable is not supported.

Why java doesn't have script engine other than Beanshell that support Compilable ? can/should we override it? is there an enhancement on this issue?

Compilable interface:

compile scripts to a form that can be executed repeatedly without recompilation

I found implementation as JavaScriptEngine and other JavaScriptEngine but I don't know if it's relevant to use.

Does java intentionally let Groovy implement it and thus become the expected scripting language to use?

答:
It's not a complete answer, but worth mention beanshell2 project,

I found beanshell2 issue to support Compilable
There's a fix that can be download since version bsh-2.1b4.jar

There's also latest bsh-2.1.6.jar

There should be 2.1.8 version according to beanshell2

Feb. 20, 2014

Update v2.1.8

Also latest Beanshell 2.0b5 (or 2.0b6) support Compilabe but it throw new Error("unimplemented");

EDIT:

New issue for implementing Compilabe in Beanshell 2.0


问:
PHP - Setup Webhook Receiver with signature verification
I need to setup a PHP page for receiving Webhooks - I've done many of these in the past so that is not a problem, but the API I'm working with for this project requires that my webhook verifies the signature provided in the header.

As part of the validation request it will send the following:

```<code>HEADER:
 "x-xero-signature" : HASH_VALUE
PAYLOAD:
{
   "events": [],
   "lastEventSequence": 0,
   "firstEventSequence": 0,
   "entropy": "S0m3r4N0m3t3xt"
}
</code>```

I've created a Webhook key (e.g. 'ABC123'), and as part of the validation request for this Webhook I must ensure that the payload which is hashed using HMACSHA256 with your webhook key and base64 encoded should match the signature in the header. This is a correctly signed payload. If the signature does not match the hashed payload it is an incorrectly signed payload.

To gain Intent to Receive validation, the receiving url must respond with status: 200 Ok for all correctly signed payloads and respond with status: 401 Unauthorized for all incorrectly signed payloads.

I'm a bit lost at this point as to how to go about this - the details for this setup can be found here:

https://developer.xero.com/documentation/getting-started/webhooks

答:
To match the sent-in data with the validation hash in the header, you need to do the following things:

Get the payload:
$payload = file_get_contents("php://input");

Generate a hash using the payload and your webhook key:
$yourHash = base64_encode(hash_hmac('sha256', $payload, $yourWebhookKey));

Check your hash against the one provided in the header:
if ($yourHash === $_SERVER['x-xero-signature']) {}

You will have to check the $_SERVER array for the correct key if this does not work directly; it is probably all upper-case to begin with.

Edit: As noted by the OP, the correct variable is $_SERVER['HTTP_X_XERO_SIGNATURE']

Body:
I need to setup a PHP page for receiving Webhooks - I've done many of these in the past so that is not a problem, but the API I'm working with for this project requires that my webhook verifies the signature provided in the header.

As part of the validation request it will send the following:

HEADER:
 "x-xero-signature" : HASH_VALUE
PAYLOAD:
{
   "events": [],
   "lastEventSequence": 0,
   "firstEventSequence": 0,
   "entropy": "S0m3r4N0m3t3xt"
}

I've created a Webhook key (e.g. 'ABC123'), and as part of the validation request for this Webhook I must ensure that the payload which is hashed using HMACSHA256 with your webhook key and base64 encoded should match the signature in the header. This is a correctly signed payload. If the signature does not match the hashed payload it is an incorrectly signed payload.

To gain Intent to Receive validation, the receiving url must respond with status: 200 Ok for all correctly signed payloads and respond with status: 401 Unauthorized for all incorrectly signed payloads.

I'm a bit lost at this point as to how to go about this - the details for this setup can be found here:

https://developer.xero.com/documentation/getting-started/webhooks


问:
How to custom handle a file not being found when using go static file server?
So I'm using a go server to serve up a single page web application.

This works for serving all the assets on the root route. All the CSS and HTML are served up correctly.

```<code>fs := http.FileServer(http.Dir("build"))
http.Handle("/", fs)
</code>```

So when the URL is http://myserverurl/index.html or http://myserverurl/styles.css, it serves the corresponding file.

But for a URL like http://myserverurl/myCustompage, it throws 404 if myCustompage is not a file in the build folder.

How do I make all routes for which a file does not exist serve index.html?

It is a single page web application and it will render the appropriate screen once the html and js are served. But it needs index.html to be served on routes for which there is no file.

How can this be done?

答:
The handler returned by http.FileServer() does not support customization, it does not support providing a custom 404 page or action.

What we may do is wrap the handler returned by http.FileServer(), and in our handler we may do whatever we want of course. In our wrapper handler we will call the file server handler, and if that would send a 404 not found response, we won't send it to the client but replace it with a redirect response.

To achieve that, in our wrapper we create a wrapper http.ResponseWriter which we will pass to the handler returned by http.FileServer(), and in this wrapper response writer we may inspect the status code, and if it's 404, we may act to not send the response to the client, but instead send a redirect to /index.html.

This is an example how this wrapper http.ResponseWriter may look like:

```<code>type NotFoundRedirectRespWr struct {
    http.ResponseWriter // We embed http.ResponseWriter
    status              int
}

func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
    w.status = status // Store the status for our own use
    if status != http.StatusNotFound {
        w.ResponseWriter.WriteHeader(status)
    }
}

func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) {
    if w.status != http.StatusNotFound {
        return w.ResponseWriter.Write(p)
    }
    return len(p), nil // Lie that we successfully written it
}
</code>```

And wrapping the handler returned by http.FileServer() may look like this:

```<code>func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        nfrw := &NotFoundRedirectRespWr{ResponseWriter: w}
        h.ServeHTTP(nfrw, r)
        if nfrw.status == 404 {
            log.Printf("Redirecting %s to index.html.", r.RequestURI)
            http.Redirect(w, r, "/index.html", http.StatusFound)
        }
    }
}
</code>```

Note that I used http.StatusFound redirect status code instead of http.StatusMovedPermanently as the latter may be cached by browsers, and so if a file with that name is created later, the browser would not request it but display index.html immediately.

And now put this in use, the main() function:

```<code>func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}
</code>```

Attempting to query a non-existing file, we'll see this in the log:

```<code>2017/11/14 14:10:21 Redirecting /a.txt3 to /index.html.
2017/11/14 14:10:21 Redirecting /favicon.ico to /index.html.
</code>```

Note that our custom handler (being well-behaviour) also redirected the request to /favico.ico to index.html because I do not have a favico.ico file in my file system. You may want to add this as an exception if you don't have it either.

The full example is available on the Go Playground. You can't run it there, save it to your local Go workspace and run it locally.

Also check this related question: Log 404 on http.FileServer

Body:
So I'm using a go server to serve up a single page web application.

This works for serving all the assets on the root route. All the CSS and HTML are served up correctly.

fs := http.FileServer(http.Dir("build"))
http.Handle("/", fs)

So when the URL is http://myserverurl/index.html or http://myserverurl/styles.css, it serves the corresponding file.

But for a URL like http://myserverurl/myCustompage, it throws 404 if myCustompage is not a file in the build folder.

How do I make all routes for which a file does not exist serve index.html?

It is a single page web application and it will render the appropriate screen once the html and js are served. But it needs index.html to be served on routes for which there is no file.

How can this be done?

Body:
The handler returned by http.FileServer() does not support customization, it does not support providing a custom 404 page or action.

What we may do is wrap the handler returned by http.FileServer(), and in our handler we may do whatever we want of course. In our wrapper handler we will call the file server handler, and if that would send a 404 not found response, we won't send it to the client but replace it with a redirect response.

To achieve that, in our wrapper we create a wrapper http.ResponseWriter which we will pass to the handler returned by http.FileServer(), and in this wrapper response writer we may inspect the status code, and if it's 404, we may act to not send the response to the client, but instead send a redirect to /index.html.

This is an example how this wrapper http.ResponseWriter may look like:

type NotFoundRedirectRespWr struct {
    http.ResponseWriter // We embed http.ResponseWriter
    status              int
}

func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
    w.status = status // Store the status for our own use
    if status != http.StatusNotFound {
        w.ResponseWriter.WriteHeader(status)
    }
}

func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) {
    if w.status != http.StatusNotFound {
        return w.ResponseWriter.Write(p)
    }
    return len(p), nil // Lie that we successfully written it
}

And wrapping the handler returned by http.FileServer() may look like this:

func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        nfrw := &NotFoundRedirectRespWr{ResponseWriter: w}
        h.ServeHTTP(nfrw, r)
        if nfrw.status == 404 {
            log.Printf("Redirecting %s to index.html.", r.RequestURI)
            http.Redirect(w, r, "/index.html", http.StatusFound)
        }
    }
}

Note that I used http.StatusFound redirect status code instead of http.StatusMovedPermanently as the latter may be cached by browsers, and so if a file with that name is created later, the browser would not request it but display index.html immediately.

And now put this in use, the main() function:

func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}

Attempting to query a non-existing file, we'll see this in the log:

2017/11/14 14:10:21 Redirecting /a.txt3 to /index.html.
2017/11/14 14:10:21 Redirecting /favicon.ico to /index.html.

Note that our custom handler (being well-behaviour) also redirected the request to /favico.ico to index.html because I do not have a favico.ico file in my file system. You may want to add this as an exception if you don't have it either.

The full example is available on the Go Playground. You can't run it there, save it to your local Go workspace and run it locally.

Also check this related question: Log 404 on http.FileServer


问:
return value inside html tag with beautifulsoup
I'm trying to get the data from some social networks and put in the mongodb.

This is the information inside the html tag

```<code><span class="ProfileNav-value" data-count="347235" data-is-compact="true">347K</span>
</code>```

I was able to recover the 347K as follows

```<code>page = requests.get("https://twitter.com/cancaonova")
soup = BeautifulSoup(page.content, 'html.parser')
followers = soup.find_all(class_="ProfileNav-value")
seguidores = followers[2]
print seguidores.get_text()
</code>```

However I wanted to get the data inside the data-cont tag I'm trying that way, but the result was: none

```<code>page = requests.get("https://twitter.com/cancaonova")
soup = BeautifulSoup(page.content, 'html.parser')
followers = soup.find('data-count')
print(followers)
</code>```

Tks for you

答:
```<code>rel_soup = BeautifulSoup('<span class="ProfileNav-value" data-count="347235" data-is-compact="true">347K</span>','html.parser')
rel_soup.span['data-count']
</code>```

Body:
I'm trying to get the data from some social networks and put in the mongodb.

This is the information inside the html tag

347K

I was able to recover the 347K as follows

page = requests.get("https://twitter.com/cancaonova")
soup = BeautifulSoup(page.content, 'html.parser')
followers = soup.find_all(class_="ProfileNav-value")
seguidores = followers[2]
print seguidores.get_text()

However I wanted to get the data inside the data-cont tag I'm trying that way, but the result was: none

page = requests.get("https://twitter.com/cancaonova")
soup = BeautifulSoup(page.content, 'html.parser')
followers = soup.find('data-count')
print(followers)

Tks for you


问:
How to invalidate that which column having data type mismatch
I have table with some records in one user and another table with empty records. I want to migrate the data of that table from one user to another but I got one error ORA: 01722 because the datatype of the target table is slightly mismatch. What should I do resolve this problem without changes the datatype.
Data type of the source table is-

Description of the target table-

In both table in different user only one column is mismatch datatype LOTFRONTAGE. In source table datatype is varchar2 and in target table datatype is Number.

How to invalidate that which column having data type mismatch.

答:
```<code>insert into md.house(ID,MSSUBCLASS,MSZONING,
                     LOTFRONTAGE ,LOTAREA,LOTSHAPE,LOTCONFIG,
                     NEIGHBORHOOD,CONDITION1,BLDGTYPE,OVERALLQUAL,
                     YEARBUILT,ROOFSTYLE,EXTERIOR1ST,MASVNRAREA)
 select ID,MSSUBCLASS,MSZONING
 --hier
       ,TO_NUMBER(LOTFRONTAGE),

        LOTAREA,LOTSHAPE,LOTCONFIG,NEIGHBORHOOD,CONDITION1,
        BLDGTYPE,OVERALLQUAL,YEARBUILT,ROOFSTYLE,
        EXTERIOR1ST,MASVNRAREA
  from SYS.HOUSE_DATA;
</code>```


问:
Should I avoid Alternative Control Syntax?
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

```<code>x = (y == true) ? "foo" : "bar";
</code>```

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

答:
As a fellow mostly self-taught programmer, I can only give you my opinion, without any special authority behind it.

I find that the ternary conditional operator (?:) is perfectly acceptable when you're using it for an expression with no side-effects. As soon as you start using it to represent a decision to do something vs. do something else, you're (in my opinion) abusing it.

In short, control constructs are for structuring the flow of the code and operators are for expressions. As long as one keeps things that way, the code remains readable.

OwnerDisplayName: Chris

Body:
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

x = (y == true) ? "foo" : "bar";

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

OwnerDisplayName: Vojislav Stojkovic


问:
Changing fopen() mode midway through?
I this piece of code:

```<code>$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
  {
  fwrite($file, $array[$i]);
  }
flock($file, LOCK_UN);
fclose($file);
</code>```

Basically what I want to do is: open a file > lock it > read it > do some stuff > clear the file > write to file > unlock it > close it.

The problem is the clearing part. I know I could do it with fopen($file, 'w+') but then reading would be a problem. Maybe I can change the mode somehow?

Any help would be appreciated, Paul

答:
If you set the pointer to 0 using fseek you can then run ftruncate like so:

```<code>// reading the file into an array and doing some stuff to it

//1
fseek($handle,0); //Set the pointer to the first byte

//2
ftruncate($handle,filesize("yourfile.ext")); //from the first byte to the last truncate

//3 - File should be empty and still in writing mode.

for ($i=0; $i<count($array); $i++)
{
    fwrite($file, $array[$i]);
}
</code>```

With ftruncate be aware of these issues regard the second param:

If size is larger than the file then the file is extended with null bytes.

If size is smaller than the file then the file is truncated to that size.

http://www.php.net/manual/en/function.ftruncate.php

http://www.php.net/manual/en/function.fseek.php

Title: Changing fopen() mode midway through?

Body:
I this piece of code:

$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
  {
  fwrite($file, $array[$i]);
  }
flock($file, LOCK_UN);
fclose($file);

Basically what I want to do is: open a file > lock it > read it > do some stuff > clear the file > write to file > unlock it > close it.

The problem is the clearing part. I know I could do it with fopen($file, 'w+') but then reading would be a problem. Maybe I can change the mode somehow?

Any help would be appreciated, Paul

Body:
If you set the pointer to 0 using fseek you can then run ftruncate like so:

// reading the file into an array and doing some stuff to it

//1
fseek($handle,0); //Set the pointer to the first byte

//2
ftruncate($handle,filesize("yourfile.ext")); //from the first byte to the last truncate

//3 - File should be empty and still in writing mode.

for ($i=0; $i<count($array); $i++)
{
    fwrite($file, $array[$i]);
}

With ftruncate be aware of these issues regard the second param:

If size is larger than the file then the file is extended with null bytes.

If size is smaller than the file then the file is truncated to that size.

http://www.php.net/manual/en/function.ftruncate.php

http://www.php.net/manual/en/function.fseek.php


问:
Return struct type confirming to protocols
Here is my piece of code,

```<code>protocol Configuration {

    static var url: String { get }
    static var username: String { get }
    static var password: String { get }
}

protocol Server {

    associatedtype Profile: Configuration
    associatedtype Payment: Configuration
    associatedtype Images: Configuration
}

struct Development: Server {

    struct Profile: Configuration {

        static var url: String { return "http://google.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://bing.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://duckduckgo.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }
}

struct Production: Server {

    struct Profile: Configuration {

        static var url: String { return "http://amazon.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://facebook.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://orkut.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }
}
</code>```

Question is I would like to fetch my 'struct' (depending on my environment). I need something like,

```<code>struct Environment {

    static func current() -> Any:Server {

        if #DEBUG
            return Development
        #endif

        return Production
    }
}
</code>```

But returning a specific type confirming to my protocol is not possible.

Any suggestion on this or a different approach will be helpful.

答:
Just return Server, not Any:Server:

```<code>static func current() -> Server {

    if #DEBUG
        return Development
    #endif

    return Production
}
</code>```

Body:
Here is my piece of code,

protocol Configuration {

    static var url: String { get }
    static var username: String { get }
    static var password: String { get }
}

protocol Server {

    associatedtype Profile: Configuration
    associatedtype Payment: Configuration
    associatedtype Images: Configuration
}

struct Development: Server {

    struct Profile: Configuration {

        static var url: String { return "http://google.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://bing.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://duckduckgo.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }
}

struct Production: Server {

    struct Profile: Configuration {

        static var url: String { return "http://amazon.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://facebook.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://orkut.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }
}

Question is I would like to fetch my 'struct' (depending on my environment). I need something like,

struct Environment {

    static func current() -> Any:Server {

        if #DEBUG
            return Development
        #endif

        return Production
    }
}

But returning a specific type confirming to my protocol is not possible.

Any suggestion on this or a different approach will be helpful.

Body:
Just return Server, not Any:Server:

static func current() -> Server {

    if #DEBUG
        return Development
    #endif

    return Production
}


问:
What is the correct SharePoint CAML query to retrieve all items from a list?
For some reason I am trying to query SharePoint 2007 using CAML and web services with the Python suds library. The call looks like:

```<code>listItems = client.service.GetListItems(
    listName, '', Raw('<Query />'), viewFields, 0,
    Raw("""<QueryOptions>
       <IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns>
       </QueryOptions>"""),
    None)
</code>```

For some reason, I get 0 results or an error with <Query/> or <Query><Where/></Query> but get all items with a simple tautology WHERE x = 1 OR x != 1.

What is the correct way to just get all list items?

答: To get all items, just put an orderby clause in there, and specify an arbitrary column. Should return everything...</p>

Body:
For some reason I am trying to query SharePoint 2007 using CAML and web services with the Python suds library. The call looks like:

listItems = client.service.GetListItems(
    listName, '', Raw('<Query />'), viewFields, 0,
    Raw("""<QueryOptions>
       <IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns>
       </QueryOptions>"""),
    None)

For some reason, I get 0 results or an error with <Query/> or <Query><Where/></Query> but get all items with a simple tautology WHERE x = 1 OR x != 1.

What is the correct way to just get all list items?


答:
Use 'element.attrs' to read attribute:</p>

```<code>seguidores = followers[2]
datacount = seguidores.attrs['data-count']
</code>```

Title: return value inside html tag with beautifulsoup

Body:
Use 'element.attrs' to read attribute:

seguidores = followers[2]
datacount = seguidores.attrs['data-count']


答:
"Development" and "Production" are values, not types. You don't need protocols here and shouldn't be using them. Just create the values you need and return them:</p>

```<code>struct Server {
    let url: String
    let username: String
    let password: String
}

struct Environment {
    let profile: Server
    let payment: Server
    let images: Server

    static let development = Environment(
        profile: Server(url: "http://google.com", username: "abc", password: "xyz"),
        payment: Server(url: "http://bing.com", username: "abc", password: "xyz"),
        images: Server(url: "http://duckduckgo.com", username: "abc", password: "xyz")
    )

    static let production = Environment(...)

    static var current: Environment {
        #if DEBUG
            return development
        #else
            return production
        #endif
    }
}
</code>```

Title: Return struct type confirming to protocols

Body:
"Development" and "Production" are values, not types. You don't need protocols here and shouldn't be using them. Just create the values you need and return them:

struct Server {
    let url: String
    let username: String
    let password: String
}

struct Environment {
    let profile: Server
    let payment: Server
    let images: Server

    static let development = Environment(
        profile: Server(url: "http://google.com", username: "abc", password: "xyz"),
        payment: Server(url: "http://bing.com", username: "abc", password: "xyz"),
        images: Server(url: "http://duckduckgo.com", username: "abc", password: "xyz")
    )

    static let production = Environment(...)

    static var current: Environment {
        #if DEBUG
            return development
        #else
            return production
        #endif
    }
}


问:
How can I retrieve second last row?
I have a table with many records and I want to know only the record which I have created at second last.

For ex: I have a table customer in which customerID are random numbers.

Now I want to select second last row.

```<code>customerID      customer_name   cont_no
---------------------------------------
 7              david sam       5284
 1              shinthol        1
11              lava            12548
 2              thomas          1
 3              peeter          1
 4              magge           1
 5              revas           1
 6              leela           123975
</code>```

Output row :

```<code>customerID      customer_name   cont_no
5               revas           1
</code>```

I don't want second highest...

I want second last row.

答:
With SQL Server 2012 or higher you can do it in one line code:</p>

```<code>LAG([MyValue],1) OVER (PARTITION BY [Category] ORDER BY [AnyColumnForOrdinal] ASC)
</code>```

Title: How can I retrieve second last row?

Body:
I have a table with many records and I want to know only the record which I have created at second last.

For ex: I have a table customer in which customerID are random numbers.

Now I want to select second last row.

customerID      customer_name   cont_no
---------------------------------------
 7              david sam       5284
 1              shinthol        1
11              lava            12548
 2              thomas          1
 3              peeter          1
 4              magge           1
 5              revas           1
 6              leela           123975

Output row :

customerID      customer_name   cont_no
5               revas           1

I don't want second highest...

I want second last row.

Body:
With SQL Server 2012 or higher you can do it in one line code:

LAG([MyValue],1) OVER (PARTITION BY [Category] ORDER BY [AnyColumnForOrdinal] ASC)


问:
Java: Adding/Subtracting Math.ulp() vs. Math.nextAfter()
I'm trying to understand floating point operations in Java in more detail. If I read the documentation correctly, the following holds for any given double x:

```<code>x - Math.ulp(x) == Math.nextAfter(x, Double.NEGATIVE_INFINITY);
x + Math.ulp(x) == Math.nextAfter(x, Double.POSITIVE_INFINITY);
</code>```

Question: Is this always the case or are there some exceptional cases in which results will differ?

答:
This program:

```<code>public class Test {
  public static void main(String[] args) {
    double x = 1;
    System.out.println(x - Math.ulp(x) == Math.nextAfter(x, Double.NEGATIVE_INFINITY));
    System.out.println(x + Math.ulp(x) == Math.nextAfter(x, Double.POSITIVE_INFINITY));
  }
}
</code>```

outputs:

```<code>false
true
</code>```

The difference between consecutive doubles changes at each normal integer power of two, including 1.0. One of the tests must fail, because it assumes constant difference. Math.ulp(double) is defined to return "the positive distance between this floating-point value and the double value next larger in magnitude" so the subtract proposition is false when the distance is different.

Body:
I'm trying to understand floating point operations in Java in more detail. If I read the documentation correctly, the following holds for any given double x:

x - Math.ulp(x) == Math.nextAfter(x, Double.NEGATIVE_INFINITY);
x + Math.ulp(x) == Math.nextAfter(x, Double.POSITIVE_INFINITY);

Question: Is this always the case or are there some exceptional cases in which results will differ?

Body:
This program:

public class Test {
  public static void main(String[] args) {
    double x = 1;
    System.out.println(x - Math.ulp(x) == Math.nextAfter(x, Double.NEGATIVE_INFINITY));
    System.out.println(x + Math.ulp(x) == Math.nextAfter(x, Double.POSITIVE_INFINITY));
  }
}

outputs:

false
true

The difference between consecutive doubles changes at each normal integer power of two, including 1.0. One of the tests must fail, because it assumes constant difference. Math.ulp(double) is defined to return "the positive distance between this floating-point value and the double value next larger in magnitude" so the subtract proposition is false when the distance is different.


问:
Opening jpegs on Android - I get an OutOfMemoryException
In my application I need to process images taken by Android's built-in applications. They're saved into JPEG format, and I need to get access to each pixel. I tried to create a Bitmap instance from the jpeg image, but very often I get an OutOfMemoryException. I can't resize or crop image. Does a solution exist?

答:
BitmapFactory will often throw OutOfMemoryExceptions and I'm afraid that I've never really discovered any workarounds.  It seems to be doing its own memory management, and sometimes it really isn't capable of parsing an image.  In a couple of applications I've worked on that had to deal with images heavily, I just had to catch the exception and then leave blank spots in the UI when I couldn't get an image parsed.  Sometimes, if you try again later, those images will parse, presumably when the internal memory state of BitmapFactory is working better.

When I was working on a J2ME application, I tried to find a pure Java open source JPEG parser so I could use it on phones that didn't have built-in JPEG support.  Turns out that such a thing is difficult to find, and the closest I could find was buried in the depths of the Eclipse source.  I was able to take that source, de-Eclipsify it and try it out.  It did have the virtue of reading in things line by line (although I'm not sure how it would have done with progressive scan JPEGs), but it was ridiculously slow on our J2ME devices (particularly since they were mostly the lower end ones) so we didn't end up using it for anything.


问:
Increment number with Delay (C#)
i have a button when i click on it it increases the number in a text block by one.
But i want to show increment with few millisecond wait.

XAML

```<code><TextBlock Name="DisplayTextBlock" FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Top"/>

<Button Name="CountingButton" Height="80" Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="CountingButton_Click"/>
</code>```

C#

```<code>int i = 0;

private void CountingButton_Click(object sender, RoutedEventArgs e)
{
    do
    {
        i++;

        DisplayTextBlock.Text = i.ToString();
    }
    while(//something is on)
}
</code>```

so how can i add wait...

答:
Add the async keyword to the method declaration. And add Task.Delay.

```<code>private async void CountingButton_Click(object sender, RoutedEventArgs e)
{
    i++;
    await Task.Delay(200);
    DisplayTestBlock.Text = i.ToString();
}
</code>```

Title: Increment number with Delay (C#)

Body:
i have a button when i click on it it increases the number in a text block by one.
But i want to show increment with few millisecond wait.

XAML

<TextBlock Name="DisplayTextBlock" FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Top"/>

<Button Name="CountingButton" Height="80" Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="CountingButton_Click"/>

C#

int i = 0;

private void CountingButton_Click(object sender, RoutedEventArgs e)
{
    do
    {
        i++;

        DisplayTextBlock.Text = i.ToString();
    }
    while(//something is on)
}

so how can i add wait...

Body:
Add the async keyword to the method declaration. And add Task.Delay.

private async void CountingButton_Click(object sender, RoutedEventArgs e)
{
    i++;
    await Task.Delay(200);
    DisplayTestBlock.Text = i.ToString();
}


问:
How do you write your layout for an Angular5 + MD2 app?
So the Material Design 2 components are out there, waiting to be used in your app but my question is how would you structure your layout in which they rest?
Do you use https://github.com/angular/flex-layout?
Write the layout manually?
Using CSS Grid, Flexbox or both?

This is for a brand new web app, and I prefer writing it using modern technologies that are here to last (as much as this is possible with Web technologies...).

答:
You should use Angular's Flex Layout. It's also specified in the docs for Angular Material:

Layout -> See angular/flex-layout