问:
PHP variable is empty in second iteration of loop
Why is the PHP variable defined as $real in the code below empty but still set after one iteration of the while loop yet the $entry variable is both set and contains the correct value on every iteration of the loop. Does the calling of a function '' put the resulting variable outside of the scope and if so how can I fix this?

```<code>    <!DOCTYPE html>
 <html>

   <head>
       <meta charset="utf-8">
        <title>Total </title>
          <link type="text/css" rel="stylesheet" href="course.css">
           <script src="../jquery.js"></script>
            <script src="../jquery-ui.js"></script>

   </head>
   <body>

  <?php
      if ($handle = opendir('../uploads'))
      {
          while (false !== ($entry = readdir($handle)))
         {

          if ($entry != "." && $entry != "..")
          {
            $real= realpath($entry);
              echo  "<button class='files accordian'>$entry $real</button>";
              $real= realpath($entry);

                 if(isset($real))
                    {
                      echo 'the real varibale is set';

                    }
                    else
                    {
                     echo 'the real varibale is not set';
                    }

                 if(empty($real))
                    {
                    echo 'the real varibale is empty';
                    }
                    else
                    {
                    echo 'the real varibale is not empty';
                     echo 'and is '. $real;
                    }

                echo  "<button class='files accordian'>$entry $real</button>
                         <div class='panel'>
                            <p>$real</p>";
          }

        }
     }

   ?>

   </body>
  </html>
</code>```

答:
Please change your code where you are getting realpath like below,

```<code>$real= realpath("../uploads/".$entry);
</code>```

Issue: you are just trying to get the realpath of a file. So, it is looking the file in your current path where you are executing your file. Hence, you need to append the origin too.

Body:
Why is the PHP variable defined as $real in the code below empty but still set after one iteration of the while loop yet the $entry variable is both set and contains the correct value on every iteration of the loop. Does the calling of a function '' put the resulting variable outside of the scope and if so how can I fix this?

    <!DOCTYPE html>

       <meta charset="utf-8">
        <title>Total </title>
          <link type="text/css" rel="stylesheet" href="course.css">

  <?php
      if ($handle = opendir('../uploads'))
      {
          while (false !== ($entry = readdir($handle)))
         {

          if ($entry != "." && $entry != "..")
          {
            $real= realpath($entry);
              echo  "<button class='files accordian'>$entry $real</button>";
              $real= realpath($entry);

                 if(isset($real))
                    {
                      echo 'the real varibale is set';

                    }
                    else
                    {
                     echo 'the real varibale is not set';
                    }

                 if(empty($real))
                    {
                    echo 'the real varibale is empty';
                    }
                    else
                    {
                    echo 'the real varibale is not empty';
                     echo 'and is '. $real;
                    }

                echo  "<button class='files accordian'>$entry $real</button>

$real
";
          }

        }
     }

   ?>

Body:
Please change your code where you are getting realpath like below,

$real= realpath("../uploads/".$entry);

Issue: you are just trying to get the realpath of a file. So, it is looking the file in your current path where you are executing your file. Hence, you need to append the origin too.


来源: stackexchange

问:
give category id to subcategory in laravel seed
I try to add data with seed in laravel 5.4, let's say I have 10 category and I added them by seed to my database now I also have another seed for subcategories but before I add my subcategories I want to tell which one is belongs to what category that I imported before. how would I do that?

Update:

I found my question might be confusing for some people so i try to explain a bit more,

this is my category seed.

```<code><?php

use Illuminate\Database\Seeder;

class CategoriessTableSeeder extends Seeder {

    public function run()
    {
        DB::table('categories')->delete();

        $categories = array(
            array('name' => 'Accounting/Finance', 'slug' => 'hccounting_finance'),
            array('name' => 'Admin/Human Resources', 'slug' => 'admin_human_resources'),
            array('name' => 'Arts/Media/Communications', 'slug' => 'arts_media_communications'),
            array('name' => 'Building/Construction', 'slug' => 'building_construction'),
            array('name' => 'Computer/Information Technology', 'slug' => 'computer_information_technology'),
            array('name' => 'Education/Training', 'slug' => 'education_training'),
            array('name' => 'Engineering', 'slug' => 'engineering'),
            array('name' => 'Healthcare', 'slug' => 'healthcare'),
            array('name' => 'Hotel/Restaurant', 'slug' => 'hotel_restaurant'),
            array('name' => 'Manufacturing', 'slug' => 'manufacturing'),
            array('name' => 'Sales/Marketing', 'slug' => 'sales_marketing'),
            array('name' => 'Sciences', 'slug' => 'sciences'),
            array('name' => 'Services', 'slug' => 'services'),
            array('name' => 'Others', 'slug' => 'others'),
        );

        DB::table('categories')->insert($categories);
    }
}
</code>```

I have another similar with this for subcategories here it is:

```<code><?php

use Illuminate\Database\Seeder;

class SubategoriessTableSeeder extends Seeder {

    public function run()
    {
        DB::table('subcategories')->delete();

        $subcategories = array(
            array('name' => 'Audit & Taxation Jobs', 'slug' => 'audit_taxation_jobs', 'category_id' => ''),
        );

        DB::table('subcategories')->insert($subcategories);
    }
}
</code>```

in this sample 'category_id' => '' has to get the id/name of 'Accounting/Finance category in category seed .

now my question is how?

UPDATE 2:

Error's

[Illuminate\Database\QueryException]   SQLSTATE[23000]: Integrity
  constraint violation: 1451 Cannot delete or update a parent row: a
  foreign key constraint fails (jobid.ads, CONSTRAINT ads_subcateg
  ory_id_foreign FOREIGN KEY (subcategory_id) REFERENCES
  subcategories (id)) (SQL: delete from subcategories)

```<code> [PDOException]
  SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
</code>```

(jobid.ads, CONSTRAINT ads_subcateg
        ory_id_foreign FOREIGN KEY (subcategory_id) REFERENCES subcategories (id))

Code used:

```<code><?php

use Illuminate\Database\Seeder;
use Carbon\Carbon;

class SubcategoriesTableSeeder extends Seeder {

    public function run()
    {
        DB::table('subcategories')->delete();

            $categoryFinance = Category::select("id")->whereSlug("hccounting_finance")->firstOrFail();
            $subcategories = array(
             array('name' => 'Audit & Taxation Jobs', 'category_id' => $categoryFinance,  'slug' => 'audit_taxation_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
             array('name' => 'Banking/Financial Jobs', 'category_id' => $categoryFinance, 'slug' => 'banking-financial_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
             array('name' => 'Corporate Finance/Investment Jobs', 'category_id' => $categoryFinance, 'slug' => 'corporate_finance_investment_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
             array('name' => 'General/Cost Accounting Jobs', 'category_id' => $categoryFinance, 'slug' => 'general_cost_accounting_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
         );

         $categoryAdmin = Category::select("id")->whereSlug("admin_human_resources")->firstOrFail();
         $subcategories = array(
            array('name' => 'testing', 'slug' => 'tesingsubs', 'category_id' => $categoryAdmin, 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
        );

        DB::table('subcategories')->insert($subcategories);
    }
}
</code>```

答:
In order to relate your categories to subcategories, you should follow the logic (depending on your relationship - N-1 N-N) in the docs  (https://laravel.com/docs/5.4/eloquent-relationships). It seems that you need the attach() method.

So after creating the category entry, if you have followed the schema convention you can apply logic for all kind or relationships, even for polymorphic ones.

Edit:

After your edit it seems that you need a way to access the entries of your table again in order to relate them.

So, you can :

```<code>$categoryFinance = Category::select("id")->whereSlug("hccounting_finance")->firstOrFail();
</code>```

in your SubategoriessTableSeeder run() function before creating your array.

And then give that id in your subcategory_id. The same will be for all categories you need to relate.

Edit 2

Please check again that your foreign keys are correct. In that case you cannot delete the subcategories table because Categories "need" subid. And that's where constraint violation comes from. You don't need to delete these tables.. You just need to "feed-seed" them.

So try to remove the "delete" statements.

Edit 3

I think the error is obvious now.. There is no Category with id of 2 in your database. But again, check if the keys are associated correctly (this is an SQL and not a Laravel issue).

Run migrations if any, and seeders again, with the correct order (first categories and then subcategories - first the dependency and then the dependent one in general)

ContentLicense: CC BY-SA 3.0

Body:
I try to add data with seed in laravel 5.4, let's say I have 10 category and I added them by seed to my database now I also have another seed for subcategories but before I add my subcategories I want to tell which one is belongs to what category that I imported before. how would I do that?

Update:

I found my question might be confusing for some people so i try to explain a bit more,

this is my category seed.

<?php

use Illuminate\Database\Seeder;

class CategoriessTableSeeder extends Seeder {

    public function run()
    {
        DB::table('categories')->delete();

        $categories = array(
            array('name' => 'Accounting/Finance', 'slug' => 'hccounting_finance'),
            array('name' => 'Admin/Human Resources', 'slug' => 'admin_human_resources'),
            array('name' => 'Arts/Media/Communications', 'slug' => 'arts_media_communications'),
            array('name' => 'Building/Construction', 'slug' => 'building_construction'),
            array('name' => 'Computer/Information Technology', 'slug' => 'computer_information_technology'),
            array('name' => 'Education/Training', 'slug' => 'education_training'),
            array('name' => 'Engineering', 'slug' => 'engineering'),
            array('name' => 'Healthcare', 'slug' => 'healthcare'),
            array('name' => 'Hotel/Restaurant', 'slug' => 'hotel_restaurant'),
            array('name' => 'Manufacturing', 'slug' => 'manufacturing'),
            array('name' => 'Sales/Marketing', 'slug' => 'sales_marketing'),
            array('name' => 'Sciences', 'slug' => 'sciences'),
            array('name' => 'Services', 'slug' => 'services'),
            array('name' => 'Others', 'slug' => 'others'),
        );

        DB::table('categories')->insert($categories);
    }
}

I have another similar with this for subcategories here it is:

<?php

use Illuminate\Database\Seeder;

class SubategoriessTableSeeder extends Seeder {

    public function run()
    {
        DB::table('subcategories')->delete();

        $subcategories = array(
            array('name' => 'Audit & Taxation Jobs', 'slug' => 'audit_taxation_jobs', 'category_id' => ''),
        );

        DB::table('subcategories')->insert($subcategories);
    }
}

in this sample 'category_id' => '' has to get the id/name of 'Accounting/Finance category in category seed .

now my question is how?

UPDATE 2:

Error's

[Illuminate\Database\QueryException]   SQLSTATE[23000]: Integrity
  constraint violation: 1451 Cannot delete or update a parent row: a
  foreign key constraint fails (jobid.ads, CONSTRAINT ads_subcateg
  ory_id_foreign FOREIGN KEY (subcategory_id) REFERENCES
  subcategories (id)) (SQL: delete from subcategories)

 [PDOException]
  SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

(jobid.ads, CONSTRAINT ads_subcateg
        ory_id_foreign FOREIGN KEY (subcategory_id) REFERENCES subcategories (id))

Code used:

<?php

use Illuminate\Database\Seeder;
use Carbon\Carbon;

class SubcategoriesTableSeeder extends Seeder {

    public function run()
    {
        DB::table('subcategories')->delete();

            $categoryFinance = Category::select("id")->whereSlug("hccounting_finance")->firstOrFail();
            $subcategories = array(
             array('name' => 'Audit & Taxation Jobs', 'category_id' => $categoryFinance,  'slug' => 'audit_taxation_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
             array('name' => 'Banking/Financial Jobs', 'category_id' => $categoryFinance, 'slug' => 'banking-financial_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
             array('name' => 'Corporate Finance/Investment Jobs', 'category_id' => $categoryFinance, 'slug' => 'corporate_finance_investment_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
             array('name' => 'General/Cost Accounting Jobs', 'category_id' => $categoryFinance, 'slug' => 'general_cost_accounting_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
         );

         $categoryAdmin = Category::select("id")->whereSlug("admin_human_resources")->firstOrFail();
         $subcategories = array(
            array('name' => 'testing', 'slug' => 'tesingsubs', 'category_id' => $categoryAdmin, 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
        );

        DB::table('subcategories')->insert($subcategories);
    }
}

Body:
In order to relate your categories to subcategories, you should follow the logic (depending on your relationship - N-1 N-N) in the docs  (https://laravel.com/docs/5.4/eloquent-relationships). It seems that you need the attach() method.

So after creating the category entry, if you have followed the schema convention you can apply logic for all kind or relationships, even for polymorphic ones.

Edit:

After your edit it seems that you need a way to access the entries of your table again in order to relate them.

So, you can :

$categoryFinance = Category::select("id")->whereSlug("hccounting_finance")->firstOrFail();

in your SubategoriessTableSeeder run() function before creating your array.

And then give that id in your subcategory_id. The same will be for all categories you need to relate.

Edit 2

Please check again that your foreign keys are correct. In that case you cannot delete the subcategories table because Categories "need" subid. And that's where constraint violation comes from. You don't need to delete these tables.. You just need to "feed-seed" them.

So try to remove the "delete" statements.

Edit 3

I think the error is obvious now.. There is no Category with id of 2 in your database. But again, check if the keys are associated correctly (this is an SQL and not a Laravel issue).

Run migrations if any, and seeders again, with the correct order (first categories and then subcategories - first the dependency and then the dependent one in general)


问:
Server-side comments: What's the equivalent of <%-- --%> in ASP Classic?
What's the equivalent of <%-- --%> in ASP Classic?

I have to modify a legacy ASP application and I'd like to comment out a block of HTML:

```<code><td>
    some table cell I'd like to comment out, including
    some <%= inlineServerSideVBScriptExpressions() %>
</td>
</code>```

Wrapping everything in <%-- ... --%>, as I'd do in ASP.NET, doesn't work and results in the compilation error "Expected statement". HTML comments  are not an option either, since the inline ASP expressions would get evaluated and fail.

答:
The way I always comment out is using:</p>

```<code><%'=Var%>
</code>```

Body:
What's the equivalent of <%-- --%> in ASP Classic?

I have to modify a legacy ASP application and I'd like to comment out a block of HTML:

    some table cell I'd like to comment out, including
    some <%= inlineServerSideVBScriptExpressions() %>

Wrapping everything in <%-- ... --%>, as I'd do in ASP.NET, doesn't work and results in the compilation error "Expected statement". HTML comments  are not an option either, since the inline ASP expressions would get evaluated and fail.

Body:
The way I always comment out is using:

<%'=Var%>


问:
execute php after json output
i am sending few data as json from php file and it works without any issue. but i want to keep executing php file after json output. if i comment this line then those php codes are executing else they are not executing.

```<code>header('Content-Type: application/json', true);
 some more code here
   exit(json_encode($response));
</code>```

next is few more php codes which makes database connection and executes.

```<code>   $res2 = $con->query("SELECT * FROM `tableA` where status='0' order by id desc limit 5");
</code>```

update code and change the status to 1
if i comment below code

```<code>      exit(json_encode($response));
</code>```

then update code works and updates the status to 1 else it is 0. mainly because its a json file as per header and it advises to close the script execution after exit code. i tried toset header as none and echo the output but it does not work. i tried to flush also. it did not work either. any idea will be great

答:
Your question is very unclear but from what I figure out, you want to send output to browser "real time" and not wait for the script to finish. Still you are using exit, which will end the script. You should echo instead and flush output immediately.

e.g.

```<code>header('Content-Type: application/json', true);
//some more code here
echo(json_encode($response));

// This is what you need
ob_flush();
flush();

// Even more code
echo(json_encode($anotherResponse));
</code>```

Title: execute php after json output

Body:
i am sending few data as json from php file and it works without any issue. but i want to keep executing php file after json output. if i comment this line then those php codes are executing else they are not executing.

header('Content-Type: application/json', true);
 some more code here
   exit(json_encode($response));

next is few more php codes which makes database connection and executes.

   $res2 = $con->query("SELECT * FROM `tableA` where status='0' order by id desc limit 5");

update code and change the status to 1
if i comment below code

      exit(json_encode($response));

then update code works and updates the status to 1 else it is 0. mainly because its a json file as per header and it advises to close the script execution after exit code. i tried toset header as none and echo the output but it does not work. i tried to flush also. it did not work either. any idea will be great

Body:
Your question is very unclear but from what I figure out, you want to send output to browser "real time" and not wait for the script to finish. Still you are using exit, which will end the script. You should echo instead and flush output immediately.

e.g.

header('Content-Type: application/json', true);
//some more code here
echo(json_encode($response));

// This is what you need
ob_flush();
flush();

// Even more code
echo(json_encode($anotherResponse));


问:
Containers and divs in CSS
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dealsglobal">
<h2>Global Coupons</h2>
    <div class="dealsleft">
 <img src="thumb-heavengifts.jpg" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
    Test
    </div>
</div>

<div class="dealsindia">
<h2>Indian Coupons</h2>
    <div class="dealsleft">
    Test
    </div>
    <div class="dealsright">
 Test
    </div>
</div></code>```

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

答:
You can get it by using flex below an example as your requirement.

.dealsglobal {
  width: 48%;
  margin-right: 10px;
  height: auto;
  float: left;
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-flow: row nowrap;
  border: 1px solid red;
  padding: 10px;
}

.dealsglobal h2 {
  margin-left: 10px;
}

.dealsindia h2 {
  margin-left: 10px;
}

.dealsleft {
  margin: 0px 25px 10px 0px;
  padding: 5px;
  border: 1px solid #ccc;
  flex: 1 0 0;
  align-self: flex-start;
}

.dealsleft img {
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
}

.dealsright {
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  overflow: auto;
  flex: 1 0 0;
  align-self: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dealsglobal">
  <h2>Global Coupons</h2>
  <div class="flex">
    <div class="dealsleft">
      <img src="http://lorempixel.com/400/200/sports/" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
      Test
    </div>
  </div>
</div>
<div class="dealsglobal">
  <h2>Global Coupons</h2>
  <div class="flex">
    <div class="dealsleft">
      <img src="http://lorempixel.com/400/200/sports/" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
      Test
    </div>
  </div>
</div></code>```

Here is working fiddle

fiddle

Title: Containers and divs in CSS

Body:
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}

Global Coupons

    Test

Indian Coupons

    Test

 Test

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

Body:
You can get it by using flex below an example as your requirement.

.dealsglobal {
  width: 48%;
  margin-right: 10px;
  height: auto;
  float: left;
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-flow: row nowrap;
  border: 1px solid red;
  padding: 10px;
}

.dealsglobal h2 {
  margin-left: 10px;
}

.dealsindia h2 {
  margin-left: 10px;
}

.dealsleft {
  margin: 0px 25px 10px 0px;
  padding: 5px;
  border: 1px solid #ccc;
  flex: 1 0 0;
  align-self: flex-start;
}

.dealsleft img {
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
}

.dealsright {
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  overflow: auto;
  flex: 1 0 0;
  align-self: flex-start;
}

<div class="dealsglobal">
  <h2>Global Coupons</h2>
  <div class="flex">
    <div class="dealsleft">
      <img src="http://lorempixel.com/400/200/sports/" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
      Test
    </div>
  </div>
</div>
<div class="dealsglobal">
  <h2>Global Coupons</h2>
  <div class="flex">
    <div class="dealsleft">
      <img src="http://lorempixel.com/400/200/sports/" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
      Test
    </div>
  </div>
</div>

Here is working fiddle

fiddle


问:
IntelliJ IDEA - "Imported project refers to unknown jdks JavaSE-1.8" while import Eclipse projects
I tried to import Eclipse project to IntelliJ IDEA, but I got this error:

答:
Here they had a similar problem, but with android sdk

You must edit Project SDK in Project Structures > Dependencies to existing Java JDK


问:
Input text type not shown in safari
I have something in this code that breaks my <input type = "text"> from showing in safari, Im not sure what it is can anyone help me?

```<code>    input[type="text"]{
border: 3px solid #eae9ef;
border-radius: 3px !important;
box-sizing: border-box !important;
background: rgba(255,255,255,0) !important;
padding:1.5em 1em !important;
}
</code>```

The issue is because of the padding 1.5em 1em, how can I fix it,I need the padding to make the input box bigger, but with it my text disappears.

答: Give a height to the text input instead of adding padding. The padding will limit the space inside the input so the text won't show.</p>

Title: Input text type not shown in safari

Body:
I have something in this code that breaks my <input type = "text"> from showing in safari, Im not sure what it is can anyone help me?

    input[type="text"]{
border: 3px solid #eae9ef;
border-radius: 3px !important;
box-sizing: border-box !important;
background: rgba(255,255,255,0) !important;
padding:1.5em 1em !important;
}

The issue is because of the padding 1.5em 1em, how can I fix it,I need the padding to make the input box bigger, but with it my text disappears.


问:
Android ksoap2 via https
has any one been able to connect to a soap server using ksoap2 android via https?

I keep getting the error that "Hostname <###>was not verified"

I'm doing

```<code>AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport (URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
</code>```

apparently looking back at other ksoap which isn't for android your ment to us a different call to connect via https, but i can't find a way to do it in the android version.

Anyone found a way about or know the call im ment to use?

thanks for you help

答:
You can set the filename as empty string (""). Looking at the source code of ksoap it passes the parameter to java.net.URL and from the Sun Javadoc it refers to file - "the file on the host".
I have given up trying to use ksoap2 for SOAP https calls. Issue is with the way Android processes SSL connections. The only solution seems to be creating a local keystore to store the SSL certificate and writing a wrapper around the Apache Httpclient to use the certificate. So I might as well implement these calls using REST. Guess that's what Google wants us to do. </p>

Title: Android ksoap2 via https

Body:
has any one been able to connect to a soap server using ksoap2 android via https?

I keep getting the error that "Hostname <###>was not verified"

I'm doing

AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport (URL);
androidHttpTransport.call(SOAP_ACTION, envelope);

apparently looking back at other ksoap which isn't for android your ment to us a different call to connect via https, but i can't find a way to do it in the android version.

Anyone found a way about or know the call im ment to use?

thanks for you help

ContentLicense: CC BY-SA 2.5


问:
How i can export RAS (Real Application Security) objects from ORACLE DB
I use RASADM-tool to create RAS objects interactively. But now i need to deploy RAS objects from DEV to TEST. Are there any tools to export this objects (SQL Developer addons or similar) ?</p>

答:
I was tired of waiting and has writing free open-source export application available on GitHub

https://github.com/glebovpavel/RAS-Export


问:
Map size and mmap Invalid argument error
I am trying to access physical addresses registers on my ARM (https://4donline.ihs.com/images/VipMasterIC/IC/ATML/ATML-S-A0001248554/ATML-S-A0001248554-1.pdf) with mmap but I don't know what length to put.
 For example, if I have a register at address 0xFFFFFCE8 in which I have access to 32 bit.
What should I put in mmap size_t ?

Thank you for you help !

EDIT :
Here and here we can see they put 4096, and on the first one it is a SAM9 almost the same as mine.
So, why did they put 4096 ?
Maybe because if I do :

```<code>#include <unistd.h>
long sz = sysconf(_SC_PAGESIZE);
printf("%ld",sz);
</code>```

Th answer is 4096...

EDIT 2 :
Based on this post I could write this :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

#define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

#define PIOD_START_ADDR                     0xFFFFFA00
#define PIOD_STOP_ADDR                      0xFFFFFC00
#define PIOD_SIZE                           (PIOD_STOP_ADDR-PIOD_START_ADDR)

#define PIO_WPMR_OFFSET                     0xE4    // PIO Write Protection Mode Register Bank D

#define PIO_PUER_OFFSET                     0x64    // PIO Pull-Up Enable Register Bank D
#define PIO_PUSR_OFFSET                     0x68    // PIO Pull-Up Status Register Bank D

#define LED7_ON                             0xFFDFFFFF  // LED7 Mask ON
#define LED7_OFF                            0xFFFFFFFF  // LED7 Mask OFF
#define DESABLE_WRITE_PROTECTION_BANK_D     0x50494F00  // Desable write protection

int main(void) {
    volatile void *gpio_D_addr;
    volatile unsigned int *gpio_pullup_enable_addr;
    volatile unsigned int *gpio_pullup_status_addr;
    volatile unsigned int *gpio_enable_write_addr;

    int fd = open("/dev/mem", O_RDWR|O_SYNC);
    if (fd < 0){
        fprintf(stderr, "Unable to open port\n\r");
        exit(fd);
    }

    gpio_D_addr = mmap(0, PIOD_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, PIOD_START_ADDR);
    gpio_addr =  mmap(0, GPIO1_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPIO1_START_ADDR);

    if(gpio_D_addr == MAP_FAILED){
        handle_error("mmap");
    }

    gpio_enable_write_addr = gpio_D_addr + PIO_WPMR_OFFSET;
    gpio_pullup_enable_addr = gpio_D_addr + PIO_PUER_OFFSET;
    gpio_pullup_status_addr = gpio_D_addr + PIO_PUSR_OFFSET;

    *gpio_enable_write_addr = DESABLE_WRITE_PROTECTION_BANK_D;

    *gpio_pullup_enable_addr = *gpio_pullup_status_addr & LED7_ON;

    return 0;
}
</code>```

But I have a mmap: Invalid argument error.
--> But by changing the mmap like so (thank to this thread): mmap(NULL, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, PIOD_START_ADDR & ~MAP_MASK); with :

```<code>#define MAP_SIZE                            4096UL
#define MAP_MASK                            (MAP_SIZE - 1)
</code>```

I no longer have the error but nothing happened...

Any idea ?

答:
Thank you to @vlk and his library in python I could make it work ! Here is a little example for toggling a LED :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

#define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

#define _PIOD_BANK_D                            0xA00

#define _PIO_OFFSET                             0xFFFFF000

/* When executing this on the board :
    long sz = sysconf(_SC_PAGESIZE);
    printf("%ld\n\r",sz);
   We have 4096.
*/
#define _MAP_SIZE                           0x1000  // 4096

#define _WPMR_OFFSET                        0x0E4   // PIO Write Protection Mode Register Bank D

#define _PIO_ENABLE                         0x000
#define _PIO_DISABLE                        0x004
#define _PIO_STATUS                         0x008
#define _OUTPUT_ENABLE                      0x010
#define _OUTPUT_DISABLE                     0x014
#define _OUTPUT_STATUS                      0x018
#define _FILTER_ENABLE                      0x020
#define _FILTER_DISABLE                     0x024
#define _FILTER_STATUS                      0x028
#define _OUTPUT_DATA_SET                    0x030
#define _OUTPUT_DATA_CLEAR                  0x034
#define _OUTPUT_DATA_STATUS                 0x038
#define _PIN_DATA_STATUS                    0x03c
#define _MULTI_DRIVER_ENABLE                0x050
#define _MULTI_DRIVER_DISABLE               0x054
#define _MULTI_DRIVER_STATUS                0x058
#define _PULL_UP_DISABLE                    0x060
#define _PULL_UP_ENABLE                     0x064
#define _PULL_UP_STATUS                     0x068
#define _PULL_DOWN_DISABLE                  0x090
#define _PULL_DOWN_ENABLE                   0x094
#define _PULL_DOWN_STATUS                   0x098

#define _DISABLE_WRITE_PROTECTION           0x50494F00  // Desable write protection

#define LED_PIN                                 21

int main(void) {

    volatile void *gpio_addr;
    volatile unsigned int *gpio_enable_addr;
    volatile unsigned int *gpio_output_mode_addr;
    volatile unsigned int *gpio_output_set_addr;
    volatile unsigned int *gpio_output_clear_addr;
    volatile unsigned int *gpio_data_status_addr;
    volatile unsigned int *gpio_write_protection_addr;

    int fd = open("/dev/mem", O_RDWR|O_SYNC);
    if (fd < 0){
        fprintf(stderr, "Unable to open port\n\r");
        exit(fd);
    }

    gpio_addr = mmap(NULL, _MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PIO_OFFSET);

    if(gpio_addr == MAP_FAILED){
        handle_error("mmap");
    }

    gpio_write_protection_addr = gpio_addr + _PIOD_BANK_D + _WPMR_OFFSET;

    gpio_enable_addr = gpio_addr + _PIOD_BANK_D + _PIO_ENABLE;

    gpio_output_mode_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_ENABLE;

    gpio_output_set_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_SET;

    gpio_output_clear_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_CLEAR;

    gpio_data_status_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_STATUS;

    *gpio_write_protection_addr = _DISABLE_WRITE_PROTECTION;

    *gpio_enable_addr = 1 << LED_PIN;
    *gpio_output_mode_addr = 1 << LED_PIN; // Output

    // If LED
    if((*gpio_data_status_addr & (1<<LED_PIN)) > 0){
        *gpio_output_clear_addr = 1 << LED_PIN;
    }else{
        *gpio_output_set_addr = 1 << LED_PIN;
    }

    return 0;
}
</code>```

I had to put _PIO_OFFSET to 0xFFFFF000, and add to the address the value of the D Bank (0xA00), instead of 0xFFFFFA00 because it resulted with mmap: Invalid argument. Don't know why..

EDIT :

Found the solution with the mmap example :

```<code>#define _PIO_OFFSET                         0xFFFFFA00 // Instead of 0xFFFFF000
#define _MAP_SIZE                           0x1000  // 4096
#define _MAP_MASK                           (_MAP_SIZE - 1)
#define _PA_OFFSET                          _PIO_OFFSET & ~_MAP_MASK
</code>```

And the mmap :

```<code>gpio_addr = mmap(NULL, _MAP_SIZE + _PIO_OFFSET - _PA_OFFSET, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PA_OFFSET);
</code>```

And for the assignation :

```<code>gpio_enable_addr = gpio_addr + _PIO_OFFSET - (_PA_OFFSET) + _PIO_ENABLE;
</code>```

Body:
I am trying to access physical addresses registers on my ARM (https://4donline.ihs.com/images/VipMasterIC/IC/ATML/ATML-S-A0001248554/ATML-S-A0001248554-1.pdf) with mmap but I don't know what length to put.
 For example, if I have a register at address 0xFFFFFCE8 in which I have access to 32 bit.
What should I put in mmap size_t ?

Thank you for you help !

EDIT :
Here and here we can see they put 4096, and on the first one it is a SAM9 almost the same as mine.
So, why did they put 4096 ?
Maybe because if I do :

#include <unistd.h>
long sz = sysconf(_SC_PAGESIZE);
printf("%ld",sz);

Th answer is 4096...

EDIT 2 :
Based on this post I could write this :

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

#define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

#define PIOD_START_ADDR                     0xFFFFFA00
#define PIOD_STOP_ADDR                      0xFFFFFC00
#define PIOD_SIZE                           (PIOD_STOP_ADDR-PIOD_START_ADDR)

#define PIO_WPMR_OFFSET                     0xE4    // PIO Write Protection Mode Register Bank D

#define PIO_PUER_OFFSET                     0x64    // PIO Pull-Up Enable Register Bank D
#define PIO_PUSR_OFFSET                     0x68    // PIO Pull-Up Status Register Bank D

#define LED7_ON                             0xFFDFFFFF  // LED7 Mask ON
#define LED7_OFF                            0xFFFFFFFF  // LED7 Mask OFF
#define DESABLE_WRITE_PROTECTION_BANK_D     0x50494F00  // Desable write protection

int main(void) {
    volatile void *gpio_D_addr;
    volatile unsigned int *gpio_pullup_enable_addr;
    volatile unsigned int *gpio_pullup_status_addr;
    volatile unsigned int *gpio_enable_write_addr;

    int fd = open("/dev/mem", O_RDWR|O_SYNC);
    if (fd < 0){
        fprintf(stderr, "Unable to open port\n\r");
        exit(fd);
    }

    gpio_D_addr = mmap(0, PIOD_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, PIOD_START_ADDR);
    gpio_addr =  mmap(0, GPIO1_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPIO1_START_ADDR);

    if(gpio_D_addr == MAP_FAILED){
        handle_error("mmap");
    }

    gpio_enable_write_addr = gpio_D_addr + PIO_WPMR_OFFSET;
    gpio_pullup_enable_addr = gpio_D_addr + PIO_PUER_OFFSET;
    gpio_pullup_status_addr = gpio_D_addr + PIO_PUSR_OFFSET;

    *gpio_enable_write_addr = DESABLE_WRITE_PROTECTION_BANK_D;

    *gpio_pullup_enable_addr = *gpio_pullup_status_addr & LED7_ON;

    return 0;
}

But I have a mmap: Invalid argument error.
--> But by changing the mmap like so (thank to this thread): mmap(NULL, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, PIOD_START_ADDR & ~MAP_MASK); with :

#define MAP_SIZE                            4096UL
#define MAP_MASK                            (MAP_SIZE - 1)

I no longer have the error but nothing happened...

Any idea ?

Body:
Thank you to @vlk and his library in python I could make it work ! Here is a little example for toggling a LED :

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

#define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

#define _PIOD_BANK_D                            0xA00

#define _PIO_OFFSET                             0xFFFFF000

/* When executing this on the board :
    long sz = sysconf(_SC_PAGESIZE);
    printf("%ld\n\r",sz);
   We have 4096.
*/
#define _MAP_SIZE                           0x1000  // 4096

#define _WPMR_OFFSET                        0x0E4   // PIO Write Protection Mode Register Bank D

#define _PIO_ENABLE                         0x000
#define _PIO_DISABLE                        0x004
#define _PIO_STATUS                         0x008
#define _OUTPUT_ENABLE                      0x010
#define _OUTPUT_DISABLE                     0x014
#define _OUTPUT_STATUS                      0x018
#define _FILTER_ENABLE                      0x020
#define _FILTER_DISABLE                     0x024
#define _FILTER_STATUS                      0x028
#define _OUTPUT_DATA_SET                    0x030
#define _OUTPUT_DATA_CLEAR                  0x034
#define _OUTPUT_DATA_STATUS                 0x038
#define _PIN_DATA_STATUS                    0x03c
#define _MULTI_DRIVER_ENABLE                0x050
#define _MULTI_DRIVER_DISABLE               0x054
#define _MULTI_DRIVER_STATUS                0x058
#define _PULL_UP_DISABLE                    0x060
#define _PULL_UP_ENABLE                     0x064
#define _PULL_UP_STATUS                     0x068
#define _PULL_DOWN_DISABLE                  0x090
#define _PULL_DOWN_ENABLE                   0x094
#define _PULL_DOWN_STATUS                   0x098

#define _DISABLE_WRITE_PROTECTION           0x50494F00  // Desable write protection

#define LED_PIN                                 21

int main(void) {

    volatile void *gpio_addr;
    volatile unsigned int *gpio_enable_addr;
    volatile unsigned int *gpio_output_mode_addr;
    volatile unsigned int *gpio_output_set_addr;
    volatile unsigned int *gpio_output_clear_addr;
    volatile unsigned int *gpio_data_status_addr;
    volatile unsigned int *gpio_write_protection_addr;

    int fd = open("/dev/mem", O_RDWR|O_SYNC);
    if (fd < 0){
        fprintf(stderr, "Unable to open port\n\r");
        exit(fd);
    }

    gpio_addr = mmap(NULL, _MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PIO_OFFSET);

    if(gpio_addr == MAP_FAILED){
        handle_error("mmap");
    }

    gpio_write_protection_addr = gpio_addr + _PIOD_BANK_D + _WPMR_OFFSET;

    gpio_enable_addr = gpio_addr + _PIOD_BANK_D + _PIO_ENABLE;

    gpio_output_mode_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_ENABLE;

    gpio_output_set_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_SET;

    gpio_output_clear_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_CLEAR;

    gpio_data_status_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_STATUS;

    *gpio_write_protection_addr = _DISABLE_WRITE_PROTECTION;

    *gpio_enable_addr = 1 << LED_PIN;
    *gpio_output_mode_addr = 1 << LED_PIN; // Output

    // If LED
    if((*gpio_data_status_addr & (1<<LED_PIN)) > 0){
        *gpio_output_clear_addr = 1 << LED_PIN;
    }else{
        *gpio_output_set_addr = 1 << LED_PIN;
    }

    return 0;
}

I had to put _PIO_OFFSET to 0xFFFFF000, and add to the address the value of the D Bank (0xA00), instead of 0xFFFFFA00 because it resulted with mmap: Invalid argument. Don't know why..

EDIT :

Found the solution with the mmap example :

#define _PIO_OFFSET                         0xFFFFFA00 // Instead of 0xFFFFF000
#define _MAP_SIZE                           0x1000  // 4096
#define _MAP_MASK                           (_MAP_SIZE - 1)
#define _PA_OFFSET                          _PIO_OFFSET & ~_MAP_MASK

And the mmap :

gpio_addr = mmap(NULL, _MAP_SIZE + _PIO_OFFSET - _PA_OFFSET, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PA_OFFSET);

And for the assignation :

gpio_enable_addr = gpio_addr + _PIO_OFFSET - (_PA_OFFSET) + _PIO_ENABLE;


问:
[ag-grid]: Free text filter/ search bar above the grid
I am new to angular so please accept my apologies if its basic question.
I have a grid defined and it is getting row data from the database. I am trying to place a search bar above the grid to apply an additional free text filter on it. The grid already has column filters on it. Any help would be really appreciated. I am using  Here is my code

```<code><input class"search" placeholder="Search..." type="text" ng-model="search-model" ng-change="$ctrl.onFilterChanged(this.search)"/>

onFilterChanged(value){
   this.gridOptions.api.setQuickFilter(value);
  }
</code>```

I have also looked into the external filter but I am not able to implement it as a free text. I am really struggling with it. Please help me out. Thank you so much.

答:
the ng-model that is wrong. The correct value is:</p>

```<code><input class"search" placeholder="Search..." type="text" ng-model="search" ng-change="$ctrl.onFilterChanged(this.search)"/>
</code>```

Body:
I am new to angular so please accept my apologies if its basic question.
I have a grid defined and it is getting row data from the database. I am trying to place a search bar above the grid to apply an additional free text filter on it. The grid already has column filters on it. Any help would be really appreciated. I am using  Here is my code

<input class"search" placeholder="Search..." type="text" ng-model="search-model" ng-change="$ctrl.onFilterChanged(this.search)"/>

onFilterChanged(value){
   this.gridOptions.api.setQuickFilter(value);
  }

I have also looked into the external filter but I am not able to implement it as a free text. I am really struggling with it. Please help me out. Thank you so much.

Body:
the ng-model that is wrong. The correct value is:

<input class"search" placeholder="Search..." type="text" ng-model="search" ng-change="$ctrl.onFilterChanged(this.search)"/>


问:
How to display the listview at the bottom of my activity ? There are 3 linear layouts above the listview
i am dividing my android screen into four vertical parts and i want to display the listview at the bottom of my screen, but whenever i placed it at bottom it wont aligned to the bottom. Even after i stretched it to the bottom it takes full screen. how to do that ?</p>

答:
Linear layout with vertical orientation will be more helpful instead of
relative layout</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="4"
android:orientation="vertical"
>
 <LinearLayout
   android:layout_width="match_parent"
   android:layout_weight="1"
   android:layout_height="0dp">
 </LinearLayout>

<LinearLayout
  android:layout_width="match_parent"
  android:layout_weight="1"
  android:layout_height="0dp">
  </LinearLayout>

<LinearLayout
   android:layout_width="match_parent"
   android:layout_weight="1"
   android:layout_height="0dp">
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_weight="1"
    android:layout_height="0dp">

    <ListView
        android:id="@+id/mListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
 </LinearLayout>
</code>```

Body:
Linear layout with vertical orientation will be more helpful instead of
relative layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="4"
android:orientation="vertical"
>
 <LinearLayout
   android:layout_width="match_parent"
   android:layout_weight="1"
   android:layout_height="0dp">
 </LinearLayout>

<LinearLayout
  android:layout_width="match_parent"
  android:layout_weight="1"
  android:layout_height="0dp">
  </LinearLayout>

<LinearLayout
   android:layout_width="match_parent"
   android:layout_weight="1"
   android:layout_height="0dp">
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_weight="1"
    android:layout_height="0dp">

    <ListView
        android:id="@+id/mListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
 </LinearLayout>


问:
php + curl + multipart/form-data + proxy-authorization(basic)
I have a problem: I trying to send headers, but nothing happens.

This is a part of the headers from "Live HTTPHeaders"(i replaced the url):

```
http://some_site/news/

POST /news/ HTTP/1.1
Host: some_site
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://some_site/news/
Proxy-Authorization: Basic MTQ4YjU5YWMtM2VlOS00ZmIzLThlODItOTU0MjcxODhhZTRlOjAyNDdkNWRkNGY1MTE2NWUzODFlNDVhYTY1YzQ5OWYwMTRhYzA2ZTg=
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=---------------------------123064818248741452271123522
Content-Length: 893
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="BJpKD8Fx"

Hello!!!
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="file"; filename=""
Content-Type: application/octet-stream

-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="parent"

155143
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="redirect"

0
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="eggs2"

UzFWa05qVnpjRmw4UWtwd1MwUTRSbmc9
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="submit"

Äîáàâèòü
-----------------------------123064818248741452271123522--

HTTP/1.1 302 Found
```

And this is my code:

```<code><?php

 $parent = 155129;

 function doPost( $url = 'http://some_site/news', $postdata = '' ){

 $resource = curl_init();
 curl_setopt($resource, CURLOPT_URL, $url);
 curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt ($resource, CURLOPT_SSL_VERIFYPEER, 0);
 curl_setopt ($resource, CURLOPT_SSL_VERIFYHOST, 0);
 curl_setopt ($resource, CURLOPT_HTTPHEADER, array('Expect:'));
 curl_setopt ($resource, CURLOPT_HEADER, 1);
 curl_setopt ($resource, CURLOPT_COOKIEJAR, 'cookie.txt');
 curl_setopt($resource,CURLOPT_COOKIEFILE,'cookie.txt');
 curl_setopt($resource, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 if( $postdata != '' ) {
     curl_setopt($resource, CURLOPT_POST, true);
     curl_setopt($resource, CURLOPT_POSTFIELDS, $postdata);
 }
 curl_setopt($resource, CURLOPT_FOLLOWLOCATION, true);
 $result = curl_exec($resource);
 curl_close($resource);
 return $result;

}

$c = doPost();
preg_match('#id="textarea_form_'.$parent.'" name="(.*?)"#ims', $c, $textName);
preg_match('#<form.*?\/form>#ims', $c, $arr );
preg_match('#name=eggs2.*?value="(.*?)">#ims', $arr[0], $egss2);

$postdata = array(
    $textName[1]=> 'Hello',
   'file'=>'@/;type=application/octet-stream',
   'parent' => $parent,
   'redirect'=> '0',
   'eggs2' => $egss2[1],
   'submit' => iconv('utf-8', 'cp1252', 'Добавить')
);

print_r(doPost('http://some_site/news',$postdata));
print_r( $postdata );
</code>```

What I am doing wrong?

Thank you!

p.s. Hehehehehehehehehehehehehehehehehehehehehehe!!!! I solved! Thanks all for watching! Good-luck

答:
You need to inject your headers like this : </p>

```<code>curl_setopt($resource, CURLOPT_HTTPHEADER, array(
'X-Apple-Tz: 0',
'X-Apple-Store-Front: 143444,12'
));
</code>```

Body:
I have a problem: I trying to send headers, but nothing happens.

This is a part of the headers from "Live HTTPHeaders"(i replaced the url):

http://some_site/news/

POST /news/ HTTP/1.1
Host: some_site
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://some_site/news/
Proxy-Authorization: Basic MTQ4YjU5YWMtM2VlOS00ZmIzLThlODItOTU0MjcxODhhZTRlOjAyNDdkNWRkNGY1MTE2NWUzODFlNDVhYTY1YzQ5OWYwMTRhYzA2ZTg=
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=---------------------------123064818248741452271123522
Content-Length: 893
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="BJpKD8Fx"

Hello!!!
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="file"; filename=""
Content-Type: application/octet-stream

-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="parent"

155143
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="redirect"

0
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="eggs2"

UzFWa05qVnpjRmw4UWtwd1MwUTRSbmc9
-----------------------------123064818248741452271123522
Content-Disposition: form-data; name="submit"

Äîáàâèòü
-----------------------------123064818248741452271123522--

HTTP/1.1 302 Found

And this is my code:

<?php

 $parent = 155129;

 function doPost( $url = 'http://some_site/news', $postdata = '' ){

 $resource = curl_init();
 curl_setopt($resource, CURLOPT_URL, $url);
 curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt ($resource, CURLOPT_SSL_VERIFYPEER, 0);
 curl_setopt ($resource, CURLOPT_SSL_VERIFYHOST, 0);
 curl_setopt ($resource, CURLOPT_HTTPHEADER, array('Expect:'));
 curl_setopt ($resource, CURLOPT_HEADER, 1);
 curl_setopt ($resource, CURLOPT_COOKIEJAR, 'cookie.txt');
 curl_setopt($resource,CURLOPT_COOKIEFILE,'cookie.txt');
 curl_setopt($resource, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 if( $postdata != '' ) {
     curl_setopt($resource, CURLOPT_POST, true);
     curl_setopt($resource, CURLOPT_POSTFIELDS, $postdata);
 }
 curl_setopt($resource, CURLOPT_FOLLOWLOCATION, true);
 $result = curl_exec($resource);
 curl_close($resource);
 return $result;

}

$c = doPost();
preg_match('#id="textarea_form_'.$parent.'" name="(.*?)"#ims', $c, $textName);
preg_match('#<form.*?\/form>#ims', $c, $arr );
preg_match('#name=eggs2.*?value="(.*?)">#ims', $arr[0], $egss2);

$postdata = array(
    $textName[1]=> 'Hello',
   'file'=>'@/;type=application/octet-stream',
   'parent' => $parent,
   'redirect'=> '0',
   'eggs2' => $egss2[1],
   'submit' => iconv('utf-8', 'cp1252', 'Добавить')
);

print_r(doPost('http://some_site/news',$postdata));
print_r( $postdata );

What I am doing wrong?

Thank you!

p.s. Hehehehehehehehehehehehehehehehehehehehehehe!!!! I solved! Thanks all for watching! Good-luck

Body:
You need to inject your headers like this :

curl_setopt($resource, CURLOPT_HTTPHEADER, array(
'X-Apple-Tz: 0',
'X-Apple-Store-Front: 143444,12'
));


问:
Force a fullscreen resolution that is not contained in display.list_modes()
I'm making a simulation for school and I'm trying to make pygame create a fullscreen display in my native resolution. However, I have a QHD screen (2560x1440), and it isn't working properly. As far as I can tell, pygame is rendering a screen at the correct resolution, but expanding it so it is scaled as if it were 1080p, so about 300-400 pixels are cut off around the edges. This causes, for example, a circle rendered at (200,200) to be completely invisible. After some research, I learned that this is because pygame doesn't officially support my resolution (it is not listed in pygame.display.list_modes()). Is there any way to force it to work? I would prefer if I could use my actual resolution instead of upscaled 1080p.

Here is the code that initializes the window:

```<code>import pygame
from pygame.locals import *
pygame.init()
w = pygame.display.Info().current_w
h = pygame.display.Info().current_h
S = pygame.display.set_mode((w,h), pygame.FULLSCREEN)
</code>```

答:
If you are using Windows, make sure in your display settings you have scaling set to 100%. This will make your text and everything smaller if you don't have it at that currently but I think Pygame windows get affected by this number for some reason.

See the below code snippet for making sure your window scales properly. Also see here.

```<code>import pygame
from ctypes import windll

def run():
    # Force windows to ignore the display scaling value.
    windll.user32.SetProcessDPIAware()

    pygame.display.init()

    # Make the screen the highest resolution that will fit the screen at 100% scaling.
    screen = pygame.display.set_mode(pygame.display.list_modes()[0])

    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True

        pygame.display.flip()

    pygame.quit()

if __name__ == "__main__":
    run()
</code>```

Body:
I'm making a simulation for school and I'm trying to make pygame create a fullscreen display in my native resolution. However, I have a QHD screen (2560x1440), and it isn't working properly. As far as I can tell, pygame is rendering a screen at the correct resolution, but expanding it so it is scaled as if it were 1080p, so about 300-400 pixels are cut off around the edges. This causes, for example, a circle rendered at (200,200) to be completely invisible. After some research, I learned that this is because pygame doesn't officially support my resolution (it is not listed in pygame.display.list_modes()). Is there any way to force it to work? I would prefer if I could use my actual resolution instead of upscaled 1080p.

Here is the code that initializes the window:

import pygame
from pygame.locals import *
pygame.init()
w = pygame.display.Info().current_w
h = pygame.display.Info().current_h
S = pygame.display.set_mode((w,h), pygame.FULLSCREEN)

Body:
If you are using Windows, make sure in your display settings you have scaling set to 100%. This will make your text and everything smaller if you don't have it at that currently but I think Pygame windows get affected by this number for some reason.

See the below code snippet for making sure your window scales properly. Also see here.

import pygame
from ctypes import windll

def run():
    # Force windows to ignore the display scaling value.
    windll.user32.SetProcessDPIAware()

    pygame.display.init()

    # Make the screen the highest resolution that will fit the screen at 100% scaling.
    screen = pygame.display.set_mode(pygame.display.list_modes()[0])

    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True

        pygame.display.flip()

    pygame.quit()

if __name__ == "__main__":
    run()


问:
Unable to send button template as response on Facebook Messenger Platform (Node.js)
I am developing a chatbot on the Facebook Messenger Platform using Node.js. This is my functioning code for setting up a text response:

```<code>const fbReq = request.defaults({
  uri: 'https://graph.facebook.com/me/messages',
  method: 'POST',
  json: true,
  qs: {
    access_token: Config.FB_PAGE_TOKEN
  },
  headers: {
    'Content-Type': 'application/json'
  },
});

const fbMessage = (recipientId, msg, cb) => {
  const opts = {
    form: {
      recipient: {
        id: recipientId,
      },
      message: {
        text: msg,
      },
    },
  };

  fbReq(opts, (err, resp, data) => {
    if (cb) {
      cb(err || data.error && data.error.message, data);
    }
  });
};
</code>```

I am also able to set up an image response this way. However, when I try to make the response a button template (https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template), no response is received. No error is thrown either.

```<code>const fbInfo = (recipientId, cb) => {
  const opts = {
    form: {
      recipient: {
        id: recipientId,
      },
      message: {
        attachment:{
          type:"template",
          text:"Check out our website",
          payload:{
            template_type:"button",
            buttons:[
              {
                type:"web_url",
                url:"https://some.website.com",
                title:"Website"
              }
            ]
          }
        }
      }
    }
  };

  fbReq(opts, (err, resp, data) => {
    if (cb) {
      cb(err || data.error && data.error.message, data);
    }
  });
};
</code>```

答:
Instead of form you should use json.

take a look at the code which I have written on glitch

should be something like:

```<code>request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: <TOKEN> },
    method: 'POST',
    json: messageData}, ...)
</code>```

Body:
I am developing a chatbot on the Facebook Messenger Platform using Node.js. This is my functioning code for setting up a text response:

const fbReq = request.defaults({
  uri: 'https://graph.facebook.com/me/messages',
  method: 'POST',
  json: true,
  qs: {
    access_token: Config.FB_PAGE_TOKEN
  },
  headers: {
    'Content-Type': 'application/json'
  },
});

const fbMessage = (recipientId, msg, cb) => {
  const opts = {
    form: {
      recipient: {
        id: recipientId,
      },
      message: {
        text: msg,
      },
    },
  };

  fbReq(opts, (err, resp, data) => {
    if (cb) {
      cb(err || data.error && data.error.message, data);
    }
  });
};

I am also able to set up an image response this way. However, when I try to make the response a button template (https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template), no response is received. No error is thrown either.

const fbInfo = (recipientId, cb) => {
  const opts = {
    form: {
      recipient: {
        id: recipientId,
      },
      message: {
        attachment:{
          type:"template",
          text:"Check out our website",
          payload:{
            template_type:"button",
            buttons:[
              {
                type:"web_url",
                url:"https://some.website.com",
                title:"Website"
              }
            ]
          }
        }
      }
    }
  };

  fbReq(opts, (err, resp, data) => {
    if (cb) {
      cb(err || data.error && data.error.message, data);
    }
  });
};

Body:
Instead of form you should use json.

take a look at the code which I have written on glitch

should be something like:

request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: <TOKEN> },
    method: 'POST',
    json: messageData}, ...)


问:
Got Error while Running Mayavi after installing it in Ubuntu
I want to install mayavi in ubuntu ,I install it successfully,but when i run mayavi2 ,it said:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/mayavi2", line 7, in <module>
    from mayavi.scripts.mayavi2 import main
  File "/usr/local/lib/python2.7/dist-packages/mayavi/scripts/mayavi2.py",
line 494, in <module>
    raise ImportError(msg)
ImportError: No module named envisage.ui.workbench.api
Could not load envisage. You might have a missing dependency.
</code>```

Do you have the EnvisageCore and EnvisagePlugins installed?

If you installed Mayavi with easy_install, try 'easy_install
  '. 'easy_install Mayavi[app]' will also work.

If you performed a source checkout and installed via 'python setup.py
  develop', be sure to run the same command in the EnvisageCore and
  EnvisagePlugins folders.

If these packages appear to be installed, check that your numpy and
  configobj are installed and working. If you need numpy, 'easy_install
  numpy' will install numpy. Similarly, 'easy_install configobj' will
  install configobj.

I don't know what to do? help!

答:
Ubuntu 14.04 ships mayavi. Use that version unless you have a strong reason to do otherwise and are willing to go a bit further in installation issues.

First you need to remove pip-installed packages from your system path. Else you are at risk of mismatched versions of packages and have little recourse for fixing these problems.

Steps:

Remove pip-installed mayavi

```<code>sudo pip uninstall mayavi
</code>```

Remove other packages that pip might have installed. For this, it will be useful if you remember or still have the console that has installed mayavi.

Install the system-provided mayavi

```<code>sudo apt-get install mayavi2
</code>```

Body:
I want to install mayavi in ubuntu ,I install it successfully,but when i run mayavi2 ,it said:

Traceback (most recent call last):
  File "/usr/local/bin/mayavi2", line 7, in <module>
    from mayavi.scripts.mayavi2 import main
  File "/usr/local/lib/python2.7/dist-packages/mayavi/scripts/mayavi2.py",
line 494, in <module>
    raise ImportError(msg)
ImportError: No module named envisage.ui.workbench.api
Could not load envisage. You might have a missing dependency.

Do you have the EnvisageCore and EnvisagePlugins installed?

If you installed Mayavi with easy_install, try 'easy_install
  '. 'easy_install Mayavi[app]' will also work.

If you performed a source checkout and installed via 'python setup.py
  develop', be sure to run the same command in the EnvisageCore and
  EnvisagePlugins folders.

If these packages appear to be installed, check that your numpy and
  configobj are installed and working. If you need numpy, 'easy_install
  numpy' will install numpy. Similarly, 'easy_install configobj' will
  install configobj.

I don't know what to do? help!

Body:
Ubuntu 14.04 ships mayavi. Use that version unless you have a strong reason to do otherwise and are willing to go a bit further in installation issues.

First you need to remove pip-installed packages from your system path. Else you are at risk of mismatched versions of packages and have little recourse for fixing these problems.

Steps:

Remove pip-installed mayavi

sudo pip uninstall mayavi

Remove other packages that pip might have installed. For this, it will be useful if you remember or still have the console that has installed mayavi.

Install the system-provided mayavi

sudo apt-get install mayavi2


问:
Clear cache programmatically on Prestashop 1.6
One important module (payment) disappears from front office randomly.

I discover that if i clear cache from the back office (see image), the module is back again.

However, no cache is activated in BO but i need to click on the clear cache button.

So, for now, as i can’t find a solution, i decided to create a cron function to clear cache.

But my function seems to be incomplete because the module doesn’t show after calling this function.
Again, if i clear cache from the  BO (by clicking on the button "clear cache"), the module appears again.

Is something missing in my function ? I use Prestashop 1.6.1.6

Here is my code :

```<code>require(dirname(__FILE__) . '/config/config.inc.php');

// sécurité pour éviter qu'un robot ou un user appelle le script
$token = Tools::getValue('token');
if (!$token || $token != '169785') {
    die();
}

Tools::clearSmartyCache();
Tools::clearXMLCache();
Media::clearCache();
PrestaShopAutoload::getInstance()->generateIndex();
</code>```

答:
As the AdminPerformance controller do:

```<code>Tools::clearSmartyCache();
Tools::clearXMLCache();
Media::clearCache();
Tools::generateIndex();
</code>```

That's enough :)

Body:
One important module (payment) disappears from front office randomly.

I discover that if i clear cache from the back office (see image), the module is back again.

However, no cache is activated in BO but i need to click on the clear cache button.

So, for now, as i can’t find a solution, i decided to create a cron function to clear cache.

But my function seems to be incomplete because the module doesn’t show after calling this function.
Again, if i clear cache from the  BO (by clicking on the button "clear cache"), the module appears again.

Is something missing in my function ? I use Prestashop 1.6.1.6

Here is my code :

require(dirname(__FILE__) . '/config/config.inc.php');

// sécurité pour éviter qu'un robot ou un user appelle le script
$token = Tools::getValue('token');
if (!$token || $token != '169785') {
    die();
}

Tools::clearSmartyCache();
Tools::clearXMLCache();
Media::clearCache();
PrestaShopAutoload::getInstance()->generateIndex();

Body:
As the AdminPerformance controller do:

Tools::clearSmartyCache();
Tools::clearXMLCache();
Media::clearCache();
Tools::generateIndex();

That's enough :)


问:
Avoid System.FormatException with Binding.Parse
I have a TextBox which is bound to a property of type decimal. As I want the value in the textfield to be shown with two decimal points (e.g. 3.15), I have implemted the binding as follows:

```<code>Binding bindDecimal = new Binding("Text", viewModel, "myDecimal");
bindDecimal.Format += FormatDecimal;
bindDecimal.Parse += ParseDecimal;
</code>```

The .Format function, so the interesting part is the .Parse function, which is implemented like this:

```<code>private void ParseDecimal(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(decimal)) return;

    e.Value = Decimal.Parse(e.Value.ToString(), NumberStyles.Number);
}
</code>```

Which works, as long as the value is a legit one. If I start using letters or (more realistically) just leave the field empty, it returns a System.FormatException, since it cannot convert the value to a decimal. A twist on the problem is, that it also occurs if you close the form window, while the TextBox is empty.

What is the best way to avoid this exception?

Also, if it makes any difference, here is the .Format function:

```<code>private void FormatDecimal(object sender, ConvertEventArgs e)
{
    // The method converts only to string type. Test this using the DesiredType.
    if (e.DesiredType != typeof(string)) return;

    // Formats the value with two decimals
    e.Value = string.Format("{0:n2}", e.Value);
}
</code>```

答:
You should use decimal.TryParse():

```<code>private void ParseDecimal(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(decimal)) return;

    Decimal bob;

    Decimal.TryParse(e.Value.ToString(), NumberStyles.Number, new CultureInfo.CurrentCulture, out bob)

    // set e.Value to bob regardless of whether a true of false is returned
    // if true bob holds the parsed value.
    // if false bob holds the default value for decimal (zero), which you probably want to use
    e.Value = bob;

 }
</code>```

Body:
I have a TextBox which is bound to a property of type decimal. As I want the value in the textfield to be shown with two decimal points (e.g. 3.15), I have implemted the binding as follows:

Binding bindDecimal = new Binding("Text", viewModel, "myDecimal");
bindDecimal.Format += FormatDecimal;
bindDecimal.Parse += ParseDecimal;

The .Format function, so the interesting part is the .Parse function, which is implemented like this:

private void ParseDecimal(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(decimal)) return;

    e.Value = Decimal.Parse(e.Value.ToString(), NumberStyles.Number);
}

Which works, as long as the value is a legit one. If I start using letters or (more realistically) just leave the field empty, it returns a System.FormatException, since it cannot convert the value to a decimal. A twist on the problem is, that it also occurs if you close the form window, while the TextBox is empty.

What is the best way to avoid this exception?

Also, if it makes any difference, here is the .Format function:

private void FormatDecimal(object sender, ConvertEventArgs e)
{
    // The method converts only to string type. Test this using the DesiredType.
    if (e.DesiredType != typeof(string)) return;

    // Formats the value with two decimals
    e.Value = string.Format("{0:n2}", e.Value);
}

Body:
You should use decimal.TryParse():

private void ParseDecimal(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(decimal)) return;

    Decimal bob;

    Decimal.TryParse(e.Value.ToString(), NumberStyles.Number, new CultureInfo.CurrentCulture, out bob)

    // set e.Value to bob regardless of whether a true of false is returned
    // if true bob holds the parsed value.
    // if false bob holds the default value for decimal (zero), which you probably want to use
    e.Value = bob;

 }


问:
Need suggestion for framework
I just went through https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why discussion and read about frameworks.

Till now I've been coding from scratch everytime I developer a new application, Now I want to start with a framework for new project. Things I am looking for in the framework

User Signup Process OAuth module for

List item Twitter (fetching tweets) (important)

OAuth module for Facebook (fetching wall-posts) (important)

MVC Architecture

Paypal module for payments

I dont know if such framework exists, and I am new to frameworks, so I am looking for suggestion for which framework to start with and what all modules/plugins to pick

Language: PHP

Backend: MySQL

Frontend: HTML5/CSS

Platform: OSX

答:
The most happening future proof, nimble framework in php at the moment I believe in Lithium checkout it out here

I highly recommend it.

Title: Need suggestion for framework


问:
Cannot authenticate into mongo, "auth fails"
I've created an admin user for mongo using these directions:

http://docs.mongodb.org/manual/tutorial/add-user-administrator/

From the mongo client it looks like I can authenticate:

```<code>> use admin
switched to db admin
> db.auth('admin','SECRETPASSWORD');
1
>
</code>```

But I can't connect any other way. For example:

mongo -u admin -p SECRETPASSWORD

gives the error:

```<code>JavaScript execution failed: Error: 18 { code: 18, ok: 0.0, errmsg: "auth fails" } at src/mongo/shell/db.js:L228
</code>```

I have auth = true in etc/mongod.conf.

What am I missing?

答:
The proper way to login into mongo shell is

mongo localhost:27017 -u 'uuuuu' -p '>xxxxxx' --authenticationDatabase dbname

ContentLicense: CC BY-SA 4.0

Body:
I've created an admin user for mongo using these directions:

http://docs.mongodb.org/manual/tutorial/add-user-administrator/

From the mongo client it looks like I can authenticate:

> use admin
switched to db admin
> db.auth('admin','SECRETPASSWORD');
1
>

But I can't connect any other way. For example:

mongo -u admin -p SECRETPASSWORD

gives the error:

JavaScript execution failed: Error: 18 { code: 18, ok: 0.0, errmsg: "auth fails" } at src/mongo/shell/db.js:L228

I have auth = true in etc/mongod.conf.

What am I missing?


问:
how to compare two different date formats in oracle ? like in one table date store in 'YYYY/MM/DD HH24:MI:SS' and another table 'dd,mm,yyyy'
how to compare two different date formats in oracle ? like in one table date store in 'YYYY/MM/DD HH24:MI:SS' and another table 'dd,mm,yyyy'</p>

答:
From your question I understand that you are storing date as string in your database column.
First convert the String to date datatype using the to_date function.
Use the function output for comparison.

Below is the sample usage of to_date function:

```<code> SELECT TO_DATE ('2017/06/06 17:30:00', 'YYYY/MM/DD HH24:MI:SS') date1,
   TO_DATE ('01,05,2017', 'DD,MM,YYYY') date2
 FROM DUAL
</code>```

Note: It is strongly recommended to store dates in columns having datatype DATE rather than storing them in VARCHAR columns. It will help to simplify the date operations.

Body:
From your question I understand that you are storing date as string in your database column.
First convert the String to date datatype using the to_date function.
Use the function output for comparison.

Below is the sample usage of to_date function:

 SELECT TO_DATE ('2017/06/06 17:30:00', 'YYYY/MM/DD HH24:MI:SS') date1,
   TO_DATE ('01,05,2017', 'DD,MM,YYYY') date2
 FROM DUAL

Note: It is strongly recommended to store dates in columns having datatype DATE rather than storing them in VARCHAR columns. It will help to simplify the date operations.


问:
Could doctrine provide records filtered by user roles, groups or permissions?
I've a project with a huge amount of data. I need to make query based on user role/group/permission. This means that a query like

```<code>$fooRepository = $this->getDoctrine()
    ->getManager()
    ->getRepository(Foo::class)
    ->findAll();
</code>```

should return different records if done by a ROLE_SUPER_ADMIN or by  ROLE_USER. Also, I need to filter record based on relations and so on.

I've different solution in mind:

inject user role inside the repository's query

create a role based repository

create a query for each role

Inject user role in repository's query

In this case each repository should be responsible to provide right data. This is a solution similar to this. In that solution record are filtered by tenant.

Create role based repository

In this case I'll need to create different repositories and instantiate them differently. But I don think this can be easy in doctrine? while I am writing, ... I am thinking this is an exaggerated solution.

Create queries for each roles

At the moment I think this is the more natural way to do queries. I just imagine that a repository should contain

```<code>+ findAllStuffForGuestRole()
+ findAllStuffForAdminRole()
</code>```

Each time I need to add a query, I MUST create different queries.

答: I think Doctrine filters are the cleanest and the simplest way to solve your problem. See the documentation</p>

Body:
I've a project with a huge amount of data. I need to make query based on user role/group/permission. This means that a query like

$fooRepository = $this->getDoctrine()
    ->getManager()
    ->getRepository(Foo::class)
    ->findAll();

should return different records if done by a ROLE_SUPER_ADMIN or by  ROLE_USER. Also, I need to filter record based on relations and so on.

I've different solution in mind:

inject user role inside the repository's query

create a role based repository

create a query for each role

Inject user role in repository's query

In this case each repository should be responsible to provide right data. This is a solution similar to this. In that solution record are filtered by tenant.

Create role based repository

In this case I'll need to create different repositories and instantiate them differently. But I don think this can be easy in doctrine? while I am writing, ... I am thinking this is an exaggerated solution.

Create queries for each roles

At the moment I think this is the more natural way to do queries. I just imagine that a repository should contain

+ findAllStuffForGuestRole()
+ findAllStuffForAdminRole()

Each time I need to add a query, I MUST create different queries.


问:
scraping whole page source in c# windows application
I'm trying to scrape page source but i found that in response whole page source not coming means some of the div values not coming though it is present in page view source but not coming in c# response.

Please guide me how to get those missing dive values in c# windows application.

答:
You can Use below syntax where panel-header is ClassName of  HTML which we are using for identify our html portion.

```<code>var panelHeader = driver.FindElement(OpenQA.Selenium.By.ClassName("panel-header")).Text;
</code>```

if you do not have classname or you want to use Id then you have to select

By.Id("dash=1234")
  this will fetch all text from the given class or id .

Body:
You can Use below syntax where panel-header is ClassName of  HTML which we are using for identify our html portion.

var panelHeader = driver.FindElement(OpenQA.Selenium.By.ClassName("panel-header")).Text;

if you do not have classname or you want to use Id then you have to select

By.Id("dash=1234")
  this will fetch all text from the given class or id .


问:
Apple Mach-O Linker & Ditto Error - Xcode 8
I have just updated my Xcode to Xcode 8 and am now trying to convert my project's code to Swift 2.3. I was able to build a couple times using Xcode 8 without any errors. Now, the following errors came up:

Error #1: Apple Mach-O Linker Error: Linker command failed with exit code 1

ld: file not found: /Users/Linus/Library/Developer/Xcode/DerivedData/MyApp-asdjeshhsetnfxbegcsbcipdreneewgr/Build/Intermediates/MyApp.build/Debug-iphonesimulator/MyApp.build/Objects-normal/x86_64/DownloadsViewController.o

  clang: error: linker command failed with exit code 1 (use -v to see invocation)

I don't even know what a .o file is. The swift file of DownloadsViewController is there, though.

Error #2: Ditto Error: Command /usr/cin/ditto failed with exit code 1

ditto: can't get real path for source '/Users/Linus/Library/Developer/Xcode/DerivedData/MyApp-asdjeshhsetnfxbbciegrfdpdreneewgr/Build/Intermediates/MyApp.build/Debug-iphonesimulator/MyApp.build/Objects-normal/x86_64/MyApp-Swift.h'

  Command /usr/bin/ditto failed with exit code 1

The ditto error occurs 3 times: for MyApp.swiftdoc, MyApp.swiftmodule, and MyApp-Swift.h.

Thanks in advance!

答: Turning Bitcode to "No" solved this issue. This is found in the Build Settings.</p>


问:
limit imput length to max 10 chars
I try to limit a form of input to 10 chars

var max_chars = 10;

$('input#ctl00$bc$custom_element_44').keydown( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

$('input#ctl00$bc$custom_element_44').keyup( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44"></code>```

But it does not seem to work, advice is sought;)

Regards Pete

答:
You can use native maxlength attribute on the input tag.

```<code><input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44" maxlength="10">
</code>```

Title: limit imput length to max 10 chars

Body:
I try to limit a form of input to 10 chars

var max_chars = 10;

$('input#ctl00$bc$custom_element_44').keydown( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

$('input#ctl00$bc$custom_element_44').keyup( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44">

But it does not seem to work, advice is sought;)

Regards Pete

Body:
You can use native maxlength attribute on the input tag.

<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44" maxlength="10">


问:
Fastest method of collection searching by DateTime
I have a Dictionary containing 10 keys, each with a list containing up to 30,000 values. The values contain a DateTime property.

I frequently need to extract a small subset of one of the keys, like a date range of 30 - 60 seconds.

Doing this is easy, but getting it to run fast is not so. What would be the most efficient way to query this in-memory data?

Thanks a lot.

答:
Sort lists by date at the first, then find your required items by binary search (i.e k item) and return them, finding the searched item is O(log(n)) because you need find first and last index. returning them is O(K) in all It's O(K+log(n))</p>

```<code>    IEnumerable<item> GetItems(int startIndex, int endIndex, List<item> input)
    {
        for (int i=startIndex;i<endIndex;i++)
           yield return input[i];
    }
</code>```

Body:
Sort lists by date at the first, then find your required items by binary search (i.e k item) and return them, finding the searched item is O(log(n)) because you need find first and last index. returning them is O(K) in all It's O(K+log(n))

    IEnumerable<item> GetItems(int startIndex, int endIndex, List<item> input)
    {
        for (int i=startIndex;i<endIndex;i++)
           yield return input[i];
    }


问:
Locate a dot with the same xpath in a highchart
I have a highchart in a graphic with dots and I need to get the data inside every dot but I can't be able to achieve the different dots because they have all the same xpath!!!
I show you:

one dot

other dot

How could I locate the different dots if they all have the same xpath??

I have the following code, but if they have the same xpath, I can't locate different dots...

```<code>    **String x1 = ".//*[@id='highcharts-0']/*[name()='svg']/*[name()='g'][5]/*[name()='g'][18]/*[name()='path'][8]";
    String x2 = ".//*[@id='highcharts-0']/div/span/span";    //xpath tooltip
    WebElement element = driver.findElement(By.xpath(x1));
    // action class para clickear el punto
    Actions action = new Actions((WebDriver) driver);
    action.click(element).build().perform();
    String toolTipText2 = driver.findElement(By.xpath(x2)).getText();
    if(!toolTipText2.contains(string))  sb.append("===> Content error: ");**
</code>```

Thanks so much for your help!!!!!

答:
The data in the "dots" is just the chart data.

You can access it, and much more, by navigating via

```<code>chart.series[i].data[j]
</code>```

Fiddle Example:

http://jsfiddle.net/jlbriggs/u4cb2rk4/

Or by accessing the data source directly.

Body:
I have a highchart in a graphic with dots and I need to get the data inside every dot but I can't be able to achieve the different dots because they have all the same xpath!!!
I show you:

one dot

other dot

How could I locate the different dots if they all have the same xpath??

I have the following code, but if they have the same xpath, I can't locate different dots...

    **String x1 = ".//*[@id='highcharts-0']/*[name()='svg']/*[name()='g'][5]/*[name()='g'][18]/*[name()='path'][8]";
    String x2 = ".//*[@id='highcharts-0']/div/span/span";    //xpath tooltip
    WebElement element = driver.findElement(By.xpath(x1));
    // action class para clickear el punto
    Actions action = new Actions((WebDriver) driver);
    action.click(element).build().perform();
    String toolTipText2 = driver.findElement(By.xpath(x2)).getText();
    if(!toolTipText2.contains(string))  sb.append("===> Content error: ");**

Thanks so much for your help!!!!!

Body:
The data in the "dots" is just the chart data.

You can access it, and much more, by navigating via

chart.series[i].data[j]

Fiddle Example:

http://jsfiddle.net/jlbriggs/u4cb2rk4/

Or by accessing the data source directly.


问:
How to call a function whenever global variable changes it value?
How can I call a function change_label whenever global variable a changes its value?  With change_variable I am trying to simulate actual changing of the variable (the variable changes on button click).

```<code>from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_variable)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        global a
        a = 1

def main():
    root = Tk()
    Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

答:
```<code>The code was supposed be like this.
from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_label)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        global a
        a = 1
        if a != 3:
            self.label.config(bg='Red', fg='Yellow')

def main():
    root = Tk()
    Application(root)
    root.mainloop()
hope that is what you wanted.
</code>```

Body:
How can I call a function change_label whenever global variable a changes its value?  With change_variable I am trying to simulate actual changing of the variable (the variable changes on button click).

from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_variable)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        global a
        a = 1

def main():
    root = Tk()
    Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()


问:
reuse mysql query code among few methods in same controller - Laravel 5.4
I have few queries which I would like to use it to few methods in the same controller.for example below code:

```<code>$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
</code>```

I need to call above query in 4 methods in UserController.

I thought of doing something like:

```<code>public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
</code>```

Then

```<code>UserController

public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}
</code>```

But I get an error. How do I do this so when I change the code in one place it reflects everywhere?

Updated question

```<code>public function notify()
    {
    $bio = User::where('id',Auth::user()->id)->value('bio');
    $photo = User::where('id',Auth::user()->id)->value('photo');
    $friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
    $notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
    $status = User::where('id',Auth::user()->id)->value('search_status');

    }

    public function index()
    {

    $this->notify();
    return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
    }
</code>```

答:
That is a poorly written code. You get everything except notifications from the logged in user model.</p>

```<code>public function fetchData()
{
    $user = auth()->user();
    $notifications = Notification::where('created_at', '>' , $user->lastlogin)->get();

    $data = [
        'lastlogin' => $user->lastlogin,
        'bio' => $user->bio,
        'photo' => $user->photo,
        'search_status' => $user->search_status,
        'notifications' => $notifications,
    ];

    return (Object)$data;
}

public function test()
{
    $data = $this->fetchData();

    // $data->lastlogin;
    // $data->bio;
    // $data->photo;
    // $data->search_status;
    // $data->notifications;
}
</code>```

Body:
I have few queries which I would like to use it to few methods in the same controller.for example below code:

$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');

I need to call above query in 4 methods in UserController.

I thought of doing something like:

public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}

Then

UserController

public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}

But I get an error. How do I do this so when I change the code in one place it reflects everywhere?

Updated question

public function notify()
    {
    $bio = User::where('id',Auth::user()->id)->value('bio');
    $photo = User::where('id',Auth::user()->id)->value('photo');
    $friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
    $notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
    $status = User::where('id',Auth::user()->id)->value('search_status');

    }

    public function index()
    {

    $this->notify();
    return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
    }

Body:
That is a poorly written code. You get everything except notifications from the logged in user model.

public function fetchData()
{
    $user = auth()->user();
    $notifications = Notification::where('created_at', '>' , $user->lastlogin)->get();

    $data = [
        'lastlogin' => $user->lastlogin,
        'bio' => $user->bio,
        'photo' => $user->photo,
        'search_status' => $user->search_status,
        'notifications' => $notifications,
    ];

    return (Object)$data;
}

public function test()
{
    $data = $this->fetchData();

    // $data->lastlogin;
    // $data->bio;
    // $data->photo;
    // $data->search_status;
    // $data->notifications;
}


问:
Shoukd I use JSON for my posting and commenting system?
I am building a social networking website and should i use JSON instead of database for storing users posts and comments? Is it good and secure?</p>

答:
JSON is a format, not a file standard. So you could even think of storing JSON in DB.

So, you will need to answer two questions

is file format better than real DB format (like MySQL like databases)?

is JSON format good for the use I have?

File format

Because you will have to deal with quick access and sometimes complex queries (search engine, statistics, ... ), it's clear that a DB system will be much more efficient than a file system oriented solution. File creations / openings / writings / closings need a lot of time and it will be a pain to create search queries. In PHP you would have to open all your files and put them in memory beforte doing the real job.

Using a Database, you would perhaps be directly be able to ask the system if someone with "%john%" in his name has posted something about "%futurama%" in the title.

So... one point for DB

JSON format stored in DB

One more time, you'd better use rows capacities of the DB system. By that, I mean using a author_id row for example. It would greatly impact the perfs. On the other hand, you would have to think of complex queries dealing with the downsides of the JSON format in your DB engine query.

One more point for not using JSON

But when using JSON?

JSON is great when dealing with APIs. If you need to serve data for an application (i.e. an Angular2 front end that will query your API), JSON is a native format to manage data... but not for storing it... JSON is more often used for stream purposes.


问:
Windsor and asp.net MVC singleton race conditions
Quick question regarding the use of Singleton lifestyle in Windsor, and Asp.Net MVC.
If the following class is registered as a singleton am I correct in thinking that I will have a race condition?</p>

```<code>public class UserMapper : IMap
{
    public void Map(MyDto dto, MyDomain domain)
    {
      domain.Username = dto.Username;
      domain.Firstname = dto.Firstname;
      domain.Surname = dto.Surname;
      domain.Password = dto.Password;
    }
}
</code>```

答: Your UserMapper does not have any data in it - everything in the Map method relies on parameters given to it, making the method reentrant and thus safe to use as a singleton.

Body:
Quick question regarding the use of Singleton lifestyle in Windsor, and Asp.Net MVC.
If the following class is registered as a singleton am I correct in thinking that I will have a race condition?

public class UserMapper : IMap
{
    public void Map(MyDto dto, MyDomain domain)
    {
      domain.Username = dto.Username;
      domain.Firstname = dto.Firstname;
      domain.Surname = dto.Surname;
      domain.Password = dto.Password;
    }
}