问:
Yocto Jethro: how do I add user to sudoers list
I added a new user as follows

```<code>inherit extrausers
EXTRA_USERS_PARAMS = "useradd -P p@ssW0rd user1;"
</code>```

I am trying to find how to add users to sudoers list. Is there a class like extrausers

Update-1:

In class classes/extrausers.bbclass I see usermod supported. Will the following work?

```<code>inherit extrausers
EXTRA_USERS_PARAMS = "useradd -P p@ssW0rd user1;\
                      usermod -aG sudo user1"
</code>```

Update-2:

I tried adding IMAGE_INSTALL_append += " sudo " and

```<code>inherit extrausers
EXTRA_USERS_PARAMS = "useradd -P foobar -G sudo user1;"
</code>```

But that does not help me in achieving the effect of adding user1 to sudoers list. I see following error when I do sudo -v

```<code>Sorry, user user1 may not run sudo on <machine-name>.
</code>```

Update-3:

I found that the sudoers file has the sudo group commented as follows:
# %sudo ALL=(ALL) ALL
Hence the reason even adding user1 to group sudo didn't help

Rather than adding user1 to group sudo I adopted approach of adding a drop-in file under /etc/sudoers.d/0001_user1 using recipes-extended/sudo/sudo_1.8.14p3.bbappend

```<code>do_install_append () {
    echo "user1 ALL=(ALL) ALL" > ${D}${sysconfdir}/sudoers.d/001_first
}
</code>```

Now I need help in understanding which of following is a better approach in terms of security?

uncomment sudo line in /etc/sudoers and adding user1 to /etc/sudoers

adding user1 in /etc/sudoers.d/001_first

答:
So there are two approaches to add an user with sudo capability

Add user to sudo group and enable sudo group in /etc/sudoers

Create a file under ${D}${sysconfdir}/sudoers.d/ and add the sudo rule for user there.

Now which approach is suitable for your distro is well answered in /etc/sudoers vs /etc/sudoers.d/ file for enabling sudo for a user

Body:
I added a new user as follows

inherit extrausers
EXTRA_USERS_PARAMS = "useradd -P p@ssW0rd user1;"

I am trying to find how to add users to sudoers list. Is there a class like extrausers

Update-1:

In class classes/extrausers.bbclass I see usermod supported. Will the following work?

inherit extrausers
EXTRA_USERS_PARAMS = "useradd -P p@ssW0rd user1;\
                      usermod -aG sudo user1"

Update-2:

I tried adding IMAGE_INSTALL_append += " sudo " and

inherit extrausers
EXTRA_USERS_PARAMS = "useradd -P foobar -G sudo user1;"

But that does not help me in achieving the effect of adding user1 to sudoers list. I see following error when I do sudo -v

Sorry, user user1 may not run sudo on <machine-name>.

Update-3:

I found that the sudoers file has the sudo group commented as follows:
# %sudo ALL=(ALL) ALL
Hence the reason even adding user1 to group sudo didn't help

Rather than adding user1 to group sudo I adopted approach of adding a drop-in file under /etc/sudoers.d/0001_user1 using recipes-extended/sudo/sudo_1.8.14p3.bbappend

do_install_append () {
    echo "user1 ALL=(ALL) ALL" > ${D}${sysconfdir}/sudoers.d/001_first
}

Now I need help in understanding which of following is a better approach in terms of security?

uncomment sudo line in /etc/sudoers and adding user1 to /etc/sudoers

adding user1 in /etc/sudoers.d/001_first


来源: stackexchange

问:
Postgres Encryption of configuration files
Currently in Postgres the largest security hole is the .conf files that the database relies on, this is because someone with access to the system (not necessarily the database) can modify the files and gain entry.  Because of this I am seeking out resources on how to encrypt those .conf files and then decrypt them during each session of the database.  Performance is not really an issue at this point.  Does anyone have any resources on this or has anyone developed any prototypes that utilize this functionality?

Edit

Since there seems to be some confusion here about what it is I am asking.  The scenario can best be illustrated on a Windows box with the following groups:

1) Administrators  System Administrators

2) Database Administrators  Postgres Administrators

3) Auditors Security Auditors

The Auditors group typically needs access to log files and configuration files to ensure system security.  However, the issue comes when a member of the Auditors group needs to view the Postgres configuration and log files.  If this member decides that they want to access the database even though they do not have a database account it is a very short task to break in .  How does one go about preventing this?  Answers such as: Get better auditors are quite poor as you can never fully predict what people will do.

答:
I think you might be stuck - here's what you said:

The Auditors group typically needs access to log files and configuration files

and then:

How does one go about preventing [Auditors from accessing the database using the values in the configuration files]?

If you really want to let Auditors get at your config files but are nervous about them accessing your database, your best bet would be to move your config files off of your server to somewhere else - and then make sure Auditors don't actually have access to your production systems. They could still look at the log files all they wanted, but they wouldn't be able to access the database server to try to get at the database itself.

ContentLicense: CC BY-SA 2.5


问:
Replace middle string by passing specific pattern
I want to replace a middle string by passing the pattern. I have tried it by using pre_replace function. But it is not working for me.

```<code>   $str = "Lead for Nebhub - Admark
          Name: Punam Kalbande
          Email: kalbandepunam@gmail.com
          Phone Number: 800-703-3209
          Nebhub Partner : Nebhub - Admark
          Address: PO Box 830395 Miami, FL 33173
          Hub : Automotive
          Products: ERP, CRM, HCM, Help Desk, Marketing";
  $pattern = '/^Hub :(.+)Products:$/i';
  $replacement = "Logistics";
  $result = preg_replace($pattern, $replacement, $str);
</code>```

but the above code is only returning original string. It is not replacing with  the new one.

答:
The s-Modifier is missing in your Pattern. Further you want to match the Pattern somewhere in the middle of the Text. You used ^, which indicates the Start of the Line and $ which indicates the End of the Line. That means, the whole String must match. Use this Regex, and it will work for you.

```<code>/(Hub :)[^\n]+/is
</code>```

Explanation:

```<code>(        start Subpattern
Hub      the Word Hub
         followed by a space
:        followed by a Doubledot
)        end Subpattern -> accessible by $1 or \1
[^\n]+   match one or more Characters except a Linebreak

i        Modifier for caseinsensitive Search
s        Modifier to include Linebreaks
</code>```

What you have to do now is to output the Subpattern in the Replacement too:

```<code>$result = preg_replace($pattern, "$1$replacement", $str);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to replace a middle string by passing the pattern. I have tried it by using pre_replace function. But it is not working for me.

   $str = "Lead for Nebhub - Admark
          Name: Punam Kalbande
          Email: kalbandepunam@gmail.com
          Phone Number: 800-703-3209
          Nebhub Partner : Nebhub - Admark
          Address: PO Box 830395 Miami, FL 33173
          Hub : Automotive
          Products: ERP, CRM, HCM, Help Desk, Marketing";
  $pattern = '/^Hub :(.+)Products:$/i';
  $replacement = "Logistics";
  $result = preg_replace($pattern, $replacement, $str);

but the above code is only returning original string. It is not replacing with  the new one.

Body:
The s-Modifier is missing in your Pattern. Further you want to match the Pattern somewhere in the middle of the Text. You used ^, which indicates the Start of the Line and $ which indicates the End of the Line. That means, the whole String must match. Use this Regex, and it will work for you.

/(Hub :)[^\n]+/is

Explanation:

(        start Subpattern
Hub      the Word Hub
         followed by a space
:        followed by a Doubledot
)        end Subpattern -> accessible by $1 or \1
[^\n]+   match one or more Characters except a Linebreak

i        Modifier for caseinsensitive Search
s        Modifier to include Linebreaks

What you have to do now is to output the Subpattern in the Replacement too:

$result = preg_replace($pattern, "$1$replacement", $str);


问:
Converting video to .mp4 with Node.js
I want to be able to do something like this:

```<code>var converter = require('converter');

converter.convert({
  from: 'avi',
  to: 'mp4',
  path: '/myvideo.avi',
  newPath: '/newvideo.mp4',
  error: function(err) {},
  success: function() {
    console.log('success!');
  }
});
</code>```

Thanks!

答:
FFMPEG is good thing for play with video.

Try this command.

```<code>exec("ffmpeg -i filePath/fileName.ext filePath/newFileName.mp4");
</code>```

You can set your other preset also.

Title: Converting video to .mp4 with Node.js

Body:
I want to be able to do something like this:

var converter = require('converter');

converter.convert({
  from: 'avi',
  to: 'mp4',
  path: '/myvideo.avi',
  newPath: '/newvideo.mp4',
  error: function(err) {},
  success: function() {
    console.log('success!');
  }
});

Thanks!

Body:
FFMPEG is good thing for play with video.

Try this command.

exec("ffmpeg -i filePath/fileName.ext filePath/newFileName.mp4");

You can set your other preset also.

ContentLicense: CC BY-SA 4.0


问:
Application appears to have two session cookies
In my application I'm seeing it's setting two session cookies:

.AspNet.ApplicationCookie

ASP.NET_SessionId

I can understand the requirement for a session cookie but why have two?  What are the specific purposes of each?

I'm using asp.net identity in case that has something to do with it.

答: Application cookie has scope for the application(to identify the application o nthe server), shared between different users, whereas a session cookie(to identify the suer session) is a user session  specific.</p>


问:
Highcharts UTC time
Im a bit lost with one graph Im trying to create using Highcharts.
By default Highcharts should use UTC. In the graph below I wanted to create sunrise/sunset graph using UTC times.
However, even though in the code I have eg:

```<code>[Date.UTC(2000,0,1,07,48),Date.UTC(2000,0,1,16,05)],
</code>```

The graph still starts at 08:48, which makes no sense to me since the date is created from 07:48

I created a Fiddle where you can see the problem.

Any help is very much appreciated, I need to use UTC because this script must work regardless of system timezone

答:
The problem is with the display, it display the time according to the local timezone of the browser. to solve it, you need to format the date object for utc time.

First fix your tooltip code, call getUTCHour instead of getHour.

The graph looks ok once tooltips show correct hour.

Title: Highcharts UTC time

Body:
Im a bit lost with one graph Im trying to create using Highcharts.
By default Highcharts should use UTC. In the graph below I wanted to create sunrise/sunset graph using UTC times.
However, even though in the code I have eg:

[Date.UTC(2000,0,1,07,48),Date.UTC(2000,0,1,16,05)],

The graph still starts at 08:48, which makes no sense to me since the date is created from 07:48

I created a Fiddle where you can see the problem.

Any help is very much appreciated, I need to use UTC because this script must work regardless of system timezone


问:
Align text on the side and top of other text css
How can I achieve this using css?

This is what I've tried:

R$
    54.133
    48```

答:
You can use flexbox:

```<code><div class="container">
  <label class="sign">R$</label>
  <label class="number">54.133</label>
  <label class="decimal";>48</label>
</div>

<style>
  .container{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  label.sign{
    align-self: flex-start;
    font-size: 20px;
  }
  label.number{
    font-size: 30px;
  }
  label.decimal{
    align-self: flex-start;
    font-size: 20px;
  }
</style>
</code>```

More Here

Body:
You can use flexbox:

<div class="container">
  <label class="sign">R$</label>
  <label class="number">54.133</label>
  <label class="decimal";>48</label>
</div>

<style>
  .container{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  label.sign{
    align-self: flex-start;
    font-size: 20px;
  }
  label.number{
    font-size: 30px;
  }
  label.decimal{
    align-self: flex-start;
    font-size: 20px;
  }
</style>

More Here


问:
How to build a dendrogram from a directory tree?
Given a root absolute directory path. How do I generate a dendrogram object of all path's below it so that I can visualize the directory tree with R?

Suppose the following call returned the following leaf nodes.

list.files(path, full.names = TRUE, recursive = TRUE)

```<code>root/a/some/file.R
root/a/another/file.R
root/a/another/cool/file.R
root/b/some/data.csv
root/b/more/data.csv
</code>```

I'd like to make a plot in R like the output of the unix tree program:

```<code>root
├── a
│   ├── another
│   │   ├── cool
│   │   │   └── file.R
│   │   └── file.R
│   └── some
│       └── file.R
└── b
    ├── more
    │   └── data.csv
    └── some
        └── data.csv
</code>```

It would be especially useful if the solution involved decomposing the file system tree into two data.frame's:

a table of nodes (with which I could include attributes such as modification date)

and a table of edges (also with attributes)

And then building the dendrogram object from those two data.frames.

答:
If you are on Windows, you can use my package dir2json, by installing it like this:

```<code>drat::addRepo("stlarepo")
install.packages("dir2json")
</code>```

It is also possible to use it on Linux, but there is a DLL linked to the GHC dynamic libraries, which must be installed on the system (while this DLL is standalone on Windows).

```<code>> library(dir2json)
> cat(dir2tree("src"))
src
|
`- contrib
   |
   +- PACKAGES.gz
   |
   +- PACKAGES
   |
   +- jsonAccess_0.1.1.tar.gz
   |
   +- expansions_1.2.tar.gz
   |
   `- dir2json_2.1.0.tar.gz
> cat(dir2tree("src", vertical=TRUE))
                                            src
                                             |
                                          contrib
                                             |
      ---------------------------------------------------------------------------
     /          |                 |                       |                      \
PACKAGES.gz  PACKAGES  jsonAccess_0.1.1.tar.gz  expansions_1.2.tar.gz  dir2json_2.1.0.tar.gz
</code>```

The package also contains a Shiny application which generates an interactive Reingold-Tilford tree representation of a folder:

```<code>> dir2json::shinyDirTree(".")
</code>```

Body:
Given a root absolute directory path. How do I generate a dendrogram object of all path's below it so that I can visualize the directory tree with R?

Suppose the following call returned the following leaf nodes.

list.files(path, full.names = TRUE, recursive = TRUE)

root/a/some/file.R
root/a/another/file.R
root/a/another/cool/file.R
root/b/some/data.csv
root/b/more/data.csv

I'd like to make a plot in R like the output of the unix tree program:

root
├── a
│   ├── another
│   │   ├── cool
│   │   │   └── file.R
│   │   └── file.R
│   └── some
│       └── file.R
└── b
    ├── more
    │   └── data.csv
    └── some
        └── data.csv

It would be especially useful if the solution involved decomposing the file system tree into two data.frame's:

a table of nodes (with which I could include attributes such as modification date)

and a table of edges (also with attributes)

And then building the dendrogram object from those two data.frames.

Body:
If you are on Windows, you can use my package dir2json, by installing it like this:

drat::addRepo("stlarepo")
install.packages("dir2json")

It is also possible to use it on Linux, but there is a DLL linked to the GHC dynamic libraries, which must be installed on the system (while this DLL is standalone on Windows).

> library(dir2json)
> cat(dir2tree("src"))
src
|
`- contrib
   |
   +- PACKAGES.gz
   |
   +- PACKAGES
   |
   +- jsonAccess_0.1.1.tar.gz
   |
   +- expansions_1.2.tar.gz
   |
   `- dir2json_2.1.0.tar.gz
> cat(dir2tree("src", vertical=TRUE))
                                            src
                                             |
                                          contrib
                                             |
      ---------------------------------------------------------------------------
     /          |                 |                       |                      \
PACKAGES.gz  PACKAGES  jsonAccess_0.1.1.tar.gz  expansions_1.2.tar.gz  dir2json_2.1.0.tar.gz

The package also contains a Shiny application which generates an interactive Reingold-Tilford tree representation of a folder:

> dir2json::shinyDirTree(".")


问:
Automatic update of entity every day
I'm creating my portfolio with Symfony 3 and I want to show my skills with my experience.

I have a "Skill" entity with a "startAt" param (type=datetime) and a "exp" param (string).

The "exp" param = the difference between "startAt" and the current date.

I add some lifecycle callback so the "exp" param update every time I touch my "Skill" entity but here is my question:

How can I update my entity every day without touching it?

For exemple right now I have "exp = 6 months" but next month this param need to be "7 months".

答: create a command that update your entity and make a cron tab with it</p>

Title: Automatic update of entity every day


问:
How to change Order Email Subject in Order.php Magento
I want to change order email subject in Magento for the order.php file.

Here is my code:

```<code>$mailSubject = "This is test subject";
Mage::getModel('core/email_template')->setTemplateSubject($mailSubject);
$translate = Mage::getSingleton('core/translate');
</code>```

It's not working. Is there any other way to set subject in order.php

I don't want to set from Transaction Emails option from back-end as there is a value generated by PHP I want to send in the subject line.

Any help would be appreciated.

Thanks

答:
In app/code/core/Mage/Sales/Model/Order.php find sendNewOrderEmail() method. Then find

```<code>$mailer->setTemplateParams(array(
        'order'        => $this,
        'billing'      => $this->getBillingAddress(),
        'payment_html' => $paymentBlockHtml
    )
);
</code>```

=> Here is array of variables from template. Add one new param for test:

'test'         => $is_test ? $is_test : ''

=> Change $is_test to your condition. For example:

public function sendNewOrderEmail($is_test = FALSE)

Now open your template file app/locale/en_US/template/email/sales/order_new_guest.html (for example).

Find subject variable on the first line:  or something like this.

Make changes:

=> Call method:
$order->sendNewOrderEmail('TEST - ');

Body:
I want to change order email subject in Magento for the order.php file.

Here is my code:

$mailSubject = "This is test subject";
Mage::getModel('core/email_template')->setTemplateSubject($mailSubject);
$translate = Mage::getSingleton('core/translate');

It's not working. Is there any other way to set subject in order.php

I don't want to set from Transaction Emails option from back-end as there is a value generated by PHP I want to send in the subject line.

Any help would be appreciated.

Thanks

Body:
In app/code/core/Mage/Sales/Model/Order.php find sendNewOrderEmail() method. Then find

$mailer->setTemplateParams(array(
        'order'        => $this,
        'billing'      => $this->getBillingAddress(),
        'payment_html' => $paymentBlockHtml
    )
);

=> Here is array of variables from template. Add one new param for test:

'test'         => $is_test ? $is_test : ''

=> Change $is_test to your condition. For example:

public function sendNewOrderEmail($is_test = FALSE)

Now open your template file app/locale/en_US/template/email/sales/order_new_guest.html (for example).

Find subject variable on the first line:  or something like this.

Make changes:

=> Call method:
$order->sendNewOrderEmail('TEST - ');


问:
DUMP(A) opcode in RPG
There is an error handling procedure that I need to write up in a module that will be called from other programs bound to the module when there is a program error. This needs to include the statement to take a DUMP. My question is suppose the call to this procedure goes from program A to Module B (to which A is bound through a service program also the Module has the error handler procedure with a Sumo statement), will the Dump work as expected?Should the dump be included in the caller program to get the dump of the correct process? Or would it work if included in the Called procedure?</p>

答:
From the manual

The DUMP operation provides a dump (all fields, all files, indicators, data structures, arrays, and tables
  defined) of the module.

So you'd want the DUMP op-code and related error handling in each module involved.

You can't have an error in A and call a procedure in B with the dump op-code.

Title: DUMP(A) opcode in RPG


问:
Case insensitive sorting with Mongoid
Right now I got:

```<code>@directories = collection.directories.all.asc(:name)
</code>```

But it's case-sensitive, how do I do case-insensitive sorting?

答:
You will probably have to store the
  field twice, once with its real value,
  and again in all lowercase. You can
  then query the lowercased version for
  case-insensitive search (don't forget
  to also lowercase the query string).

This approach works (or is necessary)
  for many database systems, and it
  should perform better than regular
  expression based techniques (at least
  for prefix or exact matching).

Check this answer

Title: Case insensitive sorting with Mongoid

Body:
Right now I got:

@directories = collection.directories.all.asc(:name)

But it's case-sensitive, how do I do case-insensitive sorting?


问:
How to filter input data of logstash based on date filed?
here is my twitter input tweets

```<code>"_source": {
"created_at": "Wed Aug 10 06:42:48 +0000 2016",
"id": 763264318242783200,
"timestamp_ms": "1470811368891",
"@version": "1",
"@timestamp": "2016-08-10T06:42:48.000Z"
}
</code>```

and my logstash config file which include twitter input plugin filter and output

```<code>input {
twitter {
consumer_key => "lvvoeonCRBOHsLAoTPbion9sK"
consumer_secret => "GNHOFzErJhuo0bNq38JUs7xea2BOktMiLa7tunoGwP0oFKCHrY"
oauth_token => "704578110616936448-gfeSklNrITu7fHIZgjw3nwoZ1S0l0Jl"
oauth_token_secret => "IHiyRJRN09jjdUTGrnesALw4DRle35WyX7pdnI3CtEnJ5"
keywords => [ "afghanistan", "TOLOnews", "kabul", "police"]
full_tweet => true
}
}
filter {
    date {
      match => ["timestamp" , "MMM d YYY HH:mm:ss", "ISO8601"]
  }
 }
output {
   stdout { codec => dots }
    elasticsearch {
        hosts => "10.20.1.123"
        index => "twitter_news"
        document_type => "tweets"
    }
}
</code>```

I want to just get new tweets for example today date is 2016-11-16, then I just want to get tweets that have @timestamp= 2016-11-16 not  @timestamp= 2016-11-15 or past days tweets, but with this configuration i get past tweets as well, any one help me to how do this ?

答:
the idea here is to use ruby code in logstash config.
I propose to use timestamp_ms for comparing date.

First need to convert timestamp_ms to integer

Add today timestamp in ms with ruby

Compare timestamps
Here is an example:

```<code>mutate {
    convert => {
        "timestamp_ms" => "integer"
    }
}
ruby {
    code => "
        t = Time.now
        today_ymd = t.strftime('%Y%m%d')
        today_timestamp_ms = DateTime.parse(today_ymd).to_time.to_i*1000
        event['@metadata']['today_timestamp_ms'] = today_timestamp_ms
    "
}

if [timestamp_ms] < [@metadata][today_timestamp_ms] {
## past days events
    mutate {
        add_field => { "test" => "past days events"  }
    }
} else {
# today events
    mutate {
        add_field => { "test" => "today events"  }
    }

}
</code>```

Body:
here is my twitter input tweets

"_source": {
"created_at": "Wed Aug 10 06:42:48 +0000 2016",
"id": 763264318242783200,
"timestamp_ms": "1470811368891",
"@version": "1",
"@timestamp": "2016-08-10T06:42:48.000Z"
}

and my logstash config file which include twitter input plugin filter and output

input {
twitter {
consumer_key => "lvvoeonCRBOHsLAoTPbion9sK"
consumer_secret => "GNHOFzErJhuo0bNq38JUs7xea2BOktMiLa7tunoGwP0oFKCHrY"
oauth_token => "704578110616936448-gfeSklNrITu7fHIZgjw3nwoZ1S0l0Jl"
oauth_token_secret => "IHiyRJRN09jjdUTGrnesALw4DRle35WyX7pdnI3CtEnJ5"
keywords => [ "afghanistan", "TOLOnews", "kabul", "police"]
full_tweet => true
}
}
filter {
    date {
      match => ["timestamp" , "MMM d YYY HH:mm:ss", "ISO8601"]
  }
 }
output {
   stdout { codec => dots }
    elasticsearch {
        hosts => "10.20.1.123"
        index => "twitter_news"
        document_type => "tweets"
    }
}

I want to just get new tweets for example today date is 2016-11-16, then I just want to get tweets that have @timestamp= 2016-11-16 not  @timestamp= 2016-11-15 or past days tweets, but with this configuration i get past tweets as well, any one help me to how do this ?

Body:
the idea here is to use ruby code in logstash config.
I propose to use timestamp_ms for comparing date.

First need to convert timestamp_ms to integer

Add today timestamp in ms with ruby

Compare timestamps
Here is an example:

mutate {
    convert => {
        "timestamp_ms" => "integer"
    }
}
ruby {
    code => "
        t = Time.now
        today_ymd = t.strftime('%Y%m%d')
        today_timestamp_ms = DateTime.parse(today_ymd).to_time.to_i*1000
        event['@metadata']['today_timestamp_ms'] = today_timestamp_ms
    "
}

if [timestamp_ms] < [@metadata][today_timestamp_ms] {
## past days events
    mutate {
        add_field => { "test" => "past days events"  }
    }
} else {
# today events
    mutate {
        add_field => { "test" => "today events"  }
    }

}


问:
Codeigniter project is not working after installing at server
I build codeigniter project and i have tested it in my local machine using http://localhost/wg/ as base url. I upload that project to server and my new url like http://project.microsols.com/wardrobe/ Home page is working. But when i click on any other link it will give error.
It is giving

Not Found

  The requested URL /index.php/person was not found on this server.

  Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

But it will work fine when i put index.php before my controller it will work fine..
And this is my .htaccess file:

```<code>RewriteEngine on
RewriteBase /wardrobe/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

What is the issue behind this error??

答: By default codeigniter urls include the index.php in the url. You need to remove index.php from the url to make it work. Please follow the answer here to do the same.</p>

Body:
I build codeigniter project and i have tested it in my local machine using http://localhost/wg/ as base url. I upload that project to server and my new url like http://project.microsols.com/wardrobe/ Home page is working. But when i click on any other link it will give error.
It is giving

Not Found

  The requested URL /index.php/person was not found on this server.

  Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

But it will work fine when i put index.php before my controller it will work fine..
And this is my .htaccess file:

RewriteEngine on
RewriteBase /wardrobe/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1 [L,QSA]

What is the issue behind this error??


问:
react js warnings in console unknown prop
I've got a reactJS application with react-toolbox

in console I got this error:

```<code>Warning: Unknown prop `raised` on <a> tag. Remove this prop from the element.
</code>```

Any Idea how I can solve this warning?
I don't want to remove the tag, is there workaround to get this worked with not removing this?

thanks

Update

```<code> <Button icon='save' type="submit" label={<T value='processes.new.save'/>} raised primary/>
</code>```

I use this stuff: http://react-toolbox.com/#/components/button

答:
React gives you a warning whenever you add attributes to a DOM-tag that is not in the HTML spec. raised is not a valid /> attribute, so therefore React lets you know that you might have made a mistake. The tag - although it will be applied to the DOM (IIRC) - is not acted upon by any browser. If you need to add custom attributes for other reasons, use data--prepended attributes, like data-raised in your case.

This looks like it needs to be a class or something instead of an attribute on the a tag - but without seeing your code, it's a bit hard to give a more precise answer.

Body:
I've got a reactJS application with react-toolbox

in console I got this error:

Warning: Unknown prop `raised` on  tag. Remove this prop from the element.

Any Idea how I can solve this warning?
I don't want to remove the tag, is there workaround to get this worked with not removing this?

thanks

Update

 <Button icon='save' type="submit" label={<T value='processes.new.save'/>} raised primary/>

I use this stuff: http://react-toolbox.com/#/components/button

Body:
React gives you a warning whenever you add attributes to a DOM-tag that is not in the HTML spec. raised is not a valid <a /> attribute, so therefore React lets you know that you might have made a mistake. The tag - although it will be applied to the DOM (IIRC) - is not acted upon by any browser. If you need to add custom attributes for other reasons, use data--prepended attributes, like data-raised in your case.

This looks like it needs to be a class or something instead of an attribute on the a tag - but without seeing your code, it's a bit hard to give a more precise answer.


问:
For loop not working in python
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

```<code>for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]
</code>```

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156

答:
Hello Emon,

Try this code,
In this below code use "\" so do not confuse because it is used for multiline code write and this functionality is python inbuilt provides.

```<code>for i in range(1,157):
    start_urls = ['https://appworld.blackberry.com/cas/producttype/apps?' \
            'countryid=100&lang=en&' \
            'page=%d' \
            '&pagesize=%s'\
            '&sortby=popular&licensetype=all&callback=_producttype_apps&_=1499255634459' % (i,page) for page in xrange(1,1001)]

    # Display starts_urls
    print(start_urls)
</code>```

Using the Format Method,

Accessing Arguments by Position

```<code>for i in range(1,157):
    start_urls = ['https://appworld.blackberry.com/cas/producttype/apps?' \
            'countryid=100&lang=en&' \
            'page={0}' \
            '&pagesize={1}' \
            '&sortby=popular&licensetype=all&callback=_producttype_apps&_=1499255634459'.format(i,page) for page in xrange(1,1001)]
</code>```

When you use long any type string/content so I suggest that use the format method because of any time easily you understand the code.

More example for this below link read,

1. https://wiki.python.org/moin/ForLoop

2. https://www.codeproject.com/Tips/820236/Python-String-Formatting-Using-format-Method

I hope my answer is helpful. Any query so comments, please.

Title: For loop not working in python

Body:
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156

Body:
Hello Emon,

Try this code,
In this below code use "\" so do not confuse because it is used for multiline code write and this functionality is python inbuilt provides.

for i in range(1,157):
    start_urls = ['https://appworld.blackberry.com/cas/producttype/apps?' \
            'countryid=100&lang=en&' \
            'page=%d' \
            '&pagesize=%s'\
            '&sortby=popular&licensetype=all&callback=_producttype_apps&_=1499255634459' % (i,page) for page in xrange(1,1001)]

    # Display starts_urls
    print(start_urls)

Using the Format Method,

Accessing Arguments by Position

for i in range(1,157):
    start_urls = ['https://appworld.blackberry.com/cas/producttype/apps?' \
            'countryid=100&lang=en&' \
            'page={0}' \
            '&pagesize={1}' \
            '&sortby=popular&licensetype=all&callback=_producttype_apps&_=1499255634459'.format(i,page) for page in xrange(1,1001)]

When you use long any type string/content so I suggest that use the format method because of any time easily you understand the code.

More example for this below link read,

1. https://wiki.python.org/moin/ForLoop

2. https://www.codeproject.com/Tips/820236/Python-String-Formatting-Using-format-Method

I hope my answer is helpful. Any query so comments, please.


问:
Connection refused to REST Django
I have a problem with access to my REST Django data. As u already understand, I have a Django app whith standart REST localhost with my data. My another application, which i made in ReactJS, got Json file with data using axios throught standart GET ajax request. Now i wanna to connect to my React app from another computer at the same network and it's go easily using http://ip4:3000. But in that way i can't get data from REST page which i have on my localhost:8000. I try to get data from terminal in the same way using ip + localhostport, but i always got an error :

curl: (7) Failed to connect to 106.120.89.142 port 8000: Connection refused

I can't do it using browser to, someone know solution for that?

答:
You can start a django development server with

```<code>./manage.py runserver 0.0.0.0:8000
</code>```

this will open your port and make django app to be visible from outside world.

Title: Connection refused to REST Django

Body:
You can start a django development server with

./manage.py runserver 0.0.0.0:8000

this will open your port and make django app to be visible from outside world.


问:
Changing Custom Property on hover || VUEJS
Trying to become friends with VUEJS. Got stuck on some simple stuff, couldn't google it. So I'm using MuseUi framework in my App. Well I want to do a simple thing, change the value of the property for each specific element on hover

```<code> <mu-paper :zDepth="1" v-on:mouseover=" ???? " class="searchBox">
</code>```

I need to change:zDepth to 3 for example, on hover of the element. How could I achieve that?

full code snippet

```<code><template>
<div>
    <div class="column is-one-quarter">
        <mu-paper :zDepth="paperHover" v-on:mouseover="changePaper" class="searchBox">
            <mu-text-field fullWidth="true" :hintText="searchHint" v-model="query" class="demo-radio"/><br/>
                <mu-radio label="Name" name="group" nativeValue="1" v-model="selected" class="demo-radio"/>
                <mu-radio label="Manager" name="group" nativeValue="2" v-model="selected" class="demo-radio"/>
                <mu-radio label="Department" name="group" nativeValue="3" v-model="selected" class="demo-radio"/>
                <mu-radio label="Stage" name="group" nativeValue="4" v-model="selected" class="demo-radio"/>
                <mu-radio label="Deadline" name="group" nativeValue="5" v-model="selected" class="demo-radio"/>
                <mu-radio label="Start Date" name="group" nativeValue="6" v-model="selected" class="demo-radio"/>
        </mu-paper>
    </div>
    <div class="column is-one-column">
        <mu-float-button icon="add" v-on:click="openModal"/>
    </div>
    <div class="column">
        <draggable v-model="projects" @start="drag=true" @end="drag=false">
            <transition-group name="list-complete staggered-fade" tad="ul" :css="false" :before-enter="beforeEnter" :enter="enter" :leave="leave">
                <li v-for="(project, index) in projectsComputed"  :key="project.name" :data-index="index" class="column is-one-third list-complete-item">
                    <mu-paper :zDepth="3">
                        <mu-icon-button icon="delete" class="delete-button"></mu-icon-button>
                        <article class="media">
                            <div class="media-content">
                                <div class="content">
                                    <div class="project-name has-text-centered">
                                        <span>{{project.name}}</span>
                                    </div>
                                    <mu-badge :content="project.stage.name" primary slot="right"/>
                                    <!--<div class="project-status has-text-centered">-->
                                        <!--<span>{{project.stage.name}}</span>-->
                                    <!--</div>-->
                                    <div class="project-desc-list has-text left">
                                        <span>Manager: </span> <span>{{project.manager.name}}</span>
                                    </div>
                                    <div class="project-desc-list has-text left">
                                        <span>Department: </span> <span>{{project.department.name}}</span>
                                    </div>
                                    <div class="project-desc-list has-text left">
                                        <span>Start Date: </span> <span>{{project.started_from}}</span>
                                    </div>
                                    <div class="project-desc-list has-text left">
                                        <span>Dealine: </span> <span>{{project.deadline}}</span>
                                    </div>
                                    <p class="project-description">
                                        {{project.description}}
                                    </p>
                                </div>
                            </div>
                        </article>
                    </mu-paper>
                </li>
            </transition-group>
        </draggable>
    </div>
    <div id="modal-ter"  :class="[isActive ? activeClass : '', modal]">
        <div class="modal-background" v-on:click="openModal"></div>
        <div class="modal-card">
            <header class="modal-card-head">
                <p class="modal-card-title">Add New Project</p>
                <button v-on:click="openModal" class="delete"></button>
            </header>
            <section class="modal-card-body">
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Project Name</label>
                        <p class="control">
                            <input class="input" v-model="newProject.name" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Project Description</label>
                        <p class="control">
                            <input class="input" v-model="newProject.description" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Start Date</label>
                        <p class="control">
                            <input class="input" v-model="newProject.started_from" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Deadline</label>
                        <p class="control">
                            <input class="input" v-model="newProject.deadline" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Manager</label>
                        <p class="control">
                            <input class="input" v-model="newProject.manager.name" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Department</label>
                        <p class="control">
                            <input class="input" v-model="newProject.department.name" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Stage</label>
                        <p class="control">
                            <input class="input" type="text" v-model="newProject.stage.name" placeholder="Text input">
                        </p>
                    </div>
                </div>
            </section>
            <footer class="modal-card-foot">
                <a v-on:click="createProject" class="button is-success">Save changes</a>
                <a class="button">Cancel</a>
            </footer>
        </div>
    </div>
</div>
</template>
<style scoped>
    .demo-radio {
        min-width: 8em;
    }
    .searchBox {
        padding: 2em;
    }
    .project-status {
        position: absolute;
        top: 0.3em;
        left: 0.3em;
        background-color: #ffdb57;
        padding: 0.2em;
        padding-left: 0.5em;
        padding-right: 0.5em;
        border-radius: 0.3em;
    }
    .project-name {
        font-weight: 900;
    }
    .project-description {
        margin-top: 0.5em;
        padding-top: 1em;
        border-top: 1px solid lightgrey;
    }
    .project-desc-list span:first-of-type{
        font-weight: 900;
    }
    .box {
        position: relative;
    }
    .project-name {
        text-align: center;
    }
    .delete-button {
        background-color: rgba(255, 8, 8, 0.4);
        transition: all .25s ease-in;
        float: right;
        position: absolute;
        right: 0.3em;
        top: 0.3em;
    }

    .delete-button:hover, .delete-button:focus{
        background-color: rgba(255, 0, 0, 0.68);
    }

    .column{
        display: inline-block;
        padding: 1em;
    }

    .list-complete-item {
        transition: all 1s;
    }

    .list-complete-enter, .list-complete-leave-active {
        opacity: 0;
    }
</style>
<script >
    export default {
        data(){
            return {
                loading: false,
                isActive: false,
                paperHover: 3,
                modal: 'modal',
                searchHint: 'Search by ...',
                activeClass: 'is-active',
                query: "",
                selected: "",
                projects: [],
                newProject: {
                    name: '',
                    description: '',
                    started_from: '',
                    deadline: '',
                    manager: {
                        name: ''
                    },
                    department: {
                        name: ''
                    },
                    stage: {
                        name: ''
                    }
                },
            }
        },
        options: {
            segmentShowStroke: false
        },
        mounted() {
            this.getData();
        },
        computed: {
            projectsComputed: function () {
               var vm = this;
               if(this.selected == '1' || this.selected == ""){
                   this.searchHint = "Search by Name";
                   return this.projects.filter(function (project) {
                       return project.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '2'){
                   this.searchHint = "Search by Manager";
                   return this.projects.filter(function (project) {
                       return project.manager.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '3'){
                   this.searchHint = "Search by Department";
                   return this.projects.filter(function (project) {
                       return project.department.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '4'){
                   this.searchHint = "Search by Stage";
                   return this.projects.filter(function (project) {
                       return project.stage.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '5'){
                   this.searchHint = "Search by Deadline";
                   return this.projects.filter(function (project) {
                       return project.deadline.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '6'){
                   this.searchHint = "Search by Start Date";
                   return this.projects.filter(function (project) {
                       return project.started_from.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }

            }
        },
        methods: {
            changePaper: function () {
              this.paperHover = 6 ;
            },
            beforeEnter: function (el) {
                el.style.opacity = 0
                el.style.height = 0
            },
            enter: function (el, done) {
                var delay = el.dataset.index * 150
                setTimeout(function () {
                    Velocity(
                        el,
                        { opacity: 1, height: '1.6em' },
                        { complete: done }
                    )
                }, delay)
            },
            leave: function (el, done) {
                var delay = el.dataset.index * 150
                setTimeout(function () {
                    Velocity(
                        el,
                        { opacity: 0, height: 0 },
                        { complete: done }
                    )
                }, delay)
            },
            getData() {
                this.loading = true;
                axios.get('/project/').then(({data}) => this.projects = data).then(() => this.loading = false)
            },
            openModal: function(){
                if(this.isActive){
                    this.isActive = false;
                }else {
                    this.isActive = true;
                }
            },
            createProject() {
                axios.post('project/store', this.newProject)
            }
        }
    }
</script>
enter code here
</code>```

答:
The easiest way is probably to wrap the mu-paper component in another component where you can encapsulate the hover behavior.

```<code>// MuPaperHover.vue

<template>
  <mu-paper :z-depth="zDepth" @mouseenter.native="zDepth = 3" @mouseleave.native="zDepth = 1">
    <slot/>
  </mu-paper>
</template>

<script>
  export default {
    data() {
      return {
        zDepth: 1,
      };
    },
  };
</script>
</code>```

You can then use mu-paper-hover in place of mu-paper.

Body:
Trying to become friends with VUEJS. Got stuck on some simple stuff, couldn't google it. So I'm using MuseUi framework in my App. Well I want to do a simple thing, change the value of the property for each specific element on hover

 <mu-paper :zDepth="1" v-on:mouseover=" ???? " class="searchBox">

I need to change:zDepth to 3 for example, on hover of the element. How could I achieve that?

full code snippet

<template>

        <mu-paper :zDepth="paperHover" v-on:mouseover="changePaper" class="searchBox">
            <mu-text-field fullWidth="true" :hintText="searchHint" v-model="query" class="demo-radio"/>

                <mu-radio label="Name" name="group" nativeValue="1" v-model="selected" class="demo-radio"/>
                <mu-radio label="Manager" name="group" nativeValue="2" v-model="selected" class="demo-radio"/>
                <mu-radio label="Department" name="group" nativeValue="3" v-model="selected" class="demo-radio"/>
                <mu-radio label="Stage" name="group" nativeValue="4" v-model="selected" class="demo-radio"/>
                <mu-radio label="Deadline" name="group" nativeValue="5" v-model="selected" class="demo-radio"/>
                <mu-radio label="Start Date" name="group" nativeValue="6" v-model="selected" class="demo-radio"/>
        </mu-paper>

        <mu-float-button icon="add" v-on:click="openModal"/>

        <draggable v-model="projects" @start="drag=true" @end="drag=false">
            <transition-group name="list-complete staggered-fade" tad="ul" :css="false" :before-enter="beforeEnter" :enter="enter" :leave="leave">

                    <mu-paper :zDepth="3">
                        <mu-icon-button icon="delete" class="delete-button"></mu-icon-button>

                                        {{project.name}}

                                    <mu-badge :content="project.stage.name" primary slot="right"/>

                                        Manager:  {{project.manager.name}}

                                        Department:  {{project.department.name}}

                                        Start Date:  {{project.started_from}}

                                        Dealine:  {{project.deadline}}

                                        {{project.description}}

                    </mu-paper>

            </transition-group>
        </draggable>

Add New Project

                <button v-on:click="openModal" class="delete"></button>

                        Project Name

                            <input class="input" v-model="newProject.name" type="text" placeholder="Text input">

                        Project Description

                            <input class="input" v-model="newProject.description" type="text" placeholder="Text input">

                        Start Date

                            <input class="input" v-model="newProject.started_from" type="text" placeholder="Text input">

                        Deadline

                            <input class="input" v-model="newProject.deadline" type="text" placeholder="Text input">

                        Manager

                            <input class="input" v-model="newProject.manager.name" type="text" placeholder="Text input">

                        Department

                            <input class="input" v-model="newProject.department.name" type="text" placeholder="Text input">

                        Stage

                            <input class="input" type="text" v-model="newProject.stage.name" placeholder="Text input">

                Save changes
                Cancel

</template>

enter code here

Body:
The easiest way is probably to wrap the mu-paper component in another component where you can encapsulate the hover behavior.

// MuPaperHover.vue

<template>
  <mu-paper :z-depth="zDepth" @mouseenter.native="zDepth = 3" @mouseleave.native="zDepth = 1">
    <slot/>
  </mu-paper>
</template>

<script>
  export default {
    data() {
      return {
        zDepth: 1,
      };
    },
  };
</script>

You can then use mu-paper-hover in place of mu-paper.


问:
Symfony UserVoter gets current logged in User in place of User in the url
On an show user action, i want to check if the logged user has the right to see this user. So i created a UserVoter.
But when I try to pass the user defined in the url  to the Voter using annotation, I get the logged User using both $subject and $token->getUser()

If I change my var name in the action, it works fine ($user -> $foo).

Do you know how can I do for not changing my var name ?

Controller :

```<code>/**
 * Finds and displays a user entity.
 *
 * @Method("GET")
 * @Route("/{id}/", name="authenticated_user_show", requirements={"id": "\d+"})
 * @ParamConverter("user", class="AppBundle:User")
 * @Security("is_granted('SHOW', user)")
 */
public function showAction(User $user)
{
</code>```

And Voter :

```<code>protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();

    if (!$user instanceof User) {
        // the user must be logged in; if not, deny access
        return false;
    }

    if ($user->hasRole(User::ROLE_SUPER_ADMIN)) {
        // if super admin, can do everything
        return true;
    }

    // you know $subject is an User object, thanks to supports
    /** @var User $userSubject */
    $userSubject = $subject;

    switch ($attribute) {
        case self::SHOW:
            return $this->canShow($userSubject, $user);
        case self::EDIT:
            return $this->canEdit($userSubject, $user);
    }

    throw new \LogicException('This code should not be reached!');
}

private function canShow(User $userSubject, User $user) : bool
{
    if ($user->getClient() === $userSubject->getClient()) {
        // if they are in the same client
        return true;
    }

    return false;
}

private function canEdit(User $userSubject, User $user, TokenInterface $token) : bool
{
    if (
        $this->decisionManager->decide($token, [User::ROLE_ADMIN]) &&
        $user->getClient() === $userSubject->getClient()
        ) {
        // if the user and the admin belong to the same client
        return true;
    } elseif (
        $this->decisionManager->decide($token, [User::ROLE_MANAGER]) &&
        $this->userManager->hasEstablishmentInCommon($user, $userSubject)
        ) {
        // if the user and the manager are linked to the same establishment
        return true;
    }

    return false;
}
</code>```

答:
Assuming that you are not trying to see the logged user I will consider that you may have a conflict with the variables in the security annotation context:

https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/security.html
The Security annotation has access to the following variables:

token: The current security token

user: The current user object

request: The request instance

roles: The user roles; and all request
attributes.

To fix, change the name of the user so you can avoid the conflict.

```<code>/**
 * Finds and displays a user entity.
 *
 * @Method("GET")
 * @Route("/{id}/", name="authenticated_user_show", requirements={"id":
   "\d+"})
 * @ParamConverter("showUser", class="AppBundle:User")
 * @Security("is_granted('SHOW', showUser)")
 */
 public function showAction(User $showUser)
</code>```

Body:
On an show user action, i want to check if the logged user has the right to see this user. So i created a UserVoter.
But when I try to pass the user defined in the url  to the Voter using annotation, I get the logged User using both $subject and $token->getUser()

If I change my var name in the action, it works fine ($user -> $foo).

Do you know how can I do for not changing my var name ?

Controller :

/**
 * Finds and displays a user entity.
 *
 * @Method("GET")
 * @Route("/{id}/", name="authenticated_user_show", requirements={"id": "\d+"})
 * @ParamConverter("user", class="AppBundle:User")
 * @Security("is_granted('SHOW', user)")
 */
public function showAction(User $user)
{

And Voter :

protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();

    if (!$user instanceof User) {
        // the user must be logged in; if not, deny access
        return false;
    }

    if ($user->hasRole(User::ROLE_SUPER_ADMIN)) {
        // if super admin, can do everything
        return true;
    }

    // you know $subject is an User object, thanks to supports
    /** @var User $userSubject */
    $userSubject = $subject;

    switch ($attribute) {
        case self::SHOW:
            return $this->canShow($userSubject, $user);
        case self::EDIT:
            return $this->canEdit($userSubject, $user);
    }

    throw new \LogicException('This code should not be reached!');
}

private function canShow(User $userSubject, User $user) : bool
{
    if ($user->getClient() === $userSubject->getClient()) {
        // if they are in the same client
        return true;
    }

    return false;
}

private function canEdit(User $userSubject, User $user, TokenInterface $token) : bool
{
    if (
        $this->decisionManager->decide($token, [User::ROLE_ADMIN]) &&
        $user->getClient() === $userSubject->getClient()
        ) {
        // if the user and the admin belong to the same client
        return true;
    } elseif (
        $this->decisionManager->decide($token, [User::ROLE_MANAGER]) &&
        $this->userManager->hasEstablishmentInCommon($user, $userSubject)
        ) {
        // if the user and the manager are linked to the same establishment
        return true;
    }

    return false;
}

Body:
Assuming that you are not trying to see the logged user I will consider that you may have a conflict with the variables in the security annotation context:

https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/security.html
The Security annotation has access to the following variables:

token: The current security token

user: The current user object

request: The request instance

roles: The user roles; and all request
attributes.

To fix, change the name of the user so you can avoid the conflict.

/**
 * Finds and displays a user entity.
 *
 * @Method("GET")
 * @Route("/{id}/", name="authenticated_user_show", requirements={"id":
   "\d+"})
 * @ParamConverter("showUser", class="AppBundle:User")
 * @Security("is_granted('SHOW', showUser)")
 */
 public function showAction(User $showUser)


问:
How to append to appended element through JQuery?
My question is related more to why is this happening, not to knowing how to solve it.

I want to firstly append a
 to a div and then an  to the
.

I have the following jQuery code:

```<code>$('.patches').empty();
for(i=0;i<patches.length;i++){
    $('.patches').append($('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }));
    $('#li'+patches[i].name).append($('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    }));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}
</code>```

The
 is appended but the  isn't, why isn't this working?

EDIT: I have modified the code as follows and it works perfectly:

```<code>$('.patches').empty();
for(i=0;i<patches.length;i++){
    var listItem=$('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    });
    $('.patches').append(listItem);
    var aItem=$('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    });
    listItem.append(aItem);
    listItem.append('<p>Version : '+patches[i].version+' Author : '+patches[i].author+'</p>');
}
</code>```

This version is almost the same as the previous one, I am just using variables. I would still like to know why the previous version of the code was not working. Could someone explain this?

答:
These elements are dynamically created. So, you need to call something like this</p>

```<code>$(document).on('event', '.class-name', function(){
    // code
});
</code>```

Body:
My question is related more to why is this happening, not to knowing how to solve it.

I want to firstly append a
 to a div and then an  to the
.

I have the following jQuery code:

$('.patches').empty();
for(i=0;i<patches.length;i++){
    $('.patches').append($('
', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }));
    $('#li'+patches[i].name).append($('',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    }));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}

The
 is appended but the  isn't, why isn't this working?

EDIT: I have modified the code as follows and it works perfectly:

$('.patches').empty();
for(i=0;i<patches.length;i++){
    var listItem=$('
', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    });
    $('.patches').append(listItem);
    var aItem=$('',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    });
    listItem.append(aItem);
    listItem.append('
Version : '+patches[i].version+' Author : '+patches[i].author+'
');
}

This version is almost the same as the previous one, I am just using variables. I would still like to know why the previous version of the code was not working. Could someone explain this?

Body:
These elements are dynamically created. So, you need to call something like this

$(document).on('event', '.class-name', function(){
    // code
});


问:
Sending data from one pod to another pod running specifically on the same host (DaemonSet)
I have an agent (datadog agent but could be something else) running on all the nodes of my cluster, deployed through a DaemonSet. This agent is collecting diverse metrics about the host: cpu and memory usage, IO, which containers are running.

It can also collect custom metrics, by listening on a specific port 1234.

How can I send data from a pod to the instance of the agent running on the same node than the pod?
If I use a Kubernetes service the calls to send the metric will be load balanced across all my agents and I'll lose the correlation between the pod emitting the metric and the host it's running on.

答:
I use the exact same setup, dd-agent running as a DaemonSet in my kubernetes cluster. Using the same port mapping you commented here, you can just send metrics to the hostname of the node an application is running on.

You can add the node name to the pods environment using the downward api in your pod spec:

```<code>env:
- name: NODE_NAME
  valueFrom:
    fieldRef:
      fieldPath: spec.nodeName
</code>```

Then, you can just open an UDP connection to ${NODE_NAME}:8125 to connect to the datadog agent.

Body:
I use the exact same setup, dd-agent running as a DaemonSet in my kubernetes cluster. Using the same port mapping you commented here, you can just send metrics to the hostname of the node an application is running on.

You can add the node name to the pods environment using the downward api in your pod spec:

env:
- name: NODE_NAME
  valueFrom:
    fieldRef:
      fieldPath: spec.nodeName

Then, you can just open an UDP connection to ${NODE_NAME}:8125 to connect to the datadog agent.


问:
VBA , Using offset
I am having 4 sht, sht1, sht2, sht3 and sht4.

I am copying the columns E and F from sht 1 to sht3. and then i look into  the corresponding values in sht 2, and paste them in sht3.

I then lookinto in my sht3, if the column "G" has "NO"; then i copy the corresponding rows to sht4.

till, this i have completed coding.

I wanted to look into the column E in sht4, and paste the corresponding ID from sht1. Could someone tell, how i could do it ?

EDIT.

In sht3, i have the rows filled only when there is Id in column F.

In few cases, i dont have column F,means there is no ID.

so, i copy them to sht4. Now i have in sht4, column E Filled. I want to look into the relevant Information of those ID in sht1. I want the Information from each and every column in sht1, except E .

I know we can use Offset, but how do I use it in this case,
I have tried the following code

```<code>Sub nlookup()
Dim i As Long
Dim totalrows As Long
Dim rng As Range
Sheets("sht1").Select
totalrows = ActiveSheet.UsedRange.Rows.Count
Sheets("sht4").Select
For i = 5 To totalrows
Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
Cells(i, 6).Value = rng.Value
Cells(i, 1).Value = rng.Offset(0, 0).Value
Cells(i, 2).Value = rng.Offset(0, 14).Value
Cells(i, 3).Value = rng.Offset(0, 1).Value
Cells(i, 4).Value = rng.Offset(0, 2).Value
Cells(i, 12).Value = rng.Offset(0, 8).Value
Cells(i, 13).Value = rng.Offset(0, 9).Value
End If
Next
End Sub
</code>```

Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value), there is no Need of looking into this line, i beleive.

答:
The code will consider the following as discussed in chat:

Data should be copied from sht1 to sht4 on Id's in both sheets

Id's are in Column L and Column E for sht1 and sht4 respectively

Columns to be copy from sht1 to sht4 as A->A, B->C,C->D,I->L,J->M,O->B

Data in sht1 and sht4 starts from Row 5 and Row 2 respectively

```<code>Sub Demo()
    Dim srcLastRow As Long, destLastRow As Long
    Dim srcWS As Worksheet, destWS As Worksheet
    Dim i As Long, j As Long

    Application.ScreenUpdating = False

    Set srcWS = ThisWorkbook.Sheets("Sht1")
    Set destWS = ThisWorkbook.Sheets("Sht4")
    srcLastRow = srcWS.Cells(srcWS.Rows.Count, "L").End(xlUp).Row
    destLastRow = destWS.Cells(destWS.Rows.Count, "E").End(xlUp).Row

    For i = 2 To destLastRow
        For j = 5 To srcLastRow
            If destWS.Cells(i, "E").Value = srcWS.Cells(j, "L").Value Then
                destWS.Cells(i, "A") = srcWS.Cells(j, "A")
                destWS.Cells(i, "B") = srcWS.Cells(j, "O")
                destWS.Cells(i, "C") = srcWS.Cells(j, "B")
                destWS.Cells(i, "D") = srcWS.Cells(j, "C")
                destWS.Cells(i, "L") = srcWS.Cells(j, "I")
                destWS.Cells(i, "M") = srcWS.Cells(j, "J")
            End If
        Next j
    Next i

    Application.ScreenUpdating = True
End Sub
</code>```

Title: VBA , Using offset

Body:
I am having 4 sht, sht1, sht2, sht3 and sht4.

I am copying the columns E and F from sht 1 to sht3. and then i look into  the corresponding values in sht 2, and paste them in sht3.

I then lookinto in my sht3, if the column "G" has "NO"; then i copy the corresponding rows to sht4.

till, this i have completed coding.

I wanted to look into the column E in sht4, and paste the corresponding ID from sht1. Could someone tell, how i could do it ?

EDIT.

In sht3, i have the rows filled only when there is Id in column F.

In few cases, i dont have column F,means there is no ID.

so, i copy them to sht4. Now i have in sht4, column E Filled. I want to look into the relevant Information of those ID in sht1. I want the Information from each and every column in sht1, except E .

I know we can use Offset, but how do I use it in this case,
I have tried the following code

Sub nlookup()
Dim i As Long
Dim totalrows As Long
Dim rng As Range
Sheets("sht1").Select
totalrows = ActiveSheet.UsedRange.Rows.Count
Sheets("sht4").Select
For i = 5 To totalrows
Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value)
'If it is found put its value on the destination sheet
If Not rng Is Nothing Then
Cells(i, 6).Value = rng.Value
Cells(i, 1).Value = rng.Offset(0, 0).Value
Cells(i, 2).Value = rng.Offset(0, 14).Value
Cells(i, 3).Value = rng.Offset(0, 1).Value
Cells(i, 4).Value = rng.Offset(0, 2).Value
Cells(i, 12).Value = rng.Offset(0, 8).Value
Cells(i, 13).Value = rng.Offset(0, 9).Value
End If
Next
End Sub

Set rng = Sheets("sht2").UsedRange.Find(Cells(i, 5).Value), there is no Need of looking into this line, i beleive.

Body:
The code will consider the following as discussed in chat:

Data should be copied from sht1 to sht4 on Id's in both sheets

Id's are in Column L and Column E for sht1 and sht4 respectively

Columns to be copy from sht1 to sht4 as A->A, B->C,C->D,I->L,J->M,O->B

Data in sht1 and sht4 starts from Row 5 and Row 2 respectively

Sub Demo()
    Dim srcLastRow As Long, destLastRow As Long
    Dim srcWS As Worksheet, destWS As Worksheet
    Dim i As Long, j As Long

    Application.ScreenUpdating = False

    Set srcWS = ThisWorkbook.Sheets("Sht1")
    Set destWS = ThisWorkbook.Sheets("Sht4")
    srcLastRow = srcWS.Cells(srcWS.Rows.Count, "L").End(xlUp).Row
    destLastRow = destWS.Cells(destWS.Rows.Count, "E").End(xlUp).Row

    For i = 2 To destLastRow
        For j = 5 To srcLastRow
            If destWS.Cells(i, "E").Value = srcWS.Cells(j, "L").Value Then
                destWS.Cells(i, "A") = srcWS.Cells(j, "A")
                destWS.Cells(i, "B") = srcWS.Cells(j, "O")
                destWS.Cells(i, "C") = srcWS.Cells(j, "B")
                destWS.Cells(i, "D") = srcWS.Cells(j, "C")
                destWS.Cells(i, "L") = srcWS.Cells(j, "I")
                destWS.Cells(i, "M") = srcWS.Cells(j, "J")
            End If
        Next j
    Next i

    Application.ScreenUpdating = True
End Sub


问:
Does this function return the same pointer as its argument?
I have written this function in C:

```<code>void *PWNRetain(void *object) {
  PWNObject *obj = (PWNObject *)object; // <-- looks stupid, I know :)
  obj->retainCount++;
  return obj;
}
</code>```

It's important that this will return the same pointer as it's argument. Is obj equal to object, or did I make another pointer mistake? Thanks. :)

答: Yes, this will return the same pointer in C.  In fact, you don't need the explicit cast on the second line, as C allows implicit conversions from void * to other pointer types.

Body:
I have written this function in C:

void *PWNRetain(void *object) {
  PWNObject *obj = (PWNObject *)object; // <-- looks stupid, I know :)
  obj->retainCount++;
  return obj;
}

It's important that this will return the same pointer as it's argument. Is obj equal to object, or did I make another pointer mistake? Thanks. :)


问:
Check if every value of a column contains integer, if not print the index of that cell
Suppose I have a column with mixture of integer and float, I need to run a loop through that column to check if all values are numeric. Values that aren't numeric, dump the index of that cell in a blank list.

A column like this:

```<code>DESCRIPTION                      RATE
79th St & Private Dr - 5022 W        1.5
79th St & Allison Ave                1.5
Allison Ave & 81st St                1
81st St & Norfolk St                 1
Norfolk St & Private Dr - 8178 N     1
Norfolk St & 84th St                 1
Moller Rd & 86th St                  1.5
Zionsville Rd & 86th St              1.5
</code>```

I wrote a code like this but the newlist loop isn't working.

```<code>import pandas as pd
import numpy as np

df = pd.read_csv("C:\\Python34\\python scripts\\BNSF\\data\\data.csv") #read csv
col=df.columns #read header
print(col)
r=df.shape[0] #gives number of row count
c=df.shape[1] #gives number of col count
print(r, c)
typ=df.dtypes
print(typ)

newlist=[] #creates blank list
for i in range(r,1):
    if df.iloc[i,1].dtype == np.int64:
        pass
    else:
        print(df.iloc[i,1])
        newlist.append(df.iloc[i,1])
        print(newlist)
</code>```

Need changes inside that loop. Please help.

答:
The beauty of pandas is that you can often avoid using loops. Sorting the data into integers/non-integers may be achieved by doing the modulo 1 operation and checking zero equivalence %1==0 producing a DataFrame of True/False values in the variable intcheck. Then just get the True rows which are the integers from the original DataFrame. Placing a ~ in front inverts the boolean to get the non-integer values.

```<code>import pandas as pd

d =[["79th St & Private Dr - 5022 W"        ,1.5],
    ["79th St & Allison Ave"                ,1.5],
    ["Allison Ave & 81st St"                ,1  ],
    ["81st St & Norfolk St"                 ,1  ],
    ["Norfolk St & Private Dr - 8178 N"     ,1  ],
    ["Norfolk St & 84th St"                 ,1  ],
    ["Moller Rd & 86th St"                  ,1.5],
    ["Zionsville Rd & 86th St"              ,1.5]]

df = pd.DataFrame(d, columns=['DESCRIPTION','RATE'])
df = df.set_index('DESCRIPTION')

intcheck = (df.RATE%1)==0

print(df[intcheck])

#                                   RATE
# DESCRIPTION
# Allison Ave & 81st St              1.0
# 81st St & Norfolk St               1.0
# Norfolk St & Private Dr - 8178 N   1.0
# Norfolk St & 84th St               1.0

print(df[~intcheck])

#                                RATE
# DESCRIPTION
# 79th St & Private Dr - 5022 W   1.5
# 79th St & Allison Ave           1.5
# Moller Rd & 86th St             1.5
# Zionsville Rd & 86th St         1.5
</code>```

Body:
Suppose I have a column with mixture of integer and float, I need to run a loop through that column to check if all values are numeric. Values that aren't numeric, dump the index of that cell in a blank list.

A column like this:

DESCRIPTION                      RATE
79th St & Private Dr - 5022 W        1.5
79th St & Allison Ave                1.5
Allison Ave & 81st St                1
81st St & Norfolk St                 1
Norfolk St & Private Dr - 8178 N     1
Norfolk St & 84th St                 1
Moller Rd & 86th St                  1.5
Zionsville Rd & 86th St              1.5

I wrote a code like this but the newlist loop isn't working.

import pandas as pd
import numpy as np

df = pd.read_csv("C:\\Python34\\python scripts\\BNSF\\data\\data.csv") #read csv
col=df.columns #read header
print(col)
r=df.shape[0] #gives number of row count
c=df.shape[1] #gives number of col count
print(r, c)
typ=df.dtypes
print(typ)

newlist=[] #creates blank list
for i in range(r,1):
    if df.iloc[i,1].dtype == np.int64:
        pass
    else:
        print(df.iloc[i,1])
        newlist.append(df.iloc[i,1])
        print(newlist)

Need changes inside that loop. Please help.

Body:
The beauty of pandas is that you can often avoid using loops. Sorting the data into integers/non-integers may be achieved by doing the modulo 1 operation and checking zero equivalence %1==0 producing a DataFrame of True/False values in the variable intcheck. Then just get the True rows which are the integers from the original DataFrame. Placing a ~ in front inverts the boolean to get the non-integer values.

import pandas as pd

d =[["79th St & Private Dr - 5022 W"        ,1.5],
    ["79th St & Allison Ave"                ,1.5],
    ["Allison Ave & 81st St"                ,1  ],
    ["81st St & Norfolk St"                 ,1  ],
    ["Norfolk St & Private Dr - 8178 N"     ,1  ],
    ["Norfolk St & 84th St"                 ,1  ],
    ["Moller Rd & 86th St"                  ,1.5],
    ["Zionsville Rd & 86th St"              ,1.5]]

df = pd.DataFrame(d, columns=['DESCRIPTION','RATE'])
df = df.set_index('DESCRIPTION')

intcheck = (df.RATE%1)==0

print(df[intcheck])

#                                   RATE
# DESCRIPTION
# Allison Ave & 81st St              1.0
# 81st St & Norfolk St               1.0
# Norfolk St & Private Dr - 8178 N   1.0
# Norfolk St & 84th St               1.0

print(df[~intcheck])

#                                RATE
# DESCRIPTION
# 79th St & Private Dr - 5022 W   1.5
# 79th St & Allison Ave           1.5
# Moller Rd & 86th St             1.5
# Zionsville Rd & 86th St         1.5


问:
Is an undefined ng-bind more expensive than an ng-bind and ng-show?
Supposing toShowVar us undefined, which is more expensive?

```<code><span ng-bind="toShowVar" ng-show="toShowVar"></span>
</code>```

or

```<code><span ng-bind="toShowVar"></span>
</code>```

The latter would obviously not print anything on the screen if the variable is undefined.

答:
To explain this, first of all ng-show and ng-bind both runs at a same priority level. there is nothing in favor of ng-show to increase performance.

here to hide the content ng-show is not required at all. ng-show will also start watching the same (here toShowVar) and will perform on the watcher registered by it (changing the display property to none by adding ng-hide class).
To explain more, if you use ng-show='false' and change toShowVar to some text in a further operation, and visit the DOM by debugger tool, you can check that the updated text is still available. So, obviously ng-show will not add any performance benefit here.
If you use ng-if (running on a higher priority that both), it will remove element from DOM and further subsequent watchers will not be active until it will be re rendered to DOM, so even in case of ng-if you are running something extra, so it will not be faster like only ng-bind but faster than ng-bind and ng-show thgother.

Note: only ng-bind and ng-bind ng-show can differ in UI, if the span having some affect of CSS (maybe inline, hierarchy parent, or any ) that is visible in UI even if it is empty (something like border), otherwise, with look and feel both are same.

Body:
Supposing toShowVar us undefined, which is more expensive?

or

The latter would obviously not print anything on the screen if the variable is undefined.


问:
Is it possible to use bash to search for a certain phrase on a website?
I was just curious if this was possible. I have tried googling it, but nothing seems to show up. I'd also rather not download the site beforehand and just through the html file that way.</p>

答:
Try curl <url> | grep <pattern> as another user detailed.

But be cognizant that that will show all matching results, which may not be ideal.

If you want to match the first (or a select set of results), use curl<url>  | grep -m <count> <pattern>.

For example: curl https://stackoverflow.com/questions/44927008/is-it-possible-to-use-bash-to-search-for-a-certain-phrase-on-a-website | grep -m 1 "possible" will only return the first match.


问:
How to block calls to print?
Is there a way to stop a function from calling print?

I am using the pygame.joystick module for a game I am working on.

I created a pygame.joystick.Joystick object and in the actual loop of the game call its member function get_button to check for user input. The function does everything I need it to do, but the problem is that it also calls print, which slows down the game considerably.

Can I block this call to print?

答:
The module I used printed to stderr. So the solution in that case would be:

```<code>sys.stdout = open(os.devnull, 'w')
</code>```

Title: How to block calls to print?

Body:
The module I used printed to stderr. So the solution in that case would be:

sys.stdout = open(os.devnull, 'w')


问:
Persist array store in session symfony
It's been several days since I've been blocking to persist items from an order into session to database.

I stock articles in session in an array and I do not know how to persist the array. I try to convert the array into an object, I can not. This is my service:

```<code> public function addArticle($id)
{

    $sessionCart = $this->session;

    $article = $this->doctrine->getRepository('AppBundle:Article')->find($id);

    $cart = $sessionCart->get('cart');

    $cart[] = $article;

    $sessionCart->set('cart', $cart);

    // use later for delivery
    $sessionCart->get('commande');

    return $sessionCart;
}

public function panier()
{

    $articles = $this->session->get('cart');

    return $articles;
}

public function delivery(Request $request)
{

    $commande = new Commande();

    $articles = $this->session->get('cart');

    $form = $this->form->create(CommandeType::class, $commande);

    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
    {

        $data = $form->getData();

        $this->session->set('commande', $data);

        $response = new RedirectResponse('payment');
        $response->send();
    }

    return [$form, $articles];
}

public function payment(Request $request)
{

    $articles = $this->session->get('cart');
    $commande = $this->session->get('commande');

    if ($request->isMethod('POST')) {

    $em =   $this->doctrine;

    $em->persist($articles);
    $em->persist($commande);

    $em->flush();
    }

    return[$articles, $commande];
}
</code>```

Error : "EntityManager#persist() expects parameter 1 to be an entity object, array given."

The order is persisted but not the items.

Thanks

答:
I can't understand these two lines

```<code>$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);
</code>```

$cart is an array and should be an entity isn't it ?

The persist is waiting for an entity,
maybe you can persist in a foreach loop:

```<code>foreach($articles as $article){
    $em->persist($article);
}
</code>```

or use a doctrineCollection instead of an array

Title: Persist array store in session symfony

Body:
It's been several days since I've been blocking to persist items from an order into session to database.

I stock articles in session in an array and I do not know how to persist the array. I try to convert the array into an object, I can not. This is my service:

 public function addArticle($id)
{

    $sessionCart = $this->session;

    $article = $this->doctrine->getRepository('AppBundle:Article')->find($id);

    $cart = $sessionCart->get('cart');

    $cart[] = $article;

    $sessionCart->set('cart', $cart);

    // use later for delivery
    $sessionCart->get('commande');

    return $sessionCart;
}

public function panier()
{

    $articles = $this->session->get('cart');

    return $articles;
}

public function delivery(Request $request)
{

    $commande = new Commande();

    $articles = $this->session->get('cart');

    $form = $this->form->create(CommandeType::class, $commande);

    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
    {

        $data = $form->getData();

        $this->session->set('commande', $data);

        $response = new RedirectResponse('payment');
        $response->send();
    }

    return [$form, $articles];
}

public function payment(Request $request)
{

    $articles = $this->session->get('cart');
    $commande = $this->session->get('commande');

    if ($request->isMethod('POST')) {

    $em =   $this->doctrine;

    $em->persist($articles);
    $em->persist($commande);

    $em->flush();
    }

    return[$articles, $commande];
}

Error : "EntityManager#persist() expects parameter 1 to be an entity object, array given."

The order is persisted but not the items.

Thanks

Body:
I can't understand these two lines

$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);

$cart is an array and should be an entity isn't it ?

The persist is waiting for an entity,
maybe you can persist in a foreach loop:

foreach($articles as $article){
    $em->persist($article);
}

or use a doctrineCollection instead of an array


问:
cURL equivalent in Node.js?
I'm looking to use information from an HTTP request using Node.js (i.e. call a remote web service and echo the response to the client).

In PHP I would have used cURL to do this.  What is the best practice in Node?

答:
I had a problem sending POST data to cloud DB from IOT RaspberryPi, but after hours I managed to get it straight.

I used command prompt to do so.

```<code>sudo curl --URL http://<username>.cloudant.com/<database_name> --user <api_key>:<pass_key> -X POST -H "Content-Type:application/json" --data '{"id":"123","type":"987"}'
</code>```

Command prompt will show the problems - wrong username/pass; bad request etc.

--URL database/server location (I used simple free Cloudant DB)
--user is the authentication part username:pass I entered through API pass
-X defines what command to call (PUT,GET,POST,DELETE)
-H content type - Cloudant is about document database, where JSON is used
--data content itself sorted as JSON

Title: cURL equivalent in Node.js?

Body:
I had a problem sending POST data to cloud DB from IOT RaspberryPi, but after hours I managed to get it straight.

I used command prompt to do so.

sudo curl --URL http://<username>.cloudant.com/<database_name> --user <api_key>:<pass_key> -X POST -H "Content-Type:application/json" --data '{"id":"123","type":"987"}'

Command prompt will show the problems - wrong username/pass; bad request etc.

--URL database/server location (I used simple free Cloudant DB)
--user is the authentication part username:pass I entered through API pass
-X defines what command to call (PUT,GET,POST,DELETE)
-H content type - Cloudant is about document database, where JSON is used
--data content itself sorted as JSON


问:
Unhandled exceptions in Google Apps Script
I have created a public Web App with access to my private spreadsheet data. I can catch and log exceptions intry..catch, but:

is it possible to catch all unhandled exceptions, like browsers window.onerror?

can I view logs of unhandled exceptions somewhere?

by exceptions like "Service invoked too many times" my app is even not getting run, so here I definitely can`t handle the exceptions. Is there logs with such kind of exceptions?

These are so simple questions, so that I'm bit confused to ask them, but after hours of research I could not find the answers.

Thank you in advance.

答:
These are issues that are being addressed currently. Right now in the Apps Script Early Access Program are two new additions that handle these cases. The first is native integration with stackdriver logging and the addition of google.script.run.withLogger().

First off for now you need to apply for the EAP:

https://developers.google.com/apps-script/guides/apps-script-eap

Stackdriver Logging:

To log to stackdriver the console object has been added to the server side.

code.gs

```<code>console.log('This will log to stackdriver')
</code>```

Check out the docs for all the methods of console.

https://developers.google.com/apps-script/guides/logging#stackdriver_logging

Example from the docs:

```<code>function measuringExecutionTime() {
  // A simple INFO log message, using sprintf() formatting.
  console.info('Timing the %s function (%d arguments)', 'myFunction', 1);

  // Log a JSON object at a DEBUG level. The log is labeled
  // with the message string in the log viewer, and the JSON content
  // is displayed in the expanded log structure under "structPayload".
  var parameters = {
      isValid: true,
      content: 'some string',
      timestamp: new Date()
  };
  console.log({message: 'Function Input', initialData: parameters});

  var label = 'myFunction() time';  // Labels the timing log entry.
  console.time(label);              // Starts the timer.
  try {
    myFunction(parameters);         // Function to time.
  } catch (e) {
    // Logs an ERROR message.
    console.error('myFunction() yielded an error: ' + e);
  }
  console.timeEnd(label);
  }
</code>```

In addition you can also check Log Exceptions in the scripts properties. This will generate a stackdriver entry every time any error occurs in your script.

Error recovery in a web app

To recover in a web app from a failure you have access to the withFailureHandler() method found in the google.script.run object. With this you can register a callback in the event your script hits an exception.

Full documentation can be found at:

https://developers.google.com/apps-script/guides/html/reference/run

If you are doing server side checks with try...catch you may be getting an exception but gracefully handling it. In this case withFailureHandler() will not execute and onSuccessHandler() propably isnt the best place to handle errors. In the EAP there is now a withLogger method to google.script.run. For now there no documentation for google.script.run.withLogger(). I found it by digging through devtools. withLogger() allows you to register a function as a callback when ever a stackdriver entry is created. This is particularly helpful when you have log exceptions checked in your script properties. In this sense it is a bit like withFailureHandler() but it can be triggered by any stackdriver entry you add though the server-side console object.

index.html

```<code><script>
  google.script.run
        .withSuccessHandler(function(){console.log('OK')})
        .withFailureHandler(function(e){console.error(e)})
        .withLogger(function(e){console.warn("The following log was generated:"+e)})
        .serverFunctionCall();
</script>
</code>```

code.gs

```<code>function serverFunctionCall(){
   console.log("This log will generate a callback");
   return true;

}
</code>```

Body:
These are issues that are being addressed currently. Right now in the Apps Script Early Access Program are two new additions that handle these cases. The first is native integration with stackdriver logging and the addition of google.script.run.withLogger().

First off for now you need to apply for the EAP:

https://developers.google.com/apps-script/guides/apps-script-eap

Stackdriver Logging:

To log to stackdriver the console object has been added to the server side.

code.gs

console.log('This will log to stackdriver')

Check out the docs for all the methods of console.

https://developers.google.com/apps-script/guides/logging#stackdriver_logging

Example from the docs:

function measuringExecutionTime() {
  // A simple INFO log message, using sprintf() formatting.
  console.info('Timing the %s function (%d arguments)', 'myFunction', 1);

  // Log a JSON object at a DEBUG level. The log is labeled
  // with the message string in the log viewer, and the JSON content
  // is displayed in the expanded log structure under "structPayload".
  var parameters = {
      isValid: true,
      content: 'some string',
      timestamp: new Date()
  };
  console.log({message: 'Function Input', initialData: parameters});

  var label = 'myFunction() time';  // Labels the timing log entry.
  console.time(label);              // Starts the timer.
  try {
    myFunction(parameters);         // Function to time.
  } catch (e) {
    // Logs an ERROR message.
    console.error('myFunction() yielded an error: ' + e);
  }
  console.timeEnd(label);
  }

In addition you can also check Log Exceptions in the scripts properties. This will generate a stackdriver entry every time any error occurs in your script.

Error recovery in a web app

To recover in a web app from a failure you have access to the withFailureHandler() method found in the google.script.run object. With this you can register a callback in the event your script hits an exception.

Full documentation can be found at:

https://developers.google.com/apps-script/guides/html/reference/run

If you are doing server side checks with try...catch you may be getting an exception but gracefully handling it. In this case withFailureHandler() will not execute and onSuccessHandler() propably isnt the best place to handle errors. In the EAP there is now a withLogger method to google.script.run. For now there no documentation for google.script.run.withLogger(). I found it by digging through devtools. withLogger() allows you to register a function as a callback when ever a stackdriver entry is created. This is particularly helpful when you have log exceptions checked in your script properties. In this sense it is a bit like withFailureHandler() but it can be triggered by any stackdriver entry you add though the server-side console object.

index.html

<script>
  google.script.run
        .withSuccessHandler(function(){console.log('OK')})
        .withFailureHandler(function(e){console.error(e)})
        .withLogger(function(e){console.warn("The following log was generated:"+e)})
        .serverFunctionCall();
</script>

code.gs

function serverFunctionCall(){
   console.log("This log will generate a callback");
   return true;

}


问:
UWP: Add styling to specific words in textblock
I have a couple of strings in a resource file, which all needs to be translated. These strings will be concatenated into one sentence and displayed inside a TextBlock in my app and I would like to make some of the strings bold inside the TextBlock.
E.g.

```<code>string a = "This {0} a {1} string.";
string b = "is";
string c = "formatted";
string output = string.Format(a, b, c);
</code>```

And I would like the output to be: This is a formatted string.

Any hints and tips are welcome.

答:
Here you can find a lot of information about styling a textblock: http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/

I recommended using the span approach for your problem since you want to work in program code

Good Luck

Body:
I have a couple of strings in a resource file, which all needs to be translated. These strings will be concatenated into one sentence and displayed inside a TextBlock in my app and I would like to make some of the strings bold inside the TextBlock.
E.g.

string a = "This {0} a {1} string.";
string b = "is";
string c = "formatted";
string output = string.Format(a, b, c);

And I would like the output to be: This is a formatted string.

Any hints and tips are welcome.


问:
Random string in PHP not enough characters
I'm trying to make some random string in PHP with 5 letters/numbers.
It's working fine but sometimes I get a shorter string.

```<code>$characterset='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$count=0;
$lenght=strlen($characterset);
$i=5; #number of characters
while($count < $i){
  $num=rand(1,$lenght);
  $letter=substr($characterset, $num, 1);
  $string.=$letter;
  $count++;
}
</code>```

And strlen($string) is sometimes 4  (checked 100 records, 85 was 4 characters)

答:
String characters, like arrays, start counting from zero. Run your code a bunch of times: in addition to sometimes getting not enough characters, notice how you never get an A in there?

$num = rand(0,$lenght-1); will do it.

As an alternative method, you could do this:

```<code>$max_b36 = str_repeat("Z",$number_of_characters);
$max_dec = base_convert($max_b36,36,10);
$rand_dec = rand(0,$max_dec);
$rand_b36 = base_convert($rand_dex,10,36);
$result = sprintf("%0".$number_of_characters."s",$rand_b36);
</code>```

This method uses (potentially) big numbers though, so it will only support 5 characters (on 32-bit systems) or 12 characters (on 64-bit systems).

Body:
I'm trying to make some random string in PHP with 5 letters/numbers.
It's working fine but sometimes I get a shorter string.

$characterset='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$count=0;
$lenght=strlen($characterset);
$i=5; #number of characters
while($count < $i){
  $num=rand(1,$lenght);
  $letter=substr($characterset, $num, 1);
  $string.=$letter;
  $count++;
}

And strlen($string) is sometimes 4  (checked 100 records, 85 was 4 characters)

Body:
String characters, like arrays, start counting from zero. Run your code a bunch of times: in addition to sometimes getting not enough characters, notice how you never get an A in there?

$num = rand(0,$lenght-1); will do it.

As an alternative method, you could do this:

$max_b36 = str_repeat("Z",$number_of_characters);
$max_dec = base_convert($max_b36,36,10);
$rand_dec = rand(0,$max_dec);
$rand_b36 = base_convert($rand_dex,10,36);
$result = sprintf("%0".$number_of_characters."s",$rand_b36);

This method uses (potentially) big numbers though, so it will only support 5 characters (on 32-bit systems) or 12 characters (on 64-bit systems).


问:
Why i can not change text view value in fragment?
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

```<code><TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</code>```

In fragment I wrote this simple method:

```<code>public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }
</code>```

I call that method in activity:

```<code>Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();
</code>```

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code

答:
In Your Fragment I hope you called your setText() method in onCreateView method of Your Fragment

In your Activity

```<code>Your_Button.setOnClickListener(new View.OnClickListener(){
 public void onClick(View v){
    Your_Fragment fragmentObject = new Fragment();
    fragmentObject.setTest();
 }
}
</code>```

I hope this will work

Body:
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

<TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

In fragment I wrote this simple method:

public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }

I call that method in activity:

Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code

Body:
In Your Fragment I hope you called your setText() method in onCreateView method of Your Fragment

In your Activity

Your_Button.setOnClickListener(new View.OnClickListener(){
 public void onClick(View v){
    Your_Fragment fragmentObject = new Fragment();
    fragmentObject.setTest();
 }
}

I hope this will work