问:
why spanish word not search properly in full text index with exacet match
I have use full text index in my food search and in a food table records are multilingual so i have search with "jamón" (Spanish language) food but it's search end of list and not showing first and show other English language(jamon food) food in top of list so how can i search exact match first then other without take too much time in search query
My code like this

```<code>$food_data = Nutrition::whereRaw("MATCH(brand_with_name) AGAINST (? IN NATURAL LANGUAGE MODE)", [$item])
            ->with('guNutrition', 'esNutrition')
            ->limit($per_page)
            ->offset($off_set)
            ->get();
</code>```

I have use Laravel and Mysql for my app.

I try with following code but it take too much time and not working proper(not showing exact match first then other) with Spanish. only working proper with English

```<code>$food_data = Nutrition::whereRaw("MATCH(brand_with_name) AGAINST (? IN NATURAL LANGUAGE MODE)", [$item])
                            ->select('*',\DB::raw('CASE WHEN brand_with_name = "' . $item . '" THEN 1 ELSE 0 END AS score'),\DB::raw('MATCH(brand_with_name) AGAINST ("' . $item . '") AS score2'))
                            ->with('guNutrition', 'esNutrition')
                            ->orderBy('score', 'DESC')
                            ->orderBy('score2', 'DESC')
                            ->limit($per_page)
                            ->offset($off_set)
                            ->get();
</code>```

答:
The issue is because of inappropriate Character sets & collations. If your searches on that field are always going to be accent-sensitive, then declare the collation of the field as utf8_bin (that'll compare for equality the utf8-encoded bytes) or use a language specific collation that distinguish between the accented and un-accented characters.

In my version (MySql 5.0), there is not available any utf8 charset collate for case insensitive, accent sensitive searches. The only accent sensitive collate for utf8 is utf8_bin. However it is also case sensitive.

Ex:

```<code>SELECT * FROM `words` WHERE LOWER(column) = LOWER('aBád') COLLATE utf8_bin
</code>```

Reference 1

Reference 2

Body:
I have use full text index in my food search and in a food table records are multilingual so i have search with "jamón" (Spanish language) food but it's search end of list and not showing first and show other English language(jamon food) food in top of list so how can i search exact match first then other without take too much time in search query
My code like this

$food_data = Nutrition::whereRaw("MATCH(brand_with_name) AGAINST (? IN NATURAL LANGUAGE MODE)", [$item])
            ->with('guNutrition', 'esNutrition')
            ->limit($per_page)
            ->offset($off_set)
            ->get();

I have use Laravel and Mysql for my app.

I try with following code but it take too much time and not working proper(not showing exact match first then other) with Spanish. only working proper with English

$food_data = Nutrition::whereRaw("MATCH(brand_with_name) AGAINST (? IN NATURAL LANGUAGE MODE)", [$item])
                            ->select('*',\DB::raw('CASE WHEN brand_with_name = "' . $item . '" THEN 1 ELSE 0 END AS score'),\DB::raw('MATCH(brand_with_name) AGAINST ("' . $item . '") AS score2'))
                            ->with('guNutrition', 'esNutrition')
                            ->orderBy('score', 'DESC')
                            ->orderBy('score2', 'DESC')
                            ->limit($per_page)
                            ->offset($off_set)
                            ->get();

Body:
The issue is because of inappropriate Character sets & collations. If your searches on that field are always going to be accent-sensitive, then declare the collation of the field as utf8_bin (that'll compare for equality the utf8-encoded bytes) or use a language specific collation that distinguish between the accented and un-accented characters.

In my version (MySql 5.0), there is not available any utf8 charset collate for case insensitive, accent sensitive searches. The only accent sensitive collate for utf8 is utf8_bin. However it is also case sensitive.

Ex:

SELECT * FROM `words` WHERE LOWER(column) = LOWER('aBád') COLLATE utf8_bin

Reference 1

Reference 2


来源: stackexchange

问:
Application_BeginRequest not being fired in stressed environment
We are obesrving strange problems when performing sress test of our applciation. We use Application_BeginRequest and Application_EndRequest to log the beginning and end of the web request, together, with the thread id.

However, from our logs, we see that Application_Begin_REquest is not being fired:

We use the following code to do the logging in global.asax.cs:

```<code>protected void Application_BeginRequest(object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("Request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));

  // integration calls measurement
  HttpContext.Current.Items.Add("wcfElapsed", new TimeSpan());

}

protected void Application_EndRequest(Object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("End request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));
}
</code>```

This is our log file. Urls are omitted The 00013 column is thread id.

```<code>  14.12.10 21:41:25.042 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.068 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:25.212 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.223 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:30.974 00013 00000            End request: 172.23.26.88
</code>```

You can see that there are two "End request" in the last two lines, but there is no (Begin) Request for the last log line.

Our Dbg.WriteLine uses System.Diagnostics trace listeners to ouput data to the file.

Environment: Windows Server 2008 R2, ASP.NET 3.5

This only happens when performin stress test. CPU utilization is around 60%, there are max 10 concurent requests executing.

Any ideas, what could be wrong?

UPDATE: I have found out that some other also did have similar problems (althoug in different configuration: http://forums.iis.net/t/1154954.aspx)
Matej

UPDATE#2: This night be related to fact, that Thread.GetHashCode() which is used to print out the thread identifier in our log fies could change. See ASP.NET - Thread.GetHashCode() changes

答:
It's probably not that the BeginRequest is not firing so much as there may be an unhandled unexception that is causing System.Diagnostics to crash without terminating the request.

The best way I could recommend to find the problem would be to install IIS Debug Diagnostics and run a crash or hang report. You won't like it much because the thing gathers tons and tons of data, but if there is some sort of thread crash/hang it will definitely catch it.

Edit:

While implementing a backup logging event directly to a custom Event Log in the system event log, we found that under heavy stress the requests for permission to access the log were causing latency (our guess was that after a certain number of requests the active directory connector was unable to respond in a timely fashion) and ultimately exceptions. This appeared to run on a separate thread which we could see dumping. W3wp.exe continued to function and the page fulfilled its response duties, but we found that of 3 events that should have been logged, the events getting logged were inconsistent. We also found that the event log itself would become busy and throw an exception. We found this one because from time to time this exception presented itself to the user interface instead of vanishing with the others. Our end solution was to use a local account to provide permission to the library to reduce the requests on the domain policy. This even cleared up the event log being busy symptom. At that point we were so happy it was gone we did not pursue it further.

ContentLicense: CC BY-SA 2.5

Body:
We are obesrving strange problems when performing sress test of our applciation. We use Application_BeginRequest and Application_EndRequest to log the beginning and end of the web request, together, with the thread id.

However, from our logs, we see that Application_Begin_REquest is not being fired:

We use the following code to do the logging in global.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("Request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));

  // integration calls measurement
  HttpContext.Current.Items.Add("wcfElapsed", new TimeSpan());

}

protected void Application_EndRequest(Object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("End request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));
}

This is our log file. Urls are omitted The 00013 column is thread id.

  14.12.10 21:41:25.042 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.068 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:25.212 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.223 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:30.974 00013 00000            End request: 172.23.26.88

You can see that there are two "End request" in the last two lines, but there is no (Begin) Request for the last log line.

Our Dbg.WriteLine uses System.Diagnostics trace listeners to ouput data to the file.

Environment: Windows Server 2008 R2, ASP.NET 3.5

This only happens when performin stress test. CPU utilization is around 60%, there are max 10 concurent requests executing.

Any ideas, what could be wrong?

UPDATE: I have found out that some other also did have similar problems (althoug in different configuration: http://forums.iis.net/t/1154954.aspx)
Matej

UPDATE#2: This night be related to fact, that Thread.GetHashCode() which is used to print out the thread identifier in our log fies could change. See ASP.NET - Thread.GetHashCode() changes


问:
JavaScript keycodes are not working in Firefox
I am using JavaScript keycodes, they are not working in Firefox but working in Chrome and IE. I have debugged the code in front end for Firefox I am getting keycode as 0.

This is my code:

```<code>$scope.Validate = function(event,indexVal){
    if ((event.keyCode > 64 && event.keyCode < 91)|| (event.keyCode > 159 && event.keyCode < 166) || (event.keyCode > 96 && event.keyCode < 123) || (event.keyCode == 165) ||(event.keyCode == 32)
                        || (event.keyCode == 164) || (event.keyCode == 130) || (event.keyCode == 181) || (event.keyCode == 144) || (event.keyCode == 214) ||
                        (event.keyCode == 224) ||(event.keyCode == 233)) {
                }else{
                    event.preventDefault();
                }
}
</code>```

Can you please suggest a way to achieve this functionality in Firefox too.

答:
It's working but slightly different

```<code>$scope.Validate = function (event, indexVal) {
    var code = event.which || event.keyCode;

    if (!(
            (code > 64 && code < 91)
            || (code > 159 && code < 166)
            || (code > 96 && code < 123)
            || ~[165, 32, 164, 130, 181, 144, 214, 224, 233].indexOf(code)
    )) {
        event.preventDefault();
    }
}
</code>```

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Deprecated KeyboardEvent.keyCode
  This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

ContentLicense: CC BY-SA 3.0

Body:
I am using JavaScript keycodes, they are not working in Firefox but working in Chrome and IE. I have debugged the code in front end for Firefox I am getting keycode as 0.

This is my code:

$scope.Validate = function(event,indexVal){
    if ((event.keyCode > 64 && event.keyCode < 91)|| (event.keyCode > 159 && event.keyCode < 166) || (event.keyCode > 96 && event.keyCode < 123) || (event.keyCode == 165) ||(event.keyCode == 32)
                        || (event.keyCode == 164) || (event.keyCode == 130) || (event.keyCode == 181) || (event.keyCode == 144) || (event.keyCode == 214) ||
                        (event.keyCode == 224) ||(event.keyCode == 233)) {
                }else{
                    event.preventDefault();
                }
}

Can you please suggest a way to achieve this functionality in Firefox too.

Body:
It's working but slightly different

$scope.Validate = function (event, indexVal) {
    var code = event.which || event.keyCode;

    if (!(
            (code > 64 && code < 91)
            || (code > 159 && code < 166)
            || (code > 96 && code < 123)
            || ~[165, 32, 164, 130, 181, 144, 214, 224, 233].indexOf(code)
    )) {
        event.preventDefault();
    }
}

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Deprecated KeyboardEvent.keyCode
  This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


问:
How do I capture the IP address of a CLI-started EC2 instance for subsequent use?
I frequently need to start AWS EC2 instances to work with from the command line to work with over SSH, and would like to write a short script to do this, but I'm stuck at the most basic steps.

For example, I can get started with

```<code>aws ec2 start-instances --instance-ids i-84Sd8jdf
</code>```

and would like to continue by grabbing the IP address assigned to the instance and using it as an environment variable or script variable to preform subsequent operations such as

```<code>ssh ubuntu@<theIP>
</code>```

or

```<code>scp ubuntu@<theIP>:~/soruce_stuff/* ~/dest_folder/
</code>```

but I can't figure out how to get the IP address from the start-instances command, or from any of the JSON emitted by other commands.

How do I script starting of EC2 instances, wearing for the IP to be assigned, and capturing the assigned IP address for subsequent use?

答:
Amazon offers wait condition to wait for the instance to be ready before you can perform other tasks on it. Here is an example might help you</p>

```<code>aws ec2 start-instances --instance-ids $instance_id
aws ec2 wait instance-running --instance-ids $instance_id
aws ec2 describe-instances --instance-ids $instance_id --output text|grep ASSOCIATION |awk '{print $3}'|head -1
</code>```

Body:
I frequently need to start AWS EC2 instances to work with from the command line to work with over SSH, and would like to write a short script to do this, but I'm stuck at the most basic steps.

For example, I can get started with

aws ec2 start-instances --instance-ids i-84Sd8jdf

and would like to continue by grabbing the IP address assigned to the instance and using it as an environment variable or script variable to preform subsequent operations such as

ssh ubuntu@<theIP>

or

scp ubuntu@<theIP>:~/soruce_stuff/* ~/dest_folder/

but I can't figure out how to get the IP address from the start-instances command, or from any of the JSON emitted by other commands.

How do I script starting of EC2 instances, wearing for the IP to be assigned, and capturing the assigned IP address for subsequent use?

Body:
Amazon offers wait condition to wait for the instance to be ready before you can perform other tasks on it. Here is an example might help you

aws ec2 start-instances --instance-ids $instance_id
aws ec2 wait instance-running --instance-ids $instance_id
aws ec2 describe-instances --instance-ids $instance_id --output text|grep ASSOCIATION |awk '{print $3}'|head -1


问:
Perl installation issue using Docker
I am trying to build the docker image with perl installation.

Dockerfile:

```<code>FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz

WORKDIR /shared/perl-5.22.1
RUN ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl

RUN make
RUN make test
RUN make install
</code>```

all these steps are executed i am can see it executing the make, make test and make install commands but when i do :

```<code>docker run -it testsh /bin/bash
</code>```

Error:

when I  check perl -v it says command not found.

and I need to go the perl directory
'cd perl-5.22.1' and run 'make install' again then perl -v works

But I want the perl installation to work when I build it with docker image. can anyone tell me what is going wrong here?

答:
At first glance I thought that when you run make install second time, it adds perl's bin directory to PATH env, but when I compared output of env before and after make install it showed the same PATH variable content.
The reason you getting perl -v working after make install in running container is that make install puts perl binary to /usr/bin/perl. I don't know why it works such way, but it is just as it is. Also, it's almost useless to store sources inside of your image.

Anyway, I agree with @belwood suggestion about adding your perl's bin directiry to PATH environment variable. I just wanna correct the path: /opt/perl-5.22.1/localperl/bin

You need to add it in your Dockerfile (basically I've rewritten your file to make it produce more efficient image), for example:

```<code>FROM amazonlinux

RUN mkdir -p /shared/perl-5.22.1
WORKDIR /shared/perl-5.22.1

RUN yum -y install gcc \
  && curl -SL http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz -o perl-5.22.1.tar.gz \
  && tar --strip-components=1 -xzf perl-5.22.1.tar.gz \
  && rm perl-5.22.1.tar.gz \
  && ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl \
  && make -j $(nproc) \
  && make -j $(nproc) test \
  && make install \
  && rm -fr /shared/perl-5.22.1 /tmp/*

ENV PATH="/opt/perl-5.22.1/localperl/bin:$PATH"
WORKDIR /root

CMD ["perl","-de0"]
</code>```

When you simply run container with this image, you'll immediately get into perl's shell. If you need bash, then use docker run -it --rm amazon-perl /bin/bash

It would be also good to look at Environment replacement section in the Dockerfile reference documentation, just to figure out how things work. For example, it isn't a best pratice to have that many RUN lines in your Dockerfile because of the RUN instruction will execute commands in a new layer on top of the current image and commit the results. So you'll get many unnecessary layers.

Title: Perl installation issue using Docker

Body:
I am trying to build the docker image with perl installation.

Dockerfile:

FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz

WORKDIR /shared/perl-5.22.1
RUN ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl

RUN make
RUN make test
RUN make install

all these steps are executed i am can see it executing the make, make test and make install commands but when i do :

docker run -it testsh /bin/bash

Error:

when I  check perl -v it says command not found.

and I need to go the perl directory
'cd perl-5.22.1' and run 'make install' again then perl -v works

But I want the perl installation to work when I build it with docker image. can anyone tell me what is going wrong here?

Body:
At first glance I thought that when you run make install second time, it adds perl's bin directory to PATH env, but when I compared output of env before and after make install it showed the same PATH variable content.
The reason you getting perl -v working after make install in running container is that make install puts perl binary to /usr/bin/perl. I don't know why it works such way, but it is just as it is. Also, it's almost useless to store sources inside of your image.

Anyway, I agree with @belwood suggestion about adding your perl's bin directiry to PATH environment variable. I just wanna correct the path: /opt/perl-5.22.1/localperl/bin

You need to add it in your Dockerfile (basically I've rewritten your file to make it produce more efficient image), for example:

FROM amazonlinux

RUN mkdir -p /shared/perl-5.22.1
WORKDIR /shared/perl-5.22.1

RUN yum -y install gcc \
  && curl -SL http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz -o perl-5.22.1.tar.gz \
  && tar --strip-components=1 -xzf perl-5.22.1.tar.gz \
  && rm perl-5.22.1.tar.gz \
  && ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl \
  && make -j $(nproc) \
  && make -j $(nproc) test \
  && make install \
  && rm -fr /shared/perl-5.22.1 /tmp/*

ENV PATH="/opt/perl-5.22.1/localperl/bin:$PATH"
WORKDIR /root

CMD ["perl","-de0"]

When you simply run container with this image, you'll immediately get into perl's shell. If you need bash, then use docker run -it --rm amazon-perl /bin/bash

It would be also good to look at Environment replacement section in the Dockerfile reference documentation, just to figure out how things work. For example, it isn't a best pratice to have that many RUN lines in your Dockerfile because of the RUN instruction will execute commands in a new layer on top of the current image and commit the results. So you'll get many unnecessary layers.


问:
document.getElementById not working on jquery load
I've loaded an  html file with jquery load function

in my profile.blade.php

```<code> <script type="text/javascript">
      $(document).ready(function(){
         $("#newJob").load('/company/new-job');
      });
    </script>
   <script src="js/location.js"></script>
</code>```

in my location.js  i am  using

document.getElementById('autocomplete') for getting an html element

but this element is in company/new-job file

the problem i got undefined error in document.getElementById('autocomplete') this part

when i directly include the location.js its working fine

答:
Try using load's callback function to insert the script you wish:

```<code>$(document).ready(function(){
    $("#newJob").load('/company/new-job', null, function(){
        $.getScript('js/location.js');
    });
});
</code>```

Body:
I've loaded an  html file with jquery load function

in my profile.blade.php

in my location.js  i am  using

document.getElementById('autocomplete') for getting an html element

but this element is in company/new-job file

the problem i got undefined error in document.getElementById('autocomplete') this part

when i directly include the location.js its working fine

Body:
Try using load's callback function to insert the script you wish:

$(document).ready(function(){
    $("#newJob").load('/company/new-job', null, function(){
        $.getScript('js/location.js');
    });
});


问:
Codeigniter upload image file with array field name
I'm quite new to the codeigniter library and function. Recently i had a form that had a few dynamic input field to be submit and insert into database for recording purpose.

The image upload file field was dynamically created if user click "+" button, and i was using array name as the name for the input field. However when i trying to call the controller to upload the file or insert with the array field name, it keep prompted me 'You did not select a file to upload'.

If i change the image field's input name to only 'reg_photo' and the do upload field name to 'reg_photo' then everything working fine but that is not i wanted because i wanted to upload it based on the dynamic input array.

I did try to look around the solution at stackoverflow and google but after i try and none of it could help me.

Here are my Controller to do the upload :

```<code> //Upload Picture Configuration
        $config['upload_path']          = './uploads/profile_picture/';
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 2048;
        $config['max_width']            = 1920;
        $config['max_height']           = 1080;
        $this->load->library('upload', $config);

        //Check and get the Areas list
        $areaList = $this->input->post('areas', true);
        $finalSeparator = $areaList;
        $resultArea = "";
        foreach ($finalSeparator as $i => $a) {
            if (next($finalSeparator )) {
                $resultArea .= $a.','; // Add comma for all elements instead of last
            }
            else
            {
                $resultArea .= $a;
            }
        }

        if ($this->input->post('reg_name')) { // returns false if no property

            //Get Last Inserted District ID
            $district = "";
            $failedUploadNameList = "";
            $photoPath = "";
            $data = array(
                'district_code' => $this->input->post('reg_district_2', true),
                'district_country' => '',
            );
            $this->db->set('district_registered_date', 'NOW()', FALSE); //Submit current date time
            if($this->Registerlanguage_admin_model->register_district($data))
            {
                $district = $this->db->insert_id(); //Last Get ID

                $name = $this->input->post('reg_name', true);
                $year1 = $this->input->post('reg_year1', true);
                $year2 = $this->input->post('reg_year2', true);
                $nickname = $this->input->post('reg_nickname', true);
                $photo = $this->input->post('reg_photo', true);

                foreach ($name as $i => $a) { // need index to match other properties

                    //Check to whether can upload image or not
                    if ( ! $this->upload->do_upload($photo[$i]))
                    {
                        $error = array('error' => $this->upload->display_errors());
                        foreach($error as $q)
                        {
                            $failedUploadNameList .= $q;
                        }
                    }
                    else
                    {
                        $data = array('upload_data' => $this->upload->data('file_name'));

                        foreach($data as $a)
                        {
                            $photoPath = $config['upload_path'].$a;
                        }
                    }
                    $data = array(
                        'area_district_id' => $district,
                        'area_name' => $resultArea,
                        'area_language' =>  $this->input->post('reg_language', true),
                        'area_year_1' => isset($year1[$i]) ? $year1[$i] : '',
                        'area_year_2' => isset($year2[$i]) ? $year2[$i] : '',
                        'area_leader_name' => isset($name[$i]) ? $name[$i] : '',
                        'area_leader_nickname' => isset($nickname[$i]) ? $nickname[$i] : '',
                        'area_leader_photo' => $photoPath
                    );
                    $this->db->set('area_registered_date', 'NOW()', FALSE); //Submit current date time
                    if (!$this->Registerlanguage_admin_model->register_area($data)) {
                        // quit if insert fails - adjust accordingly
                        $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
                        redirect('index.php/language_admin/index');
                    }
                }
            }
            else{
                // don't redirect inside the loop
                $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
                redirect('index.php/language_admin/index');
            }

            //Redirect back once all successfully insert
            $this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Insert Successfully!</div>'.$failedUploadNameList);
            redirect('index.php/language_admin/index');
        }
        else{

            // don't redirect inside the loop
            $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
            redirect('index.php/language_admin/index');
        }
</code>```

Here are my view code :

```<code> <?php $attributes = array("name" => "registerdistrictform");
                            echo form_open_multipart("index.php/registerlanguage_admin/registerDistrict", $attributes);?>
                            <div class="panel panel-default">
                                <div class="panel panel-info">
                                    <div class="panel-body  panel-group">
                                        <div class="form-group">
                                            <input class="form-control" name="reg_language" type="hidden" value="Japanese" />
                                            <label for="concept" class="col-sm-3 control-label">District ：</label>
                                            <div class="col-sm-9">
                                                <input class="form-control" name="reg_district_1" placeholder="Ex : District 3500" type="text" value="<?php echo set_value('reg_district_1'); ?>" required/>
                                                <span class="text-danger"><?php echo form_error('reg_district_1'); ?></span><br/>
                                                <input class="form-control" name="reg_district_2" placeholder="Ex : 3500" type="text" value="<?php echo set_value('reg_district_2'); ?>" required/>
                                                <span class="text-danger"><?php echo form_error('reg_district_2'); ?></span><br/>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="concept" class="col-sm-3 control-label">Area ：</label>
                                            <div id="areaContainer">
                                                <div class="col-sm-6">
                                                    Area Record #0<input class="form-control" name="areas[]" placeholder="Your Language" type="text" value="" required/>
                                                </div>
                                                <div class="col-sm-3">
                                                    <a href="#" class="btn btn-primary" id="addArea">+</a><br/>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id = "profileContainer">
                                    <div class="panel panel-danger">
                                        <div class="panel-heading">Profile #0</div>
                                        <div class="panel-body  panel-group">
                                            <div class="form-group">
                                                <label for="concept" class="col-sm-3 control-label">Years ：</label>
                                                <div class="col-sm-4">
                                                    <input class="form-control" name="reg_year1[]" placeholder="2015" type="text" value="" required/>
                                                </div>
                                                <div class="col-sm-1">
                                                    <i class="fa fa-arrow-right" aria-hidden="true" ></i>
                                                </div>
                                                <div class="col-sm-4">
                                                    <input class="form-control" name="reg_year2[]" placeholder="2017" type="text" value="" required/><br/>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label for="concept" class="col-sm-12 control-label"><u>District Governer</u></label><br/>
                                                <label for="concept" class="col-sm-3 control-label">Name ：</label>
                                                <div class="col-sm-9">
                                                    <input class="form-control" name="reg_name[]" placeholder="Your Language" type="text" required/><br/>
                                                </div>
                                                <label for="concept" class="col-sm-3 control-label">Nickname ：</label>
                                                <div class="col-sm-9">
                                                    <input class="form-control" name="reg_nickname[]" placeholder="English" type="text" required/><br/>
                                                </div>
                                                <label for="concept" class="col-sm-3 control-label">Photo ：</label>
                                                <div class="col-sm-9">
                                                    <input class="form-control" name="reg_photo[]" type="file" required/><br/>
                                                </div>
                                            </div>
                                            <div class="pull-right">
                                                <a href="#" class="btn btn-primary" id="addProfile">+</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="panel-body  panel-group">
                                    <div class="form-group">
                                        <div class="col-sm-1 text-left">
                                            <button name="submit" type="submit" class="btn btn-info btn-lg" >Submit</button>
                                            <!--                <button name="cancel" type="reset" class="btn btn-info">Cancel</button>-->
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php echo form_close(); ?>
                        </div>
</code>```

The 'reg_photo[]' are dynamically insert into HTML if user press the '+' button, so if i change to 'reg_photo' which is not dynamic anymore then it work, what should i do if i wanted to use the 'reg_photo[]' as a field name to upload my file? Please guide me through this. Thank! :)

答:
Try this code to upload image

```<code>     $directory = "./images/";
     $config['upload_path']   = $directory;
     $config['encrypt_name'] = TRUE;
     $config['allowed_types'] = 'gif|jpg|png|jpeg';
     if (!$this->upload->do_upload('mainimage'))
     {
        $error = array('error' => $this->upload->display_errors());
        print_r($error);
     }
     else {
        $data = array('upload_data' => $this->upload->data());
        print_r($data);
     }
</code>```

And one other change is :
Replace upload.php file.
take latest verison upload.php file from system directory -> libraries directory -> upload.php. Copy new version upload.php file and replace in your project

Hope it will work properly.

Body:
I'm quite new to the codeigniter library and function. Recently i had a form that had a few dynamic input field to be submit and insert into database for recording purpose.

The image upload file field was dynamically created if user click "+" button, and i was using array name as the name for the input field. However when i trying to call the controller to upload the file or insert with the array field name, it keep prompted me 'You did not select a file to upload'.

If i change the image field's input name to only 'reg_photo' and the do upload field name to 'reg_photo' then everything working fine but that is not i wanted because i wanted to upload it based on the dynamic input array.

I did try to look around the solution at stackoverflow and google but after i try and none of it could help me.

Here are my Controller to do the upload :

 //Upload Picture Configuration
        $config['upload_path']          = './uploads/profile_picture/';
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 2048;
        $config['max_width']            = 1920;
        $config['max_height']           = 1080;
        $this->load->library('upload', $config);

        //Check and get the Areas list
        $areaList = $this->input->post('areas', true);
        $finalSeparator = $areaList;
        $resultArea = "";
        foreach ($finalSeparator as $i => $a) {
            if (next($finalSeparator )) {
                $resultArea .= $a.','; // Add comma for all elements instead of last
            }
            else
            {
                $resultArea .= $a;
            }
        }

        if ($this->input->post('reg_name')) { // returns false if no property

            //Get Last Inserted District ID
            $district = "";
            $failedUploadNameList = "";
            $photoPath = "";
            $data = array(
                'district_code' => $this->input->post('reg_district_2', true),
                'district_country' => '',
            );
            $this->db->set('district_registered_date', 'NOW()', FALSE); //Submit current date time
            if($this->Registerlanguage_admin_model->register_district($data))
            {
                $district = $this->db->insert_id(); //Last Get ID

                $name = $this->input->post('reg_name', true);
                $year1 = $this->input->post('reg_year1', true);
                $year2 = $this->input->post('reg_year2', true);
                $nickname = $this->input->post('reg_nickname', true);
                $photo = $this->input->post('reg_photo', true);

                foreach ($name as $i => $a) { // need index to match other properties

                    //Check to whether can upload image or not
                    if ( ! $this->upload->do_upload($photo[$i]))
                    {
                        $error = array('error' => $this->upload->display_errors());
                        foreach($error as $q)
                        {
                            $failedUploadNameList .= $q;
                        }
                    }
                    else
                    {
                        $data = array('upload_data' => $this->upload->data('file_name'));

                        foreach($data as $a)
                        {
                            $photoPath = $config['upload_path'].$a;
                        }
                    }
                    $data = array(
                        'area_district_id' => $district,
                        'area_name' => $resultArea,
                        'area_language' =>  $this->input->post('reg_language', true),
                        'area_year_1' => isset($year1[$i]) ? $year1[$i] : '',
                        'area_year_2' => isset($year2[$i]) ? $year2[$i] : '',
                        'area_leader_name' => isset($name[$i]) ? $name[$i] : '',
                        'area_leader_nickname' => isset($nickname[$i]) ? $nickname[$i] : '',
                        'area_leader_photo' => $photoPath
                    );
                    $this->db->set('area_registered_date', 'NOW()', FALSE); //Submit current date time
                    if (!$this->Registerlanguage_admin_model->register_area($data)) {
                        // quit if insert fails - adjust accordingly
                        $this->session->set_flashdata('msg','
Oops! Error.  Please try again later!!!
');
                        redirect('index.php/language_admin/index');
                    }
                }
            }
            else{
                // don't redirect inside the loop
                $this->session->set_flashdata('msg','
Oops! Error.  Please try again later!!!
');
                redirect('index.php/language_admin/index');
            }

            //Redirect back once all successfully insert
            $this->session->set_flashdata('msg','
You are Insert Successfully!
'.$failedUploadNameList);
            redirect('index.php/language_admin/index');
        }
        else{

            // don't redirect inside the loop
            $this->session->set_flashdata('msg','
Oops! Error.  Please try again later!!!
');
            redirect('index.php/language_admin/index');
        }

Here are my view code :

 <?php $attributes = array("name" => "registerdistrictform");
                            echo form_open_multipart("index.php/registerlanguage_admin/registerDistrict", $attributes);?>

                                            <input class="form-control" name="reg_language" type="hidden" value="Japanese" />
                                            District ：

                                                <input class="form-control" name="reg_district_1" placeholder="Ex : District 3500" type="text" value="<?php echo set_value('reg_district_1'); ?>" required/>
                                                <?php echo form_error('reg_district_1'); ?>

                                                <input class="form-control" name="reg_district_2" placeholder="Ex : 3500" type="text" value="<?php echo set_value('reg_district_2'); ?>" required/>
                                                <?php echo form_error('reg_district_2'); ?>

                                            Area ：

                                                    Area Record #0<input class="form-control" name="areas[]" placeholder="Your Language" type="text" value="" required/>

                                                    +

Profile #0

                                                Years ：

                                                    <input class="form-control" name="reg_year1[]" placeholder="2015" type="text" value="" required/>

                                                    <input class="form-control" name="reg_year2[]" placeholder="2017" type="text" value="" required/>

                                                District Governer

                                                Name ：

                                                    <input class="form-control" name="reg_name[]" placeholder="Your Language" type="text" required/>

                                                Nickname ：

                                                    <input class="form-control" name="reg_nickname[]" placeholder="English" type="text" required/>

                                                Photo ：

                                                    <input class="form-control" name="reg_photo[]" type="file" required/>

                                                +

                                            <button name="submit" type="submit" class="btn btn-info btn-lg" >Submit</button>

                            <?php echo form_close(); ?>

The 'reg_photo[]' are dynamically insert into HTML if user press the '+' button, so if i change to 'reg_photo' which is not dynamic anymore then it work, what should i do if i wanted to use the 'reg_photo[]' as a field name to upload my file? Please guide me through this. Thank! :)

Body:
Try this code to upload image

     $directory = "./images/";
     $config['upload_path']   = $directory;
     $config['encrypt_name'] = TRUE;
     $config['allowed_types'] = 'gif|jpg|png|jpeg';
     if (!$this->upload->do_upload('mainimage'))
     {
        $error = array('error' => $this->upload->display_errors());
        print_r($error);
     }
     else {
        $data = array('upload_data' => $this->upload->data());
        print_r($data);
     }

And one other change is :
Replace upload.php file.
take latest verison upload.php file from system directory -> libraries directory -> upload.php. Copy new version upload.php file and replace in your project

Hope it will work properly.


问:
Generate all quarters within a start date and end date
I have a table with of different campaigns. Each campaign has a start date and end date.

```<code>campaign id | start date | end date |
</code>```

I want to know during which quarters did these campaigns happen.

Ideally it would be something like this - under those quarter columns, It would show a binary variable of 0 and 1.

```<code>account id | campaign id | start date | end date | 2015q1 | 2015q2 | 2015q3 |...etc
</code>```

For example, if a campaign happens during 1/1/2015 - 5/2/2015, then the result would be:

```<code>| 2015q1 | 2015q2 | 2015q3 |
| 1      | 1      | 0      |
</code>```

I am using Amazon Redshift.

答:
When putting results into columns, you must hard-code values. For example, this input data:

```<code>id, start_date,end_date
1,2016-03-23,2016-07-18
2,2016-01-01,2016-01-02
3,2016-10-05,2016-11-05
4,2016-01-01,2016-12-31
</code>```

With this query:

```<code>SELECT
  id,
  start_date,
  end_date,
  (CASE WHEN start_date < '2016-04-01' AND end_date >= '2016-01-01' THEN 1 ELSE 0 END) as Q1_2016,
  (CASE WHEN start_date < '2016-07-01' AND end_date >= '2016-04-01' THEN 1 ELSE 0 END) as Q2_2016,
  (CASE WHEN start_date < '2016-10-01' AND end_date >= '2016-07-01' THEN 1 ELSE 0 END) as Q3_2016,
  (CASE WHEN start_date < '2017-01-01' AND end_date >= '2016-10-01' THEN 1 ELSE 0 END) as Q4_2016
FROM campaign
</code>```

Gives this result:

```<code>1   2016-03-23  2016-07-18  1   1   1   0
2   2016-01-01  2016-01-02  1   0   0   0
3   2016-10-05  2016-11-05  0   0   0   1
4   2016-01-01  2016-12-31  1   1   1   1
</code>```

Unfortunately, there is no SQL trickery that can auto-create the columns for you.

Body:
I have a table with of different campaigns. Each campaign has a start date and end date.

campaign id | start date | end date |

I want to know during which quarters did these campaigns happen.

Ideally it would be something like this - under those quarter columns, It would show a binary variable of 0 and 1.

account id | campaign id | start date | end date | 2015q1 | 2015q2 | 2015q3 |...etc

For example, if a campaign happens during 1/1/2015 - 5/2/2015, then the result would be:

| 2015q1 | 2015q2 | 2015q3 |
| 1      | 1      | 0      |

I am using Amazon Redshift.

Body:
When putting results into columns, you must hard-code values. For example, this input data:

id, start_date,end_date
1,2016-03-23,2016-07-18
2,2016-01-01,2016-01-02
3,2016-10-05,2016-11-05
4,2016-01-01,2016-12-31

With this query:

SELECT
  id,
  start_date,
  end_date,
  (CASE WHEN start_date < '2016-04-01' AND end_date >= '2016-01-01' THEN 1 ELSE 0 END) as Q1_2016,
  (CASE WHEN start_date < '2016-07-01' AND end_date >= '2016-04-01' THEN 1 ELSE 0 END) as Q2_2016,
  (CASE WHEN start_date < '2016-10-01' AND end_date >= '2016-07-01' THEN 1 ELSE 0 END) as Q3_2016,
  (CASE WHEN start_date < '2017-01-01' AND end_date >= '2016-10-01' THEN 1 ELSE 0 END) as Q4_2016
FROM campaign

Gives this result:

1   2016-03-23  2016-07-18  1   1   1   0
2   2016-01-01  2016-01-02  1   0   0   0
3   2016-10-05  2016-11-05  0   0   0   1
4   2016-01-01  2016-12-31  1   1   1   1

Unfortunately, there is no SQL trickery that can auto-create the columns for you.


问:
Reading configuration section Failed
I'm having a problem with some application. When I execute it in local disk all is right, but when I try to execute the same application from a shared resource (Z:\resource\TheApplication.exe) I got the following error:

```<code>Error occurred creating the configuration section handler for DOMAIN/DomainUserInfo: Request failed
</code>```

The error occurs when trying to read a custom section in the configuration file:

```<code>public static class AppConfigFile {
    public static IDomainUserInfo DomainUserInfo {
        get {
            if (_domainUserInfo == null) {
                _domainUserInfo = (DomainUserInfo)ConfigurationManager.GetSection(Environment.UserDomainName + @"/DomainUserInfo");
            } return _domainUserInfo as IDomainUserInfo;
        }
    }
}
public class DomainUserInfo : ConfigurationSection, IDomainUserInfo {
    [ConfigurationProperty("SomeConfiguration", IsRequired = true, DefaultValue = "")]
    public string SomeConfiguration { get { return (string)base["SomeConfiguration"]; } }

    [ConfigurationProperty("OtherConfiguration", IsRequired = true, DefaultValue = "")]
    public string OtherConfiguration { get { return (string)base["OtherConfiguration"]; } }
}
</code>```

The configuration file looks like:

```<code><configuration>
  <configSections>
    <sectionGroup name="THE_DOMAIN" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="DomainUserInfo" type="NameSpace.Other.DomainUserInfo,NameSpace.Other" requirePermission="false"/>
    </sectionGroup>
  </configSections>

    <THE_DOMAIN>
        <DomainUserInfo SomeConfiguration="SomeValue" OtherConfiguration="OtherValue"></DomainUserInfo>
    </THE_DOMAIN>
</configuration>
</code>```

Any ideas?

Thanks.

答: You haven't declared OtherConfiguration in your class. Therefore, you cannot have it as an attribute on the DomainUserInfo in your config.

Title: Reading configuration section Failed

Body:
I'm having a problem with some application. When I execute it in local disk all is right, but when I try to execute the same application from a shared resource (Z:\resource\TheApplication.exe) I got the following error:

Error occurred creating the configuration section handler for DOMAIN/DomainUserInfo: Request failed

The error occurs when trying to read a custom section in the configuration file:

public static class AppConfigFile {
    public static IDomainUserInfo DomainUserInfo {
        get {
            if (_domainUserInfo == null) {
                _domainUserInfo = (DomainUserInfo)ConfigurationManager.GetSection(Environment.UserDomainName + @"/DomainUserInfo");
            } return _domainUserInfo as IDomainUserInfo;
        }
    }
}
public class DomainUserInfo : ConfigurationSection, IDomainUserInfo {
    [ConfigurationProperty("SomeConfiguration", IsRequired = true, DefaultValue = "")]
    public string SomeConfiguration { get { return (string)base["SomeConfiguration"]; } }

    [ConfigurationProperty("OtherConfiguration", IsRequired = true, DefaultValue = "")]
    public string OtherConfiguration { get { return (string)base["OtherConfiguration"]; } }
}

The configuration file looks like:

<configuration>
  <configSections>
    <sectionGroup name="THE_DOMAIN" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>
  </configSections>

    <THE_DOMAIN>
        <DomainUserInfo SomeConfiguration="SomeValue" OtherConfiguration="OtherValue"></DomainUserInfo>
    </THE_DOMAIN>
</configuration>

Any ideas?

Thanks.


问:
How to render woff fonts in PhantomJS 2.1+ or headless Chrome?
I'm using PhantomJS 2.1.1 on CentOS with the example script rasterize.js just to reproduce the screenshot problem, which is to take a screenshot of a simple web-font demo site:

http://castellsonclaret.com/public/external/georgiapro/demo.htm

It should render like so (as taken using the SaaS PhantomJSCloud service):

However, with PhantomJS 2.1.1 locally I get

First I increased the script timeout to 10s just to be sure that isn't the issue.

Next I thought the css or fonts were blocked somehow from downloading. When I use tcpflow (it's like wireshark) before running phantomjs scripts I can see that the above web page is downloading the .woff fonts. However, they are not being rendered in the screenshot I'm taking.

When I run the following before the phantomjs script

```<code>tcpflow -p -c -i eth0 port 80 | grep -oE '(GET|POST|HEAD) .* HTTP/1.[01]'
</code>```

I can see the fonts are being downloaded. Real console output:

```<code>GET /public/external/georgiapro/demo.htm HTTP/1.1

GET /t/1.css?apiType=css&projectid=4a82c0c9-a48a-4ef5-97ae-de0d7e62c8d0 HTTP/1.1

GET /public/external/georgiapro/Fonts/a5d15255-f5b4-4cca-808f-211ec0f25ac8.woff HTTP/1.1

GET /public/external/georgiapro/Fonts/3859825b-bdc4-47f3-af3d-a2ef42d58cfb.woff HTTP/1.1

... [snip] ...

GET /public/external/georgiapro/Fonts/ab79a7ac-4aaf-4393-896b-feb6610c9528.woff HTTP/1.1
</code>```

I then thought that PhantomJS 2.x still doesn't support woff, but 1) it is supposed to be supported (see here), and 2) the SaaS PhantomJSCloud service can render them fine. Is there something more that is needed to be done to render web fonts?

Update: I've confirmed zlib is installed, and compiled PhantomJS 2.1.1 from source, but the results are still the same as above.

Update: Chrome has headless support, and that is the reason why on April 13 the maintainer of PhrantomJS has announced he is stepping down. Eventually we will switch to headless Chrome. Can headless Chrome handle web fonts?

答:
After a lot a experimenting, tweaking, reverse engineering of PhantomJS source code, plus the fact that it is no longer maintained, I switched over to headless Chrome from version 58 with Node.js drivers. It correctly takes screenshots of sites using WOFF fonts.

Here is my setup for anyone interested.

Installing Node.js and NPM

```<code>yum install epel-release
yum install nodejs
node --version # to confirm successful install
yum install npm
# OR, for v8
# curl -sL https://rpm.nodesource.com/setup_8.x | bash -
</code>```

Installing Node.js modules

```<code>npm install chrome-remote-interface --no-bin-links --save
npm install minimist --no-bin-links --save
</code>```

Installing Chrome on CentOS

```<code>cd /tmp
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum -y localinstall google-chrome-*
google-chrome --version # to confirm successful install
</code>```

Node.js screenshot driver script

Save this script as screenshot.js. The source of this script originally came from here. I've modified my version to be more flexible, but to give credit to the author, schnerd, I will reproduce it in its original form:

```<code>const CDP = require('chrome-remote-interface');
const argv = require('minimist')(process.argv.slice(2));
const file = require('fs');

// CLI Args
const url = argv.url || 'https://www.google.com';
const format = argv.format === 'jpeg' ? 'jpeg' : 'png';
const viewportWidth = argv.viewportWidth || 1440;
const viewportHeight = argv.viewportHeight || 900;
const delay = argv.delay || 0;
const userAgent = argv.userAgent;
const fullPage = argv.full;

// Start the Chrome Debugging Protocol
CDP(async function(client) {
  // Extract used DevTools domains.
  const {DOM, Emulation, Network, Page, Runtime} = client;

  // Enable events on domains we are interested in.
  await Page.enable();
  await DOM.enable();
  await Network.enable();

  // If user agent override was specified, pass to Network domain
  if (userAgent) {
    await Network.setUserAgentOverride({userAgent});
  }

  // Set up viewport resolution, etc.
  const deviceMetrics = {
    width: viewportWidth,
    height: viewportHeight,
    deviceScaleFactor: 0,
    mobile: false,
    fitWindow: false,
  };
  await Emulation.setDeviceMetricsOverride(deviceMetrics);
  await Emulation.setVisibleSize({width: viewportWidth, height: viewportHeight});

  // Navigate to target page
  await Page.navigate({url});

  // Wait for page load event to take screenshot
  Page.loadEventFired(async () => {
    // If the `full` CLI option was passed, we need to measure the height of
    // the rendered page and use Emulation.setVisibleSize
    if (fullPage) {
      const {root: {nodeId: documentNodeId}} = await DOM.getDocument();
      const {nodeId: bodyNodeId} = await DOM.querySelector({
        selector: 'body',
        nodeId: documentNodeId,
      });
      const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId});

      await Emulation.setVisibleSize({width: viewportWidth, height: height});
      // This forceViewport call ensures that content outside the viewport is
      // rendered, otherwise it shows up as grey. Possibly a bug?
      await Emulation.forceViewport({x: 0, y: 0, scale: 1});
    }

    setTimeout(async function() {
      const screenshot = await Page.captureScreenshot({format});
      const buffer = new Buffer(screenshot.data, 'base64');
      file.writeFile('output.png', buffer, 'base64', function(err) {
        if (err) {
          console.error(err);
        } else {
          console.log('Screenshot saved');
        }
        client.close();
      });
    }, delay);
  });
}).on('error', err => {
  console.error('Cannot connect to browser:', err);
});
</code>```

Running Chrome as background process

```<code>nohup google-chrome --headless --hide-scrollbars --remote-debugging-port=9222 --disable-gpu &
</code>```

Note: --disable-gpu is currently required, see here

Taking a screenshot

```<code>node screenshot.js --url="http://castellsonclaret.com/public/external/georgiapro/demo.htm" --outFile="screenshot.png" --format="jpeg" --viewportWidth=1440 --viewportHeight=900 --delay=1000
</code>```

Results

WOFF demo:

Browser capabilities test:

Body:
I'm using PhantomJS 2.1.1 on CentOS with the example script rasterize.js just to reproduce the screenshot problem, which is to take a screenshot of a simple web-font demo site:

http://castellsonclaret.com/public/external/georgiapro/demo.htm

It should render like so (as taken using the SaaS PhantomJSCloud service):

However, with PhantomJS 2.1.1 locally I get

First I increased the script timeout to 10s just to be sure that isn't the issue.

Next I thought the css or fonts were blocked somehow from downloading. When I use tcpflow (it's like wireshark) before running phantomjs scripts I can see that the above web page is downloading the .woff fonts. However, they are not being rendered in the screenshot I'm taking.

When I run the following before the phantomjs script

tcpflow -p -c -i eth0 port 80 | grep -oE '(GET|POST|HEAD) .* HTTP/1.[01]'

I can see the fonts are being downloaded. Real console output:

GET /public/external/georgiapro/demo.htm HTTP/1.1

GET /t/1.css?apiType=css&projectid=4a82c0c9-a48a-4ef5-97ae-de0d7e62c8d0 HTTP/1.1

GET /public/external/georgiapro/Fonts/a5d15255-f5b4-4cca-808f-211ec0f25ac8.woff HTTP/1.1

GET /public/external/georgiapro/Fonts/3859825b-bdc4-47f3-af3d-a2ef42d58cfb.woff HTTP/1.1

... [snip] ...

GET /public/external/georgiapro/Fonts/ab79a7ac-4aaf-4393-896b-feb6610c9528.woff HTTP/1.1

I then thought that PhantomJS 2.x still doesn't support woff, but 1) it is supposed to be supported (see here), and 2) the SaaS PhantomJSCloud service can render them fine. Is there something more that is needed to be done to render web fonts?

Update: I've confirmed zlib is installed, and compiled PhantomJS 2.1.1 from source, but the results are still the same as above.

Update: Chrome has headless support, and that is the reason why on April 13 the maintainer of PhrantomJS has announced he is stepping down. Eventually we will switch to headless Chrome. Can headless Chrome handle web fonts?

Body:
After a lot a experimenting, tweaking, reverse engineering of PhantomJS source code, plus the fact that it is no longer maintained, I switched over to headless Chrome from version 58 with Node.js drivers. It correctly takes screenshots of sites using WOFF fonts.

Here is my setup for anyone interested.

Installing Node.js and NPM

yum install epel-release
yum install nodejs
node --version # to confirm successful install
yum install npm
# OR, for v8
# curl -sL https://rpm.nodesource.com/setup_8.x | bash -

Installing Node.js modules

npm install chrome-remote-interface --no-bin-links --save
npm install minimist --no-bin-links --save

Installing Chrome on CentOS

cd /tmp
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum -y localinstall google-chrome-*
google-chrome --version # to confirm successful install

Node.js screenshot driver script

Save this script as screenshot.js. The source of this script originally came from here. I've modified my version to be more flexible, but to give credit to the author, schnerd, I will reproduce it in its original form:

const CDP = require('chrome-remote-interface');
const argv = require('minimist')(process.argv.slice(2));
const file = require('fs');

// CLI Args
const url = argv.url || 'https://www.google.com';
const format = argv.format === 'jpeg' ? 'jpeg' : 'png';
const viewportWidth = argv.viewportWidth || 1440;
const viewportHeight = argv.viewportHeight || 900;
const delay = argv.delay || 0;
const userAgent = argv.userAgent;
const fullPage = argv.full;

// Start the Chrome Debugging Protocol
CDP(async function(client) {
  // Extract used DevTools domains.
  const {DOM, Emulation, Network, Page, Runtime} = client;

  // Enable events on domains we are interested in.
  await Page.enable();
  await DOM.enable();
  await Network.enable();

  // If user agent override was specified, pass to Network domain
  if (userAgent) {
    await Network.setUserAgentOverride({userAgent});
  }

  // Set up viewport resolution, etc.
  const deviceMetrics = {
    width: viewportWidth,
    height: viewportHeight,
    deviceScaleFactor: 0,
    mobile: false,
    fitWindow: false,
  };
  await Emulation.setDeviceMetricsOverride(deviceMetrics);
  await Emulation.setVisibleSize({width: viewportWidth, height: viewportHeight});

  // Navigate to target page
  await Page.navigate({url});

  // Wait for page load event to take screenshot
  Page.loadEventFired(async () => {
    // If the `full` CLI option was passed, we need to measure the height of
    // the rendered page and use Emulation.setVisibleSize
    if (fullPage) {
      const {root: {nodeId: documentNodeId}} = await DOM.getDocument();
      const {nodeId: bodyNodeId} = await DOM.querySelector({
        selector: 'body',
        nodeId: documentNodeId,
      });
      const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId});

      await Emulation.setVisibleSize({width: viewportWidth, height: height});
      // This forceViewport call ensures that content outside the viewport is
      // rendered, otherwise it shows up as grey. Possibly a bug?
      await Emulation.forceViewport({x: 0, y: 0, scale: 1});
    }

    setTimeout(async function() {
      const screenshot = await Page.captureScreenshot({format});
      const buffer = new Buffer(screenshot.data, 'base64');
      file.writeFile('output.png', buffer, 'base64', function(err) {
        if (err) {
          console.error(err);
        } else {
          console.log('Screenshot saved');
        }
        client.close();
      });
    }, delay);
  });
}).on('error', err => {
  console.error('Cannot connect to browser:', err);
});

Running Chrome as background process

nohup google-chrome --headless --hide-scrollbars --remote-debugging-port=9222 --disable-gpu &

Note: --disable-gpu is currently required, see here

Taking a screenshot

node screenshot.js --url="http://castellsonclaret.com/public/external/georgiapro/demo.htm" --outFile="screenshot.png" --format="jpeg" --viewportWidth=1440 --viewportHeight=900 --delay=1000

Results

WOFF demo:

Browser capabilities test:


问:
Non Printable characters of UTF-8 - SUSE Linux Java doesn't support
We are implementing a feature to support non printable characters of UTF-8in our Database. Our system stores them in the database and retrieves them. We collect input in the form of base 64, convert them into byte array and store it in database. During retrieval, database gives us the byte array and we convert them to base 64 again.

During the retrieval process (after db gives us the byte array), all the attributes are converted to string arrays and later they are converted back to byte array again and this is converted to base 64 again to give it back to the user.

The below piece of code compiles and works properly in our Windows JDK (Java 8 version). But when this is placed in the SuSe Linux environment, we see strange characters.

```<code>public class Tewst {
    public static void main(String[] args) {
        byte[] attributeValues;
        String utfString ;

        attributeValues = new byte[]{-86, -70, -54, -38, -6};
        if (attributeValues != null) {
            utfString = new String(attributeValues);
            System.out.println("The string is "+utfString);
        }
    }
}
</code>```

The output given is

"The string is ªºÊÚú"

Now when the same file is run on SuSe Linux distribution, it gives me:

"The string is   �����"

We are using Java 8 in both Windows and Linux. What is the problem that it doesnt execute properly in Linux?

We have also tried  utfString = new String(attributeValues,"UTF-8");. It didnt help in any way. What are we missing?

答:
The characters ªºÊÚú are Unicode 00AA 00BA 00CA 00DA 00FA.

In character set ISO-8859-1, that is bytes AA BA CA DA FA.

In decimal, that would be {-86, -70, -54, -38, -6}, as you have in your code.

So, your string is encoded in ISO-8859-1, not UTF-8, which is also why it doesn't work on Linux, because Linux uses UTF-8, while Windows uses ISO-8859-1.

Never use new String(byte[]), unless you're absolutely sure you want the default character set of the JVM, whatever that might be.

Change code to new String(attributeValues, StandardCharsets.ISO_8859_1).

And of course, in the reverse operation, use str.getBytes(StandardCharsets.ISO_8859_1).

Then is should work consistently on various platforms, since code it no longer using platform defaults.

ContentLicense: CC BY-SA 4.0

Body:
We are implementing a feature to support non printable characters of UTF-8in our Database. Our system stores them in the database and retrieves them. We collect input in the form of base 64, convert them into byte array and store it in database. During retrieval, database gives us the byte array and we convert them to base 64 again.

During the retrieval process (after db gives us the byte array), all the attributes are converted to string arrays and later they are converted back to byte array again and this is converted to base 64 again to give it back to the user.

The below piece of code compiles and works properly in our Windows JDK (Java 8 version). But when this is placed in the SuSe Linux environment, we see strange characters.

public class Tewst {
    public static void main(String[] args) {
        byte[] attributeValues;
        String utfString ;

        attributeValues = new byte[]{-86, -70, -54, -38, -6};
        if (attributeValues != null) {
            utfString = new String(attributeValues);
            System.out.println("The string is "+utfString);
        }
    }
}

The output given is

"The string is ªºÊÚú"

Now when the same file is run on SuSe Linux distribution, it gives me:

"The string is   �����"

We are using Java 8 in both Windows and Linux. What is the problem that it doesnt execute properly in Linux?

We have also tried  utfString = new String(attributeValues,"UTF-8");. It didnt help in any way. What are we missing?


问:
Where is Firebase authentication API listed and documented?
From the website,  https://firebase.google.com/docs/auth/

I can piece together some functions, but is there a comprehensive list of all functions, with documentation?

Using Node.js  from firebase cloud functions

Thanks!

答:
If you're accessing Firebase Auth from a Cloud Function, you're likely using the Firebase Admin SDK. The guide for that specific combination is here: https://firebase.google.com/docs/auth/admin/

You can find a list of all Auth-related methods in the Node.js Admin SDK here: https://firebase.google.com/docs/reference/admin/node/admin.auth


问:
Outlook Email via a Webpage
I have a web application developed with ASP.net and C#  that is running on my companies' intranet.  Because all the users for this application are all using Microsoft Outlook without exception, I would like for the the application to open up an Outlook message on the client-side.  I understand that Office is designed to be run on the desktop and not from a server, however I have no trouble creating a Word or Excel document on the client-side.

I have code that instantiates the Outlook object using the Microsoft.Office.Interop.Outlook namespace and Outlook installed on the server.  When I try to run the code from the server, I get a DCOM source error message that states "The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {000C101C-0000-0000-C000-000000000046} to the user This security permission can be modified using the Component Services administrative tool."  I have modified the permissions using the Component Services tool, but still get this same error.

Is there a way to overcome this or is this a fruitless exercise because Outlook cannot be opened on the client side from the server-side code?

Mailto will not work due to the extreme length that the emails can obtain.  Also, the user that sends it needs add in eye-candy to the text for the recipients.

答: If everyone in the company uses Outlook, then just using a standard "mailto" link should always open Outlook.  It sounds like you're over-engineering this.</p>

OwnerDisplayName: Keng

Title: Outlook Email via a Webpage

LastEditorDisplayName: Keng

OwnerDisplayName: Jason


问:
How to get a SharePoint-UserField with JavaScript?
Hallo,

i need to write some javascript that gets the contents of a userfield in a sharepoint-website. I can get most fields with the javascript-function 'getTagFromIdentifierAndTitle' of Using Javascript to Manipulate a List Form Field, but not UserFields.

So how can i get UserFields?

Thanks!

答:
I traced how address book interacts with user field. To get values it uses function getUplevel(ctx) and to set values can be used function EntityEditorCallback(xml, ctx). First function will return html/xml mixed string with user information. Second function input must be special formatted xml string.

```<code>// Get values
var ctx='ctl00_m_g_e5a1501a_..._ctl04_ctl00_ctl00_UserField';
var values=getUplevel(ctx);
alert(values);

// Set values
var xml='<Entities Append="False" Error="" Separator=";" MaxHeight="3">'+
    '<Entity Key="DOMAIN\\loginname" DisplayText="Display Name" IsResolved="True" Description="DOMAIN\\loginname">'+
        '<ExtraData>'+
            '<ArrayOfDictionaryEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
                '<DictionaryEntry><Key xsi:type="xsd:string">DisplayName</Key><Value xsi:type="xsd:string">Display Name</Value></DictionaryEntry>'+
                '<DictionaryEntry><Key xsi:type="xsd:string">Email</Key><Value xsi:type="xsd:string">Display.Name@domain.ee</Value></DictionaryEntry>'+
                '<DictionaryEntry><Key xsi:type="xsd:string">SPUserID</Key><Value xsi:type="xsd:string">1</Value></DictionaryEntry>'+
                '<DictionaryEntry><Key xsi:type="xsd:string">PrincipalType</Key><Value xsi:type="xsd:string">User</Value></DictionaryEntry>'+
            '</ArrayOfDictionaryEntry>'+
        '</ExtraData>'+
        '<MultipleMatches />'+
    '</Entity>'+
'</Entities>';
EntityEditorCallback(xml,ctx);
</code>```

Tricky part is ctx attribute that must be target field id. In user field html there is no title attribute, so to find right element by display name with js is very complex. I suggest to pass field id to the javascript from server side. For example you can create custom WebPart where you write to the page field id-s from collection SPContext.Current.FormContext.FieldControlCollection.

Body:
I traced how address book interacts with user field. To get values it uses function getUplevel(ctx) and to set values can be used function EntityEditorCallback(xml, ctx). First function will return html/xml mixed string with user information. Second function input must be special formatted xml string.

// Get values
var ctx='ctl00_m_g_e5a1501a_..._ctl04_ctl00_ctl00_UserField';
var values=getUplevel(ctx);
alert(values);

// Set values
var xml='<Entities Append="False" Error="" Separator=";" MaxHeight="3">'+
    '<Entity Key="DOMAIN\\loginname" DisplayText="Display Name" IsResolved="True" Description="DOMAIN\\loginname">'+
        '<ExtraData>'+
            '<ArrayOfDictionaryEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
                '<DictionaryEntry><Key xsi:type="xsd:string">DisplayName</Key><Value xsi:type="xsd:string">Display Name</Value></DictionaryEntry>'+
                '<DictionaryEntry><Key xsi:type="xsd:string">Email</Key><Value xsi:type="xsd:string">Display.Name@domain.ee</Value></DictionaryEntry>'+
                '<DictionaryEntry><Key xsi:type="xsd:string">SPUserID</Key><Value xsi:type="xsd:string">1</Value></DictionaryEntry>'+
                '<DictionaryEntry><Key xsi:type="xsd:string">PrincipalType</Key><Value xsi:type="xsd:string">User</Value></DictionaryEntry>'+
            '</ArrayOfDictionaryEntry>'+
        '</ExtraData>'+
        '<MultipleMatches />'+
    '</Entity>'+
'</Entities>';
EntityEditorCallback(xml,ctx);

Tricky part is ctx attribute that must be target field id. In user field html there is no title attribute, so to find right element by display name with js is very complex. I suggest to pass field id to the javascript from server side. For example you can create custom WebPart where you write to the page field id-s from collection SPContext.Current.FormContext.FieldControlCollection.

OwnerDisplayName: EG


问:
Java OO static ultility method help!
I recently did a method in the User class which looks like this;

```<code>  public static boolean checkUN(String username) {
  boolean check = false;
  ResultSet rs;
  String dbQuery;
  SQLController db = new SQLController();
  db.setUp();
  dbQuery = "SELECT * FROM User WHERE User_name ='" + username + "'";
  try {
   db.setUp();
   rs = db.readRequest(dbQuery);
   if (rs.next()) {
    check = true;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  db.terminate();
  return check;
 }
</code>```

I intended it to be a validation check before the User is able to continue to the next step of registration.

When I showed it to the teacher, she said that it would be ok, as im using it as a ultility method. However, she changed her mind later on, saying that I should change this to an instance method, then creating a new User object to do the validation.

Which way is more effective?

```<code>user.checkUsername(jTextUN.getText());
</code>```

and the instance way
(assuming I changed the method, removing static and the input parameter);

```<code>User user = new User();
user.setUsername(jTextUN.getText());
user.checkUsername();
</code>```

Cheers!

答: I would probably create some sort of UserValidator class and create an instance of that to contain your method.</p>

Title: Java OO static ultility method help!

Body:
I recently did a method in the User class which looks like this;

  public static boolean checkUN(String username) {
  boolean check = false;
  ResultSet rs;
  String dbQuery;
  SQLController db = new SQLController();
  db.setUp();
  dbQuery = "SELECT * FROM User WHERE User_name ='" + username + "'";
  try {
   db.setUp();
   rs = db.readRequest(dbQuery);
   if (rs.next()) {
    check = true;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  db.terminate();
  return check;
 }

I intended it to be a validation check before the User is able to continue to the next step of registration.

When I showed it to the teacher, she said that it would be ok, as im using it as a ultility method. However, she changed her mind later on, saying that I should change this to an instance method, then creating a new User object to do the validation.

Which way is more effective?

user.checkUsername(jTextUN.getText());

and the instance way
(assuming I changed the method, removing static and the input parameter);

User user = new User();
user.setUsername(jTextUN.getText());
user.checkUsername();

Cheers!


问:
Why I can't define a DOM element as a global variable?
I'm working on a form and wanted to use Javascript to output the form input.

So I have following script:

```<code><script>
function showName() {
  var box = document.getElementById("lorem").value;

  console.log(box);
}

showName();
</script> `
</code>```

The code above works really well but I wanted the var box = document.getElementById("lorem").value; to be a global variable so that I can use it in other functions without re-declaring it.

So when I have this it doesn't output anything:
`

```<code><script>
//Declared outside the function
var box = document.getElementById("lorem").value;

function showName() {
  console.log(box);
}

showName();
</script>
</code>```

Please, what am I doing wrong?

答:
You can use the same. it is not a problem. if you are still getting the null error, I would suggest to add the script at the end of the document or enclose it in a document.addEventListener("DOMContentLoaded", function(event) { block like below

document.addEventListener("DOMContentLoaded", function(event) {
var box = document.getElementById("lorem").value;
function showName() {

console.log(box);

     }
showName();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" value="hai" id="lorem"/></code>```

Body:
I'm working on a form and wanted to use Javascript to output the form input.

So I have following script:

 `

The code above works really well but I wanted the var box = document.getElementById("lorem").value; to be a global variable so that I can use it in other functions without re-declaring it.

So when I have this it doesn't output anything:
`

Please, what am I doing wrong?

Body:
You can use the same. it is not a problem. if you are still getting the null error, I would suggest to add the script at the end of the document or enclose it in a document.addEventListener("DOMContentLoaded", function(event) { block like below

document.addEventListener("DOMContentLoaded", function(event) {
var box = document.getElementById("lorem").value;
function showName() {

console.log(box);

     }
showName();
});

<input type="text" value="hai" id="lorem"/>


答:
The value of box is the initial value of your lorem element when you declare it. What you probably want is this:

```<code>var box = document.getElementById('lorem');

function showName() {
    console.log(box.value); // <-- get the current value
}

// Outputs the current value, initially it will be empty
// of course, until you change your input and call the
// function again
showName();
</code>```

Edit: the DOM needs to be loaded for this to work so make sure to put your script tags last in your

Title: Why I can't define a DOM element as a global variable?

Body:
The value of box is the initial value of your lorem element when you declare it. What you probably want is this:

var box = document.getElementById('lorem');

function showName() {
    console.log(box.value); // <-- get the current value
}

// Outputs the current value, initially it will be empty
// of course, until you change your input and call the
// function again
showName();

Edit: the DOM needs to be loaded for this to work so make sure to put your script tags last in your <body>


问:
Create a new branch on remote and local as Dev
Step 1: I cloned the master into my local

Step 2: Then I have merged another branch to master on local like this:

```<code>git fetch origin other-branch

git merge origin/other-branch
</code>```

Step 3: Now I need to create a new branch on remote and local as Dev after step 2.How can I do that?

答:
Simply checkout a new branch called Dev and push the branch to remote.

```<code>$ git checkout -b Dev      # Create lcoal 'Dev' branch and checkout to that branch
$ git push -u origin Dev
</code>```

Body:
Step 1: I cloned the master into my local

Step 2: Then I have merged another branch to master on local like this:

git fetch origin other-branch

git merge origin/other-branch

Step 3: Now I need to create a new branch on remote and local as Dev after step 2.How can I do that?

Body:
Simply checkout a new branch called Dev and push the branch to remote.

$ git checkout -b Dev      # Create lcoal 'Dev' branch and checkout to that branch
$ git push -u origin Dev


问:
Two Partial Views in One Page?
I tried to use 2 partial views under 1 view/page - first half page for search filters & 2nd half page for table display. Its working also,but the issue is the white color content panel is in fixed size. i.e., if my table got data it comes out of the white color panel.

```<code><section class="content admin_table">
   @RenderBody()
</section>
</code>```

I use above class in Layout. In Index View, I render both Partial views. My code part is below

```<code> @Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)
</code>```

My IndexPage

```<code>@model SW.Web.ViewModels.CommonVM
@{
    Layout = "~/Views/Shared/_Layout1.cshtml";
    ViewBag.Title = "Title";
    ViewBag.Header = "Details";
       }
<link href="~/Content2/plugins/datatables/dataTables.bootstrap.css" rel="stylesheet" />

  <!DOCTYPE html>

@section JavaScript{

<Script> .....</script>
<Script> .....</script>
}
@Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)
</code>```

and My Partial view 1

```<code> @model SW.Web.ViewModels.viewmodel1
     @{
    using (Html.BeginForm("Index", "Details", FormMethod.Post, new { d= Model }))
    {
        @Html.ValidationSummary(true)
  <div>.....Design</div>
}
</code>```

and my partial view 2

```<code> @model IEnumerable<SW.Web.ViewModels.Viewmodel2>
    @{
     <div> Designs for partial view 2</div>

}
</code>```

答:
So create One view with
Search partial view like

```<code>//Serach view
<div class="white">
<h2>Search view</h2>
<--! search coading-->
   @Html.RenderPartial("Table_View", objectvalue2);
</div>
</code>```

Use below line

```<code> @Html.RenderPartial("_SearchView", objectvalue1);
</code>```

in another page

Title: Two Partial Views in One Page?

Body:
I tried to use 2 partial views under 1 view/page - first half page for search filters & 2nd half page for table display. Its working also,but the issue is the white color content panel is in fixed size. i.e., if my table got data it comes out of the white color panel.

   @RenderBody()

I use above class in Layout. In Index View, I render both Partial views. My code part is below

 @Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)

My IndexPage

@model SW.Web.ViewModels.CommonVM
@{
    Layout = "~/Views/Shared/_Layout1.cshtml";
    ViewBag.Title = "Title";
    ViewBag.Header = "Details";
       }
<link href="~/Content2/plugins/datatables/dataTables.bootstrap.css" rel="stylesheet" />

  <!DOCTYPE html>

@section JavaScript{

}
@Html.Partial("_view1", Model.Filter)
 @Html.Partial("_view2", Model.Result)

and My Partial view 1

 @model SW.Web.ViewModels.viewmodel1
     @{
    using (Html.BeginForm("Index", "Details", FormMethod.Post, new { d= Model }))
    {
        @Html.ValidationSummary(true)

.....Design

}

and my partial view 2

 @model IEnumerable<SW.Web.ViewModels.Viewmodel2>
    @{

 Designs for partial view 2

}

Body:
So create One view with
Search partial view like

//Serach view
<div class="white">
<h2>Search view</h2>
<--! search coading-->
   @Html.RenderPartial("Table_View", objectvalue2);
</div>

Use below line

 @Html.RenderPartial("_SearchView", objectvalue1);

in another page


问:
If String is immutable in javascript then how splice method changing the original String?
As i heard, String is immutable in JavaScript then how splice method changing the original String?

As I know
var name = 'Alto';// it will create an new object in global space memory with 'alto' and assign to name reference.

name = 'swift'; // it will create an new object in global space memory and with 'swift' assign to name reference. ('Alto' string object will be moved to garbage collector whenever possible).

var newName = name.slice(0,2);// here splicing the 'sw' from 'swift' create an new Object in global space and assign to newName. name will have 'swift' since string is immutable.

var newName1 = name.splice(0,2);// here cut the 'sw' from 'swift'(original string) and assign to newName. now name will have 'ift'. so how String is an immutable?

Can anyone explain the process behind splice?

答: They are immutable. You cannot change a character within a string with something like var myString = "abbdef"; myString[2] = 'c'. The string manipulation methods such as trim, slice return new strings.</p>


答:
You need to include location.js in the html page returning from /company/new-job to get it work.

Or try loading the js like below. (not tested)

```<code>$(document).ready(function(){
     $("#newJob").load('/company/new-job',function(data){
     //here you can get the elements from /company/new-job.
       $.getScript('js/location.js').done(function(data, textStatus, jqxhr) {
          //here you can call functions from location.js
       });
     });
});
</code>```

Title: document.getElementById not working on jquery load

Body:
I've loaded an  html file with jquery load function

in my profile.blade.php

in my location.js  i am  using

document.getElementById('autocomplete') for getting an html element

but this element is in company/new-job file

the problem i got undefined error in document.getElementById('autocomplete') this part

when i directly include the location.js its working fine

Body:
You need to include location.js in the html page returning from /company/new-job to get it work.

Or try loading the js like below. (not tested)

$(document).ready(function(){
     $("#newJob").load('/company/new-job',function(data){
     //here you can get the elements from /company/new-job.
       $.getScript('js/location.js').done(function(data, textStatus, jqxhr) {
          //here you can call functions from location.js
       });
     });
});


问:
Docker Compose env_file in Multicontainer Elastic Beanstalk
I have the following docker compose file:

```<code>version: '2'

services:
  app:
    build: .
    command: >
      bash -cex "
        export LC_ALL=C.UTF-8
        export LANG=C.UTF-8
        /virtualenv/bin/flask run -h 0.0.0.0 -p 5050
      "
    env_file: env
    links:
    - postgres
    ports:
    - 8080:8080
</code>```

As you can see I'm using the env_file option to load my environment variables from the file env.

Now I'm trying to deploy this container to Elastic Beanstalk.
This is my file Dockerrun.aws.json so far:

```<code>{
  "AWSEBDockerrunVersion": 2,

  "containerDefinitions": [

    {
      "name": "app",
      "image": "myorg/myimage",
      "essential": true,
      "memory": 256,
      "command": [
        "/bin/bash",
        "export LC_ALL=C.UTF-8",
        "export LANG=C.UTF-8",
        "/virtualenv/bin/flask run -h 0.0.0.0 -p 5050"
      ],
      "portMappings": [
        {
          "hostPort": 8080,
          "containerPort": 8080
        }
      ],
      "links": [
        "postgres",
      ]
    }
</code>```

In the AWS Elastic Beanstalk documentation just mention the environment option to pass an array of env variables, but I can't find how to pass a file instead of an array of variables.

Does someone knows how to translate this docker-compose file to Dockerrun.aws.json file properly?

Regards.

答:
Try container-transform.

```<code>$ pip install container-transform
$ cat docker-compose.yml | container-transform  -v
</code>```

and it will print the ECS format to STDOUT.

Body:
I have the following docker compose file:

version: '2'

services:
  app:
    build: .
    command: >
      bash -cex "
        export LC_ALL=C.UTF-8
        export LANG=C.UTF-8
        /virtualenv/bin/flask run -h 0.0.0.0 -p 5050
      "
    env_file: env
    links:
    - postgres
    ports:
    - 8080:8080

As you can see I'm using the env_file option to load my environment variables from the file env.

Now I'm trying to deploy this container to Elastic Beanstalk.
This is my file Dockerrun.aws.json so far:

{
  "AWSEBDockerrunVersion": 2,

  "containerDefinitions": [

    {
      "name": "app",
      "image": "myorg/myimage",
      "essential": true,
      "memory": 256,
      "command": [
        "/bin/bash",
        "export LC_ALL=C.UTF-8",
        "export LANG=C.UTF-8",
        "/virtualenv/bin/flask run -h 0.0.0.0 -p 5050"
      ],
      "portMappings": [
        {
          "hostPort": 8080,
          "containerPort": 8080
        }
      ],
      "links": [
        "postgres",
      ]
    }

In the AWS Elastic Beanstalk documentation just mention the environment option to pass an array of env variables, but I can't find how to pass a file instead of an array of variables.

Does someone knows how to translate this docker-compose file to Dockerrun.aws.json file properly?

Regards.

Body:
Try container-transform.

$ pip install container-transform
$ cat docker-compose.yml | container-transform  -v

and it will print the ECS format to STDOUT.


答: You can either put the script all the way at the end before you close the  tag, or do as @jafarbtech suggested and add an event listener to wait for the DOM content to load.

Body: You can either put the script all the way at the end before you close the <body> tag, or do as @jafarbtech suggested and add an event listener to wait for the DOM content to load.


问:
How to install Web Deploy for Hosting Servers on Windows Server 2016
The Web Platform Installer fails to install Web Deploy for Hosting Servers on Windows Server 2016.</p>

答:
To fix this, first install the missing components using Server Manager, Manage, Add Role and Features. I think these are the ones required: Logging Tools, Request Monitor, .Net Extensibility, ASP.Net, ISAPI Extensions, ISAPI Filters, Management Service. I ended up with the following for my needs.

Next install Web Deploy 3.6 for Hosting Servers using the Web Platform Installer. (If it fails, note which components it depended on, install as above and try again.)

At this stage if you look for Deploy again in the Platform Installer it won't be installed, even though it says it was successful.

Go to Control Panel, Add or Remove Programs, find Web Deploy and choose Modify, Next, then Change.

Set IIS Deployment Handler to Entire feature will be installed, Next etc.

The Deploy menu will now appear in IIS Manager (restart it first if you already had it open) and Web Platform Installer will see that it's installed.


问:
How do you authenticate a VueJS app with Azure AD?
I'm setting up an app using the VueJS 2.x framework and it needs to authenticate users via the Azure Active Directory service. I already have "login info" (Auth and Token URLs) neccessary for the service.

So far, I've only encountered one article that shows the setup in VueJS, but it relies on a third party service (Auth0) - adding uneccessary convolution in the process.

How do you proceed when there aren't any VueJS npm modules that allow for doing authenticating easily? Or do you have to rely on a library outside of Vue like Adal JS?

Any suggestions would be helpful.

答:
I'm not sure that there is a library to help with security for Vue apps. However, we can easily leverage Adal.js for authentication.

I wrote a simple demo for your reference:

Index.html:

Hello {{ oauthData.userName }}

  <button onclick="login()" v-else>Login</button>

```

<p><strong>config.js</strong>:</p>

```var config = {
  tenant: 'xxx.onmicrosoft.com',
  clientId: '',
  redirectUri: '',
  cacheLocation: 'localStorage'
};
```

Body:
I'm not sure that there is a library to help with security for Vue apps. However, we can easily leverage Adal.js for authentication.

I wrote a simple demo for your reference:

Index.html:

<html>
<head>
  <script src="https://unpkg.com/vue"></script>
  <script src="node_modules\adal-angular\lib\adal.js"></script>
  <script src="config.js"></script>
  <script>
    var authContext = new AuthenticationContext(config);

    function login() {
      authContext.login();
    }

    function init(configOptions) {
    if (configOptions) {
      // redirect and logout_redirect are set to current location by default
      var existingHash = window.location.hash;
      var pathDefault = window.location.href;
      if (existingHash) {
        pathDefault = pathDefault.replace(existingHash, "");
      }
      configOptions.redirectUri = configOptions.redirectUri || pathDefault;
      configOptions.postLogoutRedirectUri =
      configOptions.postLogoutRedirectUri || pathDefault;

      // create instance with given config
    } else {
      throw new Error("You must set configOptions, when calling init");
    }

    // loginresource is used to set authenticated status
    updateDataFromCache(authContext.config.loginResource);
    }

    var _oauthData = {
      isAuthenticated: false,
      userName: "",
      loginError: "",
      profile: ""
    };
    var updateDataFromCache = function(resource) {
      // only cache lookup here to not interrupt with events
      var token = authContext.getCachedToken(resource);
      _oauthData.isAuthenticated = token !== null && token.length > 0;
      var user = authContext.getCachedUser() || { userName: "" };
      _oauthData.userName = user.userName;
      _oauthData.profile = user.profile;
      _oauthData.loginError = authContext.getLoginError();
    };

    function saveTokenFromHash() {
      var hash = window.location.hash;
      var requestInfo = authContext.getRequestInfo(hash);
      if (authContext.isCallback(hash)) {
        // callback can come from login or iframe request

        var requestInfo = authContext.getRequestInfo(hash);
        authContext.saveTokenFromHash(requestInfo);
        window.location.hash = "";

        if (requestInfo.requestType !== authContext.REQUEST_TYPE.LOGIN) {
          authContext.callback = window.parent.AuthenticationContext().callback;
        }
      }
    }

    function isAuthenticate() {
      return _oauthData.isAuthenticated;
    }

    saveTokenFromHash();

    init(config);
  </script>
</head>

<body>
<div id="app">
  <p v-if="_oauthData.isAuthenticated">Hello {{ oauthData.userName }}</p>
  <button onclick="login()" v-else>Login</button>
</div>

<script>
  var app = new Vue({
    el: "#app",
    data: {
      oauthData: _oauthData
    }
  });
</script>
</body>
</html>

config.js:

var config = {
  tenant: 'xxx.onmicrosoft.com',
  clientId: '',
  redirectUri: '',
  cacheLocation: 'localStorage'
};


问:
Animation Not Playing (LibGDX)
I have a valid animation called diceAnimation from a valid TextureAtlas called dice that has several frames in it. What I have an issue with is rendering it. I use the code below to render the animation but it only shows the first frame. If I set timeElapsed to add one every time instead of using the delta time, it animates but REALLY FAST, ignoring the frames per second defined in the construction. Anyone have ideas?

```<code>int elapsedTime;

@Override
public void create() {
    batch = new SpriteBatch();
    dice = new TextureAtlas("textures/dice/dice.atlas");
    diceAnimation = new Animation<TextureRegion>(0.033f, dice.findRegions("one"), PlayMode.LOOP);
}

// ...

@Override
public void render () {
    elapsedTime += Gdx.graphics.getDeltaTime();

    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    batch.draw(diceAnimation.getKeyFrame(elapsedTime, true), 100, 100);
    batch.end();
}
</code>```

答:
data type of int elapsedTime should be float instead of int.

OFF_TOPIC

PlayMode.LOOP is  PlayMode of diceAnimation so you can use

```<code>batch.draw(diceAnimation.getKeyFrame(elapsedTime), 100, 100);
</code>```

Title: Animation Not Playing (LibGDX)

Body:
I have a valid animation called diceAnimation from a valid TextureAtlas called dice that has several frames in it. What I have an issue with is rendering it. I use the code below to render the animation but it only shows the first frame. If I set timeElapsed to add one every time instead of using the delta time, it animates but REALLY FAST, ignoring the frames per second defined in the construction. Anyone have ideas?

int elapsedTime;

@Override
public void create() {
    batch = new SpriteBatch();
    dice = new TextureAtlas("textures/dice/dice.atlas");
    diceAnimation = new Animation<TextureRegion>(0.033f, dice.findRegions("one"), PlayMode.LOOP);
}

// ...

@Override
public void render () {
    elapsedTime += Gdx.graphics.getDeltaTime();

    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    batch.draw(diceAnimation.getKeyFrame(elapsedTime, true), 100, 100);
    batch.end();
}

Body:
data type of int elapsedTime should be float instead of int.

OFF_TOPIC

PlayMode.LOOP is  PlayMode of diceAnimation so you can use

batch.draw(diceAnimation.getKeyFrame(elapsedTime), 100, 100);