问:
How to Color the "Overshoot" Background of an NSCollectionView
I have implemented a collection view on my Cocoa app following Ray Wenderlich's tutorial (very helpful, given how buggy and broken Apple's API is in this area).

In the tutorial, the collection view's canvas is colored black using the following code (all code is in view controller class' viewDidLoad() method):

```<code>collectionView.layer?.backgroundColor = NSColor.black.cgColor
</code>```

However, the area that "peeks" when you overshoot ("rubber-band") the scroll  using -for example- a magic mouse/scrollwheel, is still white and very distracting:

I'm trying to make the whole content area black. In my storyboard, I set the background color of both the NSScrollView and NSClipView that contain the collection view to black, but it doesn't change the appearance.
Also tried the programmatic alternative: setup an outlet for the scrollview and call:

```<code>self.scrollview.backgroundColor = NSColor.black
self.scrollview.contentView.backgroundColor = NSColor.black
</code>```

...to no effect.

Additionally, I tried:

```<code>collectionView.superview?.layer?.backgroundColor = NSColor.black.cgColor
</code>```

...but this doesn't work either.

Neither does:

```<code>self.view.layer?.backgroundColor = NSColor.black.cgColor
</code>```

or:

```<code>self.view.window?.backgroundColor = NSColor.black
</code>```

Update:

I have set the background color of the scroll view to red, and drawsBackground to true (both in IB and programmatically). The docs for NSScrollView's backgroundColor property say:

This color is used to paint areas inside the content view that aren’t
  covered by the document view.

I have verified at runtime that the document view is indeed my collection view:

```<code>if scrollview.documentView is NSCollectionView {
        print("Document is collection")
}
</code>```

However, no red is displayed and the area beyond the document (collection view) stays white.

Update 2: I fired the View Hierarchy Debugger, and it seems that the value of drawsBackground is false at runtime (I set it to true in both code and storyboard)!:

(the background color itself seems to be reflected, though)

答:
for changing it programmatically in Swift 3 use e.g.:</p>

```<code>collectionView.backgroundColors = [NSColor.black]
</code>```

Body:
I have implemented a collection view on my Cocoa app following Ray Wenderlich's tutorial (very helpful, given how buggy and broken Apple's API is in this area).

In the tutorial, the collection view's canvas is colored black using the following code (all code is in view controller class' viewDidLoad() method):

collectionView.layer?.backgroundColor = NSColor.black.cgColor

However, the area that "peeks" when you overshoot ("rubber-band") the scroll  using -for example- a magic mouse/scrollwheel, is still white and very distracting:

I'm trying to make the whole content area black. In my storyboard, I set the background color of both the NSScrollView and NSClipView that contain the collection view to black, but it doesn't change the appearance.
Also tried the programmatic alternative: setup an outlet for the scrollview and call:

self.scrollview.backgroundColor = NSColor.black
self.scrollview.contentView.backgroundColor = NSColor.black

...to no effect.

Additionally, I tried:

collectionView.superview?.layer?.backgroundColor = NSColor.black.cgColor

...but this doesn't work either.

Neither does:

self.view.layer?.backgroundColor = NSColor.black.cgColor

or:

self.view.window?.backgroundColor = NSColor.black

Update:

I have set the background color of the scroll view to red, and drawsBackground to true (both in IB and programmatically). The docs for NSScrollView's backgroundColor property say:

This color is used to paint areas inside the content view that aren’t
  covered by the document view.

I have verified at runtime that the document view is indeed my collection view:

if scrollview.documentView is NSCollectionView {
        print("Document is collection")
}

However, no red is displayed and the area beyond the document (collection view) stays white.

Update 2: I fired the View Hierarchy Debugger, and it seems that the value of drawsBackground is false at runtime (I set it to true in both code and storyboard)!:

(the background color itself seems to be reflected, though)

Body:
for changing it programmatically in Swift 3 use e.g.:

collectionView.backgroundColors = [NSColor.black]


来源: stackexchange

问:
Send parameters to a URL and get output from that page
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

```<code> <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>
</code>```

def.php:

```<code> <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>
</code>```

Is there any kind heart who can help me solve the issue?

答:
Taken from the examples page of php.net:

```<code>// create curl resource
$ch = curl_init();

// set url
curl_setopt( $ch, CURLOPT_URL, "example.com/abc.php");

//return the transfer as a string
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec( $ch );

// close curl resource to free up system resources
curl_close( $ch );
</code>```

Edit: To send parameters

```<code>curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

 <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>

def.php:

 <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>

Is there any kind heart who can help me solve the issue?

Body:
Taken from the examples page of php.net:

// create curl resource
$ch = curl_init();

// set url
curl_setopt( $ch, CURLOPT_URL, "example.com/abc.php");

//return the transfer as a string
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec( $ch );

// close curl resource to free up system resources
curl_close( $ch );

Edit: To send parameters

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));

ContentLicense: CC BY-SA 4.0


问:
zuul API Gateway Filter
I am facing problem when i trying to access another REST API(registered in ZUUL route) from zuul pre-filter, the call is becoming recursive i.e its running my pre-filter code again and again. My Usecase is as follows-

In Zuul PreFilter run() method, I am validating the token passed in the header.

After validating the token, I am calling one rest service(User Location Service) to fetch the user details. My User Location Service is itself registered in ZUUL as below:

```<code>user-location-service:
  path: /userLocationService/**
  url: http://localhost:9002
</code>```

The problem is that the JWT token validation code is running again and again, Can you please suggest some solution where I can apply the call Userlocation service so that the PreFilter code would not run again and again?

答:
Your User Location Service is registred in Zuul. So, all the times your filter is going to be executed when you got caugth in an infinite loop.

There are two approaches here:

Do not pass again to the gateway and call direct User Location Service

OR, Create a filter rule in your ZUll Authentication Filter to not consider the User Location Service. You can use the URL Path Context to exclude this route to be executed

Title: zuul API Gateway Filter

Body:
I am facing problem when i trying to access another REST API(registered in ZUUL route) from zuul pre-filter, the call is becoming recursive i.e its running my pre-filter code again and again. My Usecase is as follows-

In Zuul PreFilter run() method, I am validating the token passed in the header.

After validating the token, I am calling one rest service(User Location Service) to fetch the user details. My User Location Service is itself registered in ZUUL as below:

user-location-service:
  path: /userLocationService/**
  url: http://localhost:9002

The problem is that the JWT token validation code is running again and again, Can you please suggest some solution where I can apply the call Userlocation service so that the PreFilter code would not run again and again?


问:
equals() doesn't work as expected with Selenium
I am trying to compare current URL with a string URL, but the following code returns false.

```<code>driver.get("https://www.facebook.com");
System.out.println(driver.getCurrentUrl().equals("https://www.facebook.com"));
</code>```

答:
I tried your code, and the URL that is being returned by driver.getCurrentUrl() was "https://www.facebook.com/"

Since you are doing an equals check with "https://www.facebook.com", it will return false because of the missing '/' at the end of returned URL. Either compare it with this URL being returned, or use contains() to check if url returned is correct.

Body:
I am trying to compare current URL with a string URL, but the following code returns false.

driver.get("https://www.facebook.com");
System.out.println(driver.getCurrentUrl().equals("https://www.facebook.com"));


问:
C# Newtsonsoft.Json - Deserialize JSON with nested arrays to DataTable
I have JSON data with nested arrays (see example below).  What I am trying to accomplish is to deserialize this data into a DataSet where each nested array gets inserted into a corresponding datatable.

Example:

```<code>[
{
    "Id": "1",
    "LastName": "John",
    "FirstName": "Doe",
    "MiddleInitial": "I",
    "DateOfBirth": "2000-10-05",
    "Gender": "M",
    "LastModifiedDate": "2017-03-13 14:36:53",
    "Classes": [
        {
            "ClassNumber": "21",
            "TeacherID": "15"
        },
        {
            "ClassNumber": "12",
            "TeacherID": "10"
        }
    ]
},
{
    "Id": "2",
    "LastName": "Jane",
    "FirstName": "Doe",
    "MiddleInitial": "K",
    "DateOfBirth": "2000-10-05",
    "Gender": "F",
    "LastModifiedDate": "2017-03-13 14:36:53",
    "Classes": [
        {
            "ClassNumber": "11",
            "TeacherID": "8"
        },
        {
            "ClassNumber": "4",
            "TeacherID": "26"
        }
    ]
}]
</code>```

So the dataset would contain 2 datatables.  One with all of the records from the main array and the second with all of the records from the "Classes" array.

答:
You kind of have to create the DataSet and its DataTables manually and fill them manually. There's no automatic way of doing it, if that's what you were hoping for. If you need to maintain the relationships between the objects you have to add a foreign key to the Class anyway, otherwise there's no way to know which person a Class belongs to.

The table columns could be generated from the JSON properties, of course, if you're careful enough with how you write the code or if the JSON structure is always the same without exception.

Body:
I have JSON data with nested arrays (see example below).  What I am trying to accomplish is to deserialize this data into a DataSet where each nested array gets inserted into a corresponding datatable.

Example:

[
{
    "Id": "1",
    "LastName": "John",
    "FirstName": "Doe",
    "MiddleInitial": "I",
    "DateOfBirth": "2000-10-05",
    "Gender": "M",
    "LastModifiedDate": "2017-03-13 14:36:53",
    "Classes": [
        {
            "ClassNumber": "21",
            "TeacherID": "15"
        },
        {
            "ClassNumber": "12",
            "TeacherID": "10"
        }
    ]
},
{
    "Id": "2",
    "LastName": "Jane",
    "FirstName": "Doe",
    "MiddleInitial": "K",
    "DateOfBirth": "2000-10-05",
    "Gender": "F",
    "LastModifiedDate": "2017-03-13 14:36:53",
    "Classes": [
        {
            "ClassNumber": "11",
            "TeacherID": "8"
        },
        {
            "ClassNumber": "4",
            "TeacherID": "26"
        }
    ]
}]

So the dataset would contain 2 datatables.  One with all of the records from the main array and the second with all of the records from the "Classes" array.


问:
PHP - ZF2 - render template from string variable
i have problem with rendering template in ZF2, where template is in string in variable. There is simple example:

```<code>$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);

$renderer = new \Zend\View\Renderer\PhpRenderer();
$html = $renderer->render($view);
</code>```

This code fail on rendering, the renderer think that the template is a path to file. And iam reallz not sure how to tell rendere its a string.

Thx for your time and respond.

答:
You have to extend  the PhpRenderer class and override the render method, in such a way that will use the string in the $template as the actual template:

```<code>class MyPhpRenderer extends PhpRenderer {
public function render($nameOrModel, $values = null)
{
    if ($nameOrModel instanceof Model) {
        $model       = $nameOrModel;
        $nameOrModel = $model->getTemplate();
        if (empty($nameOrModel)) {
            throw new Exception\DomainException(sprintf(
                '%s: received View Model argument, but template is empty',
                __METHOD__
            ));
        }
        $options = $model->getOptions();
        foreach ($options as $setting => $value) {
            $method = 'set' . $setting;
            if (method_exists($this, $method)) {
                $this->$method($value);
            }
            unset($method, $setting, $value);
        }
        unset($options);

        // Give view model awareness via ViewModel helper
        $helper = $this->plugin('view_model');
        $helper->setCurrent($model);

        $values = $model->getVariables();
        unset($model);
    }

    // find the script file name using the parent private method
    $this->addTemplate($nameOrModel);
    unset($nameOrModel); // remove $name from local scope

    $this->__varsCache[] = $this->vars();

    if (null !== $values) {
        $this->setVars($values);
    }
    unset($values);

    // extract all assigned vars (pre-escaped), but not 'this'.
    // assigns to a double-underscored variable, to prevent naming collisions
    $__vars = $this->vars()->getArrayCopy();
    if (array_key_exists('this', $__vars)) {
        unset($__vars['this']);
    }
    extract($__vars);
    unset($__vars); // remove $__vars from local scope

    while ($this->__template = array_pop($this->__templates)) {
        $this->__file = $this->resolver($this->__template);
        try {
            if (!$this->__file) {
               $this->__content = $this->__template; // this line does what you need
            }else{
              ob_start();
              $includeReturn = include $this->__file;
              $this->__content = ob_get_clean();
            }
        } catch (\Exception $ex) {
            ob_end_clean();
            throw $ex;
        }
        if ($includeReturn === false && empty($this->__content)) {
            throw new Exception\UnexpectedValueException(sprintf(
                '%s: Unable to render template "%s"; file include failed',
                __METHOD__,
                $this->__file
            ));
        }
    }

    $this->setVars(array_pop($this->__varsCache));

    if ($this->__filterChain instanceof FilterChain) {
        return $this->__filterChain->filter($this->__content); // filter output
    }

    return $this->__content;
}
}
</code>```

and then you code should look like:

```<code>$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);

$renderer = new MyPhpRenderer();
$html = $renderer->render($view);
</code>```

Body:
i have problem with rendering template in ZF2, where template is in string in variable. There is simple example:

$template = "
easy
";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);

$renderer = new \Zend\View\Renderer\PhpRenderer();
$html = $renderer->render($view);

This code fail on rendering, the renderer think that the template is a path to file. And iam reallz not sure how to tell rendere its a string.

Thx for your time and respond.

Body:
You have to extend  the PhpRenderer class and override the render method, in such a way that will use the string in the $template as the actual template:

class MyPhpRenderer extends PhpRenderer {
public function render($nameOrModel, $values = null)
{
    if ($nameOrModel instanceof Model) {
        $model       = $nameOrModel;
        $nameOrModel = $model->getTemplate();
        if (empty($nameOrModel)) {
            throw new Exception\DomainException(sprintf(
                '%s: received View Model argument, but template is empty',
                __METHOD__
            ));
        }
        $options = $model->getOptions();
        foreach ($options as $setting => $value) {
            $method = 'set' . $setting;
            if (method_exists($this, $method)) {
                $this->$method($value);
            }
            unset($method, $setting, $value);
        }
        unset($options);

        // Give view model awareness via ViewModel helper
        $helper = $this->plugin('view_model');
        $helper->setCurrent($model);

        $values = $model->getVariables();
        unset($model);
    }

    // find the script file name using the parent private method
    $this->addTemplate($nameOrModel);
    unset($nameOrModel); // remove $name from local scope

    $this->__varsCache[] = $this->vars();

    if (null !== $values) {
        $this->setVars($values);
    }
    unset($values);

    // extract all assigned vars (pre-escaped), but not 'this'.
    // assigns to a double-underscored variable, to prevent naming collisions
    $__vars = $this->vars()->getArrayCopy();
    if (array_key_exists('this', $__vars)) {
        unset($__vars['this']);
    }
    extract($__vars);
    unset($__vars); // remove $__vars from local scope

    while ($this->__template = array_pop($this->__templates)) {
        $this->__file = $this->resolver($this->__template);
        try {
            if (!$this->__file) {
               $this->__content = $this->__template; // this line does what you need
            }else{
              ob_start();
              $includeReturn = include $this->__file;
              $this->__content = ob_get_clean();
            }
        } catch (\Exception $ex) {
            ob_end_clean();
            throw $ex;
        }
        if ($includeReturn === false && empty($this->__content)) {
            throw new Exception\UnexpectedValueException(sprintf(
                '%s: Unable to render template "%s"; file include failed',
                __METHOD__,
                $this->__file
            ));
        }
    }

    $this->setVars(array_pop($this->__varsCache));

    if ($this->__filterChain instanceof FilterChain) {
        return $this->__filterChain->filter($this->__content); // filter output
    }

    return $this->__content;
}
}

and then you code should look like:

$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);

$renderer = new MyPhpRenderer();
$html = $renderer->render($view);


问:
What is the importance of IMetadataExchange in WCF?
What is the use and importance of IMetadataExchange in WCF?

I have the following app.config file in which I don't use IMetadataExchange endpoint, but I am still able to create my proxy client. I have read that if I don't use IMetadataExchange endpoint, AddServiceReference will not work because my service does not expose the metadata. How is it working without exposing IMetadataExchange endpoint?

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metaDataBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
           <service name ="WCFService.Services" behaviorConfiguration="metaDataBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8090/Services/"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="WCFService.IMathOperations"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>
</code>```

答:
The difference is:

```<code><serviceMetadata httpGetEnabled="true"/>
</code>```

allows you to retrieve metadata using the HTTP protocol.

```<code><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</code>```

allows you to retrieve metadata using the ws-metadata protocol.

Just <serviceMetadata httpGetEnabled="true"/> works, but not all clients can call you (because they can't retrieve metadata to create a proxy).

The standard is to publish both.

See also ServiceMetadataBehavior Class (MSDN).

Body:
What is the use and importance of IMetadataExchange in WCF?

I have the following app.config file in which I don't use IMetadataExchange endpoint, but I am still able to create my proxy client. I have read that if I don't use IMetadataExchange endpoint, AddServiceReference will not work because my service does not expose the metadata. How is it working without exposing IMetadataExchange endpoint?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metaDataBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
           <service name ="WCFService.Services" behaviorConfiguration="metaDataBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8090/Services/"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="WCFService.IMathOperations"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

Body:
The difference is:

<serviceMetadata httpGetEnabled="true"/>

allows you to retrieve metadata using the HTTP protocol.

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

allows you to retrieve metadata using the ws-metadata protocol.

Just <serviceMetadata httpGetEnabled="true"/> works, but not all clients can call you (because they can't retrieve metadata to create a proxy).

The standard is to publish both.

See also ServiceMetadataBehavior Class (MSDN).


问:
Lambda failed with error grpc_extension.js:38:15
I have added npm gcloud to my Lambda project and it fails immediately when my Lambda function starts, I think it as something with the node version but I could't find any resolution

Error:

module initialization error: Error at Error (native)
at Object.Module._extensions..node (module.js:434:18)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/grpc/src/node/src/grpc_extension.js:38:15)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)

my dependencies:

```<code>    "amqplib": "^0.4.2",
    "async": "^2.0.0-rc.6",
    "aws-sdk": "^2.4.4",
    "dogapi": "^2.3.0",
    "elasticsearch": "^11.0.1",
    "elasticsearch-streams": "0.0.9",
    "gcloud": "^0.37.0",
    "googleapis": "^9.0.0",
    "moment": "^2.14.1",
    "node-uuid": "^1.4.7",
    "util": "^0.10.3"
</code>```

答: It seems some node packages uses pre-compiled binary. So it needs to be compiled on a target platform, Amazon Linux AMI in your case. You can create Amazon EC2 instance put your project on it, run npm i, zip it and download on your pc, then upload archive on Lambda.

Body:
I have added npm gcloud to my Lambda project and it fails immediately when my Lambda function starts, I think it as something with the node version but I could't find any resolution

Error:

module initialization error: Error at Error (native)
at Object.Module._extensions..node (module.js:434:18)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/grpc/src/node/src/grpc_extension.js:38:15)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)

my dependencies:

    "amqplib": "^0.4.2",
    "async": "^2.0.0-rc.6",
    "aws-sdk": "^2.4.4",
    "dogapi": "^2.3.0",
    "elasticsearch": "^11.0.1",
    "elasticsearch-streams": "0.0.9",
    "gcloud": "^0.37.0",
    "googleapis": "^9.0.0",
    "moment": "^2.14.1",
    "node-uuid": "^1.4.7",
    "util": "^0.10.3"


问:
unable to solve rspec issue for a remote file resource
I tried to write rspec for one of my remote_file resource. But I am unsuccessful to make it.

My concept is using remote_file it should download a remote file which is a zip file. What happen is rspec is expecting more after It downloaded remotely.

This is my resource declaration:

```<code>remote_file zip_file_location do
  source http://google.com
  mode '0754'
  action :create
end
</code>```

This is my rspec test:

```<code>it 'creates a remote_file ' do
    expect(chef_run).to create_remote_file(::File.join(Chef::Config[:file_cache_path], 'sonarqube-5.6.6.zip'))
end
</code>```

答:
For few reasons this worked me, I modified my code by giving path for remote file which helped me to solve rspec to expect exactly the zip file location

this helped me to solve rspec

remote_file 'Download zip file'do
Path zip_file_location
source http://google.com
mode '0754'
action :create
end

it 'creates a remote_file ' do
expect(chef_run).to create_remote_file('Download remote file')
end```

Body:
I tried to write rspec for one of my remote_file resource. But I am unsuccessful to make it.

My concept is using remote_file it should download a remote file which is a zip file. What happen is rspec is expecting more after It downloaded remotely.

This is my resource declaration:

remote_file zip_file_location do
  source http://google.com
  mode '0754'
  action :create
end

This is my rspec test:

it 'creates a remote_file ' do
    expect(chef_run).to create_remote_file(::File.join(Chef::Config[:file_cache_path], 'sonarqube-5.6.6.zip'))
end


问:
I want to have a delimiter at end of a tr in jquery
I want to have a delimiter as comma for separation of a cell and a delimiter for end of a tr in a HTML table using jQuery. Also I have all these rows as a checked checkbox. I am currently using the below function:

```<code>var values = new Array();

$.each($("input[name='case[]']:checked").closest("td").siblings("td"), function () {
  values.push($(this).text());
});

alert("val---" + values.join(", "));
</code>```

答:
if I have A B C D E F then I am looking for A,B;C,D;E,F

In this case you need two loops; one through the rows and another through the cells. Each loop can build an array of the values and then be joined by , and ; respectively. Try this:

var output = $('table tr:has(:checkbox:checked)').map(function() {
  return [$(this).find('td:not(:first)').map(function() {
    return $(this).text();
  }).get().join(',')];
}).get().join(';');

console.log(output);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="checkbox" checked="true" /></td>
    <td>A</td>
    <td>B</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>C</td>
    <td>D</td>
  </tr>
  <tr>
    <td><input type="checkbox" checked="true" /></td>
    <td>E</td>
    <td>F</td>
  </tr>
</table></code>```

Body:
I want to have a delimiter as comma for separation of a cell and a delimiter for end of a tr in a HTML table using jQuery. Also I have all these rows as a checked checkbox. I am currently using the below function:

var values = new Array();

$.each($("input[name='case[]']:checked").closest("td").siblings("td"), function () {
  values.push($(this).text());
});

alert("val---" + values.join(", "));

Body:
if I have A B C D E F then I am looking for A,B;C,D;E,F

In this case you need two loops; one through the rows and another through the cells. Each loop can build an array of the values and then be joined by , and ; respectively. Try this:

var output = $('table tr:has(:checkbox:checked)').map(function() {
  return [$(this).find('td:not(:first)').map(function() {
    return $(this).text();
  }).get().join(',')];
}).get().join(';');

console.log(output);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="checkbox" checked="true" /></td>
    <td>A</td>
    <td>B</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>C</td>
    <td>D</td>
  </tr>
  <tr>
    <td><input type="checkbox" checked="true" /></td>
    <td>E</td>
    <td>F</td>
  </tr>
</table>


问:
IE 11 - How to prevent checkbox from becoming checked after it has been clicked on?
This is my HTML:

```<code><table>
    <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
    </tr>
    <tr>
        <td>R1 C1</td>
        <td>R1 C2</td>
        <td><input class="CB" type="checkbox" /></td>
    </tr>
    <tr>
        <td>R2 C1</td>
        <td>R2 C2</td>
        <td><input class="CB" type="checkbox" /></td>
    </tr>
    <tr>
        <td>R3 C1</td>
        <td>R3 C2</td>
        <td><input class="CB" type="checkbox" /></td>
    </tr>
    <tr>
        <td>R4 C1</td>
        <td>R4 C2</td>
        <td><input class="CB" type="checkbox" /></td>
    </tr>
    <tr>
        <td>R5 C1</td>
        <td>R5 C2</td>
        <td><input class="CB" type="checkbox" /></td>
    </tr>
</table>
</code>```

This is JavaScript:

```<code>      $(".CB").change(function (e)
    {
        if ($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
    }
    );
</code>```

JSFiddle

This is related to IE 11.

As you can see when you click on unchecked checkbox it becomes checked and then confirmation dialog appears. If you don't answer "OK" checkbox reverts back to being unchecked.

It works as expected in Chrome but not in IE11 (FWIW it doesn't work in FF 52 either)

How to modify this so that when you click unchecked checkbox it stays unchecked until OK is pressed on confirmation dialog?

Also: is it acceptable to use class name "CB" even though it is not actually defined anywhere? It works as far as I can tell but it may be a bad practice for reasons I am not aware of.

答:
There seems to be an issue with the event not being able to be cancelled or overruled in IE11, for this reason I have explicitly set checked to false each time and setting it according to it's previous state and the confirm response value.

$(".CB").on('change', function(e) {
  const checked = this.checked // save the previous state
  this.checked = false // uncheck the box every time
  this.checked = checked && confirm('Are you sure?') // set the new state
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="CB" type="checkbox" /></code>```

Body:
This is my HTML:

        Column 1
        Column 2
        Column 3

        R1 C1
        R1 C2
        <input class="CB" type="checkbox" />

        R2 C1
        R2 C2
        <input class="CB" type="checkbox" />

        R3 C1
        R3 C2
        <input class="CB" type="checkbox" />

        R4 C1
        R4 C2
        <input class="CB" type="checkbox" />

        R5 C1
        R5 C2
        <input class="CB" type="checkbox" />

This is JavaScript:

      $(".CB").change(function (e)
    {
        if ($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
    }
    );

JSFiddle

This is related to IE 11.

As you can see when you click on unchecked checkbox it becomes checked and then confirmation dialog appears. If you don't answer "OK" checkbox reverts back to being unchecked.

It works as expected in Chrome but not in IE11 (FWIW it doesn't work in FF 52 either)

How to modify this so that when you click unchecked checkbox it stays unchecked until OK is pressed on confirmation dialog?

Also: is it acceptable to use class name "CB" even though it is not actually defined anywhere? It works as far as I can tell but it may be a bad practice for reasons I am not aware of.

Body:
There seems to be an issue with the event not being able to be cancelled or overruled in IE11, for this reason I have explicitly set checked to false each time and setting it according to it's previous state and the confirm response value.

$(".CB").on('change', function(e) {
  const checked = this.checked // save the previous state
  this.checked = false // uncheck the box every time
  this.checked = checked && confirm('Are you sure?') // set the new state
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="CB" type="checkbox" />


问:
How to access Laravel Homestead on other devices?
My machine and Android devices are on the same network.

Machine IP: 192.168.0.11

The IP where Homestead is running: 192.168.10.10

If I enter 192.168.0.11:8000 on my Android device I can use only one site.

How can I enter all sites stored in Homestead?

This is my Homestead.yaml file:

```<code>---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Homestead-Projects
      to: /home/vagrant/Homestead-Projects

sites:
    - map: site1.com
      to: /home/vagrant/Homestead-Projects/Site1/public
    - map: site2.app
      to: /home/vagrant/Homestead-Projects/Site2/public

databases:
    - homestead
    - db_site1
    - db_site2

variables:
    - key: APP_ENV
      value: local

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 93000
#       to: 9300
#     - send: 7777
#       to: 777
#       protocol: udp
</code>```

This is my hosts file:

```<code>127.0.0.1   localhost
127.0.1.1   host

#Virtual Hosts on Homestead
192.168.10.10   site1.com
192.168.10.10   site2.com

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
</code>```

答:
tl;dr

You have to add a row for each site in your host file on the remote machine (just like in the server where Homestead is running) but with the server's IP adress. Then just type sitename.local:8000.

Example

In your case the server's IP is 192.168.0.11. Within this server, Homestead serves requests on 192.168.10.10. So in the host file of the server you have these lines:

```<code>192.168.10.10   site1.com
192.168.10.10   site2.com
</code>```

You have to copy these rows to the remote PC's host file and then replace the IP address with the server's IP: 192.168.0.11.

```<code>192.168.0.11   site1.com
192.168.0.11   site2.com
</code>```

Depending on your OS you may have to restart the PC or the DNS service. After that, you can access the sites from the remote PC in these addresses:

```<code>site1.com:8000
site2.com:8000
</code>```

Note

Keep in mind that editing (writing) the hosts file requires superuser/administrator permissions. This is easy to solve in a PC, if you have access to the administrator account, but can be complicated on a mobile device. For Android check out these questions:

Android Enthusiasts: How to edit 'etc/hosts' file?

Stack Overflow: How to change the hosts file on android?

Body:
My machine and Android devices are on the same network.

Machine IP: 192.168.0.11

The IP where Homestead is running: 192.168.10.10

If I enter 192.168.0.11:8000 on my Android device I can use only one site.

How can I enter all sites stored in Homestead?

This is my Homestead.yaml file:

---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Homestead-Projects
      to: /home/vagrant/Homestead-Projects

sites:
    - map: site1.com
      to: /home/vagrant/Homestead-Projects/Site1/public
    - map: site2.app
      to: /home/vagrant/Homestead-Projects/Site2/public

databases:
    - homestead
    - db_site1
    - db_site2

variables:
    - key: APP_ENV
      value: local

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 93000
#       to: 9300
#     - send: 7777
#       to: 777
#       protocol: udp

This is my hosts file:

127.0.0.1   localhost
127.0.1.1   host

#Virtual Hosts on Homestead
192.168.10.10   site1.com
192.168.10.10   site2.com

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Body:
tl;dr

You have to add a row for each site in your host file on the remote machine (just like in the server where Homestead is running) but with the server's IP adress. Then just type sitename.local:8000.

Example

In your case the server's IP is 192.168.0.11. Within this server, Homestead serves requests on 192.168.10.10. So in the host file of the server you have these lines:

192.168.10.10   site1.com
192.168.10.10   site2.com

You have to copy these rows to the remote PC's host file and then replace the IP address with the server's IP: 192.168.0.11.

192.168.0.11   site1.com
192.168.0.11   site2.com

Depending on your OS you may have to restart the PC or the DNS service. After that, you can access the sites from the remote PC in these addresses:

site1.com:8000
site2.com:8000

Note

Keep in mind that editing (writing) the hosts file requires superuser/administrator permissions. This is easy to solve in a PC, if you have access to the administrator account, but can be complicated on a mobile device. For Android check out these questions:

Android Enthusiasts: How to edit 'etc/hosts' file?

Stack Overflow: How to change the hosts file on android?


问:
JPA error: The state field path '***' cannot be resolved to a valid type
```<code>After running the following query method....

@Query(value = "select s.owner, " +
            "count(case when s.status = 3 then 1 else null end) as agreed," +
            "count(case when s.status = 2 then 1 else null end) as rejected," +
            "count(case when s.status = 1 then 1 else null end) as pending " +
            "from Schedule s where (s.owner = ?1) " +
            "group by s.owner")
</code>```

here status is fetched from a enum and i have a converter class for that.But during runtime it gives the below exception that while calling convertToDatabaseColumn on converter class com.orsbv.hcs.model.schedule.ScheduleStatus$TypeConverter with value 1.e

Any help regarding the issue will be very helpful.Seek experts attention.

This is the error log :

```<code>ReportQuery(referenceClass=Schedule jpql="select s.owner, count(case when s.status = 1 then 1 else null end) as agreed,count(case when s.status = 2 then 1 else null end) as rejected,count(case when s.status = 3 then 1 else null end) as pending from Schedule s where (s.owner = ?1) group by s.owner")
        at org.eclipse.persistence.exceptions.QueryException.prepareFailed(QueryException.java:1596)
        at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:685)
        at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:911)
        at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:615)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:194)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:116)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:102)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:86)
        at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1614)
        at sun.reflect.GeneratedMethodAccessor86.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
        at com.sun.proxy.$Proxy75.createQuery(Unknown Source)
        at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
        ... 48 more
Caused by: javax.persistence.PersistenceException: An exception occurred while calling convertToDatabaseColumn on converter class com.orsbv.hcs.model.schedule.ScheduleStatus$TypeConverter with value 1
</code>```

答:
you should do either

Change s.status = 3 (this should be enum)
Example s.status = Status.ACTIVE

or

Change s.status(should be integer) = 3
Example: s.status.id = 3

Body:
After running the following query method....

@Query(value = "select s.owner, " +
            "count(case when s.status = 3 then 1 else null end) as agreed," +
            "count(case when s.status = 2 then 1 else null end) as rejected," +
            "count(case when s.status = 1 then 1 else null end) as pending " +
            "from Schedule s where (s.owner = ?1) " +
            "group by s.owner")

here status is fetched from a enum and i have a converter class for that.But during runtime it gives the below exception that while calling convertToDatabaseColumn on converter class com.orsbv.hcs.model.schedule.ScheduleStatus$TypeConverter with value 1.e

Any help regarding the issue will be very helpful.Seek experts attention.

This is the error log :

ReportQuery(referenceClass=Schedule jpql="select s.owner, count(case when s.status = 1 then 1 else null end) as agreed,count(case when s.status = 2 then 1 else null end) as rejected,count(case when s.status = 3 then 1 else null end) as pending from Schedule s where (s.owner = ?1) group by s.owner")
        at org.eclipse.persistence.exceptions.QueryException.prepareFailed(QueryException.java:1596)
        at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:685)
        at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:911)
        at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:615)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:194)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:116)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:102)
        at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:86)
        at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1614)
        at sun.reflect.GeneratedMethodAccessor86.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
        at com.sun.proxy.$Proxy75.createQuery(Unknown Source)
        at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
        ... 48 more
Caused by: javax.persistence.PersistenceException: An exception occurred while calling convertToDatabaseColumn on converter class com.orsbv.hcs.model.schedule.ScheduleStatus$TypeConverter with value 1


问:
Interact with rect to take me to another page HTML JS Canvas

The Menu

I want to make it so when the user clicks play it takes you to another HTML page. I have placed a rect over the play area and want to make it so the rect is what the user is clicking as the play text is part of a single image.

This is the JS for my rect:

```<code>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Red rectangle
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(125, 140, 230, 90);
 ctx.stroke();
</code>```

答:
You can achieve it like this

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = draw;

function draw() {
    canvas.width = this.width;
    canvas.height = this.height;
    ctx.drawImage(this, 0, 0);
    ctx.beginPath();
    ctx.lineWidth = "6";
    ctx.strokeStyle = "red";
    ctx.rect(101, 114, 184, 71);
    ctx.stroke();
}

img.src = 'https://i.stack.imgur.com/M3x29.jpg';

canvas.onclick = function(e) {
    if (e.offsetX > 102 && e.offsetX < 286 && e.offsetY > 110 && e.offsetY < 182) {
        window.location = 'http://stackoverflow.com'; // another html page location
    }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas></code>```

Body:
The Menu

I want to make it so when the user clicks play it takes you to another HTML page. I have placed a rect over the play area and want to make it so the rect is what the user is clicking as the play text is part of a single image.

This is the JS for my rect:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Red rectangle
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(125, 140, 230, 90);
 ctx.stroke();

Body:
You can achieve it like this

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = draw;

function draw() {
    canvas.width = this.width;
    canvas.height = this.height;
    ctx.drawImage(this, 0, 0);
    ctx.beginPath();
    ctx.lineWidth = "6";
    ctx.strokeStyle = "red";
    ctx.rect(101, 114, 184, 71);
    ctx.stroke();
}

img.src = 'https://i.stack.imgur.com/M3x29.jpg';

canvas.onclick = function(e) {
    if (e.offsetX > 102 && e.offsetX < 286 && e.offsetY > 110 && e.offsetY < 182) {
        window.location = 'http://stackoverflow.com'; // another html page location
    }
};

<canvas id="canvas"></canvas>


问:
Showing multiple Google maps on one page with different sets of markers
I'm using the Google Maps API to try and display two Google maps on a single page - both of which have individual markers assigned to them. The markers are dynamically generated through Wordpress from different custom post types in the head.

I've managed to get one map displaying okay with the markers displaying but I cant seem to get other map working. I've tried adding separate variables for the different maps like below but still nothing.

Can anyone help?

```<code><script type="text/javascript">
                var locations = [
                    <?php  $i = 1; while ( have_posts() ) : the_post(); ?>
                        <?php $location = get_post_meta( get_the_ID(), 'rsl_latitude', true );  if($location) { ?>
                            {
                                latlng : new google.maps.LatLng(<?php echo get_post_meta( get_the_ID(), 'rsl_latitude', true ); ?>, <?php echo get_post_meta( get_the_ID(), 'rsl_longitude', true );  ?>),
                                info : document.getElementById('item<?php echo $i; ?>')
                        },

                    <?php } else {} $i++; endwhile; ?>
                ];
            </script>

        <?php else : ?>
            <!-- No matching posts, show an error -->
            <h1>Error 404 — Page not found.</h1>
        <?php endif; ?>

    <script type="text/javascript">
               var inthearea = [

      <?php $inthearea = types_child_posts("in-the-area");

               foreach ($inthearea as $area) { ?>

               <?php

                $location = get_field('location', $area->ID);
                $areacat = get_field('area_category', $area->ID);

               ?>

                <?php $i = 1 ?>
                    {
                        latlng : new google.maps.LatLng(<?php echo $location['lat'];?>, <?php echo $location['lng'];?>),

                        info : document.getElementById('item<?php echo $i; ?>')
                    },

                <?php $i++; }   ?>
                {
                        latlng : new google.maps.LatLng(<?php echo get_post_meta( get_the_ID(), 'rsl_latitude', true ); ?>, <?php echo get_post_meta( get_the_ID(), 'rsl_longitude', true );  ?>),
                        info : document.getElementById('item<?php echo $i; ?>')
                            },

    ];

              </script>

    var infowindow = new google.maps.InfoWindow();

function initialize() {
    map = new google.maps.Map(document.getElementById('map1'), {
        zoom: 12,
        center: new google.maps.LatLng(38.898748, -77.037684),
         scrollwheel:  false ,
        styles: [
        {
            "featureType": "administrative",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#245e7c"
                }
            ]
        },
        {
            "featureType": "landscape",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#f2f2f2"
                }
            ]
        },
        {
            "featureType": "poi",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "all",
            "stylers": [
                {
                    "saturation": -100
                },
                {
                    "lightness": 45
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "simplified"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "transit",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "water",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#d8dbdc"
                },
                {
                    "visibility": "on"
                }
            ]
        }
    ]
    });

    var latlngbounds = new google.maps.LatLngBounds();

    for (var i = 0; i < locations.length; i++) {
        var marker = new google.maps.Marker({
            position: locations[i].latlng,
            map: map,
            icon: 'https://rslcloud.co.uk/wp-content/themes/rsl-theme/img/map-markerv2.png'
        });
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(locations[i].info);
            infowindow.open(map, marker);
          }
        })(marker, i));

        latlngbounds.extend(marker.position);

        //Center map and adjust Zoom based on the position of all markers.
        if (latlngbounds.getNorthEast().equals(latlngbounds.getSouthWest())) {
   var extendPoint = new google.maps.LatLng(latlngbounds.getNorthEast().lat() + 0.01, latlngbounds.getNorthEast().lng() + 0.01);
   latlngbounds.extend(extendPoint);
}
map.fitBounds(latlngbounds);
        map.setCenter(latlngbounds.getCenter());

    }
}

map2 = new google.maps.Map(document.getElementById('map2'), {
        zoom: 12,
        center: new google.maps.LatLng(38.898748, -77.037684),
         scrollwheel:  false ,
        styles: [
        {
            "featureType": "administrative",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#245e7c"
                }
            ]
        },
        {
            "featureType": "landscape",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#f2f2f2"
                }
            ]
        },
        {
            "featureType": "poi",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "all",
            "stylers": [
                {
                    "saturation": -100
                },
                {
                    "lightness": 45
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "simplified"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "transit",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "water",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#d8dbdc"
                },
                {
                    "visibility": "on"
                }
            ]
        }
    ]
    });

    var latlngbounds = new google.maps.LatLngBounds();

    for (var i = 0; i < inthearea.length; i++) {
        var marker = new google.maps.Marker({
            position: inthearea[i].latlng,
            map: map2,
            icon: 'https://rslcloud.co.uk/wp-content/themes/rsl-theme/img/map-markerv2.png'
        });
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(inthearea[i].info);
            infowindow.open(map2, marker);
          }
        })(marker, i));

        latlngbounds.extend(marker.position);

        //Center map and adjust Zoom based on the position of all markers.
        if (latlngbounds.getNorthEast().equals(latlngbounds.getSouthWest())) {
   var extendPoint = new google.maps.LatLng(latlngbounds.getNorthEast().lat() + 0.01, latlngbounds.getNorthEast().lng() + 0.01);
   latlngbounds.extend(extendPoint);
}
map.fitBounds(latlngbounds);
        map.setCenter(latlngbounds.getCenter());

    }

initialize();
</code>```

答:
this s just a suggestion  .. and not a proper answer  si not easy do this in comment so

atte the end of you code you have  a reference to

```<code>map.fitBounds(latlngbounds);
    map.setCenter(latlngbounds.getCenter());

}

initialize();
</code>```

should be

```<code>  map2.fitBounds(latlngbounds);
  map2.setCenter(latlngbounds.getCenter());
</code>```

then could you some others msimatching map/map2 assignement that create problems or wrong behavior

Body:
I'm using the Google Maps API to try and display two Google maps on a single page - both of which have individual markers assigned to them. The markers are dynamically generated through Wordpress from different custom post types in the head.

I've managed to get one map displaying okay with the markers displaying but I cant seem to get other map working. I've tried adding separate variables for the different maps like below but still nothing.

Can anyone help?

        <?php else : ?>

Error 404 — Page not found.

        <?php endif; ?>

    var infowindow = new google.maps.InfoWindow();

function initialize() {
    map = new google.maps.Map(document.getElementById('map1'), {
        zoom: 12,
        center: new google.maps.LatLng(38.898748, -77.037684),
         scrollwheel:  false ,
        styles: [
        {
            "featureType": "administrative",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#245e7c"
                }
            ]
        },
        {
            "featureType": "landscape",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#f2f2f2"
                }
            ]
        },
        {
            "featureType": "poi",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "all",
            "stylers": [
                {
                    "saturation": -100
                },
                {
                    "lightness": 45
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "simplified"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "transit",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "water",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#d8dbdc"
                },
                {
                    "visibility": "on"
                }
            ]
        }
    ]
    });

    var latlngbounds = new google.maps.LatLngBounds();

    for (var i = 0; i < locations.length; i++) {
        var marker = new google.maps.Marker({
            position: locations[i].latlng,
            map: map,
            icon: 'https://rslcloud.co.uk/wp-content/themes/rsl-theme/img/map-markerv2.png'
        });
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(locations[i].info);
            infowindow.open(map, marker);
          }
        })(marker, i));

        latlngbounds.extend(marker.position);

        //Center map and adjust Zoom based on the position of all markers.
        if (latlngbounds.getNorthEast().equals(latlngbounds.getSouthWest())) {
   var extendPoint = new google.maps.LatLng(latlngbounds.getNorthEast().lat() + 0.01, latlngbounds.getNorthEast().lng() + 0.01);
   latlngbounds.extend(extendPoint);
}
map.fitBounds(latlngbounds);
        map.setCenter(latlngbounds.getCenter());

    }
}

map2 = new google.maps.Map(document.getElementById('map2'), {
        zoom: 12,
        center: new google.maps.LatLng(38.898748, -77.037684),
         scrollwheel:  false ,
        styles: [
        {
            "featureType": "administrative",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#245e7c"
                }
            ]
        },
        {
            "featureType": "landscape",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#f2f2f2"
                }
            ]
        },
        {
            "featureType": "poi",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "all",
            "stylers": [
                {
                    "saturation": -100
                },
                {
                    "lightness": 45
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "simplified"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "transit",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "water",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#d8dbdc"
                },
                {
                    "visibility": "on"
                }
            ]
        }
    ]
    });

    var latlngbounds = new google.maps.LatLngBounds();

    for (var i = 0; i < inthearea.length; i++) {
        var marker = new google.maps.Marker({
            position: inthearea[i].latlng,
            map: map2,
            icon: 'https://rslcloud.co.uk/wp-content/themes/rsl-theme/img/map-markerv2.png'
        });
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(inthearea[i].info);
            infowindow.open(map2, marker);
          }
        })(marker, i));

        latlngbounds.extend(marker.position);

        //Center map and adjust Zoom based on the position of all markers.
        if (latlngbounds.getNorthEast().equals(latlngbounds.getSouthWest())) {
   var extendPoint = new google.maps.LatLng(latlngbounds.getNorthEast().lat() + 0.01, latlngbounds.getNorthEast().lng() + 0.01);
   latlngbounds.extend(extendPoint);
}
map.fitBounds(latlngbounds);
        map.setCenter(latlngbounds.getCenter());

    }

initialize();

Body:
this s just a suggestion  .. and not a proper answer  si not easy do this in comment so

atte the end of you code you have  a reference to

map.fitBounds(latlngbounds);
    map.setCenter(latlngbounds.getCenter());

}

initialize();

should be

  map2.fitBounds(latlngbounds);
  map2.setCenter(latlngbounds.getCenter());

then could you some others msimatching map/map2 assignement that create problems or wrong behavior


问:
Datatables - no search or filter feature
I recently got this to work on another application I am working on and thought I'd apply it to an existing project, but it's not working for the second thing. I feel like I'm missing some js file or something but I've tried everything I can find. I tried to get it to work on a simple page test and it seems to show the CSS, but not the search or filtering.

Here is my page:

```<code>    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment-with-locales.min.js"></script>
<script type="text/javascript" language="javascript" src='https://cdn.datatables.net/1.10.13/js/jquery.dataTables.js'></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/javascript" language="javascript" src="http://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"></script>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js">

<script>
    $(document).ready(function(){
        $('#myTable').DataTable( {

        } );
    });
</script>

<table id="myTable" class="display table" width="80%">
    <tr>
        <th>stuff</th><th>things</th><th>hi</th>
    </tr>
    <tr>
        <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
    </tr>
    <tr>
        <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
    </tr>
    <tr>
        <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
    </tr>
</table>
</code>```

Any ideas?

答:
Datatables website states in the usage page you need thead and tbody tags for it to initialize</p>

```<code><table id="myTable" class="display table" width="80%">
       <thead> <tr>
            <th>stuff</th><th>things</th><th>hi</th>
        </tr>
       </thead>
       <tbody>
        <tr>
            <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
        </tr>
        <tr>
        <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
    </tr>
    <tr>
        <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
    </tr>
   </tbody>
</table>
</code>```

Body:
I recently got this to work on another application I am working on and thought I'd apply it to an existing project, but it's not working for the second thing. I feel like I'm missing some js file or something but I've tried everything I can find. I tried to get it to work on a simple page test and it seems to show the CSS, but not the search or filtering.

Here is my page:

    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" href="http://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js">

        stuff	things	hi

        gofgdjk	sdf	tedsdf

        gofgdjk	sdf	tedsdf

        gofgdjk	sdf	tedsdf

Any ideas?

Body:
Datatables website states in the usage page you need thead and tbody tags for it to initialize

<table id="myTable" class="display table" width="80%">
       <thead> <tr>
            <th>stuff</th><th>things</th><th>hi</th>
        </tr>
       </thead>
       <tbody>
        <tr>
            <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
        </tr>
        <tr>
        <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
    </tr>
    <tr>
        <td>gofgdjk</td><td>sdf</td><td>tedsdf</td>
    </tr>
   </tbody>
</table>


问:
Can not run tests from non-root folder
I have a tests which looks like:

```<code>package tst

import (
    "testing"
    "github.com/demas/cowl-go/pkg/postgres"
    "log"
    "os"
    "fmt"
    "github.com/jmoiron/sqlx"
    "github.com/demas/cowl-go/pkg/quzx-crawler"
    "github.com/SlyMarbo/rss"
    "time"
    _ "github.com/lib/pq"
)

func TestMain(m *testing.M) {

    prepare()
    retCode := m.Run()
    os.Exit(retCode)
}

func prepare() {
    connectionString := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=disable",
        os.Getenv("DBUSER"),
        os.Getenv("DBPASS"),
        os.Getenv("DBHOST"),
        os.Getenv("DBPORT"),
        os.Getenv("DBNAME"))

    db, err := sqlx.Open("postgres", connectionString)
    if err != nil {
        log.Fatal(err)
    }

    db.Exec(`DELETE FROM Settings`)
    db.Exec(`DELETE FROM HackerNews`)
    // ....
}
</code>```

Tests works fine if I keep in the root project folder, but if I move them to tst folder I get error message:

```<code>D:\development\gopath\src\github.com\demas\cowl-go\tst>go test -v
2017/03/31 16:30:06 sql: unknown driver "postgres" (forgotten import?)
exit status 1
FAIL    github.com/demas/cowl-go/tst    0.085s
</code>```

Why ?

答:
As already mentioned by @JimB in the comments, the error means that you're trying to open a db connection, using sqlx.Open, without first importing a db driver. This can be fixed by, in your case, adding this _ "github.com/lib/pq" import spec.

If, even after adding that import, you're still seeing the same error, then that means that one of your dependencies is also trying to open a db connection without first importing the necessary driver.

Please note that while log.Fatal is a nice and clean way to stop your program it can sometimes be lacking, as you already know. You might want to consider using panic instead, its output is much more chaotic but, on the other hand, you'll get the line number and file name that caused the panic and eventually you'll learn to parse it quickly.

Title: Can not run tests from non-root folder

Body:
I have a tests which looks like:

package tst

import (
    "testing"
    "github.com/demas/cowl-go/pkg/postgres"
    "log"
    "os"
    "fmt"
    "github.com/jmoiron/sqlx"
    "github.com/demas/cowl-go/pkg/quzx-crawler"
    "github.com/SlyMarbo/rss"
    "time"
    _ "github.com/lib/pq"
)

func TestMain(m *testing.M) {

    prepare()
    retCode := m.Run()
    os.Exit(retCode)
}

func prepare() {
    connectionString := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=disable",
        os.Getenv("DBUSER"),
        os.Getenv("DBPASS"),
        os.Getenv("DBHOST"),
        os.Getenv("DBPORT"),
        os.Getenv("DBNAME"))

    db, err := sqlx.Open("postgres", connectionString)
    if err != nil {
        log.Fatal(err)
    }

    db.Exec(`DELETE FROM Settings`)
    db.Exec(`DELETE FROM HackerNews`)
    // ....
}

Tests works fine if I keep in the root project folder, but if I move them to tst folder I get error message:

D:\development\gopath\src\github.com\demas\cowl-go\tst>go test -v
2017/03/31 16:30:06 sql: unknown driver "postgres" (forgotten import?)
exit status 1
FAIL    github.com/demas/cowl-go/tst    0.085s

Why ?


问:
How to hint use of UIView subclass for compiler
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

```<code>- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}
</code>```

This is fine until I call a method of UIWebView's. For example...

```<code>[self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...leads to a compiler warning...

```<code>warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'
</code>```

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

```<code>[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

```<code>warning: property 'view' type does not match super class 'UIViewController' property type
</code>```

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...

答:
Cast the value or add a new UIWebView instance variable to you viewController.

It is not the job of UIViewController's view method to tell your fellows what kind of subclass you have used.

If you could do what you wanted to do you would just have to cast back to UIView in all the places UIKit expects UIViewController's view method to return a UIView.

ContentLicense: CC BY-SA 2.5

Body:
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}

This is fine until I call a method of UIWebView's. For example...

[self.view loadHTMLString:HTMLString baseURL:baseURL];

...leads to a compiler warning...

warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

warning: property 'view' type does not match super class 'UIViewController' property type

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...


问:
html attributes coming as encoded values from Database instead of same values Ex; " as "
We have a set of links, whose href and anchor text is coming from Database.
anchor text.

Requirement is  to add the tooltip for one of the links with title attribute.
So,  I am trying to add title attribute by making changes href_value in DB as
href_value" title="title
So that my first double quotes in DB will pair up with starting double quotes of href in code and my second double quotes with closing double quotes of href in code

```<code><a href="*href_value" title="title_value"
</code>```

But the browser is considering the whole entry as href_value neglecting the internal double quotes coming from Database.

JSF output link is used for list of links.

Whatever coming from Database, It is coming as enquoted ones.

```<code><span> as <span;>
</code>```

答:
You can use the Apache Commons Lang library for this purposes:

```<code>import org.apache.commons.lang3.StringEscapeUtils;
</code>```

Encode:

```<code>System.out.println( StringEscapeUtils.escapeHtml4( "<to_encode>" ) );
</code>```

Decode:

```<code>System.out.println( StringEscapeUtils.unescapeHtml4( "<to_decode>" ) );
</code>```

Body:
We have a set of links, whose href and anchor text is coming from Database.
anchor text.

Requirement is  to add the tooltip for one of the links with title attribute.
So,  I am trying to add title attribute by making changes href_value in DB as
href_value" title="title
So that my first double quotes in DB will pair up with starting double quotes of href in code and my second double quotes with closing double quotes of href in code

<a href="*href_value" title="title_value"

But the browser is considering the whole entry as href_value neglecting the internal double quotes coming from Database.

JSF output link is used for list of links.

Whatever coming from Database, It is coming as enquoted ones.

 as

Body:
You can use the Apache Commons Lang library for this purposes:

import org.apache.commons.lang3.StringEscapeUtils;

Encode:

System.out.println( StringEscapeUtils.escapeHtml4( "<to_encode>" ) );

Decode:

System.out.println( StringEscapeUtils.unescapeHtml4( "&lt;to_decode&gt;" ) );


问:
Change db credentials while login in websphere
I have an application hosted on  IBM Websphere and WebSeal as proxy server.

I need to change the database password, but I`m not sure how can I configure the new db credentials in the web server so that the application can access the database.

答: Database credentials for relational databases connected to WebSphere app server via a JDBC driver are configured and managed via one or more DataSources and JDBCProviders.   Start with this IBM KnowledgeCenter topic.  The credentials are properties of the DataSource.</p>


问:
Inception-v3 using RMSProp epsilon=1
I just read the Inception-v3 paper, and its training code released by the authors. And I found that when do RMSProp
optimization, the authors used epsilon=1. However, to my knowledge, people usually used 1e-10 or some small values and Tensorflow set the default value to 1e-10.

So my question is how will the epsilon influence the optimization? Why we need a epsilon=1 here?
Thank you!

答:
Through this github issue I found a post explaining the value: https://groups.google.com/a/tensorflow.org/d/msg/discuss/1JDPbuHN39w/AVXdYeaDCAAJ

In this post one of the inception v3 authors explains that they needed such a high epsilon to train it with async SGD and that lower values might actually work (better) for sync SGD.

Title: Inception-v3 using RMSProp epsilon=1


问:
How to use list values as range?
I have a list of integers and a QTableWidget populated with 33 rows.

My list is like this (which corresponds to the rows in the QTableWidget):

```<code>my_list = [15, 14, 1, 2, 1]
</code>```

I would like to extract information from the table by the number of rows.

For example, I want to loop through the table for the first 15 rows, then the next 14 rows, then the next 1 row etc. So at the moment, I'm using:

```<code>my_list = [15, 14, 1, 2, 1]

for row in range(15):
    # Do something

for row in range(15,29)
    # Do something

for row in range(29,30)
    # Do something

...
</code>```

As the values in the list (and the number of items) can change, what is the most efficient way of doing this?

答:
This way you can get your pairs an use them for range():

```<code>import numpy as np

my_list = [15, 14, 1, 2, 1]

top = list(np.cumsum(my_list))
bottom = list(np.subtract(np.cumsum(my_list),my_list))

pairs = zip(bottom,top)
ranges = iter([range(x[0], x[1]) for x in pairs])
</code>```

Now, you can just go:

```<code>for item in next(ranges):
</code>```

EDIT #1

If your # Do something is always different you can use:

```<code>for row in next(ranges):
    # Do something

for row in next(ranges):
    # Do something
</code>```

EDIT #2

If you your #Do something is always the same you can go:

```<code>for item in my_list:
    for row in next(ranges):
        # Do something
</code>```

Title: How to use list values as range?

Body:
I have a list of integers and a QTableWidget populated with 33 rows.

My list is like this (which corresponds to the rows in the QTableWidget):

my_list = [15, 14, 1, 2, 1]

I would like to extract information from the table by the number of rows.

For example, I want to loop through the table for the first 15 rows, then the next 14 rows, then the next 1 row etc. So at the moment, I'm using:

my_list = [15, 14, 1, 2, 1]

for row in range(15):
    # Do something

for row in range(15,29)
    # Do something

for row in range(29,30)
    # Do something

...

As the values in the list (and the number of items) can change, what is the most efficient way of doing this?

Body:
This way you can get your pairs an use them for range():

import numpy as np

my_list = [15, 14, 1, 2, 1]

top = list(np.cumsum(my_list))
bottom = list(np.subtract(np.cumsum(my_list),my_list))

pairs = zip(bottom,top)
ranges = iter([range(x[0], x[1]) for x in pairs])

Now, you can just go:

for item in next(ranges):

EDIT #1

If your # Do something is always different you can use:

for row in next(ranges):
    # Do something

for row in next(ranges):
    # Do something

EDIT #2

If you your #Do something is always the same you can go:

for item in my_list:
    for row in next(ranges):
        # Do something


问:
create iptables rule per process/service
is it possible to use iptables in order to permit traffic initiated by a "process", ie using the process name? I would like for example to allow everything that is initiated by ping command. </p>

答:
It looks like the owner iptables module is that what you want. First, check if it's available in Your system:

```<code>iptables -m owner --help
</code>```

You can read more here: http://www.frozentux.net/iptables-tutorial/iptables-tutorial.html#OWNERMATCH

Body:
It looks like the owner iptables module is that what you want. First, check if it's available in Your system:

iptables -m owner --help

You can read more here: http://www.frozentux.net/iptables-tutorial/iptables-tutorial.html#OWNERMATCH


问:
how can i close the gab between the rows
I have six blocks. I combined the top and bottom and now there is a gap. anyway to move this row up without breaking anything?I would like to know how to solve this issue with bootstrap.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="" crossorigin="anonymous">

                    ss

```

答:
The gaps are coming from the padding on the bootstrap rows, create a class to remove the padding and add it to each of your rows.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="" crossorigin="anonymous">

        ss

```

Body:
The gaps are coming from the padding on the bootstrap rows, create a class to remove the padding and add it to each of your rows.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="" crossorigin="anonymous">
<div class='col-lg-8'>
<div class='row'>
<div class="col-lg-6 col-md-4 col-sm-6">
    <a href="portfolio-item.html">
         <img class="img-responsive img-home-portfolio" src="https://placehold.it/600x250">
    </a>
&nbsp;&nbsp;&nbsp;&nbsp;</div>
<div class="col-lg-6 col-md-4 col-sm-6">
    <a href="portfolio-item.html">
        <img class="img-responsive img-home-portfolio" src="https://placehold.it/600x250">
    </a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
<div class="col-lg-6 col-md-4 col-sm-6">
    <a href="portfolio-item.html">
         <img class="img-responsive img-home-portfolio" src="https://placehold.it/600x250">
    </a>
&nbsp;&nbsp;&nbsp;&nbsp;</div>
<div class="col-lg-6 col-md-4 col-sm-6">
    <a href="portfolio-item.html">
        <img class="img-responsive img-home-portfolio" src="https://placehold.it/600x250">
    </a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
</div>
</div>

<div class="col-lg-4">
    <a href="portfolio-item.html">
        <img class="img-responsive img-home-portfolio" src="https://placehold.it/400x450">ss
    </a>
&nbsp;&nbsp;&nbsp;&nbsp;</div>
</div>
        <!-- /.row -->

    </div>
    <!-- /.container -->
</div>


问:
Marklogic- How get a list of elements in a document
I describe table_name in Oracle to show list of fields.  How can I do that in Marklogic to get a list of elements in a document. Thanks in advance.

Oracle:
DESCRIBE EMP_DETAILS

Name

EMPLOYEE_ID

 JOB_ID

 MANAGER_ID

 DEPARTMENT_ID

答:
It's definitely not an apples-to-apples comparison, since documents in MarkLogic equate more to rows than tables.  But since documents are self-describing, you're right that you can ask for a list of elements in a document.  Using XQuery, try this:

```<code>doc($uri)//*/name()
</code>```

That selects all elements, and prints their name.  In MarkLogic, that will also show you the names of properties in a JSON document.

But if you really want to do something more like Oracle, with a describe table, you can create views and use good 'ol SQL to describe them.

Body:
It's definitely not an apples-to-apples comparison, since documents in MarkLogic equate more to rows than tables.  But since documents are self-describing, you're right that you can ask for a list of elements in a document.  Using XQuery, try this:

doc($uri)//*/name()

That selects all elements, and prints their name.  In MarkLogic, that will also show you the names of properties in a JSON document.

But if you really want to do something more like Oracle, with a describe table, you can create views and use good 'ol SQL to describe them.


问:
MySQL / PHP - how to refer to and compare current loop field name from inside nested loop
I'm building a TV Guide.
I want to do a single query "select * from programmes".
Because, I've had it working with lots of little queries, i.e., 1 per each channel, but that's inefficient.
Please can somebody help see what is wrong here?
I'm getting "Fatal error: Cannot use object of type mysqli_result as array in script.php"

channels table

```<code>name
bbcone
bbctwo
</code>```

programmes table

```<code>channel - time - title
bbcone - 6pm - news
bbcone - 6.30 - weather
bbcone - 7pm - the talk show
bbctwo - 6pm - simpsons
bbctwo - 6.30 - futurama
bbctwo - 7pm - nature

$channels=mysqli_query($db,$getchans);
$programmes=mysqli_query($db,$getprogs);  //holds all programmes

while ($channel = $channels->fetch_assoc())
{
css channel name divs and echo $channel['name']; //works

       while ($programme = $programmes->fetch_assoc())
       {
           if ($programme['channel'] == $channel['name']);
           {
            do programme divs
           }
       }
}
</code>```

I can echo both values $programme['channel'] and $channel['name'] elsewhere and they both work, e.g., BBC1.

I can't for the life of me work out how to loop through, foreach channel, then loop through the programmes for that channel

(expected output)

```<code>bbcone - 6pm news - 6.30 weather - 7pm the talk show - 8pm etc
bbctwo - 6pm simpsons - 6.30 futurama - 7pm nature - 8pm etc
</code>```

Please can anyone tell me what I'm doing wrong?

答:
```<code>while ($channel = $channels->fetch_assoc())
{
  // $getprogs "select * from programmes where channel_name = $channel["channel_name"]"
  $programmes=mysqli_query($db,$getprogs);
  while ($programme = $programmes->fetch_assoc())
   {
   }
}
</code>```

Body:
I'm building a TV Guide.
I want to do a single query "select * from programmes".
Because, I've had it working with lots of little queries, i.e., 1 per each channel, but that's inefficient.
Please can somebody help see what is wrong here?
I'm getting "Fatal error: Cannot use object of type mysqli_result as array in script.php"

channels table

name
bbcone
bbctwo

programmes table

channel - time - title
bbcone - 6pm - news
bbcone - 6.30 - weather
bbcone - 7pm - the talk show
bbctwo - 6pm - simpsons
bbctwo - 6.30 - futurama
bbctwo - 7pm - nature

$channels=mysqli_query($db,$getchans);
$programmes=mysqli_query($db,$getprogs);  //holds all programmes

while ($channel = $channels->fetch_assoc())
{
css channel name divs and echo $channel['name']; //works

       while ($programme = $programmes->fetch_assoc())
       {
           if ($programme['channel'] == $channel['name']);
           {
            do programme divs
           }
       }
}

I can echo both values $programme['channel'] and $channel['name'] elsewhere and they both work, e.g., BBC1.

I can't for the life of me work out how to loop through, foreach channel, then loop through the programmes for that channel

(expected output)

bbcone - 6pm news - 6.30 weather - 7pm the talk show - 8pm etc
bbctwo - 6pm simpsons - 6.30 futurama - 7pm nature - 8pm etc

Please can anyone tell me what I'm doing wrong?


问:
Update document if a field in last element in array does not equal value
I wonder how I should match a document by last element in an Array in mongodb document.
Say I want to update a specific document with new data if a field in last element of array is not equal some specific value.
I know that I can do this to check if a field in Array does not contain that value already:

```<code>myTable.update({ Thing: thisThing,
                 'myArray.Element': {$ne: parseInt(thisValue)} }, ...)
</code>```

But how should one check that the last Element (myArray.Element) in myArray is not equal to thisValue?
Note that I want to do this with findand not aggregate.

Best Regards

答:
Let's say we have collection names, looking like this:

```<code>/* 1 */
{
    "_id" : ObjectId("58de74f8c1bb7f4256adf32c"),
    "user" : "John",
    "list_friends" : [
        "Alice",
        "Bob"
    ]
}

/* 2 */
{
    "_id" : ObjectId("58de75d3c1bb7f4256adf32d"),
    "user" : "Pop",
    "list_friends" : [
        "Eve",
        "Oscar"
    ]
}
</code>```

Now, let's say we want to change "user" field to "Updated" for all users whose last friend name is different than "Oscar" (in this case that is John). This query:

```<code>db.getCollection('names').update({$where: "this.list_friends[this.list_friends.length - 1] !== 'Oscar'"}, {"$set": {"user": "Updated"}})
</code>```

modifies the collection and the final result is:

```<code>/* 1 */
{
    "_id" : ObjectId("58de74f8c1bb7f4256adf32c"),
    "user" : "Updated",
    "list_friends" : [
        "Alice",
        "Bob"
    ]
}

/* 2 */
{
    "_id" : ObjectId("58de75d3c1bb7f4256adf32d"),
    "user" : "Pop",
    "list_friends" : [
        "Eve",
        "Oscar"
    ]
}
</code>```

I tested the solution using Mongo 3.2, I am not sure if it works for older versions.

Body:
I wonder how I should match a document by last element in an Array in mongodb document.
Say I want to update a specific document with new data if a field in last element of array is not equal some specific value.
I know that I can do this to check if a field in Array does not contain that value already:

myTable.update({ Thing: thisThing,
                 'myArray.Element': {$ne: parseInt(thisValue)} }, ...)

But how should one check that the last Element (myArray.Element) in myArray is not equal to thisValue?
Note that I want to do this with findand not aggregate.

Best Regards

Body:
Let's say we have collection names, looking like this:

/* 1 */
{
    "_id" : ObjectId("58de74f8c1bb7f4256adf32c"),
    "user" : "John",
    "list_friends" : [
        "Alice",
        "Bob"
    ]
}

/* 2 */
{
    "_id" : ObjectId("58de75d3c1bb7f4256adf32d"),
    "user" : "Pop",
    "list_friends" : [
        "Eve",
        "Oscar"
    ]
}

Now, let's say we want to change "user" field to "Updated" for all users whose last friend name is different than "Oscar" (in this case that is John). This query:

db.getCollection('names').update({$where: "this.list_friends[this.list_friends.length - 1] !== 'Oscar'"}, {"$set": {"user": "Updated"}})

modifies the collection and the final result is:

/* 1 */
{
    "_id" : ObjectId("58de74f8c1bb7f4256adf32c"),
    "user" : "Updated",
    "list_friends" : [
        "Alice",
        "Bob"
    ]
}

/* 2 */
{
    "_id" : ObjectId("58de75d3c1bb7f4256adf32d"),
    "user" : "Pop",
    "list_friends" : [
        "Eve",
        "Oscar"
    ]
}

I tested the solution using Mongo 3.2, I am not sure if it works for older versions.


问:
Error Standardising variables in R : 'only defined on a data frame with all numeric variables'
I am simply looking to standardise my set of data frame variables to a 100 point scale. The original variables were on a 10 point scale with 4 decimal points.

I can see that my error is not unheard of e.g

Why am I getting a function error in seemingly similar R code?

Error: only defined on a data frame with all numeric variables with ddply on large dataset

but I have verified that all variables are numeric using

```<code>library(foreign)
library(scales)
ches <- read.csv("chesshort15.csv", header = TRUE)
ches2 <- ches[1:244, 3:10]
rescale(ches2, to = c(0,100), from = range(ches2, na.rm = TRUE, finite = TRUE))
</code>```

This gives the error: Error in FUN(X[[i]], ...) :
  only defined on a data frame with all numeric variables

I have verified that all variables are of type numeric using str(ches2) - see below:

```<code>'data.frame':   244 obs. of  8 variables:
 $ galtan            : num  8.8 9 9.65 8.62 8 ...
 $ civlib_laworder   : num  8.5 8.6 9.56 8.79 8.56 ...
 $ sociallifestyle   : num  8.89 7.2 9.65 9.21 8.25 ...
 $ immigrate_policy  : num  9.89 9.6 9.38 9.43 9.13 ...
 $ multiculturalism  : num  9.9 9.6 9.57 8.77 9.07 ...
 $ ethnic_minorities : num  8.8 9.6 9.87 9 8.93 ...
 $ nationalism       : num  9.4 10 9.82 9 8.81 ...
 $ antielite_salience: num  8 9 9.47 8.88 8.38
</code>```

In short, I'm stumped as to why it refuses to carry out the code.

For info, Head(bb) gives :

```<code>  galtan civlib_laworder sociallifestyle immigrate_policy multiculturalism ethnic_minorities
1  8.800           8.500           8.889            9.889            9.900             8.800
2  9.000           8.600           7.200            9.600            9.600             9.600
3  9.647           9.563           9.647            9.375            9.571             9.867
4  8.625           8.786           9.214            9.429            8.769             9.000
5  8.000           8.563           8.250            9.133            9.071             8.929
6  7.455           8.357           7.923            8.800            7.800             8.455
  nationalism antielite_salience
1       9.400              8.000
2      10.000              9.000
3       9.824              9.471
4       9.000              8.882
5       8.813              8.375
6       8.000              8.824
</code>```

答:
The rescale function is throwing that error because it expects a numeric vector, and you are feeding it a dataframe instead. You need to iterate; go through every column on your dataframe and scale them individually.

Try this:

```<code>sapply(ches2, rescale, to = c(0,100))
</code>```

You don't need the range(ches2, na.rm = TRUE, finite = TRUE) portion of your code because rescale is smart enough to remove NA values on its own

Body:
I am simply looking to standardise my set of data frame variables to a 100 point scale. The original variables were on a 10 point scale with 4 decimal points.

I can see that my error is not unheard of e.g

Why am I getting a function error in seemingly similar R code?

Error: only defined on a data frame with all numeric variables with ddply on large dataset

but I have verified that all variables are numeric using

library(foreign)
library(scales)
ches <- read.csv("chesshort15.csv", header = TRUE)
ches2 <- ches[1:244, 3:10]
rescale(ches2, to = c(0,100), from = range(ches2, na.rm = TRUE, finite = TRUE))

This gives the error: Error in FUN(X[[i]], ...) :
  only defined on a data frame with all numeric variables

I have verified that all variables are of type numeric using str(ches2) - see below:

'data.frame':   244 obs. of  8 variables:
 $ galtan            : num  8.8 9 9.65 8.62 8 ...
 $ civlib_laworder   : num  8.5 8.6 9.56 8.79 8.56 ...
 $ sociallifestyle   : num  8.89 7.2 9.65 9.21 8.25 ...
 $ immigrate_policy  : num  9.89 9.6 9.38 9.43 9.13 ...
 $ multiculturalism  : num  9.9 9.6 9.57 8.77 9.07 ...
 $ ethnic_minorities : num  8.8 9.6 9.87 9 8.93 ...
 $ nationalism       : num  9.4 10 9.82 9 8.81 ...
 $ antielite_salience: num  8 9 9.47 8.88 8.38

In short, I'm stumped as to why it refuses to carry out the code.

For info, Head(bb) gives :

  galtan civlib_laworder sociallifestyle immigrate_policy multiculturalism ethnic_minorities
1  8.800           8.500           8.889            9.889            9.900             8.800
2  9.000           8.600           7.200            9.600            9.600             9.600
3  9.647           9.563           9.647            9.375            9.571             9.867
4  8.625           8.786           9.214            9.429            8.769             9.000
5  8.000           8.563           8.250            9.133            9.071             8.929
6  7.455           8.357           7.923            8.800            7.800             8.455
  nationalism antielite_salience
1       9.400              8.000
2      10.000              9.000
3       9.824              9.471
4       9.000              8.882
5       8.813              8.375
6       8.000              8.824

Body:
The rescale function is throwing that error because it expects a numeric vector, and you are feeding it a dataframe instead. You need to iterate; go through every column on your dataframe and scale them individually.

Try this:

sapply(ches2, rescale, to = c(0,100))

You don't need the range(ches2, na.rm = TRUE, finite = TRUE) portion of your code because rescale is smart enough to remove NA values on its own