问:
Is it possible to run protractor tests in more than one browser language?
I need to run protractor tests in more than one browser language.
Can this be set up in the args value under chrome options?</p>

```<code>Node Version: v8.9.0
Protractor Version: 5.2.0
Browser(s): Chrome
My config file:

exports.config = {
    framework: 'jasmine',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    capabilities: {
         browserName: 'chrome',
         chromeOptions: {
              //i'd like to config >1 lang here if possible
              args: ['lang=en-AU', 'lang=ja-JP'],
              prefs: { accept_languages: ['en-AU','ja-JP'] }
              },
         suites: {
              home: './home/home.spec.js'
              }
     }
</code>```

答:
You can create multiple Chrome profiles and then select, with which profile you want to launch the browser.

In the profile you specify the language.
I guess, that's the best way, as the language option itself seems not exposed.

Alternatively, change the regional settings of your OS, as most probably that language is selected, if no other language is specified in the profile.

Body:
I need to run protractor tests in more than one browser language.
Can this be set up in the args value under chrome options?

Node Version: v8.9.0
Protractor Version: 5.2.0
Browser(s): Chrome
My config file:

exports.config = {
    framework: 'jasmine',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    capabilities: {
         browserName: 'chrome',
         chromeOptions: {
              //i'd like to config >1 lang here if possible
              args: ['lang=en-AU', 'lang=ja-JP'],
              prefs: { accept_languages: ['en-AU','ja-JP'] }
              },
         suites: {
              home: './home/home.spec.js'
              }
     }


来源: stackexchange

问:
Can I have terraform keep the old versions of objects?
New to terraform, so perhaps it just not supposed to work this way. I want to use aws_s3_bucket_object to upload a package to a bucket- this is part of an app deploy. Im going to be changing the package for each deploy and I want to keep the old versions.

```<code>resource "aws_s3_bucket_object" "object" {
    bucket = "mybucket-app-versions"
    key    = "version01.zip"
    source = "version01.zip"
}
</code>```

But after running this for a future deploy I will want to upload version02 and then version03 etc. Terraform replaces the old zip with the new one- expected behavior.

But is there a way to have terraform not destroy the old version? Is this a supported use case here or is this not how I'm supposed to use terraform? I wouldn't want to force this with an ugly hack if terraform doesn't have official support for doing something like what I'm trying to do here.

I could of course just call the S3 api via script, but it would be great to have this defined with the rest of the terraform definition for this app.

答:
Currently, you tell terraform to manage one aws_s3_bucket_object and terraform takes care of its whole life-cycle, meaning terraform will also replace the file if it sees any changes to it.

What you are maybe looking for is the null_resource. You can use it to run a local-exec provisioner to upload the file you need with a script. That way, the old file won't be deleted, as it is not directly managed by terraform. You'd still be calling the API via a script then, but the whole process of uploading to s3 would still be included in your terraform apply step.

Here an outline of the null_resource:

```<code>resource "null_resource" "upload_to_s3" {
  depends_on = ["<any resource that should already be created before upload>"]
  ...

  triggers = ["<A resource change that must have happened so terraform starts the upload>"]

  provisioner "local-exec" {
    command = "<command to upload local package to s3>"
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
New to terraform, so perhaps it just not supposed to work this way. I want to use aws_s3_bucket_object to upload a package to a bucket- this is part of an app deploy. Im going to be changing the package for each deploy and I want to keep the old versions.

resource "aws_s3_bucket_object" "object" {
    bucket = "mybucket-app-versions"
    key    = "version01.zip"
    source = "version01.zip"
}

But after running this for a future deploy I will want to upload version02 and then version03 etc. Terraform replaces the old zip with the new one- expected behavior.

But is there a way to have terraform not destroy the old version? Is this a supported use case here or is this not how I'm supposed to use terraform? I wouldn't want to force this with an ugly hack if terraform doesn't have official support for doing something like what I'm trying to do here.

I could of course just call the S3 api via script, but it would be great to have this defined with the rest of the terraform definition for this app.

Body:
Currently, you tell terraform to manage one aws_s3_bucket_object and terraform takes care of its whole life-cycle, meaning terraform will also replace the file if it sees any changes to it.

What you are maybe looking for is the null_resource. You can use it to run a local-exec provisioner to upload the file you need with a script. That way, the old file won't be deleted, as it is not directly managed by terraform. You'd still be calling the API via a script then, but the whole process of uploading to s3 would still be included in your terraform apply step.

Here an outline of the null_resource:

resource "null_resource" "upload_to_s3" {
  depends_on = ["<any resource that should already be created before upload>"]
  ...

  triggers = ["<A resource change that must have happened so terraform starts the upload>"]

  provisioner "local-exec" {
    command = "<command to upload local package to s3>"
  }
}


问:
Blog sub-domain using existing database - Wordpress
I have wordpress website like example.com and my current blog as follow example.com/blog, Now I want to move subdomain as blog.example.com also wordpress, There is anyway to fetching 'Posts' data on my blog.example.com? If possible how I can do it.

答:
for this you have to create multisite in wordpress.

create a multisite in your existing wordpress and setup a new site named blog


问:
Visual Studio 2008: .pdb files not created by "Build Solution"
I have a Visual Studio 2008 solution containing a number of C++ projects.  When I select the Debug configuration, and build each project individually, I find .pdb files for each project in the Debug directory.  But when I build the entire solution, I don't.  The output files show up in the Debug directory, but the .pdb files are missing.

Any ideas?

答:
Building the entire solution indeed builds the individual projects (in parallel, if possible). The project configuration being built is specified in the Configuration Manager Dialog Box. This also specifies if a project is built at all, or if it will be excluded from the build in that solution configuration.

So, if your PDBs aren't showing up, double-check that your projects are being built (you seem to say so, but just to be sure, delete all the intermediate and output folders, and build the solution again). Also check what project configurations are being assigned to each solution configuration. Maybe your Debug solution config actually references some Release project configs (or Debug_but_no_pdb).

If this still doesn't help, enable verbose output for the build process:

Tools > Options > Projects and Solutions > Build and Run > MSBuild project build output verbosity: Diagnostic

Also, double-check all project dependencies for invalid references.

ContentLicense: CC BY-SA 2.5


问:
How to use tomcat with spring without web.xml?
I have a JAX-RS application deployed on Tomcat 7. I am deploying the application on Tomcat without any web.xml file.

I want to use spring for injecting some of the dependencies in my project. I am not using any XML file to configure beans, instead I have created a class and annotated it with @Configuration annotation, which contains all the bean definitions. Now, I am trying to use that bean by annotating a field in a separate class with @Autowired, but the field is null.

How should I make spring work with this setup ?

EDIT:
I was able to initialize spring application context , by creating a web.xml in WEB-INF/ with the following contents.

```<code><web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
</code>```

I checked the tomcat logs , and verified that the bean is created by spring. But the problem is when I try to use that bean, the field in the class is null.

答:
You may want to use Spring Boot, which helps you develop a web application as easy as developing a stand-alone application that you can "just run".

According to official website of Spring Boot, you can create

Create stand-alone Spring applications

Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

Provide opinionated 'starter' POMs to simplify your Maven configuration

Automatically configure Spring whenever possible

Provide production-ready features such as metrics, health checks and externalized configuration

Absolutely no code generation and no requirement for XML configuration

You can learn it in just 1 hour I found this YouTube video very interesting watch Getting Started with Spring Boot.

Body:
I have a JAX-RS application deployed on Tomcat 7. I am deploying the application on Tomcat without any web.xml file.

I want to use spring for injecting some of the dependencies in my project. I am not using any XML file to configure beans, instead I have created a class and annotated it with @Configuration annotation, which contains all the bean definitions. Now, I am trying to use that bean by annotating a field in a separate class with @Autowired, but the field is null.

How should I make spring work with this setup ?

EDIT:
I was able to initialize spring application context , by creating a web.xml in WEB-INF/ with the following contents.

<web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

I checked the tomcat logs , and verified that the bean is created by spring. But the problem is when I try to use that bean, the field in the class is null.


问:
Softlayer API: Error using invoiceItem in nextInvoiceTopLevelBillingItems mask - PHP
I am trying to pull the user information from a billing item using PHP - just like in this example: https://knowledgelayer.softlayer.com/procedure/how-extract-user-billing-information-using-softlayers-api.

My code:

```<code>?php
require_once __DIR__.'/vendor/autoload.php';
.
.
.
$client = \SoftLayer\SoapClient::getClient('SoftLayer_Account', null, $apiUsername, $apiKey);

$mask = "mask[id,orderItem[id,order[userRecordId,userRecord[username]]],invoiceItem[id,totalRecurringAmount]]";
$client->setObjectMask($mask);
$userBill = $client->getNextInvoiceTopLevelBillingItems();
?>
</code>```

However, I get this error if invoiceItem included in the mask.

```<code>PHP Fatal error:  Uncaught SoapFault exception: [SOAP-ENV:Server] Internal Error in /opt/devices/vendor/softlayer/softlayer-api-php-client/src/SoapClient.php:200
Stack trace:
#0 /opt/devices/vendor/softlayer/softlayer-api-php-client/src/SoapClient.php(200): SoapClient->__call('getNextInvoiceT...', Array, NULL, Array, Array)
#1 /opt/devices/invoiceProd3.php(17): SoftLayer\SoapClient->__call('getNextInvoiceT...', Array)
#2 /opt/devices/invoiceProd3.php(17): SoftLayer\SoapClient->getNextInvoiceTopLevelBillingItems()
#3 {main}
   thrown in /opt/devices/vendor/softlayer/softlayer-api-php-client/src/SoapClient.php on line 200
</code>```

When the mask is limited to orderItem, all is good. That is, this mask works just fine.

```<code>$mask = "mask[id,orderItem[id,order[userRecordId,userRecord[username]]]];
</code>```

However, no luck with invoiceItem.

```<code>   "mask[id,invoiceItem[id,totalRecurringAmount]]";
</code>```

I'm using the 9/25/2015 soap client.

答:
for me your request is working fine using PHP, so the issue is likely that your request is returning a big amount of data, when you are using the API and the request is fetching a lot of data you may get internal errors like the one that you got. In order to solve that issue you have the followings options:

1.- Reduce the amount of data, like you did reducing the objectMask or using objectFilters
2.- Increase the timeout of the request, you can do this at moment to create the client e.g.:

```<code> $client = \SoftLayer\SoapClient::getClient($serviceName, null, $empUsername, $empPassword, $endPoint, array(
'trace' =>true,
'connection_timeout' => 500000000,
'keep_alive' => false,
));
</code>```

3.- Use pagination (result limits) in order to fetch less data in the request, you can see how to do that here:
https://sldn.softlayer.com/article/PHP

Body:
I am trying to pull the user information from a billing item using PHP - just like in this example: https://knowledgelayer.softlayer.com/procedure/how-extract-user-billing-information-using-softlayers-api.

My code:

?php
require_once __DIR__.'/vendor/autoload.php';
.
.
.
$client = \SoftLayer\SoapClient::getClient('SoftLayer_Account', null, $apiUsername, $apiKey);

$mask = "mask[id,orderItem[id,order[userRecordId,userRecord[username]]],invoiceItem[id,totalRecurringAmount]]";
$client->setObjectMask($mask);
$userBill = $client->getNextInvoiceTopLevelBillingItems();
?>

However, I get this error if invoiceItem included in the mask.

PHP Fatal error:  Uncaught SoapFault exception: [SOAP-ENV:Server] Internal Error in /opt/devices/vendor/softlayer/softlayer-api-php-client/src/SoapClient.php:200
Stack trace:
#0 /opt/devices/vendor/softlayer/softlayer-api-php-client/src/SoapClient.php(200): SoapClient->__call('getNextInvoiceT...', Array, NULL, Array, Array)
#1 /opt/devices/invoiceProd3.php(17): SoftLayer\SoapClient->__call('getNextInvoiceT...', Array)
#2 /opt/devices/invoiceProd3.php(17): SoftLayer\SoapClient->getNextInvoiceTopLevelBillingItems()
#3 {main}
   thrown in /opt/devices/vendor/softlayer/softlayer-api-php-client/src/SoapClient.php on line 200

When the mask is limited to orderItem, all is good. That is, this mask works just fine.

$mask = "mask[id,orderItem[id,order[userRecordId,userRecord[username]]]];

However, no luck with invoiceItem.

   "mask[id,invoiceItem[id,totalRecurringAmount]]";

I'm using the 9/25/2015 soap client.

Body:
for me your request is working fine using PHP, so the issue is likely that your request is returning a big amount of data, when you are using the API and the request is fetching a lot of data you may get internal errors like the one that you got. In order to solve that issue you have the followings options:

1.- Reduce the amount of data, like you did reducing the objectMask or using objectFilters
2.- Increase the timeout of the request, you can do this at moment to create the client e.g.:

 $client = \SoftLayer\SoapClient::getClient($serviceName, null, $empUsername, $empPassword, $endPoint, array(
'trace' =>true,
'connection_timeout' => 500000000,
'keep_alive' => false,
));

3.- Use pagination (result limits) in order to fetch less data in the request, you can see how to do that here:
https://sldn.softlayer.com/article/PHP


问:
How can I print the output of my custom php function in twig?
In my custom module I have the following code:

```<code>     public function url() {
      $current_path = \Drupal::service('path.current')->getPath();
      return $current_path;
 }
</code>```

How can I use this function in my twig template?

Note: I know I can get the current path much easier. I only specified this function so I can get the idea of using custom php functions in twig.

答:
You can get current path in Twig (Drupal) like this :

```<code><a href="{{ url('<current>') }}">{{ 'I represent current page URL :)'|t }}</a>
</code>```

Edit

And as defined in the Drupal doc, you can add your own functions to the twig template following this example which shows how to add a function or a filter to the twig template :

```<code>namespace Drupal\twig_extension_test\TwigExtension;

use Drupal\Core\Template\TwigExtension;

/**
 * A test Twig extension that adds a custom function and a custom filter.
 */
class TestExtension extends TwigExtension {

/**
 * Generates a list of all Twig functions that this extension defines.
 *
 * @return array
 *   A key/value array that defines custom Twig functions. The key denotes the
 *   function name used in the tag, e.g.:
 *   @code
 *   {{ testfunc() }}
 *   @endcode
 *
 *   The value is a standard PHP callback that defines what the function does.
 */
 public function getFunctions() {
     return array(
         'testfunc' => new \Twig_Function_Function(array('Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFunction')),
);
}

/**
 * Generates a list of all Twig filters that this extension defines.
 *
 * @return array
 *   A key/value array that defines custom Twig filters. The key denotes the
 *   filter name used in the tag, e.g.:
 *   @code
 *   {{ foo|testfilter }}
 *   @endcode
 *
 *   The value is a standard PHP callback that defines what the filter does.
 */
 public function getFilters() {
     return array(
          'testfilter' => new \Twig_Filter_Function(array('Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFilter')),
);
 }

/**
 * Gets a unique identifier for this Twig extension.
 *
 * @return string
 *   A unique identifier for this Twig extension.
 */
 public function getName() {
     return 'twig_extension_test.test_extension';
 }

/**
 * Outputs either an uppercase or lowercase test phrase.
 *
 * The function generates either an uppercase or lowercase version of the
 * phrase "The quick brown fox jumps over the lazy dog 123.", depending on
 * whether or not the $upperCase parameter evaluates to TRUE. If $upperCase
 * evaluates to TRUE, the result will be uppercase, and if it evaluates to
 * FALSE, the result will be lowercase.
 *
 * @param bool $upperCase
 *   (optional) Whether the result is uppercase (true) or lowercase (false).
 *
 * @return string
 *   The generated string.
 *
 * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFunction()
 */
 public static function testFunction($upperCase = FALSE) {
      $string = "The quick brown box jumps over the lazy dog 123.";
      if ($upperCase == TRUE) {
           return strtoupper($string);
      }
      else {
           return strtolower($string);
      }
  }

 /**
  * Replaces all instances of "animal" in a string with "plant".
  *
  * @param string $string
  *   The string to be filtered.
  *
  * @return string
  *   The filtered string.
  *
  * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFilter()
  */
  public static function testFilter($string) {
      return str_replace(array('animal'), array('plant'), $string);
  }

  }
</code>```

Body:
In my custom module I have the following code:

     public function url() {
      $current_path = \Drupal::service('path.current')->getPath();
      return $current_path;
 }

How can I use this function in my twig template?

Note: I know I can get the current path much easier. I only specified this function so I can get the idea of using custom php functions in twig.

Body:
You can get current path in Twig (Drupal) like this :

<a href="{{ url('<current>') }}">{{ 'I represent current page URL :)'|t }}</a>

Edit

And as defined in the Drupal doc, you can add your own functions to the twig template following this example which shows how to add a function or a filter to the twig template :

namespace Drupal\twig_extension_test\TwigExtension;

use Drupal\Core\Template\TwigExtension;

/**
 * A test Twig extension that adds a custom function and a custom filter.
 */
class TestExtension extends TwigExtension {

/**
 * Generates a list of all Twig functions that this extension defines.
 *
 * @return array
 *   A key/value array that defines custom Twig functions. The key denotes the
 *   function name used in the tag, e.g.:
 *   @code
 *   {{ testfunc() }}
 *   @endcode
 *
 *   The value is a standard PHP callback that defines what the function does.
 */
 public function getFunctions() {
     return array(
         'testfunc' => new \Twig_Function_Function(array('Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFunction')),
);
}

/**
 * Generates a list of all Twig filters that this extension defines.
 *
 * @return array
 *   A key/value array that defines custom Twig filters. The key denotes the
 *   filter name used in the tag, e.g.:
 *   @code
 *   {{ foo|testfilter }}
 *   @endcode
 *
 *   The value is a standard PHP callback that defines what the filter does.
 */
 public function getFilters() {
     return array(
          'testfilter' => new \Twig_Filter_Function(array('Drupal\twig_extension_test\TwigExtension\TestExtension', 'testFilter')),
);
 }

/**
 * Gets a unique identifier for this Twig extension.
 *
 * @return string
 *   A unique identifier for this Twig extension.
 */
 public function getName() {
     return 'twig_extension_test.test_extension';
 }

/**
 * Outputs either an uppercase or lowercase test phrase.
 *
 * The function generates either an uppercase or lowercase version of the
 * phrase "The quick brown fox jumps over the lazy dog 123.", depending on
 * whether or not the $upperCase parameter evaluates to TRUE. If $upperCase
 * evaluates to TRUE, the result will be uppercase, and if it evaluates to
 * FALSE, the result will be lowercase.
 *
 * @param bool $upperCase
 *   (optional) Whether the result is uppercase (true) or lowercase (false).
 *
 * @return string
 *   The generated string.
 *
 * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFunction()
 */
 public static function testFunction($upperCase = FALSE) {
      $string = "The quick brown box jumps over the lazy dog 123.";
      if ($upperCase == TRUE) {
           return strtoupper($string);
      }
      else {
           return strtolower($string);
      }
  }

 /**
  * Replaces all instances of "animal" in a string with "plant".
  *
  * @param string $string
  *   The string to be filtered.
  *
  * @return string
  *   The filtered string.
  *
  * @see \Drupal\system\Tests\Theme\TwigExtensionTest::testTwigExtensionFilter()
  */
  public static function testFilter($string) {
      return str_replace(array('animal'), array('plant'), $string);
  }

  }


问:
JavaScript user input text to options value not sending to php
I want user to enter number of items from a few different textboxes in iframe and display them in parent.php as one combine options list where you can select each item and delete it if you what to. Then I want to send the final list of all options values to an email through php. I got everything working until assigning the options values to php variable. I keep getting nothing no list kin email. I'm not sure how to pass the options values to php.

This is what I got so far.

parent.php

```<code><?php

 $to = 'myemail@email.com';
 $subject = 'Available Item Lists';

 if(isset($_POST['submit'])){
      foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }

      $headers = '$email';
      $headers .=  'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

      mail ($to, $subject, $body, $headers);
  }
  ?>

    <form method="post" id="quote-form" name="quote-form" action="?">
        <label for="items">List of items</label><br />
        <div class="form-section">
            <select name="qlist[]" id="qlist" multiple="multiple"></select>
            <button id="deleteButton" onclick="deleteEntry(); return
false;">Delete</button>
       <input type="submit" value="Send" name="submit" id="submit">
    </div>

<script type="text/javascript">

       function displayQuantity(noOfitems, labelVal)  {
          var qq = noOfitems;
          var labelName = labelVal;
          var quoteQuantity = document.getElementById("qlist");
          var quantity = quoteQuantity.value;
          quantity += labelName + ": ";
          quantity += qq;
          quantity += " pcs\n";
          quoteQuantity.value = quantity;
          var option = document.createElement("option");
          option.text = quantity;
          quoteQuantity.add(option);

       }

       function deleteEntry() {
          var myList = document.getElementById('qlist');
          var i;
          for (i = myList.length - 1; i>=0; i--) {
              if (myList.options[i].selected) {
                  myList.remove(i);
              }
          }
       }
</script>
</code>```

iframe.php

```<code><div class="order-quantity">
   <form name="form">
        <label id="itemType">Heavy Duty Square Core Drilled</label>
        <input type="number" id="total-quantity" name="quantity" />
        <button type="button" id="addItem"
             onclick="parent.displayQuantity(this.form.quantity.value,
         getVal())">Add</button>
   </form>
</div>

    <script type="text/javascript">
    function getVal() {
       var labelVal = document.getElementById("itemType").textContent;
       return labelVal;
    }
    </script>
</code>```

答:
Please check "enable_post_data_reading" status

Disabling this option causes $_POST and $_FILES not to be populated.

if it disabled in your php.ini file then please enable it and restart the apache

Body:
I want user to enter number of items from a few different textboxes in iframe and display them in parent.php as one combine options list where you can select each item and delete it if you what to. Then I want to send the final list of all options values to an email through php. I got everything working until assigning the options values to php variable. I keep getting nothing no list kin email. I'm not sure how to pass the options values to php.

This is what I got so far.

parent.php

<?php

 $to = 'myemail@email.com';
 $subject = 'Available Item Lists';

 if(isset($_POST['submit'])){
      foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }

      $headers = '$email';
      $headers .=  'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

      mail ($to, $subject, $body, $headers);
  }
  ?>

    <form method="post" id="quote-form" name="quote-form" action="?">
        List of items

            <select name="qlist[]" id="qlist" multiple="multiple"></select>
            <button id="deleteButton" onclick="deleteEntry(); return
false;">Delete</button>
       <input type="submit" value="Send" name="submit" id="submit">

iframe.php

   <form name="form">
        Heavy Duty Square Core Drilled
        <input type="number" id="total-quantity" name="quantity" />
        <button type="button" id="addItem"
             onclick="parent.displayQuantity(this.form.quantity.value,
         getVal())">Add</button>
   </form>


问:
How do I read a file line by line while modifying lines as needed?
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

```<code>while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}
</code>```

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

```<code>use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}
</code>```

答:
I don't think it's a good idea to read from a file and write to it at the same time like you do.

You could use Tie::File. It ties the lines of a file to an array. You can modify the array as you need which in turn modifies the file transparently in the background.

Body:
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}


问:
Message LINQ to Entities does not recognize the method System.Object Get(Int32, Int32) method
I am trying to get a List from Linq to entity-query

```<code>List<int> meas_i = wc.measures
   .Where(meas => meas.shortname == (valueArray[i, 8] ?? "").ToString())
   .Select(meas => meas.idmeasure)
   .ToList<int>();
</code>```

But after the execution I obtain the following exception (not suppported) message:

An unhandled exception of type 'System.NotSupportedException' occurred in ComplexWorkWinDraw.exe

Additional information: LINQ to Entities does not recognize the method
  'System.Object Get(Int32, Int32)' method, and this method cannot be
  translated into a store expression.

Please help. Thanks to all

答:
Try to store this in a variable before the query: valueArray[i, 8]

```<code>string shortName = (valueArray[i, 8] ?? "").ToString();

List<int> meas_i = wc.measures
   .Where(meas => meas.shortname == shortName)
   .Select(meas => meas.idmeasure)
   .ToList<int>();
</code>```

Everything in this query must be translated to SQL. But since this value is not related to the record/item you can store it in a separate variable before the query.

Body:
I am trying to get a List from Linq to entity-query

List<int> meas_i = wc.measures
   .Where(meas => meas.shortname == (valueArray[i, 8] ?? "").ToString())
   .Select(meas => meas.idmeasure)
   .ToList<int>();

But after the execution I obtain the following exception (not suppported) message:

An unhandled exception of type 'System.NotSupportedException' occurred in ComplexWorkWinDraw.exe

Additional information: LINQ to Entities does not recognize the method
  'System.Object Get(Int32, Int32)' method, and this method cannot be
  translated into a store expression.

Please help. Thanks to all

Body:
Try to store this in a variable before the query: valueArray[i, 8]

string shortName = (valueArray[i, 8] ?? "").ToString();

List<int> meas_i = wc.measures
   .Where(meas => meas.shortname == shortName)
   .Select(meas => meas.idmeasure)
   .ToList<int>();

Everything in this query must be translated to SQL. But since this value is not related to the record/item you can store it in a separate variable before the query.


问:
AWS CloudWatch alert on every change in metric
Can you set up CloudWatch to fire an event (which can lead to a Lambda function being called) on every change to a metric? I can see how to fire an even when it meets a boundary via alerts, but I'd like an event on every change.</p>

答:
If you have a metric that behaves in a predictable way then you can indeed achieve this kind of behaviour.

If you have a metric with a small set of possible values, for example, consider a metric where the value can be 0 or 1.

You could then create a CloudWatch alarm where the threshold is 0 for 1 period and then a second alarm where the threshold is 1 for 1 period.

So basically for each possible value that your metric can be, you would have an alarm. Each of these alarms would trigger an action of your choice e.g. SNS

As I said, this would only work if you have a metric with a known set of possible values, not with a metric that can have unpredictable values.


问:
How can I correctly and efficiently object initialize a List within a List object initialization?
Hello I'm asking this question because I couldn't find the necessary answer for my specific issue. I'm deeply sorry if this is duplicated, please do excuse me and I'd like to have your help on this matter.

```<code>public class MultipleChoiceQuestion {
String text;
List<String> choices;

}
</code>```

MultipleChoiceQuestion class has a list of choices.

```<code>public static void main(string[] args){

List<Question> questions = new List<Question> {

new MultipleChoiceQuestion { text = "what's 1+1", choices = ???? };

}
}
</code>```

This is my issue in particular. How can I add to a list in object initialization in object init?

答:
```<code>public static void main(string[] args)
{
    List<Question> questions = new List<Question>
    {
        new MultipleChoiceQuestion
        {
            text = "what's 1+1",
            choices = new List<string> { "2", "67" }
        };
    };
}
</code>```

Compiler-side, that inline initialization statement is translated into:

```<code>List<string> <>xxx = new List<string>();
<>xxx.Add("2");
<>xxx.Add("67");
</code>```

Body:
Hello I'm asking this question because I couldn't find the necessary answer for my specific issue. I'm deeply sorry if this is duplicated, please do excuse me and I'd like to have your help on this matter.

public class MultipleChoiceQuestion {
String text;
List<String> choices;

}

MultipleChoiceQuestion class has a list of choices.

public static void main(string[] args){

List<Question> questions = new List<Question> {

new MultipleChoiceQuestion { text = "what's 1+1", choices = ???? };

}
}

This is my issue in particular. How can I add to a list in object initialization in object init?

Body:
public static void main(string[] args)
{
    List<Question> questions = new List<Question>
    {
        new MultipleChoiceQuestion
        {
            text = "what's 1+1",
            choices = new List<string> { "2", "67" }
        };
    };
}

Compiler-side, that inline initialization statement is translated into:

List<string> <>xxx = new List<string>();
<>xxx.Add("2");
<>xxx.Add("67");


问:
How to implement Index and Row function in VBA
I would like to write the following in VBA:

```<code>=INDEX(Sheet1!B$4:B$15;(ROW(A1)-1)/730+1)
</code>```

I m trying:

```<code>With Application.WorksheetFunction

 ActiveWorkbook.Worksheets("Some_Sheet").Range("H6") = .Index(ActiveWorkbook.Worksheets("Sheet1").Range("B4:B15")), (Range("A1").Row - 1) / 730 + 1)

End With
</code>```

答: Try ActiveCell.Formula = WorksheetFunction.Index(Range("B$4:B$15"), (Range("A1").Row - 1) / 730 + 1)

Body:
I would like to write the following in VBA:

=INDEX(Sheet1!B$4:B$15;(ROW(A1)-1)/730+1)

I m trying:

With Application.WorksheetFunction

 ActiveWorkbook.Worksheets("Some_Sheet").Range("H6") = .Index(ActiveWorkbook.Worksheets("Sheet1").Range("B4:B15")), (Range("A1").Row - 1) / 730 + 1)

End With


问:
Yii2- How to align text on left and right side php
I want to align text on both the right and the left side. For solution I have looked into the text on left and right side of element. But it didn't worked for me.

What I have done?

```<code><section class="content">

<div>
    <div class="div1" style="text-align:left; float: left;">
        Date:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black">
            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>
        </span>

    </div>
    <div class="div2" style="text-align:right; float: right;">
        Reciept#:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black">
            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>
        </span>

    </div>

</div>

</section>
</code>```

Output

As mentioned I already have checked for the solution.

Any help would be highly appreciated.

答:
you can define a dimension for div1 and div2 for example 50% each. and set display:inline-block or use floating.

```<code> .div1{
         text-align:left;
         float: left;
         width:50%;
   }
   .div2{
         text-align:right;
         float:right;
         width:50%;
   }
</code>```

alternatively you can use flexbox

Body:
I want to align text on both the right and the left side. For solution I have looked into the text on left and right side of element. But it didn't worked for me.

What I have done?

        Date:

            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>

        Reciept#:

            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>

Output

As mentioned I already have checked for the solution.

Any help would be highly appreciated.

Body:
you can define a dimension for div1 and div2 for example 50% each. and set display:inline-block or use floating.

 .div1{
         text-align:left;
         float: left;
         width:50%;
   }
   .div2{
         text-align:right;
         float:right;
         width:50%;
   }

alternatively you can use flexbox


问:
Equal Transition
I want to have a transition that extends a div both at the top and bottom on hover. Right now it overlaps the div above and pushes away the div on the bottom.

I want to either push away on both sides or overlap on both sides. Not one of both.

#blue, #red {
  width: 100%;
  height: 100px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 200px;
  font-size: 48px;
  margin-top: -50px;
}
```

<p>This is what I'm working with:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#blue, #red {
  width: 100%;
  height: 50px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 100px;
  margin-top: -25px;
}</code>```

```

Thanks!

答:
Here are your problems:

Let's remove the float here, this is not required.

Remove the negative margin, as this is what the overlapping code.

Finally, correct the HTML without the repeating ID.

Snippet here:

.blue, .red {
  width: 100%;
  height: 50px;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
}

.blue:hover, .red:hover {
  height: 100px;
  margin-top: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="blue"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="red"></div>
<div class="blue"></div></code>```

Title: Equal Transition

Body:
I want to have a transition that extends a div both at the top and bottom on hover. Right now it overlaps the div above and pushes away the div on the bottom.

I want to either push away on both sides or overlap on both sides. Not one of both.

#blue, #red {
  width: 100%;
  height: 100px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 200px;
  font-size: 48px;
  margin-top: -50px;
}

This is what I'm working with:

#blue, #red {
  width: 100%;
  height: 50px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 100px;
  margin-top: -25px;
}

Thanks!

Body:
Here are your problems:

Let's remove the float here, this is not required.

Remove the negative margin, as this is what the overlapping code.

Finally, correct the HTML without the repeating ID.

Snippet here:

.blue, .red {
  width: 100%;
  height: 50px;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
}

.blue:hover, .red:hover {
  height: 100px;
  margin-top: 0px;
}

<div class="blue"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="red"></div>
<div class="blue"></div>


问:
How to size a content div to cover the entire content area in jQuery Mobile
I started a simple jQuery Mobile Page with a header and a content div. The content div should serve as a map container for openlayers. The map should fill up the entire screen, except for the header bar.

Sizing the content div with a width/height of 100% didn't work (nothing was displayed), so I'm looking for a CSS approach to pixel-size the div or a relative-size workaround.

Especially I like to know:

How can I account for screen orientation changes (landscape/portrait)?

How can I make my layout "height-elastic", i.e. resistant to the toggling of the browser's address bar?

Here is my markup so far:

```<code><body>

<div data-role="page">

<div data-role="header">
    <h1>My Map</h1>
</div>

<div id="mapcontainer"  data-role="content">
     <!-- OpenLayers Map goes here -->
</div>

</div>

</body>
</code>```

答:
I didn't test it yet, but see if this works:

set fulscreen mode as described here: http://jquerymobile.com/demos/1.0a2/#docs/toolbars/bars-fullscreen.html

and set #mapcontainer width and height to 100% (and put some content in it when testing)

Body:
I started a simple jQuery Mobile Page with a header and a content div. The content div should serve as a map container for openlayers. The map should fill up the entire screen, except for the header bar.

Sizing the content div with a width/height of 100% didn't work (nothing was displayed), so I'm looking for a CSS approach to pixel-size the div or a relative-size workaround.

Especially I like to know:

How can I account for screen orientation changes (landscape/portrait)?

How can I make my layout "height-elastic", i.e. resistant to the toggling of the browser's address bar?

Here is my markup so far:

My Map


答:
If you want to use @Autowired the in a Class it first has to be a Bean. You can do this by annotating the Class with @Component or by using the @Bean Annotation in the Configuration.

```<code>@Bean
Yourclass yourclass(){
     return new YourClass();
}
</code>```

Second you will have to add the @ComponentScan Annotation to your Configuration.

```<code>@ComponentScan("your.package")
@Configuration
</code>```

Third you must instantiate an ApplicationContext. For example like this

```<code>JavaConfigApplicationContext context = new JavaConfigApplicationContext(YourConfig.class);
</code>```

Because it is a Webapplication it probably would be best to have a look at WebApplicationInitializer, implement your own and initialize the Context there.

Title: How to use tomcat with spring without web.xml?

Body:
I have a JAX-RS application deployed on Tomcat 7. I am deploying the application on Tomcat without any web.xml file.

I want to use spring for injecting some of the dependencies in my project. I am not using any XML file to configure beans, instead I have created a class and annotated it with @Configuration annotation, which contains all the bean definitions. Now, I am trying to use that bean by annotating a field in a separate class with @Autowired, but the field is null.

How should I make spring work with this setup ?

EDIT:
I was able to initialize spring application context , by creating a web.xml in WEB-INF/ with the following contents.

<web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

I checked the tomcat logs , and verified that the bean is created by spring. But the problem is when I try to use that bean, the field in the class is null.

Body:
If you want to use @Autowired the in a Class it first has to be a Bean. You can do this by annotating the Class with @Component or by using the @Bean Annotation in the Configuration.

@Bean
Yourclass yourclass(){
     return new YourClass();
}

Second you will have to add the @ComponentScan Annotation to your Configuration.

@ComponentScan("your.package")
@Configuration

Third you must instantiate an ApplicationContext. For example like this

JavaConfigApplicationContext context = new JavaConfigApplicationContext(YourConfig.class);

Because it is a Webapplication it probably would be best to have a look at WebApplicationInitializer, implement your own and initialize the Context there.


问:
How to convert SQL Query to CodeIgniter?
How to convert this query :

```<code>SELECT pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah
FROM pembelian_detail_tb
INNER JOIN produk_tb ON pembelian_detail_tb.kode_produk = produk_tb.kode_produk;
</code>```

I have try many code, and i still got undefine.

答:
Try this</p>

```<code>$query = $this->db->select('pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah')
->from('pembelian_detail_tb')
->join('produk_tb', 'pembelian_detail_tb.kode_produk = produk_tb.kode_produk', 'inner')
->get();
</code>```

Body:
How to convert this query :

SELECT pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah
FROM pembelian_detail_tb
INNER JOIN produk_tb ON pembelian_detail_tb.kode_produk = produk_tb.kode_produk;

I have try many code, and i still got undefine.

Body:
Try this

$query = $this->db->select('pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah')
->from('pembelian_detail_tb')
->join('produk_tb', 'pembelian_detail_tb.kode_produk = produk_tb.kode_produk', 'inner')
->get();


问:
Automatically wrap text to a width in RaphaelJS?
I am currently trying to add some text, which is added dynamically, using RaphaelJS.  I want the text to break at 200 pixels, then continue on the next line. Just like if you had a regular DIV with a width in HTML.

https://jsfiddle.net/qLvuztcy/

I've tried something like:

```<code>.text {
    width: 200px;
    max-width: 200px; //and this
}
</code>```

But that's not how it works, unfortunately. Does anyone know how I can achieve this? I know that adding a \n to the text will make a new line, but I'm not sure how to achieve what I want.

答:
SVG doesn't have automatic text wrapping.  Well not in the current version anyway.

You have to split the text up into lines yourself.  Or if you are displaying the SVG in a browser, you have the option of embedding HTML in the SVG. You can do this with the <foreignObject> element.

I'm not sure whether Raphael has an API for creating foreignObject elements.  You'll need to investigate.

Body:
I am currently trying to add some text, which is added dynamically, using RaphaelJS.  I want the text to break at 200 pixels, then continue on the next line. Just like if you had a regular DIV with a width in HTML.

https://jsfiddle.net/qLvuztcy/

I've tried something like:

.text {
    width: 200px;
    max-width: 200px; //and this
}

But that's not how it works, unfortunately. Does anyone know how I can achieve this? I know that adding a \n to the text will make a new line, but I'm not sure how to achieve what I want.


问:
Putting footer at the bottom
I am currently making an app. However, my footer is directly below the button. I would like my footer to be at the bottom of the app instead. I will attach a link to the picture of how it is looking like right now.

```<code><body>
    <div data-role="page" id="mainpage">
        <div data-role="header" class="header" data-position="fixed">
            <a href="index.html" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
            <h1><b>Converter App</b></h1>
        </div>

        <div class="app">
            <a href="converter.html" class="ui-btn">Converter</a>
        </div>

        <footer data-role="footer">
            <h4>Copyright 2017</h4>
        </footer>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="scripts/platformOverrides.js"></script>
    <script type="text/javascript" src="scripts/index.js"></script>
</body>
</code>```

I have added the CSS below as requested.

```<code>.ui-header-fixed,
.ui-footer-fixed {
    left: 0;
    right: 0;
    width: 100%;
    position: fixed;
    z-index: 1000;
}
</code>```

https://imgur.com/a/ECjxq

答:
Add css class or id

```<code>#footer {
    position: fixed;
    left: 0;
    bottom: 0;
}
</code>```

In html

```<code><div id="footer">
    <h4>Copyright 2017</h4>
</div>
</code>```

Explicity fix your footer container at the bottom of your page

https://jsfiddle.net/5qj7eggm/

Title: Putting footer at the bottom

Body:
I am currently making an app. However, my footer is directly below the button. I would like my footer to be at the bottom of the app instead. I will attach a link to the picture of how it is looking like right now.

            Home

Converter App

            Converter

Copyright 2017

I have added the CSS below as requested.

.ui-header-fixed,
.ui-footer-fixed {
    left: 0;
    right: 0;
    width: 100%;
    position: fixed;
    z-index: 1000;
}

https://imgur.com/a/ECjxq

Body:
Add css class or id

#footer {
    position: fixed;
    left: 0;
    bottom: 0;
}

In html

<div id="footer">
    <h4>Copyright 2017</h4>
</div>

Explicity fix your footer container at the bottom of your page

https://jsfiddle.net/5qj7eggm/


问:
Query that creates 1000 rows in Oracle SQL
I am trying to write a query to generates 1000 rows, I have a table called CCHOMEWORK with 2 columns, ID integer (PK) and StudentID varchar which contains the value for all the 1000 rows.

I tried this, but I keep getting errors and does not work

```<code>SET @MyCounter = 1

WHILE @MyCounter < 1000

BEGIN

INSERT INTO CCHOMEWORK
    (ID)
VALUES
    @MyCounter)

    set @MyCounter = @MyCounter + 1;

END
</code>```

答:
Syntax for Oracle database (using PL/SQL):</p>

```<code>DECLARE
    MyCounter NUMBER := 1;
BEGIN
    LOOP
        EXIT WHEN MyCounter> 1000;
        INSERT INTO CCHOMEWORK (ID)
        VALUES(MyCounter);
        MyCounter := MyCounter+1;
    END LOOP;
    COMMIT;
END;
/
</code>```

Body:
I am trying to write a query to generates 1000 rows, I have a table called CCHOMEWORK with 2 columns, ID integer (PK) and StudentID varchar which contains the value for all the 1000 rows.

I tried this, but I keep getting errors and does not work

SET @MyCounter = 1

WHILE @MyCounter < 1000

BEGIN

INSERT INTO CCHOMEWORK
    (ID)
VALUES
    @MyCounter)

    set @MyCounter = @MyCounter + 1;

END

Body:
Syntax for Oracle database (using PL/SQL):

DECLARE
    MyCounter NUMBER := 1;
BEGIN
    LOOP
        EXIT WHEN MyCounter> 1000;
        INSERT INTO CCHOMEWORK (ID)
        VALUES(MyCounter);
        MyCounter := MyCounter+1;
    END LOOP;
    COMMIT;
END;
/


问:
How to trim table cell values in MS Word with VBA
I have a table in a Word file.
This vba program below will iterate through all the table cells

```<code>Dim strCellText As String
Dim uResp As String
Dim Row As Integer
Dim Col As Integer

Dim itable As Table

For Each itable In ThisDocument.Tables

    uResp = ""

    For Row = 1 To itable.Rows.Count

        For Col = 1 To itable.Columns.Count

            strCellText = itable.Cell(Row, Col).Range.Text
            uResp = uResp & Trim(strCellText)

        Next

    Next

    MsgBox uResp
Next
</code>```

In the line uResp = uResp & Trim(strCellText)   VBA appends a newline and a dot to each cell.So MsgBox uResp will display a 'column' message box.How can I remove the newline and dot while displaying the message box.

答:
The solution I use is:</p>

```<code>endOfCell = Chr(13) + Chr(7)
uResp = uResp & Split(strCellText, endOfCell)(0)
</code>```

Body:
I have a table in a Word file.
This vba program below will iterate through all the table cells

Dim strCellText As String
Dim uResp As String
Dim Row As Integer
Dim Col As Integer

Dim itable As Table

For Each itable In ThisDocument.Tables

    uResp = ""

    For Row = 1 To itable.Rows.Count

        For Col = 1 To itable.Columns.Count

            strCellText = itable.Cell(Row, Col).Range.Text
            uResp = uResp & Trim(strCellText)

        Next

    Next

    MsgBox uResp
Next

In the line uResp = uResp & Trim(strCellText)   VBA appends a newline and a dot to each cell.So MsgBox uResp will display a 'column' message box.How can I remove the newline and dot while displaying the message box.

Body:
The solution I use is:

endOfCell = Chr(13) + Chr(7)
uResp = uResp & Split(strCellText, endOfCell)(0)


问:
Linux - Splash screen for Java application
On Windows I use Exe4J to start my Java Application. This has the following advantages:

Splashscreen which shows before Java starts

Possibility to update a Label on the splash screen during the startup, until the application is folly loaded ("Initializing Flux compensator","Reordering high nibbles", etc.)

Now I want to implement this on Linux. I start my App with a Shell script, but would love an easy way to show some kind of splash GUI with a label on it, which I can update from my shell script during startup.

Is there an easy way to fire up a minimal GUI from a shell script, and to update the label in it from the shell script, without having to compile a separate executable for it for linux (and maybe even Mac OS X)?

PS: I don't want to use the Java build in splash screen because of the Label which has to be updated dynamically.

答: The Eclipse launcher supports this functionality on all platforms, but moving to SWT may be going too far? There are details here.</p>


问:
Select row(s) from a summary data table and use cell value to subset original data and create a new data table in Shiny
I have created a summary table from iris data set and when i select any row from that datatable I want to use the row selected to subset main data and later publish that subset data as a datatable.

```<code>    library(shiny)
    library(dplyr)
    library(DT)

    setwd("C:/Users/143812/Documents/Shiny")

    df <- iris
    vchoices <- colnames(df)
    ui <- fluidPage(h1("PLOT FOR NOW"),
                    sidebarLayout(sidebarPanel(
                      fluidPage(
                        column(10,selectInput(inputId = "group",label = "Group BY",choices = vchoices)),
                        column(10,selectInput(inputId = "operator",label = "OPERATOR",choices = c("sum","mean"),selected = "sum")),
                        column(10,uiOutput("operateUI"))
                      )

                    ),
                    mainPanel(dataTableOutput("summarytable"),dataTableOutput("drilldata")))
    )

    server <- function(input,output,session){
      df1 <- reactive({df %>% group_by_(input$group) %>% summarise(Result = get(input$operator)(get(input$operate)))})

      #input for integer and numeric columns
      a <- (sapply(df,class))
      lv <- a=="integer" | a=="numeric"
      b <- a[lv]
      numchoice <- names(b)
      output$operateUI <- renderUI({
        selectInput(inputId = "operate",label = input$operator,choices = numchoice)
      })

      #publish summary table to select output from by name summary table
      output$summarytable <- DT::renderDataTable(df1())

      #create data for drill report
      drilldata <- reactive({
                            shiny::validate(need(length(input$summarytable_rows_selected) > 0, "Select Rows to drill down")
                                            )
                            selected_column <-  df1[as.integer(input$summarytable_rows_selected),]$get(input$group)

                            df[df$get(input$group) %in% selected_column, ]

      })
      output$drilldata <- DT::renderDataTable(drilldata())

      #function end
    }

    shinyApp(ui,server)
</code>```

This code gives me error: object of type 'closure' is not subsettable.
I'm asking the user to select the column for group by and operation to be performed, either sum or mean as well as the column on which the operation is to be performed. This method seems to work in this code by mlegge where the values are predefined and not asked from user. link to question

答:
Your error message most probably comes from this line

```<code>selected_column <-  df1[as.integer(input$summarytable_rows_selected),]$get(input$group)
</code>```

where you have forgotten the function brackets () after df1. For me get() didn't work so I used [[ instead

try with

```<code>selected_column <-  df1()[as.integer(input$summarytable_rows_selected),][[input$group]]
</code>```

I also had problem with this line as well

```<code>df[df$get(input$group) %in% selected_column, ]
</code>```

and changed it to

```<code>df[df[[input$group]] %in% selected_column, ]
</code>```

and it was working for me

Body:
I have created a summary table from iris data set and when i select any row from that datatable I want to use the row selected to subset main data and later publish that subset data as a datatable.

    library(shiny)
    library(dplyr)
    library(DT)

    setwd("C:/Users/143812/Documents/Shiny")

    df <- iris
    vchoices <- colnames(df)
    ui <- fluidPage(h1("PLOT FOR NOW"),
                    sidebarLayout(sidebarPanel(
                      fluidPage(
                        column(10,selectInput(inputId = "group",label = "Group BY",choices = vchoices)),
                        column(10,selectInput(inputId = "operator",label = "OPERATOR",choices = c("sum","mean"),selected = "sum")),
                        column(10,uiOutput("operateUI"))
                      )

                    ),
                    mainPanel(dataTableOutput("summarytable"),dataTableOutput("drilldata")))
    )

    server <- function(input,output,session){
      df1 <- reactive({df %>% group_by_(input$group) %>% summarise(Result = get(input$operator)(get(input$operate)))})

      #input for integer and numeric columns
      a <- (sapply(df,class))
      lv <- a=="integer" | a=="numeric"
      b <- a[lv]
      numchoice <- names(b)
      output$operateUI <- renderUI({
        selectInput(inputId = "operate",label = input$operator,choices = numchoice)
      })

      #publish summary table to select output from by name summary table
      output$summarytable <- DT::renderDataTable(df1())

      #create data for drill report
      drilldata <- reactive({
                            shiny::validate(need(length(input$summarytable_rows_selected) > 0, "Select Rows to drill down")
                                            )
                            selected_column <-  df1[as.integer(input$summarytable_rows_selected),]$get(input$group)

                            df[df$get(input$group) %in% selected_column, ]

      })
      output$drilldata <- DT::renderDataTable(drilldata())

      #function end
    }

    shinyApp(ui,server)

This code gives me error: object of type 'closure' is not subsettable.
I'm asking the user to select the column for group by and operation to be performed, either sum or mean as well as the column on which the operation is to be performed. This method seems to work in this code by mlegge where the values are predefined and not asked from user. link to question

Body:
Your error message most probably comes from this line

selected_column <-  df1[as.integer(input$summarytable_rows_selected),]$get(input$group)

where you have forgotten the function brackets () after df1. For me get() didn't work so I used [[ instead

try with

selected_column <-  df1()[as.integer(input$summarytable_rows_selected),][[input$group]]

I also had problem with this line as well

df[df$get(input$group) %in% selected_column, ]

and changed it to

df[df[[input$group]] %in% selected_column, ]

and it was working for me


问:
Slow javascript time counter on mobile phones
I'm making a counter in javascript to be run on mobile phones, it works on my computer but on my mobile phone the counter goes from 0 to 2 to 4 etc...

I really need this timer to work, and I can not seem to find an answer anywhere. The code works on my computer but I think the Javascript on my phone is slow. Is there an alternative to Javascript, maybe some HTML5 code I don't know of?

I put this script in the body tag.

```<code><script type="text/javascript">
    var time = 0;
    setInterval(
        function () {
            time += 1;
            document.getElementById("timer").innerHTML = time;
        }, 1000
    );
</script>
</code>```

答:
this is a simple counter exapmple

```<code>function countdown(elementName, minutes, seconds) {
var element,endTime,hours,mins,msLeft,time;
function twoDigits(n) {
    return (n <= 9 ? "0" + n : n);
}
function updateTimer() {
    msLeft = endTime - (+new Date);
    if (msLeft < 1000) {
        element.innerHTML = "countdown's over!";
    } else {
        time = new Date(msLeft);
        hours = time.getUTCHours();
        mins = time.getUTCMinutes();
        element.innerHTML = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds());
        setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
    }
}element = document.getElementById(elementName);
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();}
</code>```

to call a function

```<code>countdown("countdown", 1, 5);
countdown("countdown2", 100, 0);
</code>```

Body:
this is a simple counter exapmple

function countdown(elementName, minutes, seconds) {
var element,endTime,hours,mins,msLeft,time;
function twoDigits(n) {
    return (n <= 9 ? "0" + n : n);
}
function updateTimer() {
    msLeft = endTime - (+new Date);
    if (msLeft < 1000) {
        element.innerHTML = "countdown's over!";
    } else {
        time = new Date(msLeft);
        hours = time.getUTCHours();
        mins = time.getUTCMinutes();
        element.innerHTML = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds());
        setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
    }
}element = document.getElementById(elementName);
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();}

to call a function

countdown("countdown", 1, 5);
countdown("countdown2", 100, 0);


问:
Using ABC, PolymorphicModel, django-models gives metaclass conflict
So far every other answer on SO answers in the exact same way: construct your metaclasses and then inherit the 'joined' version of those metaclasses, i.e.

```<code>class M_A(type): pass
class M_B(type): pass
class A(metaclass=M_A): pass
class B(metaclass=M_B): pass

class M_C(M_A, M_B): pass
class C:(A, B, metaclass=M_C): pass
</code>```

But I don't know what world these people are living in, where they're constructing your own metaclasses! Obviously, one would be using classes from other libraries and unless you have a perfect handle on meta programming, how are you supposed to know whether you can just override a class's metaclass? (Clearly I do not have a handle on them yet).

My problem is:

```<code>class InterfaceToTransactions(ABC):
    def account(self):
        return None
    ...

class Category(PolymorphicModel, InterfaceToTransactions):
    def account(self):
        return self.source_account
    ...

class Income(TimeStampedModel, InterfaceToTransactions):
    def account(self):
        return self.destination_account
    ...
</code>```

Which of course gives me the error: "metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases"
I've tried many variations of the solution given above, the following does not work, gives the same error.

```<code>class InterfaceToTransactionsIntermediaryMeta(type(PolymorphicModel), type(InterfaceToTransactions)):
pass

class Category(PolymorphicModel, InterfaceToTransactions):
    __metaclass__ = InterfaceToTransactionsIntermediaryMeta
    ...
</code>```

Nor does putting anything inside the class Meta function. I've read every single other SO question on this topic, please don't simply mark it as duplicate.

-------------------Edited 1/8/18 after accepting the solution-------

Oddly enough, if I try to makemigrations with this new configuration (the one I accepted), it starts giving the metaclass error again, but it still works during runtime. If I comment out the metaclass parts then makemigrations and migrate, it will do it successfully, but then I have to put it back in there after migrating every time.

答:
If you are using Python 3, you are trying to use your derived metaclass incorrectly.

And since you get "the same error", and not other possible, more subtle, error, I'd say this is what is happening.

Try just changing to:

```<code>class IntermediaryMeta(type(InterfaceToTransactions), type(PolymorphicModel)):
    pass

class Category(PolymorphicModel, InterfaceToTransactions, metaclass=IntermediaryMeta):
    ...
</code>```

(At least the  ABCMeta class is guaranteed to work collaboratively using super, that is enough motive to place the classe it first on the bases )
tuple)

If that yields you new and improved errors, this means that one or both of those classes can't really  collaborate properly due to one of several motives. Then, the way to go is to force your inheritance tree that depends on ABCMeta not to do so, since its role is almost aesthetical in a language where everything else is for "consenting adults" like Python.

Unfortunatelly, the way to that is to use varying methods of brute-force, from safe "rewritting everything" to monkey patching ABCMeta and abstractmethod on the place were "InterfaceToTransactions" is defined to simply do nothing.

If you need to get there, and need some help, please post another question.

Sorry - this is actually the major drawbacks of using metaclasses.

Body:
So far every other answer on SO answers in the exact same way: construct your metaclasses and then inherit the 'joined' version of those metaclasses, i.e.

class M_A(type): pass
class M_B(type): pass
class A(metaclass=M_A): pass
class B(metaclass=M_B): pass

class M_C(M_A, M_B): pass
class C:(A, B, metaclass=M_C): pass

But I don't know what world these people are living in, where they're constructing your own metaclasses! Obviously, one would be using classes from other libraries and unless you have a perfect handle on meta programming, how are you supposed to know whether you can just override a class's metaclass? (Clearly I do not have a handle on them yet).

My problem is:

class InterfaceToTransactions(ABC):
    def account(self):
        return None
    ...

class Category(PolymorphicModel, InterfaceToTransactions):
    def account(self):
        return self.source_account
    ...

class Income(TimeStampedModel, InterfaceToTransactions):
    def account(self):
        return self.destination_account
    ...

Which of course gives me the error: "metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases"
I've tried many variations of the solution given above, the following does not work, gives the same error.

class InterfaceToTransactionsIntermediaryMeta(type(PolymorphicModel), type(InterfaceToTransactions)):
pass

class Category(PolymorphicModel, InterfaceToTransactions):
    __metaclass__ = InterfaceToTransactionsIntermediaryMeta
    ...

Nor does putting anything inside the class Meta function. I've read every single other SO question on this topic, please don't simply mark it as duplicate.

-------------------Edited 1/8/18 after accepting the solution-------

Oddly enough, if I try to makemigrations with this new configuration (the one I accepted), it starts giving the metaclass error again, but it still works during runtime. If I comment out the metaclass parts then makemigrations and migrate, it will do it successfully, but then I have to put it back in there after migrating every time.

Body:
If you are using Python 3, you are trying to use your derived metaclass incorrectly.

And since you get "the same error", and not other possible, more subtle, error, I'd say this is what is happening.

Try just changing to:

class IntermediaryMeta(type(InterfaceToTransactions), type(PolymorphicModel)):
    pass

class Category(PolymorphicModel, InterfaceToTransactions, metaclass=IntermediaryMeta):
    ...

(At least the  ABCMeta class is guaranteed to work collaboratively using super, that is enough motive to place the classe it first on the bases )
tuple)

If that yields you new and improved errors, this means that one or both of those classes can't really  collaborate properly due to one of several motives. Then, the way to go is to force your inheritance tree that depends on ABCMeta not to do so, since its role is almost aesthetical in a language where everything else is for "consenting adults" like Python.

Unfortunatelly, the way to that is to use varying methods of brute-force, from safe "rewritting everything" to monkey patching ABCMeta and abstractmethod on the place were "InterfaceToTransactions" is defined to simply do nothing.

If you need to get there, and need some help, please post another question.

Sorry - this is actually the major drawbacks of using metaclasses.


问:
Assign data from LocalStorage to a block of data (Angular2)
So, I used data declared by myself, but now i switch the code to LocalStorage, and I'd like to know, how to get the data from one element of LocalStorage, and insert it to a block of data from my program.

Here's a part of code which shows the procedure which i use for inserting data

```<code>let l = this.lists;
localStorage.setItem('lists', JSON.stringify(l));
</code>```

l is of type string, and lists is an array with data block.

I wanted to use this command

```<code>this.lists = localStorage.getItem('lists');
</code>```

but unfortunately,it wants a string element, and doesn't want to work with my lists element...

Info time:

LocalStorage is implementation of Storage interface and it accepts and
  returns plain strings so every time you want to store there something
  a little bit more complex you have to serialize when inserting
  (JSON.stringify) and deserialize when retrieving (JSON.parse)

答:
You can use JSON.parse()

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

```<code>this.lists = JSON.parse(localStorage.getItem('lists'));
</code>```

localStorage is implementation of Storage interface, It works on plain strings. When you want to work with complex object serialize it using JSON.stringify() and deserialize using JSON.parse()

Body:
So, I used data declared by myself, but now i switch the code to LocalStorage, and I'd like to know, how to get the data from one element of LocalStorage, and insert it to a block of data from my program.

Here's a part of code which shows the procedure which i use for inserting data

let l = this.lists;
localStorage.setItem('lists', JSON.stringify(l));

l is of type string, and lists is an array with data block.

I wanted to use this command

this.lists = localStorage.getItem('lists');

but unfortunately,it wants a string element, and doesn't want to work with my lists element...

Info time:

LocalStorage is implementation of Storage interface and it accepts and
  returns plain strings so every time you want to store there something
  a little bit more complex you have to serialize when inserting
  (JSON.stringify) and deserialize when retrieving (JSON.parse)

Body:
You can use JSON.parse()

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

this.lists = JSON.parse(localStorage.getItem('lists'));

localStorage is implementation of Storage interface, It works on plain strings. When you want to work with complex object serialize it using JSON.stringify() and deserialize using JSON.parse()


问:
Design pattern for person with multiple roles
I want to create a base model Person with some person related attributes like name, address, phone and so on. One Person can be one ore more of the following:

LoginUser with fields for login, password, last_login, ...

CardHolder with fields for card_id, last_entrance, ...

Supplier with just a flag whether or not the person is a supplier

Recipient with just a flag whether or not the person is a recipient

Is there a common sense or best practise design pattern in Ruby on Rails to represent that inheritance? How it should be represented in the model(s) and table structure so that it is possible to check whether a Person is a LoginUser and to access the corresponding fields.
In another project I worked already with STI but in this case this isn't the right pattern.

答:
What you're looking for is a reverse polymorphic association. Polymorphic associations allow you to link one model to many different ones. A reverse polymorphic association allows you to link many models to one single one. They're a little tricky to set up, but once you get the hang of it it's no problem.

In order to accomplish this, you need another model that acts as a go-between for the Person model and each of the different roles. This go-between model is the one that actually has the polymorphic association. Your Person model will has_many that model, and your various role models will has_one of it. You then use :through to make the rest of the necessary associations so your code doesn't know any different. Shazam!

Here's an example of how to do it with the Person and CardHolder models. I'm calling the extra model Role because that seems like an obvious choice:

```<code>class Person < ApplicationRecord
  has_many :roles
  # Reach through the Roles association to get the CardHolders, via polymorphic :rollable.
  # Unfortunately, you can't has_one, so you'll have to enforce uniqueness in Role
  # with a validation.
  has_many :card_holders, through: :roles, source: :rollable, source_type: 'CardHolder'
end

class Role < ApplicationRecord
  belongs_to :person
  # Here is where our actual polymorphic connection is:
  belongs_to :rollable, polymorphic: true
end

class CardHolder < ApplicationRecord
  # The other side of the polymorphic connection, with has_one:
  has_one :role, as: :rollable
  # Get the person via the role, just like the inverse:
  has_one :person, through: :role
end
</code>```

The database setup is like this:

```<code>class CreatePeople < ActiveRecord::Migration[5.1]
  def change
    create_table :people do |t|
      t.string :name
      # put in whatever other Person columns you need

      t.timestamps
    end
  end
end

class CreateRoles < ActiveRecord::Migration[5.1]
  def change
    create_table :roles do |t|
      t.references :person, index: true
      t.references :rollable, polymorphic: true, index: true
      t.timestamps
    end
  end
end

class CreateCardHolders < ActiveRecord::Migration[5.1]
  def change
    create_table :card_holders do |t|
      t.integer :card_id
      t.datetime :last_entrance
      # put in whatever other columns you need

      t.timestamps
    end
  end
end
</code>```

Using it is quite simple:

```<code>> p = Person.create(name: "Sven Reuter")
# directly add a card holder
> p.card_holders << CardHolder.create(card_id: 1, last_entrance: Time.current)
# build a role instead
> p.roles.build(rollable: CardHolder.new(card_id: 2, last_entrance: Time.current)
# get all of the roles
> p.roles
</code>```

Body:
What you're looking for is a reverse polymorphic association. Polymorphic associations allow you to link one model to many different ones. A reverse polymorphic association allows you to link many models to one single one. They're a little tricky to set up, but once you get the hang of it it's no problem.

In order to accomplish this, you need another model that acts as a go-between for the Person model and each of the different roles. This go-between model is the one that actually has the polymorphic association. Your Person model will has_many that model, and your various role models will has_one of it. You then use :through to make the rest of the necessary associations so your code doesn't know any different. Shazam!

Here's an example of how to do it with the Person and CardHolder models. I'm calling the extra model Role because that seems like an obvious choice:

class Person < ApplicationRecord
  has_many :roles
  # Reach through the Roles association to get the CardHolders, via polymorphic :rollable.
  # Unfortunately, you can't has_one, so you'll have to enforce uniqueness in Role
  # with a validation.
  has_many :card_holders, through: :roles, source: :rollable, source_type: 'CardHolder'
end

class Role < ApplicationRecord
  belongs_to :person
  # Here is where our actual polymorphic connection is:
  belongs_to :rollable, polymorphic: true
end

class CardHolder < ApplicationRecord
  # The other side of the polymorphic connection, with has_one:
  has_one :role, as: :rollable
  # Get the person via the role, just like the inverse:
  has_one :person, through: :role
end

The database setup is like this:

class CreatePeople < ActiveRecord::Migration[5.1]
  def change
    create_table :people do |t|
      t.string :name
      # put in whatever other Person columns you need

      t.timestamps
    end
  end
end

class CreateRoles < ActiveRecord::Migration[5.1]
  def change
    create_table :roles do |t|
      t.references :person, index: true
      t.references :rollable, polymorphic: true, index: true
      t.timestamps
    end
  end
end

class CreateCardHolders < ActiveRecord::Migration[5.1]
  def change
    create_table :card_holders do |t|
      t.integer :card_id
      t.datetime :last_entrance
      # put in whatever other columns you need

      t.timestamps
    end
  end
end

Using it is quite simple:

> p = Person.create(name: "Sven Reuter")
# directly add a card holder
> p.card_holders << CardHolder.create(card_id: 1, last_entrance: Time.current)
# build a role instead
> p.roles.build(rollable: CardHolder.new(card_id: 2, last_entrance: Time.current)
# get all of the roles
> p.roles


问:
typoscript menu foundation containing page contents
I am looking to develop a menu with 3 levels dropdown menu with foundation 5.5.0 ! A menu containing the contents of a page. I can see the title, but the content does not change when I change page or tab (links are : | ---1--- |... and Title 11, Title 12, Title 13 ... and link 1 to link 8 or more). It initialises to the content of the activated page via the link of the menu. For each title I want to display the content of the page in question. I want the page not to be displayed elsewhere than in the menu.

```<code>[ --- 1 --- (*)][--- 2 --- ][--- 3 --- ]
| Title 11      | Title 12      | Title 13      |
| Content 11    | Content 12    | Content 13    |
|               |               |               |
| link 1        | link 4        | link 6        |
| link 2        | link 5        | link 7        |
| link 3        |               | link 8        |
</code>```

(*) actived.

Menu containing page contents :
I can display 'Content 11' but it appears everywhere in all the other 'Content' (Content 11 = Content 12 = Content 13). And not the corresponding content of the title. When I click on another link it is this one that takes the place of the other and that is displayed everywhere in the 'Content x'.

The menu itself works.

```<code>    lib.menuprincipal = COA
lib.menuprincipal {
    wrap (
      <div data-magellan-expedition="fixed" class="large-12 column" data-magellan>
        <nav class="top-bar" data-topbar role="navigation">
      |
        </nav>
      </div>
    )

    # NavBar Header
    10 = TEXT
    10 {
        data = leveltitle:0
        typolink {
            parameter.data = parameters : allParams
            ATagParams = class="TestAddParamClass"
            title.data = leveltitle:0
          #forceAbsoluteUrl = 1
        }

        wrap (
            <ul class="title-area">
              <li class="name">
                 <div class="show-for-small left">
                    <div id="poslogomin1" class="right">
                       <h2>Titre site/h2>
                    </div>
                  </div>
               </li>
               <li class="toggle-topbar menu-icon">|</li>
            </ul>
        )
    }

    # menu
    20 = HMENU
    20 {
        #entryLevel = 0
        wrap (
               <section class="top-bar-section">
                    <ul class="left">
                        |
                    </ul>
               </section>
        )

        # Premier niveau
        1 = TMENU
        1 {
          entryLevel = 0
          #wrap = |
          expAll = 1
          maxItems = 5

          NO = 1
          NO {
            doNotLinkIt = 1
            stdWrap.cObject = COA
            stdWrap.cObject{

                10 = TEXT
                10.typolink.no_cache = 1
                10.typolink.ATagBeforeWrap = 1
                10.typolink.parameter.field = uid

                10.cObject = COA
                10.cObject{
                        10 = TEXT
                        10.wrap = <div class="tile tile|">
                        10.field = layout

                        20 = TEXT
                        20.wrap = <div class="title"><h2 style='color:darkblue'>|</h2></div>
                        20.field = title

                        30 = TEXT
                        30.wrap = <div class = "subtitle"><h2 style='color:darkred'>|</h2></div>
                        30.field = subtitle

                        40 = CONTENT
                        40.wrap = <div class = "subtitle"><div>|</div></div>
                        40 {
                          table = tt_content
                            select {
                              where= colPos=0
                              uidInList.field = this
                            }
                        }
                        40.field < styles.content.get

                        50 = TEXT
                        50.value = </div>
               }
            }
          }

          NO.wrapItemAndSub =  <li class="has-dropdown">|</li>

          ACT = 1
          ACT.wrapItemAndSub =  <li class="has-dropdown">|</li>

          IFSUB = 1
          IFSUB.wrapItemAndSub =  <li class="has-dropdown">|</li>
        }//1

        # Deuxième niveau
        2 < .1
        2 = TMENU
        2 {
          #entryLevel = 0
          maxItems = 5
            wrap (
                <ul class="dropdown">
                  <li>
                     <div class="row mynav" id="nav-2">
                       |
                     </div>
                  </li>
                </ul>
            )
            expAll = 1

            NO = 1

            NO.wrapItemAndSub =  <div class="large-3 medium-6 column">|</div>
            NO.stdWrap.wrap = <h2 style='color:darkgreen'>|</h2>

          ACT < .NO
          CUR < .NO
          IFSUB < .NO
          ACTIFSUB < .NO
        }//2

        # Troisième niveau
        3 = TMENU
        3 {
          #entryLevel = 0
          maxItems = 5

          wrap = <p>|</p>
        }//3
    }
}
</code>```

I am a beginner in typoscript, can you help me? Thank you !
Best regards.

答:
Hello i have make that at 40 point and add :

```<code>40 = CONTENT
40 {
   table = tt_content
       select {
         orderBy = sorting
         pidInList.field = uid
         where = {#colPos}=0 and deleted = 0 and hidden = 0
       }
   renderObj = COA
   renderObj {
     10 = TEXT
     10.stdWrap.field = header

     10.stdWrap.wrap = <div class = "subtitle"><div>|</div></div>

     20 = TEXT
     20.stdWrap.field = bodytext

     20.stdWrap.wrap = <p>|</p>
  }
}
</code>```

Now this is correct.

Best regards

Body:
I am looking to develop a menu with 3 levels dropdown menu with foundation 5.5.0 ! A menu containing the contents of a page. I can see the title, but the content does not change when I change page or tab (links are : | ---1--- |... and Title 11, Title 12, Title 13 ... and link 1 to link 8 or more). It initialises to the content of the activated page via the link of the menu. For each title I want to display the content of the page in question. I want the page not to be displayed elsewhere than in the menu.

[ --- 1 --- (*)][--- 2 --- ][--- 3 --- ]
| Title 11      | Title 12      | Title 13      |
| Content 11    | Content 12    | Content 13    |
|               |               |               |
| link 1        | link 4        | link 6        |
| link 2        | link 5        | link 7        |
| link 3        |               | link 8        |

(*) actived.

Menu containing page contents :
I can display 'Content 11' but it appears everywhere in all the other 'Content' (Content 11 = Content 12 = Content 13). And not the corresponding content of the title. When I click on another link it is this one that takes the place of the other and that is displayed everywhere in the 'Content x'.

The menu itself works.

    lib.menuprincipal = COA
lib.menuprincipal {
    wrap (

      |

    )

    # NavBar Header
    10 = TEXT
    10 {
        data = leveltitle:0
        typolink {
            parameter.data = parameters : allParams
            ATagParams = class="TestAddParamClass"
            title.data = leveltitle:0
          #forceAbsoluteUrl = 1
        }

        wrap (

Titre site/h2>

|

        )
    }

    # menu
    20 = HMENU
    20 {
        #entryLevel = 0
        wrap (

                        |

        )

        # Premier niveau
        1 = TMENU
        1 {
          entryLevel = 0
          #wrap = |
          expAll = 1
          maxItems = 5

          NO = 1
          NO {
            doNotLinkIt = 1
            stdWrap.cObject = COA
            stdWrap.cObject{

                10 = TEXT
                10.typolink.no_cache = 1
                10.typolink.ATagBeforeWrap = 1
                10.typolink.parameter.field = uid

                10.cObject = COA
                10.cObject{
                        10 = TEXT
                        10.wrap =

                        10.field = layout

                        20 = TEXT
                        20.wrap =

|

                        20.field = title

                        30 = TEXT
                        30.wrap =

|

                        30.field = subtitle

                        40 = CONTENT
                        40.wrap =

|

                        40 {
                          table = tt_content
                            select {
                              where= colPos=0
                              uidInList.field = this
                            }
                        }
                        40.field < styles.content.get

                        50 = TEXT
                        50.value =

               }
            }
          }

          NO.wrapItemAndSub =
|

          ACT = 1
          ACT.wrapItemAndSub =
|

          IFSUB = 1
          IFSUB.wrapItemAndSub =
|

        }//1

        # Deuxième niveau
        2 < .1
        2 = TMENU
        2 {
          #entryLevel = 0
          maxItems = 5
            wrap (

                       |

            )
            expAll = 1

            NO = 1

            NO.wrapItemAndSub =
|

            NO.stdWrap.wrap =
|

          ACT < .NO
          CUR < .NO
          IFSUB < .NO
          ACTIFSUB < .NO
        }//2

        # Troisième niveau
        3 = TMENU
        3 {
          #entryLevel = 0
          maxItems = 5

          wrap =
|

        }//3
    }
}

I am a beginner in typoscript, can you help me? Thank you !
Best regards.

Body:
Hello i have make that at 40 point and add :

40 = CONTENT
40 {
   table = tt_content
       select {
         orderBy = sorting
         pidInList.field = uid
         where = {#colPos}=0 and deleted = 0 and hidden = 0
       }
   renderObj = COA
   renderObj {
     10 = TEXT
     10.stdWrap.field = header

     10.stdWrap.wrap = <div class = "subtitle"><div>|</div></div>

     20 = TEXT
     20.stdWrap.field = bodytext

     20.stdWrap.wrap = <p>|</p>
  }
}

Now this is correct.

Best regards


问:
Powershell - Retrieve List of Groups, Use List To Find Specific Group Member
Good afternoon.  So I have the below line of code that retrieves any AD group with the suffix of -blah1 and blah2.

```<code>import-module activedirectory

$group = Get-ADGroup -Filter { (name -like "*-blah1") -or (name -like "*-blah2") } | Select Name
</code>```

The above code shows groups:

abc-blah1

  abc-blah2

I want to be able to query these groups for a specific user (for example: blahuser).  If the user does not exist in the group, I want to script to tell me.  Any ideas?  Thanks.

答:
You can do it like this:</p>

```<code>$userName = "ThisIsMyUserName"
$Groups = Get-ADGroup -Filter { (name -like "*-blah1") -or (name -like "*-blah2") } | Where-Object { $userName -notin ($_ | Get-ADGroupMember).SamAccountName} |select -ExpandProperty name
</code>```

Body:
Good afternoon.  So I have the below line of code that retrieves any AD group with the suffix of -blah1 and blah2.

import-module activedirectory

$group = Get-ADGroup -Filter { (name -like "*-blah1") -or (name -like "*-blah2") } | Select Name

The above code shows groups:

abc-blah1

  abc-blah2

I want to be able to query these groups for a specific user (for example: blahuser).  If the user does not exist in the group, I want to script to tell me.  Any ideas?  Thanks.

Body:
You can do it like this:

$userName = "ThisIsMyUserName"
$Groups = Get-ADGroup -Filter { (name -like "*-blah1") -or (name -like "*-blah2") } | Where-Object { $userName -notin ($_ | Get-ADGroupMember).SamAccountName} |select -ExpandProperty name


问:
Convert EditText to TextView after inputting a name
I want to input a name through EditText and then after inputting it should set itself as permanent so that there can't be anymore editing on the EditText. Basically, convert it to TextView and display the inputted name.

答:
Simple make the editext non editable like this</p>

```<code>yourEditText.setFocusable(false);
yourEditText.setFocusableInTouchMode(false);
yourEditText.setClickable(false);
</code>```

Body:
Simple make the editext non editable like this

yourEditText.setFocusable(false);
yourEditText.setFocusableInTouchMode(false);
yourEditText.setClickable(false);


问:
How to install Caret package? While installing, I am getting this message
```<code>library(caret)
</code>```

Loading required package: ggplot2 Error: package or namespace load
  failed for ‘ggplot2’ in loadNamespace(i, c(lib.loc, .libPaths()),
  versionCheck = vI[[i]]):  there is no package called ‘gtable’ Error:
  package ‘ggplot2’ could not be loaded

答:
just try this</p>

```<code>install.packages(pkgs = "caret",
             dependencies = c("Depends", "Imports"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
library(caret)

Loading required package: ggplot2 Error: package or namespace load
  failed for ‘ggplot2’ in loadNamespace(i, c(lib.loc, .libPaths()),
  versionCheck = vI[[i]]):  there is no package called ‘gtable’ Error:
  package ‘ggplot2’ could not be loaded

Body:
just try this

install.packages(pkgs = "caret",
             dependencies = c("Depends", "Imports"))


问:
Form not saving - form.is_valid() returning false
Below is all my models. Basically this is an auction website

```<code>class Item(models.Model):

    name = models.CharField(max_length = 30)
    description = models.TextField()
    image = models.ImageField(upload_to='media/')
    category = models.CharField(max_length=100)
    ask = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    closes = models.DateTimeField()

class Bid(models.Model):
    item = models.ForeignKey(Item)
    user = models.ForeignKey(User)
    price = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    created_at = models.DateTimeField(default=datetime.now, blank=True)
</code>```

This is the form:

```<code>class itemform(ModelForm):
    class Meta:
        model = Item
        fields =['name','description','image','category','ask','closes']
</code>```

View for saving the form:

```<code>def createitem(request):
    if request.method == "POST":
        form= itemform(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return redirect('/items')
    else:
        form = itemform()
        return render(request, 'app/create.html', {'form':form})
</code>```

create.html

```<code>{% extends 'app/layout.html' %}
{% block content %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p}}
        <button type ="submit">Save</button>
    </form>
{% endblock %}
</code>```

答:
You should change your view slightly so that you only redirect when the form is valid. When the form is not valid, you should re-render the form.

```<code>def createitem(request):
    if request.method == "POST":
        form= itemform(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/items')
    else:
        form = itemform()
    return render(request, 'app/create.html', {'form':form})
</code>```

This way, you will see the form's error messages, which should help you figure out what the problem is.

Body:
Below is all my models. Basically this is an auction website

class Item(models.Model):

    name = models.CharField(max_length = 30)
    description = models.TextField()
    image = models.ImageField(upload_to='media/')
    category = models.CharField(max_length=100)
    ask = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    closes = models.DateTimeField()

class Bid(models.Model):
    item = models.ForeignKey(Item)
    user = models.ForeignKey(User)
    price = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    created_at = models.DateTimeField(default=datetime.now, blank=True)

This is the form:

class itemform(ModelForm):
    class Meta:
        model = Item
        fields =['name','description','image','category','ask','closes']

View for saving the form:

def createitem(request):
    if request.method == "POST":
        form= itemform(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return redirect('/items')
    else:
        form = itemform()
        return render(request, 'app/create.html', {'form':form})

create.html

{% extends 'app/layout.html' %}
{% block content %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p}}
        <button type ="submit">Save</button>
    </form>
{% endblock %}

Body:
You should change your view slightly so that you only redirect when the form is valid. When the form is not valid, you should re-render the form.

def createitem(request):
    if request.method == "POST":
        form= itemform(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/items')
    else:
        form = itemform()
    return render(request, 'app/create.html', {'form':form})

This way, you will see the form's error messages, which should help you figure out what the problem is.


问:
batch script to send email
How to write a Windows batch script to send a mail? Give an example</p>

答:
I would suggest downloading and installing a command line emailing program. The best freeware one that I can see is:

http://www.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm

From there, save the downloaded .exe to a good location on your HDD (possibly in c:/program files/bmail) and add that directory to your PATH ( see http://www.brightrev.com/how-to/windows/35-add-a-utilities-directory-to-your-pc.html?start=1 for instructions ).

From then, you could setup a small batch script such as this:

```<code>@echo off
bmail -s smtp.example.com -p 465 -t toemail@example.com -f fromemail@example.com -h -a "INSERT SUBJECT HERE" -b "INSERT MESSAGE TEXT HERE"
</code>```

Then to send an email to that email address, just run the batch file.

If you want, you could change it to accept parameters so you can customise the message: http://www.robvanderwoude.com/parameters.php .

Important: I'm pretty sure bmail won't work if the SMTP server requires authentication, so you'll need to find one you can use. Maybe set one up on the server without a username and password, and that can only be accessed from localhost?

Title: batch script to send email

Body:
I would suggest downloading and installing a command line emailing program. The best freeware one that I can see is:

http://www.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm

From there, save the downloaded .exe to a good location on your HDD (possibly in c:/program files/bmail) and add that directory to your PATH ( see http://www.brightrev.com/how-to/windows/35-add-a-utilities-directory-to-your-pc.html?start=1 for instructions ).

From then, you could setup a small batch script such as this:

@echo off
bmail -s smtp.example.com -p 465 -t toemail@example.com -f fromemail@example.com -h -a "INSERT SUBJECT HERE" -b "INSERT MESSAGE TEXT HERE"

Then to send an email to that email address, just run the batch file.

If you want, you could change it to accept parameters so you can customise the message: http://www.robvanderwoude.com/parameters.php .

Important: I'm pretty sure bmail won't work if the SMTP server requires authentication, so you'll need to find one you can use. Maybe set one up on the server without a username and password, and that can only be accessed from localhost?