问:
bundler incorrectly trying to install "development" and "test" group gems in production
I have a small web app, which uses a bunch of gems. Some of them are only used for test and development environments. Now, when I try to start unicorn on the production server using the following command, it fails.

```<code>unicorn_rails -E production -D -c config/unicorn.rb
</code>```

The error I see in the log files is:

```<code>Refreshing Gem list
Could not find gem 'spork (>= 0.9.0.rc2, runtime)' in any of the gem sources listed in your Gemfile.
Try running `bundle install`.
</code>```

I've pasted my gemfile below:

```<code>source 'http://rubygems.org'

gem 'rails', '3.0.1'
gem 'unicorn'
gem 'mongoid', '>= 2.0.0.beta.19'
gem 'devise'
gem 'cancan'
gem 'haml', '>= 3.0.0'
gem 'bson'
gem 'bson_ext'
gem 'formtastic'
gem 'bluecloth'

group :production do
  gem 'capistrano'
end

group :development do
  gem 'haml-rails'
  gem 'hpricot', '0.8.2'
  gem 'ruby_parser', '2.0.5'
  gem 'less'
  gem 'rspec-rails', '>= 2.0.1'
end

group :development,:test do
  gem 'spork', '>=0.9.0.rc2'
  gem 'mongoid-rspec'
end

group :test do
  gem 'factory_girl_rails'
  gem 'autotest'
  gem 'cucumber-rails'
  gem 'cucumber'
  gem 'capybara'
  gem 'shoulda'
  gem 'database_cleaner'
  gem 'test_notifier'
  gem 'rspec', '2.0.1'
  gem 'launchy'
end
</code>```

Bundler is supposed to detect the right environment and ignore the other gems, right? Right now, I am deleting all the lines which are not in the default group on the server to get this working, but that's an ugly hack.

答: You haven't defined a production group =)</p>

Body:
I have a small web app, which uses a bunch of gems. Some of them are only used for test and development environments. Now, when I try to start unicorn on the production server using the following command, it fails.

unicorn_rails -E production -D -c config/unicorn.rb

The error I see in the log files is:

Refreshing Gem list
Could not find gem 'spork (>= 0.9.0.rc2, runtime)' in any of the gem sources listed in your Gemfile.
Try running `bundle install`.

I've pasted my gemfile below:

source 'http://rubygems.org'

gem 'rails', '3.0.1'
gem 'unicorn'
gem 'mongoid', '>= 2.0.0.beta.19'
gem 'devise'
gem 'cancan'
gem 'haml', '>= 3.0.0'
gem 'bson'
gem 'bson_ext'
gem 'formtastic'
gem 'bluecloth'

group :production do
  gem 'capistrano'
end

group :development do
  gem 'haml-rails'
  gem 'hpricot', '0.8.2'
  gem 'ruby_parser', '2.0.5'
  gem 'less'
  gem 'rspec-rails', '>= 2.0.1'
end

group :development,:test do
  gem 'spork', '>=0.9.0.rc2'
  gem 'mongoid-rspec'
end

group :test do
  gem 'factory_girl_rails'
  gem 'autotest'
  gem 'cucumber-rails'
  gem 'cucumber'
  gem 'capybara'
  gem 'shoulda'
  gem 'database_cleaner'
  gem 'test_notifier'
  gem 'rspec', '2.0.1'
  gem 'launchy'
end

Bundler is supposed to detect the right environment and ignore the other gems, right? Right now, I am deleting all the lines which are not in the default group on the server to get this working, but that's an ugly hack.


来源: stackexchange

问:
Sharing intent doesn't open on certain devices
What I am using:

```<code> ShareCompat.IntentBuilder
     .from(getActivity())
     .setText("text")
     .setType("text/plain")
     .startChooser();
</code>```

I also tried the below:

```<code> Intent sendIntent = new Intent();
 sendIntent.setAction(Intent.ACTION_SEND);
 sendIntent.putExtra(Intent.EXTRA_TEXT, url);
 sendIntent.setType("text/plain");
 context.startActivity(sendIntent);
</code>```

On all my emulators, versions from 5 to 7. In both above codes, the intent would open and the text I am trying to share works successfully.

Nexus 5X, HTC One M8 both work too. However, when I use a Samsung device, version 5 and 7 do not open anything when I call both codes above.

EDIT

I turned off battery optimization on the Samsung with android version 5 and it worked? I then disabled it again but it kept working.

答:
Try this code </p>

```<code>        Intent intent_share = new Intent();
        intent_share.setAction(Intent.ACTION_SEND);
        intent_share.setFlags(R.drawable.ic_share);

        intent_share.putExtra(Intent.EXTRA_TEXT, "www.googleplay.com/acount");
        intent_share.setType("text/plain");
        startActivity(Intent.createChooser(intent_share, "Share it"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What I am using:

 ShareCompat.IntentBuilder
     .from(getActivity())
     .setText("text")
     .setType("text/plain")
     .startChooser();

I also tried the below:

 Intent sendIntent = new Intent();
 sendIntent.setAction(Intent.ACTION_SEND);
 sendIntent.putExtra(Intent.EXTRA_TEXT, url);
 sendIntent.setType("text/plain");
 context.startActivity(sendIntent);

On all my emulators, versions from 5 to 7. In both above codes, the intent would open and the text I am trying to share works successfully.

Nexus 5X, HTC One M8 both work too. However, when I use a Samsung device, version 5 and 7 do not open anything when I call both codes above.

EDIT

I turned off battery optimization on the Samsung with android version 5 and it worked? I then disabled it again but it kept working.

Body:
Try this code

        Intent intent_share = new Intent();
        intent_share.setAction(Intent.ACTION_SEND);
        intent_share.setFlags(R.drawable.ic_share);

        intent_share.putExtra(Intent.EXTRA_TEXT, "www.googleplay.com/acount");
        intent_share.setType("text/plain");
        startActivity(Intent.createChooser(intent_share, "Share it"));


问:
add sender's name in the from field of the email in python
I am trying to send email with below code.

```<code>import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
mail_me(cont,['xyz@xyzcom'])
</code>```

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

```<code>[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]
</code>```

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

答:
Just tested the following code with gmx.com and it works fine. Although, whether you get the same mileage is a moot point.

I have replaced all references to my email service with gmail

```<code>#!/usr/bin/python

#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

sender = 'example@gmail.com'
receivers = ['example@gmail.com']

msg = MIMEMultipart()
msg['From'] = 'example@gmail.com'
msg['To'] = 'example@gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))

ServerConnect = False
try:
    smtp_server = SMTP('smtp.gmail.com','465')
    smtp_server.login('#name#@gmail.com', '#password#')
    ServerConnect = True
except SMTPHeloError as e:
    print "Server did not reply"
except SMTPAuthenticationError as e:
    print "Incorrect username/password combination"
except SMTPException as e:
    print "Authentication failed"

if ServerConnect == True:
    try:
        smtp_server.sendmail(sender, receivers, msg.as_string())
        print "Successfully sent email"
    except SMTPException as e:
        print "Error: unable to send email", e
    finally:
        smtp_server.close()
</code>```

Body:
I am trying to send email with below code.

import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\

Hi!

          How are you?

          Here is the link you wanted.

   """
mail_me(cont,['xyz@xyzcom'])

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

Body:
Just tested the following code with gmx.com and it works fine. Although, whether you get the same mileage is a moot point.

I have replaced all references to my email service with gmail

#!/usr/bin/python

#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

sender = 'example@gmail.com'
receivers = ['example@gmail.com']

msg = MIMEMultipart()
msg['From'] = 'example@gmail.com'
msg['To'] = 'example@gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))

ServerConnect = False
try:
    smtp_server = SMTP('smtp.gmail.com','465')
    smtp_server.login('#name#@gmail.com', '#password#')
    ServerConnect = True
except SMTPHeloError as e:
    print "Server did not reply"
except SMTPAuthenticationError as e:
    print "Incorrect username/password combination"
except SMTPException as e:
    print "Authentication failed"

if ServerConnect == True:
    try:
        smtp_server.sendmail(sender, receivers, msg.as_string())
        print "Successfully sent email"
    except SMTPException as e:
        print "Error: unable to send email", e
    finally:
        smtp_server.close()


问:
Is it possible to prevent the browser from parsing certain elements?
Consider the following markup:

```<code><div hidden id="table-template">
<table>
<tbody>
  <slot></slot>
</tbody>
</table>
</div>
<div hidden id="table-row-template">
<tr>
  <td>
    Some Content
  </td>
</tr>
</div>
</code>```

I would like to use 'table-template' and 'table-row-template' as re-usable components in my script.
(clone them and append them on demand)
but as the page loads the browser parses the markup and mutates it (taking 'slot' element and insert it before the 'table' element, and stripping 'td' and 'tr' tags).

This is reasonable (not valid HTML of course), but is there any way I can prevent the browser from parsing those elements?

So far I have tried:
using hidden elements,
wrapping with 'pre'/'code' tags,
but none seem to work.

答:
So I have researched a bit about my problem, and this is what i figured out -
the 'tbody' element accpets only 'tr' elements as children.
so browsers will 'fix' the markup while parsing it one way or the other.
using template tags as vassiliskrikonis suggested will not work for the 'table-template' but will fix the 'table-row-template' issue,
using script tag as @Mihaly_KR suggested will work for both, but when accessing the template you will get a plain string to work with (injecting this string into the DOM will make the browser parse it and 'fix' it once again...)

The workaround I have found is to use other tag as a placeholder for my content.
one way is using a comment e.g.
but accessing this comment element requires a use of treeWalker or nodeIterator (which are much less performant then querySelector or getElementsByTagName)
other way is using a script tag as a placeholder.
browsers will not change the markup, and it can be accessed later using querySelector or getElementsByTagName.

so my refactored code looks like this:

```<code><template id="table-template">
<table>
<tbody>
  <script type="slot"></script>
</tbody>
</table>
</template>
<template id="table-row-template">
<tr>
  <td>
    Some Content
  </td>
</tr>
</template>
</code>```

Body:
Consider the following markup:

  <slot></slot>

    Some Content

I would like to use 'table-template' and 'table-row-template' as re-usable components in my script.
(clone them and append them on demand)
but as the page loads the browser parses the markup and mutates it (taking 'slot' element and insert it before the 'table' element, and stripping 'td' and 'tr' tags).

This is reasonable (not valid HTML of course), but is there any way I can prevent the browser from parsing those elements?

So far I have tried:
using hidden elements,
wrapping with 'pre'/'code' tags,
but none seem to work.

Body:
So I have researched a bit about my problem, and this is what i figured out -
the 'tbody' element accpets only 'tr' elements as children.
so browsers will 'fix' the markup while parsing it one way or the other.
using template tags as vassiliskrikonis suggested will not work for the 'table-template' but will fix the 'table-row-template' issue,
using script tag as @Mihaly_KR suggested will work for both, but when accessing the template you will get a plain string to work with (injecting this string into the DOM will make the browser parse it and 'fix' it once again...)

The workaround I have found is to use other tag as a placeholder for my content.
one way is using a comment e.g.
but accessing this comment element requires a use of treeWalker or nodeIterator (which are much less performant then querySelector or getElementsByTagName)
other way is using a script tag as a placeholder.
browsers will not change the markup, and it can be accessed later using querySelector or getElementsByTagName.

so my refactored code looks like this:

<template id="table-template">
<table>
<tbody>
  <script type="slot"></script>
</tbody>
</table>
</template>
<template id="table-row-template">
<tr>
  <td>
    Some Content
  </td>
</tr>
</template>


问:
My Python LinkedList implementation crashes after second addition to List
```<code>class Node:
  def __init__(self, data = None, next = None):
    self.data = data
    self.next = next

class LinkedList(Node):
  def __init__(self, l_size = 0, head = None, tail = None):
    Node.__init__(self)
    self.l_size = 0
    self.head = head
    self.tail = tail

  def add(self, data):
    n = Node(data, None)
    if(self.l_size == 0):
      self.head.next = n
      self.head.data = n.data
    else:
      self.tail.next = n
      self.tail.data = n.data
      n = n.next
      print(n)
    self.tail = n
    self.l_size += 1
    return True

l = LinkedList()
l.add(7)
l.add(8)
l.add(2)
</code>```

I'm just trying to achieve (h)-> 7 -> 8 -> 2 <- (l)
Where (h) and (l) are the head and tail pointers respectively. The way I'm implementing this the LL is basically the head and the tail pointers, the Nodes chain together on their own, that's why I made Node a super class.

答:
I don't get why you've decided to use this messy assignments. You should assign whole object and then move tail to next if needed:

```<code>class Node:
  def __init__(self, data = None, next = None):
    self.data = data
    self.next = next

class LinkedList:
  def __init__(self, l_size = 0, head = None, tail = None):
    Node.__init__(self)
    self.l_size = 0
    self.head = head
    self.tail = tail

  def add(self, data):
    n = Node(data, None)
    if self.l_size == 0:
      self.head = n
      self.tail = n
      print(n)
    else:
      self.tail.next = n
      self.tail = self.tail.next
      print(n)
    self.l_size += 1
    return True

l = LinkedList()
l.add(7)
l.add(8)
l.add(2)
</code>```

EDIT deleted subclassing from Node

Body:
class Node:
  def __init__(self, data = None, next = None):
    self.data = data
    self.next = next

class LinkedList(Node):
  def __init__(self, l_size = 0, head = None, tail = None):
    Node.__init__(self)
    self.l_size = 0
    self.head = head
    self.tail = tail

  def add(self, data):
    n = Node(data, None)
    if(self.l_size == 0):
      self.head.next = n
      self.head.data = n.data
    else:
      self.tail.next = n
      self.tail.data = n.data
      n = n.next
      print(n)
    self.tail = n
    self.l_size += 1
    return True

l = LinkedList()
l.add(7)
l.add(8)
l.add(2)

I'm just trying to achieve (h)-> 7 -> 8 -> 2 <- (l)
Where (h) and (l) are the head and tail pointers respectively. The way I'm implementing this the LL is basically the head and the tail pointers, the Nodes chain together on their own, that's why I made Node a super class.

Body:
I don't get why you've decided to use this messy assignments. You should assign whole object and then move tail to next if needed:

class Node:
  def __init__(self, data = None, next = None):
    self.data = data
    self.next = next

class LinkedList:
  def __init__(self, l_size = 0, head = None, tail = None):
    Node.__init__(self)
    self.l_size = 0
    self.head = head
    self.tail = tail

  def add(self, data):
    n = Node(data, None)
    if self.l_size == 0:
      self.head = n
      self.tail = n
      print(n)
    else:
      self.tail.next = n
      self.tail = self.tail.next
      print(n)
    self.l_size += 1
    return True

l = LinkedList()
l.add(7)
l.add(8)
l.add(2)

EDIT deleted subclassing from Node


问:
How to use traits in Laravel models?
Hello i'm laravel beginner

I want to make trait and use it in my model but at run time i got error that the trait is not found

my trait :

```<code>namespace App;
use Illuminate\Support\Facades\Schema;

trait GeneralModel
{
    public static function testStaticFunction()
    {
        dd('test');
    }
}
</code>```

my model :

```<code>namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use GeneralModel;
}
</code>```

my controller

```<code>namespace App\Http\Controllers;

use App\Comment;

class SearchController extends Controller
{
    public function find()
    {
        Comment::testStaticFunction();
    }
}
</code>```

error received

Trait 'App\GeneralModel' not found

答:
Please check the GeneralModel.php in app folder. And execute the below command in your project root path.</p>

```<code>php artisan dump-autoload
</code>```

Title: How to use traits in Laravel models?

Body:
Hello i'm laravel beginner

I want to make trait and use it in my model but at run time i got error that the trait is not found

my trait :

namespace App;
use Illuminate\Support\Facades\Schema;

trait GeneralModel
{
    public static function testStaticFunction()
    {
        dd('test');
    }
}

my model :

namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use GeneralModel;
}

my controller

namespace App\Http\Controllers;

use App\Comment;

class SearchController extends Controller
{
    public function find()
    {
        Comment::testStaticFunction();
    }
}

error received

Trait 'App\GeneralModel' not found

Body:
Please check the GeneralModel.php in app folder. And execute the below command in your project root path.

php artisan dump-autoload


问:
list-style & bullet effect with proper text alignment

.lists li{
        list-style-type: none;
    }
    .lists li:before {
        content: '\00b7';
        font-size: 140px;
        line-height: 60px;
        vertical-align: middle;
        color: #114576;
        /* margin-left: -5.5%; */
    }
    .lists ul{
        padding-top: 2%;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lists">
 <ul>
  <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra  by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
  <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
  <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
  <li class="text-muted">Students can access the        results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) -  a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>
  <li class="text-muted">These courses are further mapped to the student’s relevant district and assessed interest</li>
  <li class="text-muted">The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)</li>
  <li class="text-muted">SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)</li>
  </ul>
</div></code>```

here i have implemented the code for the designing the paragraph with bullets.but,i am facing some problem like the second line taking top space between two lines as well the text is not appearing in proper alignment as like displayed in image.
some css effects are missing to display the code same as like displayed in image.

答:
you can use display:flex on the li and it will work. or use display:table-row see both solutions below

display:flex on li

.lists li {
  display: flex;
  margin: 40px 0;
}

.lists li:before {
  content: '\00b7';
  font-size: 140px;
  line-height: 20px;
  vertical-align: top;
  color: #114576;
  /* margin-left: -5.5%; */
}

.lists ul {
  padding-top: 2%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lists">
  <ul>
    <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
    <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
    <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
    <li class="text-muted">Students can access the results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) - a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>
    <li class="text-muted">These courses are further mapped to the student’s relevant district and assessed interest</li>
    <li class="text-muted">The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)</li>
    <li class="text-muted">SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)</li>
  </ul>
</div></code>```

display:table-row on li and display-table on ul ( but in this way you cannot add margins between lis because table-rows do not accept margins )

.lists li {
  display: table-row;
  margin: 40px 0;
}

.lists li:before {
  content: '\00b7';
  font-size: 140px;
  line-height: 20px;
  vertical-align: top;
  color: #114576;
  display: table-cell;
  /* margin-left: -5.5%; */
}

.lists ul {
  padding-top: 2%;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lists">
  <ul>
    <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
    <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
    <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
    <li class="text-muted">Students can access the results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) - a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>
    <li class="text-muted">These courses are further mapped to the student’s relevant district and assessed interest</li>
    <li class="text-muted">The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)</li>
    <li class="text-muted">SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)</li>
  </ul>
</div></code>```

let me know if these solutions worked for you.

Body:
.lists li{
        list-style-type: none;
    }
    .lists li:before {
        content: '\00b7';
        font-size: 140px;
        line-height: 60px;
        vertical-align: middle;
        color: #114576;
        /* margin-left: -5.5%; */
    }
    .lists ul{
        padding-top: 2%;
    }

In 2016, SAF lent technical support to the Government of Maharashtra  by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling

In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University

In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test

Students can access the        results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) -  a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra

These courses are further mapped to the student’s relevant district and assessed interest

The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)

SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)

here i have implemented the code for the designing the paragraph with bullets.but,i am facing some problem like the second line taking top space between two lines as well the text is not appearing in proper alignment as like displayed in image.
some css effects are missing to display the code same as like displayed in image.

Body:
you can use display:flex on the li and it will work. or use display:table-row see both solutions below

display:flex on li

.lists li {
  display: flex;
  margin: 40px 0;
}

.lists li:before {
  content: '\00b7';
  font-size: 140px;
  line-height: 20px;
  vertical-align: top;
  color: #114576;
  /* margin-left: -5.5%; */
}

.lists ul {
  padding-top: 2%;
}

<div class="lists">
  <ul>
    <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
    <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
    <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
    <li class="text-muted">Students can access the results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) - a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>
    <li class="text-muted">These courses are further mapped to the student’s relevant district and assessed interest</li>
    <li class="text-muted">The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)</li>
    <li class="text-muted">SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)</li>
  </ul>
</div>

display:table-row on li and display-table on ul ( but in this way you cannot add margins between lis because table-rows do not accept margins )

.lists li {
  display: table-row;
  margin: 40px 0;
}

.lists li:before {
  content: '\00b7';
  font-size: 140px;
  line-height: 20px;
  vertical-align: top;
  color: #114576;
  display: table-cell;
  /* margin-left: -5.5%; */
}

.lists ul {
  padding-top: 2%;
  display: table;
}

<div class="lists">
  <ul>
    <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
    <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
    <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
    <li class="text-muted">Students can access the results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) - a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>
    <li class="text-muted">These courses are further mapped to the student’s relevant district and assessed interest</li>
    <li class="text-muted">The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)</li>
    <li class="text-muted">SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)</li>
  </ul>
</div>

let me know if these solutions worked for you.


问:
Google Analytics core API - External sources of data
I have been exploring some with the Google Analytics Core API. I reached the point where I wish to collect queries from external/other sources. Yes, I do know for some people this may sound a bit stupid, since this is very sensitive data for some companies or whatever. Anyhow, is this possible? Is it some kind of identification that can be found in the dashboard of Google API:s? That lets others to get access of the same data, but from other API requests?

I have tried other webpages view ID:s but without success.

I can not find any documentation about this matter either.

This is possible on the Adobe Analytics API. So I see no reason why it shouldnt be able to do on Google Analytics?

Edited, scenario added.

Im trying to figure out how many sessions a website for which I do not
  own has.

I want access of the data in google analytics that my company has. I'm wondering if this is possible to get their data from my API requests based on their identifications,etc. I want to create my own dashboard with many different Google analytics sources. Or, do I need to use the same client_secrets that is connected in the Google API dashboard of the owners?

Kind regards, Peter

答:
You should understand the difference between private and public data.  Private data is owned by a user public data is owned by no one.   Searching for public videows on YouTube would be a good example of public data.

Google Analytics data is private it is owned by the person or people who have access to that Google analytics account.   You can not access the data associated with my website unless I grant you access to it.   If you are working on an application and need to access someone else's Google analytics data then you can use Oauth2 (using client id and secret) and have them authenticate the application and you will be able to access their data.

You can not access Google Analytics data that you do not have permission to access.  We get permission by using Oauth2 or a service account.

If you have been added to your companies google analytics account and you have access to it then you can use the Google Analytics API to access the data for those accounts.   By going though the management api you will be able to see all of the accounts that you have access to and use that to make your dashboard.

Just remember though the Google Analytics api returns raw data not graphs you will have to create your dashboard yourself.  or try checking out the embedded api but that will only work with one view at a time i as far as i know.


问:
Convert array to tuple?
Is it possible to convert array to tuple in C#? Something like this:</p>

```<code>var ar = new int[2] {5, 7};
Tuple<int,int> t = Tuple.Create(ar);
</code>```

答:
No, System.Tuple has a maximum size for good reason. It's simply the wrong tool for the job you appear to be doing. Why don't you just return the array instead of a tuple? Your approach could end up needing a tuple with dozens of elements which is beyond ridiculous and not at all maintainable.

Even better instead of returning the array, return an interface such as ICollection<T> or IEnumerable<T>.

Title: Convert array to tuple?

Body:
Is it possible to convert array to tuple in C#? Something like this:

var ar = new int[2] {5, 7};
Tuple<int,int> t = Tuple.Create(ar);


问:
Can't reach an specific element by jquery: Undefined
This is my first question here. So be fair, please. :)

I don't get it.. I think my syntax isn't wrong but I only get an undefined object back from jquery. I try to pick an specific a tag element with the attribute-selector from jquery and after that I go down in the DOM till the last div before my img. At last I picked the img with the .find method.

Here is my code:

```<code>var cURL = $(this).find("img").attr("name");
console.log($("a[href=cURL] > div.image-box > div.image-content").find("img").attr("src"));
</code>```

The var cURL contains the right parameter as a string.

And the HTML/DOM:

```<code><div class="product-wrapper...">
  <div class="product-cell...">
   <a class="image-wrapper" href="myArticle50">
     <div class="image-box..">
       <div class="image-content">
         <img alt="..." src="media/testArticle/.../myArticle50.jpg">
       </div>
     </div>
   </a>
   ....
  </div>
</div>
</code>```

In this case my var cURL would contain 'myArticle50' and I need the src from the img -> 'media/testArticle/.../myArticle50.jpg'. But I only get an undefined back.

May you see my failure in the code.. :/

Kind Regards.

答:
You have two mistakes, first:

This

```<code>console.log($("a[href=cURL] > div.image-box > div.image-content").find("img").attr("src"));
</code>```

Should look like this

```<code>console.log($("a[href=" + cURL + "] > div.image-box > div.image-content").find("img").attr("src"));
</code>```

and your class

```<code><div class="image-box..">
</code>```

Shouldn't have dots.

```<code><div class="image-box">
</code>```

Fix these, and your code should work fine and dandy.

Body:
This is my first question here. So be fair, please. :)

I don't get it.. I think my syntax isn't wrong but I only get an undefined object back from jquery. I try to pick an specific a tag element with the attribute-selector from jquery and after that I go down in the DOM till the last div before my img. At last I picked the img with the .find method.

Here is my code:

var cURL = $(this).find("img").attr("name");
console.log($("a[href=cURL] > div.image-box > div.image-content").find("img").attr("src"));

The var cURL contains the right parameter as a string.

And the HTML/DOM:

   ....

In this case my var cURL would contain 'myArticle50' and I need the src from the img -> 'media/testArticle/.../myArticle50.jpg'. But I only get an undefined back.

May you see my failure in the code.. :/

Kind Regards.

Body:
You have two mistakes, first:

This

console.log($("a[href=cURL] > div.image-box > div.image-content").find("img").attr("src"));

Should look like this

console.log($("a[href=" + cURL + "] > div.image-box > div.image-content").find("img").attr("src"));

and your class

<div class="image-box..">

Shouldn't have dots.

<div class="image-box">

Fix these, and your code should work fine and dandy.


问:
WPF - MenuItem missing Icon/Image
Im getting menuItem icon appearing only on last menuItem.
If i snoop the app only last menuItem has image in icon, while if i debug all MenuItems appear to have image in icon. Also if i add submenuItem the icon on menuItem dissapears once i open submenus and the last submenu gets the icon... Any idea? PS: also tooltips on menu item dont work.
Im using caliburn micro and fluent ribbon controls.</p>

```<code>        <ControlTemplate x:Key="dropDownButton">
        <ef:DropDownButton Header="{Binding DisplayName}"
                           ItemsSource="{Binding Items}"
                           LargeIcon="{Binding LargeIconPath}"
                           cm:Message.Attach="ClickAction()"
                           ef:KeyTip.Keys="{Binding KeyTip}">
            <ef:DropDownButton.ItemContainerStyle>
                <Style TargetType="MenuItem">
                    <Setter Property="Header"
                            Value="{Binding DisplayName}"/>
                    <Setter Property="Icon">
                        <Setter.Value>
                            <Image Source="{Binding Path=IconPath}"/>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="ItemsSource"
                            Value="{Binding Items}"/>
                    <Setter Property="cm:Message.Attach"
                            Value="ClickAction()"/>
                    <Setter Property="ef:KeyTip.Keys"
                            Value="{Binding KeyTip}"/>
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ef:ScreenTip Title="{Binding DisplayName}"
                                          HelpTopic="ScreenTip help ..."
                                          Image="{Binding LargeIconPath}"
                                          Text="Text for ScreenTip"/>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ef:DropDownButton.ItemContainerStyle>
            <ef:DropDownButton.ToolTip>
                <ef:ScreenTip Title="{Binding DisplayName}"
                              HelpTopic="ScreenTip help ..."
                              Image="{Binding LargeIconPath}"
                              Text="Text for ScreenTip"/>
            </ef:DropDownButton.ToolTip>
        </ef:DropDownButton>
</code>```

答:
You are setting Icon property to an Image control in Style. Now, only one copy of Style is created and thus, only one copy of Image is created. Now, any control can have only one parent at a time. So, when it is assigned to last MenuItem, it is removed from previous MenuItem controls. To fix this, use Templates.

Instead of setting Header property, set HeaderTemplate:

```<code>            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0"
                                   Source="{Binding Path=IconPath}" />
                            <TextBlock Grid.Column="1"
                                       Text="{Binding DisplayName}" />
                        </Grid>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
</code>```

I'm not sure of what properties are exposed by the control toolkit you are using. But, I'm sure they must have a template property.

After doing this, you don't need to set Icon property in style.

ContentLicense: CC BY-SA 2.5

Title: WPF - MenuItem missing Icon/Image

Body:
Im getting menuItem icon appearing only on last menuItem.
If i snoop the app only last menuItem has image in icon, while if i debug all MenuItems appear to have image in icon. Also if i add submenuItem the icon on menuItem dissapears once i open submenus and the last submenu gets the icon... Any idea? PS: also tooltips on menu item dont work.
Im using caliburn micro and fluent ribbon controls.

        <ControlTemplate x:Key="dropDownButton">
        <ef:DropDownButton Header="{Binding DisplayName}"
                           ItemsSource="{Binding Items}"
                           LargeIcon="{Binding LargeIconPath}"
                           cm:Message.Attach="ClickAction()"
                           ef:KeyTip.Keys="{Binding KeyTip}">
            <ef:DropDownButton.ItemContainerStyle>

            </ef:DropDownButton.ItemContainerStyle>
            <ef:DropDownButton.ToolTip>
                <ef:ScreenTip Title="{Binding DisplayName}"
                              HelpTopic="ScreenTip help ..."
                              Image="{Binding LargeIconPath}"
                              Text="Text for ScreenTip"/>
            </ef:DropDownButton.ToolTip>
        </ef:DropDownButton>

Body:
You are setting Icon property to an Image control in Style. Now, only one copy of Style is created and thus, only one copy of Image is created. Now, any control can have only one parent at a time. So, when it is assigned to last MenuItem, it is removed from previous MenuItem controls. To fix this, use Templates.

Instead of setting Header property, set HeaderTemplate:

            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0"
                                   Source="{Binding Path=IconPath}" />
                            <TextBlock Grid.Column="1"
                                       Text="{Binding DisplayName}" />
                        </Grid>
                    </DataTemplate>
                </Setter.Value>
            </Setter>

I'm not sure of what properties are exposed by the control toolkit you are using. But, I'm sure they must have a template property.

After doing this, you don't need to set Icon property in style.


问:
Keytab file: /path/a.keytab does not exist
I have keytab file in local directory , path. I am trying to pass this keytab and principal via --keytab and --principal in <spark-opts> in oozie. However I am getting error Keytab file: /path/a.keytab does not exist . However the file exists in path directory. What could be issue

答: With oozie, you have to put the keytab in the lib directory of your workflow stored in HDFS. Then, your spark action should be able to read it.</p>


问:
Adding button with Text dynamically to UI at runtime in Unity
I am working with C# an Unity 5.6.1f1, I done a mechanism that on UI button click should add an additional button with text to Panel that is already on UI, and it does work... since I am able to see Object appear there

```<code>public void MakeButton(string direction)
{

    GameObject button = new GameObject();
    button.AddComponent<RectTransform>();
    button.AddComponent<Button>();

    var panel = GameObject.Find("CommandPanel");
    button.transform.position = panel.transform.position;
    button.GetComponent<RectTransform>().SetParent(panel.transform);
    button.GetComponent<RectTransform>().SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,0,10);
    button.SetActive(true);
    button.layer = 5;

    //button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text";

}
</code>```

problem is it isn't visible and reason for that I believe that there is no text there... now how do I know that...

I tried running the following button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text";

and it gave me

IndexOutOfRangeException: Array index is out of range.
  Hero.MakeButton (System.String direction) (at Assets/Scripts/Hero.cs:37)
  Hero.Down () (at Assets/Scripts/Hero.cs:14)
  UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:154)
  UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:637)
  UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:773)
  UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:52)
  UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
  UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
  UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
  UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
  UnityEngine.EventSystems.EventSystem:Update()

Also as you can see in the screenshot there is no triangle Under New Game Object like it is under Run which is also a button...

How do I add from the script Button that has Text on it to panel in Unity?

答:
I highly advise you to instantiate a prefab instead of creating the button from scratch.

A gameobject with a RectTransform and button only won't be visible, and won't react to clicks, because you need additionnal components (such as Canvas Renderer and Image / Raw Image).

```<code>// Drag & Drop the prefab of the button you will instantiate
public GameObject buttonPrefab ;

public void MakeButton(string direction)
{
    // Instantiate (clone) the prefab
    GameObject button = (GameObject) Instantiate( buttonPrefab ) ;

    var panel = GameObject.Find("CommandPanel");
    button.transform.position = panel.transform.position;
    button.GetComponent<RectTransform>().SetParent(panel.transform);
    button.GetComponent<RectTransform>().SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,0,10);
    button.layer = 5;

}
</code>```

Moreover, you have to be careful to one additional thing : when you ask Unity to create a button (Using GameObject > UI > Button), Unity creates several gameobjects (the button + child) with all the appropriates components (button, canvas renderer, text, ...).

Adding the Button component won't add all the other components and children Unity does. Thus button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text"; won't work (since you haven't added the child and its Text component in your script)

Additional note : Check this link if you have some problems with placing your object : https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html

Body:
I am working with C# an Unity 5.6.1f1, I done a mechanism that on UI button click should add an additional button with text to Panel that is already on UI, and it does work... since I am able to see Object appear there

public void MakeButton(string direction)
{

    GameObject button = new GameObject();
    button.AddComponent<RectTransform>();
    button.AddComponent<Button>();

    var panel = GameObject.Find("CommandPanel");
    button.transform.position = panel.transform.position;
    button.GetComponent<RectTransform>().SetParent(panel.transform);
    button.GetComponent<RectTransform>().SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,0,10);
    button.SetActive(true);
    button.layer = 5;

    //button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text";

}

problem is it isn't visible and reason for that I believe that there is no text there... now how do I know that...

I tried running the following button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text";

and it gave me

IndexOutOfRangeException: Array index is out of range.
  Hero.MakeButton (System.String direction) (at Assets/Scripts/Hero.cs:37)
  Hero.Down () (at Assets/Scripts/Hero.cs:14)
  UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:154)
  UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:637)
  UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:773)
  UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:52)
  UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
  UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
  UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
  UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
  UnityEngine.EventSystems.EventSystem:Update()

Also as you can see in the screenshot there is no triangle Under New Game Object like it is under Run which is also a button...

How do I add from the script Button that has Text on it to panel in Unity?

Body:
I highly advise you to instantiate a prefab instead of creating the button from scratch.

A gameobject with a RectTransform and button only won't be visible, and won't react to clicks, because you need additionnal components (such as Canvas Renderer and Image / Raw Image).

// Drag & Drop the prefab of the button you will instantiate
public GameObject buttonPrefab ;

public void MakeButton(string direction)
{
    // Instantiate (clone) the prefab
    GameObject button = (GameObject) Instantiate( buttonPrefab ) ;

    var panel = GameObject.Find("CommandPanel");
    button.transform.position = panel.transform.position;
    button.GetComponent<RectTransform>().SetParent(panel.transform);
    button.GetComponent<RectTransform>().SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,0,10);
    button.layer = 5;

}

Moreover, you have to be careful to one additional thing : when you ask Unity to create a button (Using GameObject > UI > Button), Unity creates several gameobjects (the button + child) with all the appropriates components (button, canvas renderer, text, ...).

Adding the Button component won't add all the other components and children Unity does. Thus button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text"; won't work (since you haven't added the child and its Text component in your script)

Additional note : Check this link if you have some problems with placing your object : https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html


问:
Java - append excel
i need to append excel. I write code:

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

    public class AppendExcel {

public static void main(String[] args) throws Exception {
    String excelFilePath = "append.xlsx";

    try {
        FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
        Workbook workbook = WorkbookFactory.create(inputStream);

        Sheet sheet = workbook.getSheetAt(0);

        DbManagerSQL test = new DbManagerSQL();
        String sql = "select distinct Code,Item,Description from MyTable";

        Statement stmt = test.dbConnect().createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        int rowCount = sheet.getLastRowNum();
        while (rs.next()) {

            Row row = sheet.createRow(++rowCount);

            int columnCount = 0;

            Cell cell = row.createCell(columnCount);
            cell.setCellValue(rowCount);

            cell = row.createCell(++columnCount);
            cell.setCellValue((String) rs.getString(1));
            cell.setCellValue((String) rs.getString(2));
            cell.setCellValue((String) rs.getString(3));

        }

        inputStream.close();

        FileOutputStream outputStream = new FileOutputStream("append.xlsx");
        workbook.write(outputStream);
        // workbook.close();
        outputStream.close();

    } catch (IOException | EncryptedDocumentException | InvalidFormatException ex) {
        ex.printStackTrace();
    }
}

}
</code>```

My Excel has the column

but when I append Excel I got next

It looks like remember only the last column. I think the prblem is in this line of code

cell = row.createCell(++columnCount);

but i don't now how to add data to get excel like this

Any idea???

答:
Create a cell for every entry:</p>

```<code>int columnCount = 0;

Cell cell = row.createCell(columnCount);
cell.setCellValue(rowCount);
columnCount++;

cell = row.createCell(columnCount);
cell.setCellValue((String) rs.getString(1));
columnCount++;

cell = row.createCell(columnCount);
cell.setCellValue((String) rs.getString(2));
columnCount++;

cell = row.createCell(columnCount);
cell.setCellValue((String) rs.getString(3));
</code>```

Title: Java - append excel

Body:
i need to append excel. I write code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

    public class AppendExcel {

public static void main(String[] args) throws Exception {
    String excelFilePath = "append.xlsx";

    try {
        FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
        Workbook workbook = WorkbookFactory.create(inputStream);

        Sheet sheet = workbook.getSheetAt(0);

        DbManagerSQL test = new DbManagerSQL();
        String sql = "select distinct Code,Item,Description from MyTable";

        Statement stmt = test.dbConnect().createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        int rowCount = sheet.getLastRowNum();
        while (rs.next()) {

            Row row = sheet.createRow(++rowCount);

            int columnCount = 0;

            Cell cell = row.createCell(columnCount);
            cell.setCellValue(rowCount);

            cell = row.createCell(++columnCount);
            cell.setCellValue((String) rs.getString(1));
            cell.setCellValue((String) rs.getString(2));
            cell.setCellValue((String) rs.getString(3));

        }

        inputStream.close();

        FileOutputStream outputStream = new FileOutputStream("append.xlsx");
        workbook.write(outputStream);
        // workbook.close();
        outputStream.close();

    } catch (IOException | EncryptedDocumentException | InvalidFormatException ex) {
        ex.printStackTrace();
    }
}

}

My Excel has the column

but when I append Excel I got next

It looks like remember only the last column. I think the prblem is in this line of code

cell = row.createCell(++columnCount);

but i don't now how to add data to get excel like this

Any idea???

Body:
Create a cell for every entry:

int columnCount = 0;

Cell cell = row.createCell(columnCount);
cell.setCellValue(rowCount);
columnCount++;

cell = row.createCell(columnCount);
cell.setCellValue((String) rs.getString(1));
columnCount++;

cell = row.createCell(columnCount);
cell.setCellValue((String) rs.getString(2));
columnCount++;

cell = row.createCell(columnCount);
cell.setCellValue((String) rs.getString(3));


问:
data is entering multiple time in db when using ajax and jquery in php
I am sort of new in PHP, so i am not really good in debugging. i am trying this for a while now and after not getting anywhere, i decided to put it here and hope if i can get solution.
i have information on page with edit and add buttons on screen. when i am adding any entry, it is getting there (on main page as well as DB (mySQL)for multiple times. there is a pattern that I observed in my case. when i am using  add button for first time there is no repetition. when i do it for 2nd time i got 2 repetitions,3rd time i get 4 repetition, 4th time 8 ,5th time 16 and 6th time 32 time. So it is making a series like 1, 2,4,8,16,32.

What I am trying to do …

On add button I am opening a form on model and collecting info from there. On save of that model form, I am calling a jquery function and with the help of AJAX. I am using a third page to perform DB operations. after the insertion info is getting prepended on same section. I am sharing a piece of code of AJAX part and hope it is helpful for debugging .

thanks for everyone who put some effort even if I don’t get a solution.

JAVASCRIPT

```<code>$("#saved-education").click(function () {
            //         alert("insside save-edu");
            var msg1 = $("#education-course").val();
            var msg2 = $("#education-board").val();
            var msg3 = $("#education-school").val();
            var msg4 = $("#education-start-year").val();
            var msg5 = $("#education-end-year").val();
            var msg6 = $("#education-grade").val();
            //       alert(msg1 + msg2 + msg3 + msg4 + msg5 + msg6);
            var content = '&em1=' + msg1 + '&em2=' + msg2 + '&em3=' + msg3 +
                    '&em4=' + msg4 + '&em5=' + msg5 + '&em6=' + msg6;
            $.ajax({
              url: "ajexupdate.php",
              type: "POST",
              data: content,
              dataType: 'text',
              cache: false,
              success: function (e) {
                //      alert(e);
                $("#dislay_education_1").html(e);
                $("#modal-edu").modal('hide');
              }
            });
            return false;
          });
</code>```

PHP UPDATE CODE

```<code>if (isset($_POST['em1'])) {
  $edu_id = generate_random_edu_id();
  $course = $_POST['em1'];
  $board = $_POST['em2'];
  $school = $_POST['em3'];
  $start_year = $_POST['em4'];
  $end_year = $_POST['em5'];
  $grade = $_POST['em6'];
  $eduation_insert = mysql_query("INSERT INTO `user_education`(`edu_id`, `course`, `board`, `school`, `start_year`, `end_year`, `grade`, `uid_fk`,`colg_id`) VALUES ('$edu_id','$course','$board','$school','$start_year','$end_year','$grade','$user_id','$colg_id')", $db1);
  $education_query = mysql_query("SELECT * FROM  `user_education` WHERE  `uid_fk` ='$user_id' AND `edu_id`='$edu_id' ORDER BY edu_created DESC LIMIT 1", $db1);
  $education_result = mysql_fetch_object($education_query);
  }
</code>```

HTML FORM

```<code> <div class="form-group">
            <label class="col-sm-2 control-label" for="textinput">Duration</label>
            <div class="col-sm-5">
                <select id="education-start-year" name="start_year" >
                    <option disabled="disabled">From</option>
                    <?php
                    $year = range(2017, 1900);
                    foreach ($year as $d) { ?>
                    <option value="<?php echo $d; ?>" <?php   if ($row_edit_exp->start_year == $d){ echo selected; } ?> > <?php echo $d; ?></option>
                    <?php } ?>
                </select>
            </div>

            <label class="control-label" for="textinput"></label>
            <div class="col-sm-5">
                <select  id="education-end-year" >
                    <option disabled="disabled">From</option>
                    <?php
                    $year = range(2017, 1900);
                    foreach ($year as $d) { ?>
                    <option value="<?php echo $d; ?>" <?php   if ($row_edit_exp->end_year == $d){ echo selected; } ?> > <?php echo $d; ?></option>
                    <?php } ?>
                </select>
            </div>
        </div>
        <br><br>

    </div>
    <div class="modal-footer">
        <div class="col-sm-6">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div> <div class="col-sm-6">
            <button type="button" id="saved-education" class="btn btn-primary">Save</button>

        </div>
    </div>
</code>```

答:
In my case the answer , was not found by entering something new piece of code.it was found through a debugging suggestion made by Saad suri. i cant rate him up as i dont have enough repo.
actually i was including the JS function in my AJAX file too, to make sure the edit and delete in HTML view that was displayed on front end was still working. so i included the JS in AJAX page just to make sure the buttons were still working in the updated view. this was causing the multiple entering in Db.
thanks saad for your suggestion and sorry i cant rate your comment.</p>

Body:
I am sort of new in PHP, so i am not really good in debugging. i am trying this for a while now and after not getting anywhere, i decided to put it here and hope if i can get solution.
i have information on page with edit and add buttons on screen. when i am adding any entry, it is getting there (on main page as well as DB (mySQL)for multiple times. there is a pattern that I observed in my case. when i am using  add button for first time there is no repetition. when i do it for 2nd time i got 2 repetitions,3rd time i get 4 repetition, 4th time 8 ,5th time 16 and 6th time 32 time. So it is making a series like 1, 2,4,8,16,32.

What I am trying to do …

On add button I am opening a form on model and collecting info from there. On save of that model form, I am calling a jquery function and with the help of AJAX. I am using a third page to perform DB operations. after the insertion info is getting prepended on same section. I am sharing a piece of code of AJAX part and hope it is helpful for debugging .

thanks for everyone who put some effort even if I don’t get a solution.

JAVASCRIPT

$("#saved-education").click(function () {
            //         alert("insside save-edu");
            var msg1 = $("#education-course").val();
            var msg2 = $("#education-board").val();
            var msg3 = $("#education-school").val();
            var msg4 = $("#education-start-year").val();
            var msg5 = $("#education-end-year").val();
            var msg6 = $("#education-grade").val();
            //       alert(msg1 + msg2 + msg3 + msg4 + msg5 + msg6);
            var content = '&em1=' + msg1 + '&em2=' + msg2 + '&em3=' + msg3 +
                    '&em4=' + msg4 + '&em5=' + msg5 + '&em6=' + msg6;
            $.ajax({
              url: "ajexupdate.php",
              type: "POST",
              data: content,
              dataType: 'text',
              cache: false,
              success: function (e) {
                //      alert(e);
                $("#dislay_education_1").html(e);
                $("#modal-edu").modal('hide');
              }
            });
            return false;
          });

PHP UPDATE CODE

if (isset($_POST['em1'])) {
  $edu_id = generate_random_edu_id();
  $course = $_POST['em1'];
  $board = $_POST['em2'];
  $school = $_POST['em3'];
  $start_year = $_POST['em4'];
  $end_year = $_POST['em5'];
  $grade = $_POST['em6'];
  $eduation_insert = mysql_query("INSERT INTO `user_education`(`edu_id`, `course`, `board`, `school`, `start_year`, `end_year`, `grade`, `uid_fk`,`colg_id`) VALUES ('$edu_id','$course','$board','$school','$start_year','$end_year','$grade','$user_id','$colg_id')", $db1);
  $education_query = mysql_query("SELECT * FROM  `user_education` WHERE  `uid_fk` ='$user_id' AND `edu_id`='$edu_id' ORDER BY edu_created DESC LIMIT 1", $db1);
  $education_result = mysql_fetch_object($education_query);
  }

HTML FORM

            Duration

                <select id="education-start-year" name="start_year" >
                    <option disabled="disabled">From</option>
                    <?php
                    $year = range(2017, 1900);
                    foreach ($year as $d) { ?>
                    <option value="<?php echo $d; ?>" <?php   if ($row_edit_exp->start_year == $d){ echo selected; } ?> > <?php echo $d; ?></option>
                    <?php } ?>
                </select>

                <select  id="education-end-year" >
                    <option disabled="disabled">From</option>
                    <?php
                    $year = range(2017, 1900);
                    foreach ($year as $d) { ?>
                    <option value="<?php echo $d; ?>" <?php   if ($row_edit_exp->end_year == $d){ echo selected; } ?> > <?php echo $d; ?></option>
                    <?php } ?>
                </select>

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" id="saved-education" class="btn btn-primary">Save</button>


问:
fatal: unable to stat "file": Permission denied
I searched and tried answer but problem didn't solve, I git init into android project and after making first push, I changed alot of things removed added new files and fonts (I don't remember if i git added during this) now when I ready to pus i ran command git status I see files in red as untract files, then I ran git add . but Im getting this error:

```<code>warning: LF will be replaced by CRLF in app/app.iml.
The file will have its original line endings in your working directory.
fatal: unable to stat 'app/src/main/res/drawable/slide_thre.jpg':
Permission denied
</code>```

the file slide_thre.jpg I deleted way before git add wen I was working but its still showing this error, I dont know if its cached

I tried closing IDE before git add and tried other solution but didn't work

">

答: did you close your photoviewer application which open slide_thre.jpg?</p>

Body:
I searched and tried answer but problem didn't solve, I git init into android project and after making first push, I changed alot of things removed added new files and fonts (I don't remember if i git added during this) now when I ready to pus i ran command git status I see files in red as untract files, then I ran git add . but Im getting this error:

warning: LF will be replaced by CRLF in app/app.iml.
The file will have its original line endings in your working directory.
fatal: unable to stat 'app/src/main/res/drawable/slide_thre.jpg':
Permission denied

the file slide_thre.jpg I deleted way before git add wen I was working but its still showing this error, I dont know if its cached

I tried closing IDE before git add and tried other solution but didn't work

">


问:
JavaFx ImageView won't resize on fitWidthProperty bind to VBox
I am trying to re-size an image so it fits (scaled) in the space allotted by a SplitPane (for workaround suggestions: this image will change when running the program, it should be generated from the text). The ImageView I'm using currently changes the location of the SplitPane Divider. The divider can never cause the ImageView to decrease past the size of the image.

Two images showing this behavior.

Linking the ImageView fitWidthProperty to a VBox has not given me the resize behavior I expected. Increasing the ImageView's size does work (where it is fixed without the binding), but the image never grows, it just gets borders around it.

My MWE:

sample.fxml:

```<code><?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<SplitPane orientation="HORIZONTAL" xmlns:fx="http://javafx.com/fxml">
    <TextArea fx:id="textArea"/>
    <VBox fx:id="vBox" alignment="CENTER">
        <HBox fx:id="hBox" alignment="CENTER">
            <ImageView fx:id="imageView"/>
        </HBox>
    </VBox>
</SplitPane>
</code>```

Controller.java:

```<code>import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

public class Controller {
    @FXML
    private TextArea textArea = new TextArea();
    @FXML
    private VBox vBox = new VBox();
    @FXML
    private HBox hBox = new HBox();
    @FXML
    private ImageView imageView = new ImageView();

    public Controller() {
        imageView.fitWidthProperty().bind(vBox.widthProperty());
        imageView.fitHeightProperty().bind(hBox.heightProperty());
    }

    public void start() {
        textArea.setText("text");

        Image image = new Image("https://www.google.nl/images/srpr/logo11w.png");
        imageView.setImage(image);
    }
}
</code>```

and Main.java:

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(final Stage primaryStage) throws Exception {
        final Controller controller = new Controller();

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("sample.fxml"));
        fxmlLoader.setController(controller);

        final Parent root = fxmlLoader.load();
        primaryStage.setTitle("MWE");
        final Scene scene = new Scene(root, 640, 480);
        primaryStage.setScene(scene);
        primaryStage.show();

        controller.start();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

答:
this is my sample for you!

```<code><?import javafx.scene.control.SplitPane?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>
<StackPane fx:controller="sample.Controller"
       xmlns:fx="http://javafx.com/fxml" alignment="center">

<SplitPane fx:id="splitpane">
    <VBox fx:id="left" prefWidth="300" prefHeight="200" style="-fx-background-color: antiquewhite">
        <ImageView fx:id="image1" preserveRatio="true" pickOnBounds="true">
            <image>
                <Image url="@/sample/test.jpg"/>
            </image>
        </ImageView>
    </VBox>
    <VBox fx:id="right" prefWidth="300" prefHeight="300" style="-fx-background-color: aquamarine">
        <ImageView fx:id="image2" preserveRatio="true" pickOnBounds="true">
            <image>
                <Image url="@/sample/test.jpg"/>
            </image>
        </ImageView>
    </VBox>
</SplitPane>
</code>```

```<code>package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.SplitPane;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    @FXML
    ImageView image1;
    @FXML
    ImageView image2;
    @FXML
    SplitPane splitpane;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
   splitpane.getDividers().get(0).positionProperty().addListener((observable, oldValue, newValue) -> {
        System.out.println(newValue);
        int w = 600;
        double w1 = w * newValue.doubleValue();
        double w2 = w - w1;
        image1.setFitWidth(w1);
        image2.setFitWidth(w2);
    });
   }
}
</code>```

Body:
I am trying to re-size an image so it fits (scaled) in the space allotted by a SplitPane (for workaround suggestions: this image will change when running the program, it should be generated from the text). The ImageView I'm using currently changes the location of the SplitPane Divider. The divider can never cause the ImageView to decrease past the size of the image.

Two images showing this behavior.

Linking the ImageView fitWidthProperty to a VBox has not given me the resize behavior I expected. Increasing the ImageView's size does work (where it is fixed without the binding), but the image never grows, it just gets borders around it.

My MWE:

sample.fxml:

<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<SplitPane orientation="HORIZONTAL" xmlns:fx="http://javafx.com/fxml">
    <TextArea fx:id="textArea"/>
    <VBox fx:id="vBox" alignment="CENTER">
        <HBox fx:id="hBox" alignment="CENTER">
            <ImageView fx:id="imageView"/>
        </HBox>
    </VBox>
</SplitPane>

Controller.java:

import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

public class Controller {
    @FXML
    private TextArea textArea = new TextArea();
    @FXML
    private VBox vBox = new VBox();
    @FXML
    private HBox hBox = new HBox();
    @FXML
    private ImageView imageView = new ImageView();

    public Controller() {
        imageView.fitWidthProperty().bind(vBox.widthProperty());
        imageView.fitHeightProperty().bind(hBox.heightProperty());
    }

    public void start() {
        textArea.setText("text");

        Image image = new Image("https://www.google.nl/images/srpr/logo11w.png");
        imageView.setImage(image);
    }
}

and Main.java:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(final Stage primaryStage) throws Exception {
        final Controller controller = new Controller();

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("sample.fxml"));
        fxmlLoader.setController(controller);

        final Parent root = fxmlLoader.load();
        primaryStage.setTitle("MWE");
        final Scene scene = new Scene(root, 640, 480);
        primaryStage.setScene(scene);
        primaryStage.show();

        controller.start();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Body:
this is my sample for you!

<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>
<StackPane fx:controller="sample.Controller"
       xmlns:fx="http://javafx.com/fxml" alignment="center">

<SplitPane fx:id="splitpane">
    <VBox fx:id="left" prefWidth="300" prefHeight="200" style="-fx-background-color: antiquewhite">
        <ImageView fx:id="image1" preserveRatio="true" pickOnBounds="true">
            <image>
                <Image url="@/sample/test.jpg"/>
            </image>
        </ImageView>
    </VBox>
    <VBox fx:id="right" prefWidth="300" prefHeight="300" style="-fx-background-color: aquamarine">
        <ImageView fx:id="image2" preserveRatio="true" pickOnBounds="true">
            <image>
                <Image url="@/sample/test.jpg"/>
            </image>
        </ImageView>
    </VBox>
</SplitPane>

package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.SplitPane;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    @FXML
    ImageView image1;
    @FXML
    ImageView image2;
    @FXML
    SplitPane splitpane;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
   splitpane.getDividers().get(0).positionProperty().addListener((observable, oldValue, newValue) -> {
        System.out.println(newValue);
        int w = 600;
        double w1 = w * newValue.doubleValue();
        double w2 = w - w1;
        image1.setFitWidth(w1);
        image2.setFitWidth(w2);
    });
   }
}


问:
Android Drawing Separator/Divider Line in Layout?
I would like to draw a line right in the middle of a layout and use it as a separator of other items like TextView. Is there a good widget for this.  I don't really want to use an image as it would be hard to match the other components to it.  And I want it to be relatively positioned as well.  Thanks</p>

答:
This would help you to resolve this problem.
Here a small view is created to make a black line as a separator between two views.</p>

```<code> <View
        android:layout_width="3dp"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
         />
</code>```

Body:
This would help you to resolve this problem.
Here a small view is created to make a black line as a separator between two views.

 <View
        android:layout_width="3dp"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
         />


问:
receiving an intent when completing a browser download
I'm writing a software update application that (among other stuff) does the following:

When I find an image I want to download, I'm passing an ACTION_VIEW intent to the Browser application.
The browser starts the download, and when it completes, I see the download complete message in the notification bar.

now I am facing the following problem:
I would like to receive an intent when the download is complete.

Can anyone help?

答: Why don't you download the image yourself directly using HttpClient for example ?</p>


问:
Hadoop 2.7.3 Exception from container-launch, failed due to AM Container Exit code:127
I have installed Hadoop 2.7.3 stable version. I set all environment variables like JAVA_HOME, HADOOP_HOME, PATH etc.. I configured yarn-site.xml, hdfs-site.xml, core-site.xml, mapred-site.xml.

I uploaded sample files in HDFS. When I am executing the wordcount program in hadoop-mapreduce-examples-2.7.3.jar using below command

```<code>bin/hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.3.jar grep input output 'as[a-z.]+'
</code>```

it is throwing me following exception.

```<code>    17/01/28 00:59:33 INFO input.FileInputFormat: Total input paths to process : 36
    17/01/28 00:59:33 INFO mapreduce.JobSubmitter: number of splits:36
    17/01/28 00:59:33 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1485582326336_0001
    17/01/28 00:59:34 INFO impl.YarnClientImpl: Submitted application application_1485582326336_0001
    17/01/28 00:59:34 INFO mapreduce.Job: The url to track the job: http://XXXX.local:8088/proxy/application_1485582326336_0001/
    17/01/28 00:59:34 INFO mapreduce.Job: Running job: job_1485582326336_0001
    17/01/28 00:59:38 INFO mapreduce.Job: Job job_1485582326336_0001 running in uber mode : false
    17/01/28 00:59:38 INFO mapreduce.Job:  map 0% reduce 0%
    17/01/28 00:59:38 INFO mapreduce.Job: Job job_1485582326336_0001 failed with state FAILED due to: Application application_1485582326336_0001 failed 2 times due to AM Container for appattempt_1485582326336_0001_000002 exited with  exitCode: 127
    For more detailed output, check application tracking page:http://XXXXXX.local:8088/cluster/app/application_1485582326336_0001Then, click on links to logs of each attempt.
    Diagnostics: Exception from container-launch.
    Container id: container_1485582326336_0001_02_000001
    Exit code: 127
    Stack trace: ExitCodeException exitCode=127:
        at org.apache.hadoop.util.Shell.runCommand(Shell.java:582)
        at org.apache.hadoop.util.Shell.run(Shell.java:479)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:773)
        at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:212)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

    Container exited with a non-zero exit code 127
    Failing this attempt. Failing the application.
    17/01/28 00:59:38 INFO mapreduce.Job: Counters: 0
    17/01/28 00:59:38 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
    17/01/28 00:59:38 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/sumitdeshmukh/.staging/job_1485582326336_0002
    org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:9000/user/<username>/grep-temp-155204726
</code>```

Any solution to this problem?

答:
The problem is with the java home.
In the hadoop-env.sh, make the following changes:</p>

```<code>#export JAVA_HOME=${JAVA_HOME}
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home
</code>```

Body:
I have installed Hadoop 2.7.3 stable version. I set all environment variables like JAVA_HOME, HADOOP_HOME, PATH etc.. I configured yarn-site.xml, hdfs-site.xml, core-site.xml, mapred-site.xml.

I uploaded sample files in HDFS. When I am executing the wordcount program in hadoop-mapreduce-examples-2.7.3.jar using below command

bin/hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.3.jar grep input output 'as[a-z.]+'

it is throwing me following exception.

    17/01/28 00:59:33 INFO input.FileInputFormat: Total input paths to process : 36
    17/01/28 00:59:33 INFO mapreduce.JobSubmitter: number of splits:36
    17/01/28 00:59:33 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1485582326336_0001
    17/01/28 00:59:34 INFO impl.YarnClientImpl: Submitted application application_1485582326336_0001
    17/01/28 00:59:34 INFO mapreduce.Job: The url to track the job: http://XXXX.local:8088/proxy/application_1485582326336_0001/
    17/01/28 00:59:34 INFO mapreduce.Job: Running job: job_1485582326336_0001
    17/01/28 00:59:38 INFO mapreduce.Job: Job job_1485582326336_0001 running in uber mode : false
    17/01/28 00:59:38 INFO mapreduce.Job:  map 0% reduce 0%
    17/01/28 00:59:38 INFO mapreduce.Job: Job job_1485582326336_0001 failed with state FAILED due to: Application application_1485582326336_0001 failed 2 times due to AM Container for appattempt_1485582326336_0001_000002 exited with  exitCode: 127
    For more detailed output, check application tracking page:http://XXXXXX.local:8088/cluster/app/application_1485582326336_0001Then, click on links to logs of each attempt.
    Diagnostics: Exception from container-launch.
    Container id: container_1485582326336_0001_02_000001
    Exit code: 127
    Stack trace: ExitCodeException exitCode=127:
        at org.apache.hadoop.util.Shell.runCommand(Shell.java:582)
        at org.apache.hadoop.util.Shell.run(Shell.java:479)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:773)
        at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:212)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

    Container exited with a non-zero exit code 127
    Failing this attempt. Failing the application.
    17/01/28 00:59:38 INFO mapreduce.Job: Counters: 0
    17/01/28 00:59:38 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
    17/01/28 00:59:38 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/sumitdeshmukh/.staging/job_1485582326336_0002
    org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:9000/user/<username>/grep-temp-155204726

Any solution to this problem?

Body:
The problem is with the java home.
In the hadoop-env.sh, make the following changes:

#export JAVA_HOME=${JAVA_HOME}
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home


答:
By doing this you can get an list of tuples but I don't see the reason to do this:

```<code>      var ar = new int[2] { 5, 7 };

        List<Tuple<int>> result = ar
            .Select(x => Tuple.Create(x))
            .ToList();
</code>```

Or if you want to have it in one tuple instead:

```<code>   var ar = new int[2] { 5, 7 };
    Tuple<int[]> result = Tuple.Create(ar);
</code>```

If you know the size do this:

```<code>  Tuple<int, int> tuple = Tuple.Create(ar[0], ar[1]);
</code>```

Title: Convert array to tuple?

Body:
By doing this you can get an list of tuples but I don't see the reason to do this:

      var ar = new int[2] { 5, 7 };

        List<Tuple<int>> result = ar
            .Select(x => Tuple.Create(x))
            .ToList();

Or if you want to have it in one tuple instead:

   var ar = new int[2] { 5, 7 };
    Tuple<int[]> result = Tuple.Create(ar);

If you know the size do this:

  Tuple<int, int> tuple = Tuple.Create(ar[0], ar[1]);


问:
lateinit modifier is not allowed on primitive type properties in Kotlin
I am defining like a instance variable in kotlin and want to initialize it onCreate method of an activity.

```<code>var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}
</code>```

Here I am getting a below error on count variable.

Property must be initialized or be abstract in Kotlin

Well, I read this thread Property must be initialized or be abstract and tried same but again I am getting a below error.

lateinit modifier is not allowed on primitive type properties

```<code>lateinit var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}
</code>```

Is there any way to do this in Kotlin ?

答:
There are several ways to resolve this issue.

You can Initialise it with default value (e.i 0 or -1 or whatever) and then initialise it whenever your logic says.

Or tell compiler that count will be initialised later in this code by using Delegates.notNull check notNull.

```<code>var count: Int by Delegates.notNull<Int>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // You can not call `Int.inc()` in onCreate()` function until `count` is initialised.
    // count.inc()
    // **initialise count**
}
</code>```

And if you need count value on demand (if not necessary to initialise in onCreate), you can use lazy function. Use this only if you have an intensive (Some calculation/Inflating a layout etc) task that you want to do on demand, Not to just assign a value.

```<code>var count:Int by lazy {
    // initialise
}
</code>```

Now you can decide what to use.

I hope it helps.

Body:
I am defining like a instance variable in kotlin and want to initialize it onCreate method of an activity.

var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Here I am getting a below error on count variable.

Property must be initialized or be abstract in Kotlin

Well, I read this thread Property must be initialized or be abstract and tried same but again I am getting a below error.

lateinit modifier is not allowed on primitive type properties

lateinit var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Is there any way to do this in Kotlin ?

Body:
There are several ways to resolve this issue.

You can Initialise it with default value (e.i 0 or -1 or whatever) and then initialise it whenever your logic says.

Or tell compiler that count will be initialised later in this code by using Delegates.notNull check notNull.

var count: Int by Delegates.notNull<Int>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // You can not call `Int.inc()` in onCreate()` function until `count` is initialised.
    // count.inc()
    // **initialise count**
}

And if you need count value on demand (if not necessary to initialise in onCreate), you can use lazy function. Use this only if you have an intensive (Some calculation/Inflating a layout etc) task that you want to do on demand, Not to just assign a value.

var count:Int by lazy {
    // initialise
}

Now you can decide what to use.

I hope it helps.

ContentLicense: CC BY-SA 4.0


问:
How to repeat one loop in foreach
Hi guys how can you repeat one iteration in a foreach?

```<code>foreach (string line in File.ReadLines("file.txt"))
{
     // now line == "account", next line == "account1"
     if (line.Contains("a"))
         //next loop take "account1";
     else
        // need to set that next loop will take line == "account" again
}
</code>```

How to do it?

答:
I guess this might also helpful if someone else come</p>

```<code>for (int i = 0; i < inventoryTimeBlocks.Count; i++)
{
 if (line.Contains("a"))
     //next loop take "account1";
 else
 {
   if(i > 0)
   {
    i = i - 1;
    continue;
   }
 }
}
</code>```

Title: How to repeat one loop in foreach

Body:
Hi guys how can you repeat one iteration in a foreach?

foreach (string line in File.ReadLines("file.txt"))
{
     // now line == "account", next line == "account1"
     if (line.Contains("a"))
         //next loop take "account1";
     else
        // need to set that next loop will take line == "account" again
}

How to do it?

Body:
I guess this might also helpful if someone else come

for (int i = 0; i < inventoryTimeBlocks.Count; i++)
{
 if (line.Contains("a"))
     //next loop take "account1";
 else
 {
   if(i > 0)
   {
    i = i - 1;
    continue;
   }
 }
}


问:
Align to the right in visual block
I would like to know how to align to the right in a visual block without changing the text before and the block.

I used this code till before:

```<code>:<C-U>'<,'>s/\%V\(.\{-}\)\(\s\{-}\)\%(\%V\@!\|$\)/\2\1/
</code>```

However I noted that it doesn't work when after the visual block is only spaces.
(There has to be text after the visual block in order to make above code work)

Is there no way to align text to the right in a visual block whatever is written after the block?

Example:

```<code>text before +align text     text after
text before   align text    text after
text before  align text     text after
text before     align text+ text after
</code>```

What I want to do is select a block of text from + to + (see example above)
and align it to the right. Output must be:

```<code>text before      align text text after
text before      align text text after
text before      align text text after
text before      align text text after
</code>```

Above code does the job but it does not work when there is not something written after align text in every line.

答:
I use this. Put the cursor before the text which should be aligned to right. Run :Right
How does it work:

v0 Visualy select the text from current position to the beginning of the line

d Delete selected text and put into the buffer

:right Align the text on the right side of the cursor

0 Put cursor to the first column

gv Visualy select same area which we deleted before

p Replace selection with deleted text

command! Right execute "normal v0d\<CR>:right\<CR>0gvp"

Title: Align to the right in visual block

Body:
I would like to know how to align to the right in a visual block without changing the text before and the block.

I used this code till before:

:<C-U>'<,'>s/\%V\(.\{-}\)\(\s\{-}\)\%(\%V\@!\|$\)/\2\1/

However I noted that it doesn't work when after the visual block is only spaces.
(There has to be text after the visual block in order to make above code work)

Is there no way to align text to the right in a visual block whatever is written after the block?

Example:

text before +align text     text after
text before   align text    text after
text before  align text     text after
text before     align text+ text after

What I want to do is select a block of text from + to + (see example above)
and align it to the right. Output must be:

text before      align text text after
text before      align text text after
text before      align text text after
text before      align text text after

Above code does the job but it does not work when there is not something written after align text in every line.


问:
How can I add file names as the first line in AWK command
I'm trying to get the ninth column from multiple files in one single file using paste and awk , this worked with this code:

```<code>paste <(awk '{FS="\t"}{OFS="\t"}{ a[FNR] = (a[FNR] ? a[FNR] FS : "") $9 } END { for(i=1;i<=FNR;i++) print a[i] }' $(ls -1v */groups.txt))>file.txt
</code>```

now I want the first row to be the parent directory  for each of these files
how could this be done?

I tried:

```<code>paste <(awk '{FS="\t"}{OFS="\t"}}BEGIN{var=$FILENAME; split (var,b,/\//); print b[3]}{ a[FNR] = (a[FNR] ? a[FNR] FS : "") $9 } END { for(i=1;i<=FNR;i++) print a[i] }' $(ls -1v */groups.txt))>file.txt
</code>```

but it prints an empty line at the beginning of the file

答:
So if you just want the parent directory for each of these files you could use something like: </p>

```<code>for file in */groups.txt; do echo ${file%%/*} ; done
</code>```

Body:
I'm trying to get the ninth column from multiple files in one single file using paste and awk , this worked with this code:

paste <(awk '{FS="\t"}{OFS="\t"}{ a[FNR] = (a[FNR] ? a[FNR] FS : "") $9 } END { for(i=1;i<=FNR;i++) print a[i] }' $(ls -1v */groups.txt))>file.txt

now I want the first row to be the parent directory  for each of these files
how could this be done?

I tried:

paste <(awk '{FS="\t"}{OFS="\t"}}BEGIN{var=$FILENAME; split (var,b,/\//); print b[3]}{ a[FNR] = (a[FNR] ? a[FNR] FS : "") $9 } END { for(i=1;i<=FNR;i++) print a[i] }' $(ls -1v */groups.txt))>file.txt

but it prints an empty line at the beginning of the file

Body:
So if you just want the parent directory for each of these files you could use something like:

for file in */groups.txt; do echo ${file%%/*} ; done