问:
WordPress Contact Form 7 Validation Not Working
I am using class:required on my form fields but the validation is not working.</p>

```<code><div class="request-form animation" data-animation="fadeInRight">
    <h4>REQUEST AN ESTIMATE</h4>
    <div style="margin-bottom: 18px">Our estimates are free, professional and fair. Most estimates require a site visit. </div>
    [text Full Name class:input-custom class:input-full placeholder class:required "Name:"]
    [text Phone class:input-custom class:input-full placeholder class:required "Phone:"]
    [text E-mail class:input-custom class:input-full placeholder class:required "Email:"]
    [textarea Message class:input-custom class:input-full placeholder class:required "Message:"]
    [submit class:btn class:btn-light "SEND MESSAGE"]
</div>
</code>```

答:
You are mising to add * after type of input.

To make a form field required in CF7, you have to add * after type of input.
eg.

```<code>[text* Full Name class:your-class placeholder "Name"]
</code>```

So, just replace your code with below

```<code><div class="request-form animation" data-animation="fadeInRight">
    <h4>REQUEST AN ESTIMATE</h4>
    <div style="margin-bottom: 18px">Our estimates are free, professional and fair. Most estimates require a site visit. </div>
    [text* Full Name class:input-custom class:input-full placeholder "Name:"]
    [text* Phone class:input-custom class:input-full placeholder "Phone:"]
    [text* E-mail class:input-custom class:input-full placeholder "Email:"]
    [textarea* Message class:input-custom class:input-full placeholder "Message:"]
[submit class:btn class:btn-light "SEND MESSAGE"]
</code>```

Body:
I am using class:required on my form fields but the validation is not working.

REQUEST AN ESTIMATE

Our estimates are free, professional and fair. Most estimates require a site visit.

    [text Full Name class:input-custom class:input-full placeholder class:required "Name:"]
    [text Phone class:input-custom class:input-full placeholder class:required "Phone:"]
    [text E-mail class:input-custom class:input-full placeholder class:required "Email:"]
    [textarea Message class:input-custom class:input-full placeholder class:required "Message:"]
    [submit class:btn class:btn-light "SEND MESSAGE"]

Body:
You are mising to add * after type of input.

To make a form field required in CF7, you have to add * after type of input.
eg.

[text* Full Name class:your-class placeholder "Name"]

So, just replace your code with below

<div class="request-form animation" data-animation="fadeInRight">
    <h4>REQUEST AN ESTIMATE</h4>
    <div style="margin-bottom: 18px">Our estimates are free, professional and fair. Most estimates require a site visit. </div>
    [text* Full Name class:input-custom class:input-full placeholder "Name:"]
    [text* Phone class:input-custom class:input-full placeholder "Phone:"]
    [text* E-mail class:input-custom class:input-full placeholder "Email:"]
    [textarea* Message class:input-custom class:input-full placeholder "Message:"]
[submit class:btn class:btn-light "SEND MESSAGE"]


来源: stackexchange

问:
Having trouble running an if statement on a jquery ajax output
in my check.php I have an echo "ok";

however my if statement to check if the value is ok does not work.
Basically I want to execute a javascript function after check.php looks for the email in the database.

```<code>    $.ajax({
type: "POST",
 url: "check.php",
   data: "checkit=" + $("#checkEmail").val(),
    success: function(output){
    $("#userCheck").html(output);

            if(output == "ok"){
                alert("yay");
            }
        }

    });
</code>```

答:
try this:</p>

```<code>$.ajax({
    type: "POST",
    url: "check.php",
    dataType: "text", //<---
    contentType: "application/x-www-form-urlencoded",
    data: "checkit=" + encodeURIComponent($("#checkEmail").val()),
    success: function(output){

       $("#userCheck").html(output);
       if(output == "ok")
          alert("yay");

    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
in my check.php I have an echo "ok";

however my if statement to check if the value is ok does not work.
Basically I want to execute a javascript function after check.php looks for the email in the database.

    $.ajax({
type: "POST",
 url: "check.php",
   data: "checkit=" + $("#checkEmail").val(),
    success: function(output){
    $("#userCheck").html(output);

            if(output == "ok"){
                alert("yay");
            }
        }

    });

Body:
try this:

$.ajax({
    type: "POST",
    url: "check.php",
    dataType: "text", //<---
    contentType: "application/x-www-form-urlencoded",
    data: "checkit=" + encodeURIComponent($("#checkEmail").val()),
    success: function(output){

       $("#userCheck").html(output);
       if(output == "ok")
          alert("yay");

    }
});


问:
How to change active configuration all projects in eclipse?
I have more than 50 projects in my eclipse work space. I would like to know if there is a way to change active configuration of all the projects with single setting instead of doing it for each project individually</p>

答: The Project General / Paths and Symbols / References you can change the configuration for every referenced project or all together at once. After you change the checkboxes you can check the folders as per your need to change the active configurations for all projects in a work space in eclipse.</p>

ContentLicense: CC BY-SA 3.0


问:
Add the value of a variable to a HashTable as the key
PowerShell V5 Windows 10

For example, the variable $EmployeeID contains the string testValue, and I want to simply use the value of the previous variable inside the $HastTable.Add() function. It would look like this:

```<code>$HashTable.Add($EmployeeID, 'some_value')
</code>```

Except of course that does not work, but hopefully I am clear in what I want to achieve.

With that, I can then access the value like I normally do:

```<code>$var = $HashTable.testValue
</code>```

答:
You are doing it right and should be able to access the key wihtout any issues (you only don't get auto completion this way):

```<code>$HashTable = @{ }
$EmployeeID = "testValue"
$HashTable.Add($EmployeeID, 'some_value')
$var = $HashTable.testValue
$var
</code>```

Output:

```<code>some_value
</code>```

ContentLicense: CC BY-SA 4.0

Body:
PowerShell V5 Windows 10

For example, the variable $EmployeeID contains the string testValue, and I want to simply use the value of the previous variable inside the $HastTable.Add() function. It would look like this:

$HashTable.Add($EmployeeID, 'some_value')

Except of course that does not work, but hopefully I am clear in what I want to achieve.

With that, I can then access the value like I normally do:

$var = $HashTable.testValue

Body:
You are doing it right and should be able to access the key wihtout any issues (you only don't get auto completion this way):

$HashTable = @{ }
$EmployeeID = "testValue"
$HashTable.Add($EmployeeID, 'some_value')
$var = $HashTable.testValue
$var

Output:

some_value


问:
Get date from self object
I am attempting to pull the date field from the current item. I can't seem to get the syntax right. How would I go about getting the date data from the form I just submitted? Whenever I try the code below I get the following error:

```<code>'NoneType' object has no attribute 'get'
</code>```

views.py

```<code>class EntryCreate(CreateView):
    form_class = EntryForm
    template_name = 'argent/entry_form.html'

    def form_valid(self, form):
        e_item = self.object.get()
        e_date = e_item.get('date')
        e_month = e_date.strftime('%B')
        e_year = e_date.year
        qs = MonthYear.objects.filter(month=e_month, year=e_year)
</code>```

models.py

```<code>class Entry(models.Model):
    date = models.DateField(blank=True, null=True,)
    euros = models.CharField(max_length=500, blank=True, null=True)
    comments = models.CharField(max_length=900, blank=True, null=True)
</code>```

Thanks in advance for your help.

答:
SOLUTION:

So the trick to pulling data from an item immediately after it is submitted is to first save the form.

```<code>class EntryCreate(CreateView):
    form_class = EntryForm
    template_name = 'argent/entry_form.html'

    def form_valid(self, form):
        item = form.save()
        item_date = item.date
        e_month_d = item_date.strftime('%m')
        e_month = item_date.strftime('%B')
        e_year = item_date.year
</code>```

After saving the form the data within the form becomes available for manipulation.

Title: Get date from self object

Body:
I am attempting to pull the date field from the current item. I can't seem to get the syntax right. How would I go about getting the date data from the form I just submitted? Whenever I try the code below I get the following error:

'NoneType' object has no attribute 'get'

views.py

class EntryCreate(CreateView):
    form_class = EntryForm
    template_name = 'argent/entry_form.html'

    def form_valid(self, form):
        e_item = self.object.get()
        e_date = e_item.get('date')
        e_month = e_date.strftime('%B')
        e_year = e_date.year
        qs = MonthYear.objects.filter(month=e_month, year=e_year)

models.py

class Entry(models.Model):
    date = models.DateField(blank=True, null=True,)
    euros = models.CharField(max_length=500, blank=True, null=True)
    comments = models.CharField(max_length=900, blank=True, null=True)

Thanks in advance for your help.

Body:
SOLUTION:

So the trick to pulling data from an item immediately after it is submitted is to first save the form.

class EntryCreate(CreateView):
    form_class = EntryForm
    template_name = 'argent/entry_form.html'

    def form_valid(self, form):
        item = form.save()
        item_date = item.date
        e_month_d = item_date.strftime('%m')
        e_month = item_date.strftime('%B')
        e_year = item_date.year

After saving the form the data within the form becomes available for manipulation.


问:
HTML5 / CSS: Is there a benefit in using multiple wrapper-divs within section-elements?
Years ago I have learned to made a website by putting everything below the body-tag into a div with a class "wrapper".
These makes sense (without doubt) because that way one can align the whole content vertically and horizontally.

Yesterday I have seen this video-tutorial

At 07:15 he tells that the technique I have described above shouldn't be used any longer. Instead one should use multiple section-tags and within that sections a div of class "wrapper".

So that the section-tags are full-screen and the content can be aligned with the wrapper-divs.

I've made this demo to tinker with such a structure:

$color1: rgba(173, 216, 230, 1.0);
html,
body {
  height: 100%;
}

body {
  background-color: #bbb;
  margin: 0 1%;
}

.wrap {
  width: 100%;
  max-width: 800px;
  margin: 5vh auto;
  background-color: white;
  text-align: center;
}

.content .wrap p {
  padding: 20px 5%;
}

.footer .wrap {
  background-color: #999;
  color: white;
  font-weight: 900;
  letter-spacing: 1.2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<section class="header">
  <div class="wrap">
    <div class="callout secondary">
      <h1>This is a Top-Headline.</h1>
      <p>This is a Sub-Header.</p>
    </div>
  </div>
</section>

<section class="content">
  <div class="wrap">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>
    <p>Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra
      nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet
      adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus
      tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna.</p>
  </div>
</section>

<section class="footer">
  <div class="wrap">
    <p>© 2017 by xyz</p>
  </div>
</section></code>```

I mean: It works. Of course ...

But I don't get the idea what's the concrete benefit. Currently I think it's just more HTML.

On the other hand I don't want to reject the idea without doing some inquiry.

Therefore:

Can someone show me a concrete example of how one can benefit from having such a nested section-wrap structure? Respectively what purpose does it serve?

答:
Whether to put all content inside a wrapper or not to, all depends upon your requirement and how you want to manage it.

In Web2.0 websites we practiced wrapper div as parent and all content inside it - this gave a fixed width container and our content looks proper in the center of page.

But now since Web3.0, we focus more on responsive and full-screen websites and then sometimes it requires to have a specific or different background-color or background-image to one of the page sections, in such scenarios having multiple wrapper class structure comes to rescue. Check the code-snippet showing same approach. You can't get this same output in old approach with ease.

section {
  padding: 30px 0;
  color: #333;
}

.section-1 {
  background: tomato;
  color: #fff;
}

.section-2 {
  background: yellow;
}

.container {
  width: 90%;
  margin: 0 auto;
}

.bg {
  background: url('http://lorempixel.com/output/nightlife-q-c-1024-720-6.jpg') no-repeat center;
  background-size: cover;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section-1">
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>
  </div>
</section>
<!-- I need a image as background and then text inside -->
<section class="bg">
  <div class="container">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
  </div>
</section>

<section class="section-2">
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>
  </div>
</section></code>```

Body:
Years ago I have learned to made a website by putting everything below the body-tag into a div with a class "wrapper".
These makes sense (without doubt) because that way one can align the whole content vertically and horizontally.

Yesterday I have seen this video-tutorial

At 07:15 he tells that the technique I have described above shouldn't be used any longer. Instead one should use multiple section-tags and within that sections a div of class "wrapper".

So that the section-tags are full-screen and the content can be aligned with the wrapper-divs.

I've made this demo to tinker with such a structure:

$color1: rgba(173, 216, 230, 1.0);
html,
body {
  height: 100%;
}

body {
  background-color: #bbb;
  margin: 0 1%;
}

.wrap {
  width: 100%;
  max-width: 800px;
  margin: 5vh auto;
  background-color: white;
  text-align: center;
}

.content .wrap p {
  padding: 20px 5%;
}

.footer .wrap {
  background-color: #999;
  color: white;
  font-weight: 900;
  letter-spacing: 1.2px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />

This is a Top-Headline.

This is a Sub-Header.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.

Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra
      nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet
      adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus
      tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna.

© 2017 by xyz

I mean: It works. Of course ...

But I don't get the idea what's the concrete benefit. Currently I think it's just more HTML.

On the other hand I don't want to reject the idea without doing some inquiry.

Therefore:

Can someone show me a concrete example of how one can benefit from having such a nested section-wrap structure? Respectively what purpose does it serve?

Body:
Whether to put all content inside a wrapper or not to, all depends upon your requirement and how you want to manage it.

In Web2.0 websites we practiced wrapper div as parent and all content inside it - this gave a fixed width container and our content looks proper in the center of page.

But now since Web3.0, we focus more on responsive and full-screen websites and then sometimes it requires to have a specific or different background-color or background-image to one of the page sections, in such scenarios having multiple wrapper class structure comes to rescue. Check the code-snippet showing same approach. You can't get this same output in old approach with ease.

section {
  padding: 30px 0;
  color: #333;
}

.section-1 {
  background: tomato;
  color: #fff;
}

.section-2 {
  background: yellow;
}

.container {
  width: 90%;
  margin: 0 auto;
}

.bg {
  background: url('http://lorempixel.com/output/nightlife-q-c-1024-720-6.jpg') no-repeat center;
  background-size: cover;
  color: #fff;
}

<section class="section-1">
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>
  </div>
</section>
<!-- I need a image as background and then text inside -->
<section class="bg">
  <div class="container">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
  </div>
</section>

<section class="section-2">
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>
  </div>
</section>


问:
Parent div to match tallest child div's height?
I'm making a website with a "page" div, and inside that contains the left div "navigation" and the right div "content". I want to make the height of the "page" div (so the background matches) equal to the height of the tallest div, either "navigation" or "content".

How would I go about doing this?

答:
This will help you

HTML

```<code><div class="page">
  <div class="navigation">i am navigation</div>
  <div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est maiores, ex? Mollitia assumenda veniam aliquid commodi ex, libero in quia perspiciatis sint voluptatibus soluta exercitationem quas quos repudiandae deserunt obcaecati.</div>
</div>
</code>```

CSS

```<code> .page {
  background-color: #000;
 }
 /* for clearfix*/
.page:after{
    content: "";
    display: table;
    clear: both;
 }
 /* for clearfix end*/

 .navigation,.content {
   float: left;
 }
 .navigation {
   width: 20%;
   background-color: #cd6a51;
 }
 .content {
   width: 80%;
   background-color: #4CAF50;
 }
</code>```

Body:
This will help you

HTML

<div class="page">
  <div class="navigation">i am navigation</div>
  <div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est maiores, ex? Mollitia assumenda veniam aliquid commodi ex, libero in quia perspiciatis sint voluptatibus soluta exercitationem quas quos repudiandae deserunt obcaecati.</div>
</div>

CSS

 .page {
  background-color: #000;
 }
 /* for clearfix*/
.page:after{
    content: "";
    display: table;
    clear: both;
 }
 /* for clearfix end*/

 .navigation,.content {
   float: left;
 }
 .navigation {
   width: 20%;
   background-color: #cd6a51;
 }
 .content {
   width: 80%;
   background-color: #4CAF50;
 }


问:
How can I remove every listener from a page?
I know how to remove a listener from an element, but how can I remove every event listener from every element on the page?

A jQuery and pure JS solution would be nice.

答:
Just Clone the HTML dom, that will remove the events by default.

Here is an example.

    <button id="EventButton">Remove Events</button>

```

Body:
Just Clone the HTML dom, that will remove the events by default.

Here is an example.

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#EventButton").click(function () {
                alert("Click event worked");
                var old_element = document.documentElement;
                var new_element = old_element.cloneNode(true);
                old_element.parentNode.replaceChild(new_element, old_element);
            });
        });
    </script>
</head>

<body>
    <button id="EventButton">Remove Events</button>
</body>

</html>


问:
how to write regex expression in java
I have requirement to block certain user based on there chat word, below is the rules allowed and disallowed in regex

mob no should be banned

sexual context also banned

other than this everything allowed

in the expression/word i can give disallowed words like "rs|RS|rupee|1234567890" in the configuration and java regEx should give me output about whether that words is allowed or not.

答:
You can use java.util.regex.Pattern class and java.util.regex.Matcher class  like below.

```<code>String str = "targetStr";
String regEx = "regEx";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(str);
</code>```

Title: how to write regex expression in java

Body:
You can use java.util.regex.Pattern class and java.util.regex.Matcher class  like below.

String str = "targetStr";
String regEx = "regEx";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(str);


问:
Only 14 bytes are uploaded into Google Cloud Storage
I'm trying to upload some files into Google Cloud Storage using PHP. It seems to be partially working, since I'm seeing the files in the web console, however I've noticed that all files are only 14 bytes in size, while the original is much bigger.

This is the code I'm using:

```<code>/**
 *
 */
public static function saveFile($originalFile, $newFilename) {

    $bucket = MyStorage::getBucket();

    if ($bucket == null) {

        // Save locally
        Storage::disk('local')->put(FileController::$FILE_DIR . $newFilename, file_get_contents($originalFile));

    } else {

        // Save to Google Cloud Platform
        $bucket->upload($originalFile->getRealPath(), ['name' => $newFilename]);

    }
}

/**
 *
 */
private static function getBucket() {

    $appEnv = getenv('APP_ENV');

    if ($appEnv == "production" || $appEnv == "test") {

        $GOOGLE_CLOUD_PROJECT_ID = getenv('GOOGLE_PROJECT_ID');
        $GOOGLE_CLOUD_BUCKET_NAME = getenv('GOOGLE_BUCKET_NAME');

        $storage = new StorageClient(['projectId' => $GOOGLE_CLOUD_PROJECT_ID]);
        $bucket = $storage->bucket($GOOGLE_CLOUD_BUCKET_NAME);

        return $bucket;

    } else {

        return null;
    }
}
</code>```

$originalFile->getRealPath() returns something like /tmp/asdfasdfadf and I've verified that that file exists and is a reasonable size. The $newFilename variable name is what I want it to be stored as and this part seems to work as I'm seeing that filename in the web console.

Any ideas what could be happening?

答:
```<code>else {

    // Save to Google Cloud Platform
    $bucket->upload($originalFile->getRealPath(), ['name' => $newFilename]);

}
</code>```

Should be:

```<code>else {

    // Save to Google Cloud Platform
    $bucket->upload(fopen($originalFile->getRealPath(), 'rb'), ['name' => $newFilename]);

    if( fclose($originalFile->getRealPath()) === false){
       // Success
    } else{
       // Failure
    }

}
</code>```

The reason that your code didn't work is because you were uploading only the filename to Google Cloud. "/tmp/asdfasd" is 14 characters.

Here is an answer on why the 'b' is important for the fopen command.

FClose closes the resource, preventing data leaks. Also, check the return value from fclose(), as some OS only flush file output. Checking the return value can save severe data leaks.

Body:
I'm trying to upload some files into Google Cloud Storage using PHP. It seems to be partially working, since I'm seeing the files in the web console, however I've noticed that all files are only 14 bytes in size, while the original is much bigger.

This is the code I'm using:

/**
 *
 */
public static function saveFile($originalFile, $newFilename) {

    $bucket = MyStorage::getBucket();

    if ($bucket == null) {

        // Save locally
        Storage::disk('local')->put(FileController::$FILE_DIR . $newFilename, file_get_contents($originalFile));

    } else {

        // Save to Google Cloud Platform
        $bucket->upload($originalFile->getRealPath(), ['name' => $newFilename]);

    }
}

/**
 *
 */
private static function getBucket() {

    $appEnv = getenv('APP_ENV');

    if ($appEnv == "production" || $appEnv == "test") {

        $GOOGLE_CLOUD_PROJECT_ID = getenv('GOOGLE_PROJECT_ID');
        $GOOGLE_CLOUD_BUCKET_NAME = getenv('GOOGLE_BUCKET_NAME');

        $storage = new StorageClient(['projectId' => $GOOGLE_CLOUD_PROJECT_ID]);
        $bucket = $storage->bucket($GOOGLE_CLOUD_BUCKET_NAME);

        return $bucket;

    } else {

        return null;
    }
}

$originalFile->getRealPath() returns something like /tmp/asdfasdfadf and I've verified that that file exists and is a reasonable size. The $newFilename variable name is what I want it to be stored as and this part seems to work as I'm seeing that filename in the web console.

Any ideas what could be happening?

Body:
else {

    // Save to Google Cloud Platform
    $bucket->upload($originalFile->getRealPath(), ['name' => $newFilename]);

}

Should be:

else {

    // Save to Google Cloud Platform
    $bucket->upload(fopen($originalFile->getRealPath(), 'rb'), ['name' => $newFilename]);

    if( fclose($originalFile->getRealPath()) === false){
       // Success
    } else{
       // Failure
    }

}

The reason that your code didn't work is because you were uploading only the filename to Google Cloud. "/tmp/asdfasd" is 14 characters.

Here is an answer on why the 'b' is important for the fopen command.

FClose closes the resource, preventing data leaks. Also, check the return value from fclose(), as some OS only flush file output. Checking the return value can save severe data leaks.


问:
How to get string from arraylist
I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string @....

Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.

```<code>public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    lvProduct = (ListView)findViewById(R.id.listView1);

    mProductList = new ArrayList<>();
    mProductList.add(new Product(1, "Product_1", "Price", "Description"));
    mProductList.add(new Product(2, "Product_2", "Price", "Description"));
    mProductList.add(new Product(3, "Product_3", "Price", "Description"));

    adapter = new ProductListAdapter(getApplicationContext(), mProductList);
    lvProduct.setAdapter(adapter);

    lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(???));
            newActivity.putExtra("2nd column value", mProductList.get(???));
            newActivity.putExtra("3rd column value", mProductList.get(???));
            newActivity.putExtra("4th column value", mProductList.get(???));
            startActivity(newActivity);
        }
    });
}
</code>```

}

答:
```<code>@Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
</code>```

You can get the clicked item position from the int position parameter of the callback method

Title: How to get string from arraylist

Body:
I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string @....

Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.

public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    lvProduct = (ListView)findViewById(R.id.listView1);

    mProductList = new ArrayList<>();
    mProductList.add(new Product(1, "Product_1", "Price", "Description"));
    mProductList.add(new Product(2, "Product_2", "Price", "Description"));
    mProductList.add(new Product(3, "Product_3", "Price", "Description"));

    adapter = new ProductListAdapter(getApplicationContext(), mProductList);
    lvProduct.setAdapter(adapter);

    lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(???));
            newActivity.putExtra("2nd column value", mProductList.get(???));
            newActivity.putExtra("3rd column value", mProductList.get(???));
            newActivity.putExtra("4th column value", mProductList.get(???));
            startActivity(newActivity);
        }
    });
}

}

Body:
@Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }

You can get the clicked item position from the int position parameter of the callback method


问:
How to upload zip file to azure blob then unzip it there
I have lot of zip files, which will have few folders and 50+ files in it. How can I upload those zip files to azure blob then unzip it there.

Unzipping the file in server and uploading files in it one by one to azure blob will be a cumbersome process.

Does azure has any easy way to achieve this or is there any workaround?

I'm implementing this in PHP.

答:
Simple answer is Azure Blob Storage will not do the unzipping for you. This is something you would need to do on your own. How you do it is up to you.

One possibility is (like you mentioned) that you upload zip files on your server, unzip them there and then upload individual files.

Another possibility is to do this unzipping through a background process if you are concerned about the processing happening on the web server. In this approach, you will simply upload the zip files in blob storage. Then through some background process (could be WebJobs, Functions, Worker Roles, or Virtual Machines), you would download these zip files, unzip them and then re-upload these individual files.

To trigger the background process on demand, once the zip file is uploaded you could simply write a message in a queue telling background process to download the zip file and start unzipping process.


问:
How to use vector of vector for reading a graph?
```<code>#include <iostream>
#include <vector>
using namespace std;
void addEdge( vector<vector<int> > adj, int, int);
void print_graph(vector<vector<int> > adj);

int main()
{

    vector<vector<int> > adj(4);
    addEdge(adj,1,2);     // edge from node 1 to node 2
    addEdge(adj,1,3);
    addEdge(adj,1,4);
    addEdge(adj,2,3);
    addEdge(adj,3,4);
    print_graph(adj);
    return 0;
}

void addEdge(vector<vector<int> > adj, int u , int v)
{
    adj[u].push_back(v);

}

void print_graph( vector<vector<int> > adj)
{
    for( int i = 0; i < adj.size() ; i++ )
    {
        for( int j = 0 ; j < adj[i].size(); j++ )
        {
            cout<< i+1 << " , " << cout<< adj[i][j]<<endl;
        }
    }
}
</code>```

I have written the code for reading the graph and printing it.

Prior to this for reading graph I used to use

```<code>vector<int>adj[5];
</code>```

But I have been told that , use

```<code>`vector<vector<int> > adj`  or `list<list<int> > adj`
</code>```

I tried but now I am getting No output.    ( update)

Can anyone help me in using vector of vector ?? Please help for list of list also.

答:
Your version of addEdge takes adj as a copy. You manipulate that copy which is then destroyed when the function returns. You need to use reference to access the outer adj:

```<code>void addEdge(vector<vector<int> >& adj, int u , int v)
{
    adj[u].push_back(v);

}
</code>```

and use:

```<code>void print_graph(const vector<vector<int> >& adj)
</code>```

to avoid another copy

Body:
#include <iostream>
#include <vector>
using namespace std;
void addEdge( vector<vector<int> > adj, int, int);
void print_graph(vector<vector<int> > adj);

int main()
{

    vector<vector<int> > adj(4);
    addEdge(adj,1,2);     // edge from node 1 to node 2
    addEdge(adj,1,3);
    addEdge(adj,1,4);
    addEdge(adj,2,3);
    addEdge(adj,3,4);
    print_graph(adj);
    return 0;
}

void addEdge(vector<vector<int> > adj, int u , int v)
{
    adj[u].push_back(v);

}

void print_graph( vector<vector<int> > adj)
{
    for( int i = 0; i < adj.size() ; i++ )
    {
        for( int j = 0 ; j < adj[i].size(); j++ )
        {
            cout<< i+1 << " , " << cout<< adj[i][j]<<endl;
        }
    }
}

I have written the code for reading the graph and printing it.

Prior to this for reading graph I used to use

vector<int>adj[5];

But I have been told that , use

`vector<vector<int> > adj`  or `list<list<int> > adj`

I tried but now I am getting No output.    ( update)

Can anyone help me in using vector of vector ?? Please help for list of list also.

Body:
Your version of addEdge takes adj as a copy. You manipulate that copy which is then destroyed when the function returns. You need to use reference to access the outer adj:

void addEdge(vector<vector<int> >& adj, int u , int v)
{
    adj[u].push_back(v);

}

and use:

void print_graph(const vector<vector<int> >& adj)

to avoid another copy


问:
Android Studio Density
I change from Eclipse to Android Studio. I'm facing a problem with the densities of the Emulators.
For example, in Eclipse the Samsung S4 was density xxhdpi but in Android Studio is xhdpi.
Samsung S4: 4,99' - 1080 x 1920.

This is my code:

```<code>Float density = getResources().getDisplayMetrics().density;

if(density >= 1.0 && density < 1.5){ //mdpi
 ...
} else if(density >= 1.5 && density < 2.0){ //hdpi
 ...
} else if(density >= 2.0 && density < 3.0){ //xhdpi
 ...
} else if(density >= 3.0 && density < 4.0){ //xxhdpi
 ...
} else if(density >= 4.0){ //xxxhdpi
 ...
}
</code>```

Value of density is 2.625. So enters in the xhdpi case, but I need to enter in the xxhdpi!
What is the problem? Is there a better way to do this?.

Thanks

答:
Put this code in your manifest.xml

```<code>   <supports-screens android:anyDensity="true"
    android:largeScreens="true"
    android:normalScreens="true"
    android:resizeable="true"
    android:smallScreens="true"
    android:xlargeScreens="true"/>
</code>```

Hope it will help you.

Title: Android Studio Density

Body:
I change from Eclipse to Android Studio. I'm facing a problem with the densities of the Emulators.
For example, in Eclipse the Samsung S4 was density xxhdpi but in Android Studio is xhdpi.
Samsung S4: 4,99' - 1080 x 1920.

This is my code:

Float density = getResources().getDisplayMetrics().density;

if(density >= 1.0 && density < 1.5){ //mdpi
 ...
} else if(density >= 1.5 && density < 2.0){ //hdpi
 ...
} else if(density >= 2.0 && density < 3.0){ //xhdpi
 ...
} else if(density >= 3.0 && density < 4.0){ //xxhdpi
 ...
} else if(density >= 4.0){ //xxxhdpi
 ...
}

Value of density is 2.625. So enters in the xhdpi case, but I need to enter in the xxhdpi!
What is the problem? Is there a better way to do this?.

Thanks

Body:
Put this code in your manifest.xml

   <supports-screens android:anyDensity="true"
    android:largeScreens="true"
    android:normalScreens="true"
    android:resizeable="true"
    android:smallScreens="true"
    android:xlargeScreens="true"/>

Hope it will help you.


问:
Scrollview and OnClick handlers not working when view is cleared and re-created
I'm having an odd problem and I am not sure where the issue is.

I have an XML file which contains two linear layouts, only one is visible at a time depending on what setting has been used. Both views are dynamically generated and set an on click listener and onlongclicklistener.

Below is the XML layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout android:id="@+id/resultTableContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="horizontal"
            android:fillViewport="true">
            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fillViewport="true">
                <TableLayout android:id="@+id/resultTable"
                    android:stretchColumns="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:shrinkColumns="false">
                </TableLayout>
            </HorizontalScrollView>
        </ScrollView>
    </LinearLayout>
    <LinearLayout android:id="@+id/formattedResultContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView android:id="@+id/formattedScrollContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical">
            <LinearLayout android:id="@+id/formattedResult"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"/>
        </ScrollView>
    </LinearLayout>
</RelativeLayout>
</code>```

For simplicity I'll call the first linear layout container view 1 and the second linear layout container view 2.

Both views have their visibility set to gone by default, and when the screen first loads, view 1's visibility is set to visible and the view is dynamically generated using the following code:

```<code>@Override
    public void processResult(final View.OnClickListener editRowClickListener, final View.OnLongClickListener columnLongClickListener)
    {
        try
        {
            this.getActivity().runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if (shouldExistingResultBeCleared())
                    {
                        resultView.removeAllViews();
                    }
                    if (getSettings().getInt(Defines.SharedPreferenceSettings.APPLICATION_THEME, com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                            == com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                    {
                        resultView.setBackgroundColor(Color.WHITE);
                    }
                    else
                    {
                        resultView.setBackgroundColor(Color.BLACK);
                    }
                }
            });

            this.showDialog(getJSONResult().length());

            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        for (int i = 0; i < getJSONResult().length(); i++)
                        {
                            HashMap<Integer, String> fieldIndexAndValue = new HashMap<Integer, String>();
                            final TableRow tr;
                            if (!getSettings().getBoolean("IsDarkTheme", false))
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_light_theme, resultView, false);
                            } else
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_dark_theme, resultView, false);
                            }
                            if (i == 0)
                            {
                                tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.appPrimaryColour));
                            }
                            else if (i % 2 == 0)
                            {
                                if (!getSettings().getBoolean("IsDarkTheme", false))
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowLightThemeAlternateRow));
                                } else
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowDarkThemeAlternateRow));
                                }
                            }
                            ImageButton imageButton = (ImageButton) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.row_edit_image, tr, false);
                            imageButton.setOnClickListener(editRowClickListener);
                            tr.addView(imageButton);

                            if (i == 0)
                            {
                                imageButton.setVisibility(View.INVISIBLE);
                            }

                            JSONArray array = getJSONResult().getJSONArray(i);
                            String currentField = null;
                            for (int j = 0; j < array.length(); j++)
                            {
                                final TextView textView;
                                textView = (TextView) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_textview, tr, false);
                                textView.setText(array.getString(j));
                                if (!getSettings().getBoolean(Defines.SharedPreferenceSettings.MULTILINE_RESULT, true))
                                {
                                    textView.setSingleLine(true);
                                }
                                if (i == 0)
                                {
                                    textView.setTypeface(null, Typeface.BOLD);
                                    //Get the fields into a index and field hash map
                                    addIndexAndField(j, array.getString(j));
                                } else
                                {
                                    textView.setOnLongClickListener(columnLongClickListener);
                                    fieldIndexAndValue.put(j, array.getString(j));
                                }
                                getActivity().runOnUiThread(new Runnable()
                                {

                                    @Override
                                    public void run()
                                    {
                                        tr.addView(textView);
                                    }
                                });
                            }
                            imageButton.setTag(fieldIndexAndValue);

                            getActivity().runOnUiThread(new Runnable()
                            {

                                @Override
                                public void run()
                                {
                                    resultView.addView(tr);
                                }
                            });
                            updateProgressDialog();
                            //handler.sendMessage(handler.obtainMessage());
                        }
                        closeDialog();
                        //((ResultProcessor)resultProcessor).closeDialog();
                    }
                    catch (JSONException ex)
                    {

                    }
                }
            }).start();
        }
        catch (Exception ex)
        {

        }
    }
</code>```

This works perfectly fine. The user presses an option to switch to view 2, so view 1 is cleared, visibility set to gone ans view 2 is set to visible. This view is then dynamically generated and the on click listeners are set to the view accordingly. (I haven't included the code for this view as I don't believe it is related and this view always works without exception).

If the user then switches back to view 1, view 2 is cleared, and visibility set to gone and view 1 is back to being visible and the same method, as shown above, is used to re-create the view dynamically and assign the on click listeners.

The view itself looks fine, however, there is no user interaction possible, the scroll view no longer scrolls vertically or horizontally and neither of the click handlers works.

As view 1 work once, I don't understand why it won't when it is re-generated, but view 2 always works no matter what.

答:
Set layout visibility:

```<code>view1.setVisibility(View.VISIBLE)
view2.setVisibility(View.GONE)
</code>```

instead of:

```<code>resultView.removeAllViews();
resultView.addView();
</code>```

Body:
I'm having an odd problem and I am not sure where the issue is.

I have an XML file which contains two linear layouts, only one is visible at a time depending on what setting has been used. Both views are dynamically generated and set an on click listener and onlongclicklistener.

Below is the XML layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout android:id="@+id/resultTableContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="horizontal"
            android:fillViewport="true">
            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fillViewport="true">
                <TableLayout android:id="@+id/resultTable"
                    android:stretchColumns="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:shrinkColumns="false">
                </TableLayout>
            </HorizontalScrollView>
        </ScrollView>
    </LinearLayout>
    <LinearLayout android:id="@+id/formattedResultContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView android:id="@+id/formattedScrollContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical">
            <LinearLayout android:id="@+id/formattedResult"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"/>
        </ScrollView>
    </LinearLayout>
</RelativeLayout>

For simplicity I'll call the first linear layout container view 1 and the second linear layout container view 2.

Both views have their visibility set to gone by default, and when the screen first loads, view 1's visibility is set to visible and the view is dynamically generated using the following code:

@Override
    public void processResult(final View.OnClickListener editRowClickListener, final View.OnLongClickListener columnLongClickListener)
    {
        try
        {
            this.getActivity().runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if (shouldExistingResultBeCleared())
                    {
                        resultView.removeAllViews();
                    }
                    if (getSettings().getInt(Defines.SharedPreferenceSettings.APPLICATION_THEME, com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                            == com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                    {
                        resultView.setBackgroundColor(Color.WHITE);
                    }
                    else
                    {
                        resultView.setBackgroundColor(Color.BLACK);
                    }
                }
            });

            this.showDialog(getJSONResult().length());

            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        for (int i = 0; i < getJSONResult().length(); i++)
                        {
                            HashMap<Integer, String> fieldIndexAndValue = new HashMap<Integer, String>();
                            final TableRow tr;
                            if (!getSettings().getBoolean("IsDarkTheme", false))
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_light_theme, resultView, false);
                            } else
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_dark_theme, resultView, false);
                            }
                            if (i == 0)
                            {
                                tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.appPrimaryColour));
                            }
                            else if (i % 2 == 0)
                            {
                                if (!getSettings().getBoolean("IsDarkTheme", false))
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowLightThemeAlternateRow));
                                } else
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowDarkThemeAlternateRow));
                                }
                            }
                            ImageButton imageButton = (ImageButton) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.row_edit_image, tr, false);
                            imageButton.setOnClickListener(editRowClickListener);
                            tr.addView(imageButton);

                            if (i == 0)
                            {
                                imageButton.setVisibility(View.INVISIBLE);
                            }

                            JSONArray array = getJSONResult().getJSONArray(i);
                            String currentField = null;
                            for (int j = 0; j < array.length(); j++)
                            {
                                final TextView textView;
                                textView = (TextView) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_textview, tr, false);
                                textView.setText(array.getString(j));
                                if (!getSettings().getBoolean(Defines.SharedPreferenceSettings.MULTILINE_RESULT, true))
                                {
                                    textView.setSingleLine(true);
                                }
                                if (i == 0)
                                {
                                    textView.setTypeface(null, Typeface.BOLD);
                                    //Get the fields into a index and field hash map
                                    addIndexAndField(j, array.getString(j));
                                } else
                                {
                                    textView.setOnLongClickListener(columnLongClickListener);
                                    fieldIndexAndValue.put(j, array.getString(j));
                                }
                                getActivity().runOnUiThread(new Runnable()
                                {

                                    @Override
                                    public void run()
                                    {
                                        tr.addView(textView);
                                    }
                                });
                            }
                            imageButton.setTag(fieldIndexAndValue);

                            getActivity().runOnUiThread(new Runnable()
                            {

                                @Override
                                public void run()
                                {
                                    resultView.addView(tr);
                                }
                            });
                            updateProgressDialog();
                            //handler.sendMessage(handler.obtainMessage());
                        }
                        closeDialog();
                        //((ResultProcessor)resultProcessor).closeDialog();
                    }
                    catch (JSONException ex)
                    {

                    }
                }
            }).start();
        }
        catch (Exception ex)
        {

        }
    }

This works perfectly fine. The user presses an option to switch to view 2, so view 1 is cleared, visibility set to gone ans view 2 is set to visible. This view is then dynamically generated and the on click listeners are set to the view accordingly. (I haven't included the code for this view as I don't believe it is related and this view always works without exception).

If the user then switches back to view 1, view 2 is cleared, and visibility set to gone and view 1 is back to being visible and the same method, as shown above, is used to re-create the view dynamically and assign the on click listeners.

The view itself looks fine, however, there is no user interaction possible, the scroll view no longer scrolls vertically or horizontally and neither of the click handlers works.

As view 1 work once, I don't understand why it won't when it is re-generated, but view 2 always works no matter what.

Body:
Set layout visibility:

view1.setVisibility(View.VISIBLE)
view2.setVisibility(View.GONE)

instead of:

resultView.removeAllViews();
resultView.addView();


问:
How to replace an array in perl with a query for contents of a sql database?
Edit: (See Revised Code Near bottom) I have the code working to pull from the 2 databases (I know some cleaning is still needed),
but where I am stuck is, I was prviously able to use:

```<code>next unless $currentuser ~~ @las;
</code>```

but once I linked the mySQL database, it isn't filtering out undefined/unqualified (blank) results. I am not sure how to restructure this function to re-enable the functionality. (I think the way I am approaching the logic may be off). But this is where I am currently confused and need guidance.

I currently use this code to view logged in users to check for employees in our department:

```<code> #! /usr/bin/perl
use strict;
use warnings;

$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

#current emplyees go here:
my @las = qw(

user12
user13
user14
user15
user16
user17
user18
user19
user20
user21
user22
user23
user24
user25
user26
user27
user28
user29
user30
user31
user32
user33
user34
user35
user36
user37
user38
user39
user40
user41
user42
user43
user44
user45
user46
user47
user48
user49
user50
user51
user52
user53
user54
user55
user56
user57
user58
user59
user60
user61
user62
user63
user64
user65
user66
user67
user68
user69
user70
user71
user72
user73
user74
user75
user76
user77
user78
user79
user80
user81
user82
user83
user84
user85
user86
user87
user88
user89
user90
user91
user92
user93
user94
user95
user96
user97
user98
user99
user100
user101
user102
user103
user104
user105
user106
user107
user108
user109
user110
user111
user112
user113
user114
user115
user116
user117
user118
user119
user120
user121
user122
user123
user124
user125
user126
user127
user128
user129
user130
user131
user132
user133
user134
user135
user136
user137
user138
user139
user140
user141
user142
user143
user144
user145
user146
user147
user148
user149
user150
user151
user152
user153
user154
user155
user156
user157
user158
user159
user160
user161
user162
user163
user164
user165
user166
user167
user168
user169
user170
user171
user172
user173
user174
user175
user176
user177
user178
user179
user180
user181
user182
user183
user184
user185
user186
user187
user188
user189
user190
user191
user192
user193
user194
user195
user196
user197
user198
user199
user200
user201
user202
user203
user204
user205
user206
user207
user208
user209
user210
user211
user212
user213
user214
user215
user216
user217
user218
user219
user220
user221
user222
user223
user224
user225
user226
user227
user228
user229
user230
user231
user232
user233
user234
user235
user236
user237
user238
user239
user240
user241
user242
user243
user244
user245
user246
user247
user248
user249
user250
user251
user252
user253
user254
user255
user256
user257
user258
user259
user260
user261
user262
user263
user264
user265
user266
user267
user268
user269
user270
user271
user272
user273
user274
user275
user276
user277

systemdefault
admin1
admin2
admin3

);

#Find Current Users
$login="logg";
$password="pass32";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Search Zone 2

my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE  (hosts.host_name = '1408bcc204ap1')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')
OR      (hosts.host_name = '1408mathg135m1')
OR      (hosts.host_name = '1408mathb10p1')
OR      (hosts.host_name = '1408mathb10p2')
OR      (hosts.host_name = '1408mathb10p3')
OR      (hosts.host_name = '1408mathb10p4')
OR      (hosts.host_name = '1408mathb10p5')
OR      (hosts.host_name = '1408mathb10p6')
OR      (hosts.host_name = '1408mathb10p7')
OR      (hosts.host_name = '1408mathb10p8')
OR      (hosts.host_name = '1408mathb10p9')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')

ORDER BY hosts.host_name
};
my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "<html>\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "<style type=\"text/css\">\n";
print "body { font-family: \"Arial\", sans-serif; font-size: small; color: black }\n";
print "</style>\n";
print "<head>\n";
print "<title>\n";
print "Staff Stations\n";
print "</title>\n";
print "</head>\n";
print "<body>\n";
print "<table>\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "<tr><td><u>Zone 2</u></td><td><u>Login</u></td></tr>\n";
while($sth->fetch()) {
        next unless $currentuser~~@las  ;
        $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "<tr>";
        print "<td>$host_name</td>";
        print "<td><font color=\"$lacolor\">$currentuser</font></td><td> </td>";
}
$sth->finish();

print "</table>";
print "</body>\n";
print "</html>\n";

$sth->finish();$sth->finish();

#end code

$
b
->disconnect();
</code>```

The usernames are already stored in a mysql database, I am trying to add lines to connect to it as follows, but I am stuck as to how to continue:

```<code>#Read Employee database

my $dbh = DBI->connect("DBI:mysql:myadmpr01", "user", "pass64");
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

my $sql = qq{
SELECT  user_id,
FROM    lsoemployee_info

};
my $sth = $dbh->prepare($sql);
$sth->execute();
</code>```

I am trying to compare the icsprodagainst the myadmpr01 for usernames so that out hr department can maintain this easily as they update the myadmpr01 database for current/non-current employees. icsprod is updated continuously and simply defines the current user. We would also like to return the user's fullname, rather than continuously look up usernames. Any help is greatly appreciated.

Revised code:

```<code>  #! /usr/bin/perl
$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

my $dbh = DBI->connect("DBI:mysql:lsopskeys:myadmpr01.itap.purdue.edu", "lsops", "Fl4sh_l1ght")
  or die "Unable to connect: $DBI::errstr\n";

my $sql = qq{
  SELECT  user_id,
  FROM    lsoemployee_data
};

my $sth = $dbh->prepare($sql);
$sth->execute();

my @las = map { $_->[0] } $sth->fetchall_arrayref;

$login="user";
$password="pass";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Zone 2 ROWS CODE
my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE   (hosts.host_name = '1408stew102p1')
OR      (hosts.host_name = '1408stew102p2')
OR      (hosts.host_name = '1408stew102p3')

OR      (hosts.host_name = '1408stew111p1')
OR      (hosts.host_name = '1408stew111p2')
OR      (hosts.host_name = '1408stew111p3')
OR      (hosts.host_name = '1408stew111p4')
OR      (hosts.host_name = '1408stew111p5')
OR      (hosts.host_name = '1408stew111p6')
OR      (hosts.host_name = '1408stew111p7')
OR      (hosts.host_name = '1408stew111p8')
OR      (hosts.host_name = '1408stew111p9')
OR      (hosts.host_name = '1408stew111p10')
OR      (hosts.host_name = '1408stew111p11')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathb18p5')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')

OR      (hosts.host_name = '1408heav227m1')
OR      (hosts.host_name = '1408heav227m2')
OR      (hosts.host_name = '1408heav227m3')
OR      (hosts.host_name = '1408mthw116p1')
OR      (hosts.host_name = '1408hamp3144p21')

ORDER BY hosts.host_name
};

my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "<html>\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "<style type=\"text/css\">\n";
print "body { font-family: \"Arial\", sans-serif; font-size: small; color: black }\n";
print "</style>\n";
print "<head>\n";
print "<title>\n";
print "LA station usage.\n";
print "</title>\n";
print "</head>\n";
print "<body>\n";
print "<table>\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "<tr><td><font color=\"DodgerBlue \"><u>Zone 2 Station</u></td><td><font color=\"DodgerBlue \"><u>Login</u></td></tr>\n";
while($sth->fetch()) {
      #next unless $currentuser ~~ @las;
       $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "<tr>";
        print "<td>$host_name</td>";
        print "<td><font color=\"$lacolor\">$currentuser</font></td><td> </td>";
}
$sth->finish();
print "</table>";
print "</body>\n";
print "</html>\n";
$sth->finish();$sth->finish();

#end code
$
b
->disconnect();
</code>```

答:
If you're trying to populate @las from the database, then you want something like this:

```<code>my $dbh = DBI->connect('DBI:mysql:myadmpr01', 'user', 'pass64')
  or die "Unable to connect: $DBI::errstr\n";

my $sql = qq{
  SELECT  user_id,
  FROM    lsoemployee_info
};

my $sth = $dbh->prepare($sql);
$sth->execute();

my @las = map { $_->[0] } $sth->fetchall_arrayref;
</code>```

Update: I wrote that last line of code as I would write it for a client. I always assume that my code will be read and maintained by people who know Perl. If you have doubts about the abilities of your programmers, you might be better advised to write something like that:

```<code>my @las;

foreach ($sth->fetchall_arrayref) {
  push @las, $_->[0];
}
</code>```

Body:
Edit: (See Revised Code Near bottom) I have the code working to pull from the 2 databases (I know some cleaning is still needed),
but where I am stuck is, I was prviously able to use:

next unless $currentuser ~~ @las;

but once I linked the mySQL database, it isn't filtering out undefined/unqualified (blank) results. I am not sure how to restructure this function to re-enable the functionality. (I think the way I am approaching the logic may be off). But this is where I am currently confused and need guidance.

I currently use this code to view logged in users to check for employees in our department:

 #! /usr/bin/perl
use strict;
use warnings;

$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

#current emplyees go here:
my @las = qw(

user12
user13
user14
user15
user16
user17
user18
user19
user20
user21
user22
user23
user24
user25
user26
user27
user28
user29
user30
user31
user32
user33
user34
user35
user36
user37
user38
user39
user40
user41
user42
user43
user44
user45
user46
user47
user48
user49
user50
user51
user52
user53
user54
user55
user56
user57
user58
user59
user60
user61
user62
user63
user64
user65
user66
user67
user68
user69
user70
user71
user72
user73
user74
user75
user76
user77
user78
user79
user80
user81
user82
user83
user84
user85
user86
user87
user88
user89
user90
user91
user92
user93
user94
user95
user96
user97
user98
user99
user100
user101
user102
user103
user104
user105
user106
user107
user108
user109
user110
user111
user112
user113
user114
user115
user116
user117
user118
user119
user120
user121
user122
user123
user124
user125
user126
user127
user128
user129
user130
user131
user132
user133
user134
user135
user136
user137
user138
user139
user140
user141
user142
user143
user144
user145
user146
user147
user148
user149
user150
user151
user152
user153
user154
user155
user156
user157
user158
user159
user160
user161
user162
user163
user164
user165
user166
user167
user168
user169
user170
user171
user172
user173
user174
user175
user176
user177
user178
user179
user180
user181
user182
user183
user184
user185
user186
user187
user188
user189
user190
user191
user192
user193
user194
user195
user196
user197
user198
user199
user200
user201
user202
user203
user204
user205
user206
user207
user208
user209
user210
user211
user212
user213
user214
user215
user216
user217
user218
user219
user220
user221
user222
user223
user224
user225
user226
user227
user228
user229
user230
user231
user232
user233
user234
user235
user236
user237
user238
user239
user240
user241
user242
user243
user244
user245
user246
user247
user248
user249
user250
user251
user252
user253
user254
user255
user256
user257
user258
user259
user260
user261
user262
user263
user264
user265
user266
user267
user268
user269
user270
user271
user272
user273
user274
user275
user276
user277

systemdefault
admin1
admin2
admin3

);

#Find Current Users
$login="logg";
$password="pass32";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Search Zone 2

my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE  (hosts.host_name = '1408bcc204ap1')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')
OR      (hosts.host_name = '1408mathg135m1')
OR      (hosts.host_name = '1408mathb10p1')
OR      (hosts.host_name = '1408mathb10p2')
OR      (hosts.host_name = '1408mathb10p3')
OR      (hosts.host_name = '1408mathb10p4')
OR      (hosts.host_name = '1408mathb10p5')
OR      (hosts.host_name = '1408mathb10p6')
OR      (hosts.host_name = '1408mathb10p7')
OR      (hosts.host_name = '1408mathb10p8')
OR      (hosts.host_name = '1408mathb10p9')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')
OR      (hosts.host_name = '1408mathb10p10')

ORDER BY hosts.host_name
};
my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "\n";
print "\n";
print "<title>\n";
print "Staff Stations\n";
print "</title>\n";
print "\n";
print "\n";
print "
\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "
Zone 2	Login
\n";
while($sth->fetch()) {
        next unless $currentuser~~@las  ;
        $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "
";
        print "$host_name	";
        print "$currentuser	 	";
}
$sth->finish();

print "
";
print "\n";
print "\n";

$sth->finish();$sth->finish();

#end code

$
b
->disconnect();

The usernames are already stored in a mysql database, I am trying to add lines to connect to it as follows, but I am stuck as to how to continue:

#Read Employee database

my $dbh = DBI->connect("DBI:mysql:myadmpr01", "user", "pass64");
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

my $sql = qq{
SELECT  user_id,
FROM    lsoemployee_info

};
my $sth = $dbh->prepare($sql);
$sth->execute();

I am trying to compare the icsprodagainst the myadmpr01 for usernames so that out hr department can maintain this easily as they update the myadmpr01 database for current/non-current employees. icsprod is updated continuously and simply defines the current user. We would also like to return the user's fullname, rather than continuously look up usernames. Any help is greatly appreciated.

Revised code:

  #! /usr/bin/perl
$ENV{'ORACLE_HOME'} ="/usr/lib/oracle/11.2/client64";
use DBI;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

my $dbh = DBI->connect("DBI:mysql:lsopskeys:myadmpr01.itap.purdue.edu", "lsops", "Fl4sh_l1ght")
  or die "Unable to connect: $DBI::errstr\n";

my $sql = qq{
  SELECT  user_id,
  FROM    lsoemployee_data
};

my $sth = $dbh->prepare($sql);
$sth->execute();

my @las = map { $_->[0] } $sth->fetchall_arrayref;

$login="user";
$password="pass";
my $dbh = DBI->connect("DBI:Oracle:icsprod",$login,$password);
die "Unable to connect: $DBI::errstr\n" unless (defined $dbh);

# Zone 2 ROWS CODE
my $sql = qq{
SELECT  hosts.currentuser, TO_CHAR(hosts.lastlogin, 'HH:MM:SS MM/DD/YYYY'),
        hosts.host_name
FROM    infadmin.inv_hosts hosts
WHERE   (hosts.host_name = '1408stew102p1')
OR      (hosts.host_name = '1408stew102p2')
OR      (hosts.host_name = '1408stew102p3')

OR      (hosts.host_name = '1408stew111p1')
OR      (hosts.host_name = '1408stew111p2')
OR      (hosts.host_name = '1408stew111p3')
OR      (hosts.host_name = '1408stew111p4')
OR      (hosts.host_name = '1408stew111p5')
OR      (hosts.host_name = '1408stew111p6')
OR      (hosts.host_name = '1408stew111p7')
OR      (hosts.host_name = '1408stew111p8')
OR      (hosts.host_name = '1408stew111p9')
OR      (hosts.host_name = '1408stew111p10')
OR      (hosts.host_name = '1408stew111p11')
OR      (hosts.host_name = '1408mathg135p1')
OR      (hosts.host_name = '1408mathb18p5')
OR      (hosts.host_name = '1408mathg135p2')
OR      (hosts.host_name = '1408mathg135p3')
OR      (hosts.host_name = '1408mathg135p4')

OR      (hosts.host_name = '1408heav227m1')
OR      (hosts.host_name = '1408heav227m2')
OR      (hosts.host_name = '1408heav227m3')
OR      (hosts.host_name = '1408mthw116p1')
OR      (hosts.host_name = '1408hamp3144p21')

ORDER BY hosts.host_name
};

my $sth = $dbh->prepare($sql);
$sth->execute();
my($currentuser, $lastlogin, $host_name);
$sth->bind_columns(undef, \$currentuser, \$lastlogin, \$host_name);
print "Content-type: text/html\n\n";
print "\n";
print "<meta http-equiv=refresh content=300>\n";
print "<meta http-equiv='pragma' content='no-cache'>\n";
print "\n";
print "\n";
print "<title>\n";
print "LA station usage.\n";
print "</title>\n";
print "\n";
print "\n";
print "
\n";
printf("%02d:%02d:%02d", $hour, $min, $sec);
print "
Zone 2 Station	Login
\n";
while($sth->fetch()) {
      #next unless $currentuser ~~ @las;
       $lastlogin=~s/ .*$//;
        $host_name=~s/1408//;
        foreach(@las)   {
                if ($currentuser eq "$_") {
                       $lacolor = "orange";
                        last;
                } else {
                        $lacolor = "black";
                }
        }
        print "
";
        print "$host_name	";
        print "$currentuser	 	";
}
$sth->finish();
print "
";
print "\n";
print "\n";
$sth->finish();$sth->finish();

#end code
$
b
->disconnect();

Body:
If you're trying to populate @las from the database, then you want something like this:

my $dbh = DBI->connect('DBI:mysql:myadmpr01', 'user', 'pass64')
  or die "Unable to connect: $DBI::errstr\n";

my $sql = qq{
  SELECT  user_id,
  FROM    lsoemployee_info
};

my $sth = $dbh->prepare($sql);
$sth->execute();

my @las = map { $_->[0] } $sth->fetchall_arrayref;

Update: I wrote that last line of code as I would write it for a client. I always assume that my code will be read and maintained by people who know Perl. If you have doubts about the abilities of your programmers, you might be better advised to write something like that:

my @las;

foreach ($sth->fetchall_arrayref) {
  push @las, $_->[0];
}


问:
Getting java.lang.ClassNotFoundException while running Spark Application
I am new to Spark (Scala) and I am trying to run one spark application through spark submit. Unfortunately I am getting java.lang.ClassNotFoundException exception.

Here is my spark submit command:

```<code>./spark-submit --class "spark.phoenix.a" --master local --deploy-mode client /home/ec2-user/phoenix-0.0.1-SNAPSHOT.jar
</code>```

Here is my Exception:

```<code>java.lang.ClassNotFoundException: spark.phoenix.a
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:175)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:689)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

Here is my sample code:

```<code>package spark.phoenix
import org.apache.spark.SparkConf
import org.apache.spark.sql.SQLContext

object a {

  def main(args: Array[String]) {
    import org.apache.phoenix.spark._
    import org.apache.spark.SparkContext

    val zkQuorum = "localhost:2181"
    val master = "local[*]"
    val sparkConf = new SparkConf()
    sparkConf.setAppName("phoenix-spark-save")
        .setMaster(s"${master}")
    val sc = new SparkContext(sparkConf)
    val sqlContext = new SQLContext(sc)

    // read from orders phoenix table
    val df = sqlContext.phoenixTableAsDataFrame("TABLE1",
        Seq.apply("ID", "COL1"),
        zkUrl = Some.apply(s"${zkQuorum}") )

  }
}
</code>```

答:
please remove the "" from your command.

Try something like this.

```<code>./spark-submit --class spark.phoenix.a --master local --deploy-mode client /home/ec2-user/phoenix-0.0.1-SNAPSHOT.jar
</code>```

Body:
I am new to Spark (Scala) and I am trying to run one spark application through spark submit. Unfortunately I am getting java.lang.ClassNotFoundException exception.

Here is my spark submit command:

./spark-submit --class "spark.phoenix.a" --master local --deploy-mode client /home/ec2-user/phoenix-0.0.1-SNAPSHOT.jar

Here is my Exception:

java.lang.ClassNotFoundException: spark.phoenix.a
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:175)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:689)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

Here is my sample code:

package spark.phoenix
import org.apache.spark.SparkConf
import org.apache.spark.sql.SQLContext

object a {

  def main(args: Array[String]) {
    import org.apache.phoenix.spark._
    import org.apache.spark.SparkContext

    val zkQuorum = "localhost:2181"
    val master = "local[*]"
    val sparkConf = new SparkConf()
    sparkConf.setAppName("phoenix-spark-save")
        .setMaster(s"${master}")
    val sc = new SparkContext(sparkConf)
    val sqlContext = new SQLContext(sc)

    // read from orders phoenix table
    val df = sqlContext.phoenixTableAsDataFrame("TABLE1",
        Seq.apply("ID", "COL1"),
        zkUrl = Some.apply(s"${zkQuorum}") )

  }
}

Body:
please remove the "" from your command.

Try something like this.

./spark-submit --class spark.phoenix.a --master local --deploy-mode client /home/ec2-user/phoenix-0.0.1-SNAPSHOT.jar


问:
Error: undefined is not an object (evaluating 'ProfileService.getProfile(1).then')
Trying to load data in from a service and I get the following error message: Error: undefined is not an object (evaluating 'ProfileService.getProfile(1).then.

ProfileController

Error happens here...

```<code>vm.user = {};

vm.loadProfile = function() {
  ProfileService.getProfile(1).then(function(profileData) {
    console.log(profileData);
    vm.user = profileData;
  })
};

vm.loadProfile()
</code>```

ProfileService

```<code>function getProfile(id) {
  var profile = [];

  $log.debug('Getting profile with id: ' + id);
  StubFactory.getProfileData().then(function(result) {
    for(var i = 0; i < result.data.profiles.length; i++) {
      if(result.data.profiles[i].id === id) {
        profile = result.data.profiles[i];
      }
    }

    $log.debug('Getting contacts for profile with id: ' + id);
    profile.contacts = [];
    StubFactory.getContactsData().then(function(result) {
      for(i = 0; i < profile.contactMapper.length; i++) {
        for(var j = 0; j < result.data.contacts.length; j++) {
          if(profile.contactMapper[i] === result.data.contacts[j].id) {
            profile.contacts.push(result.data.contacts[j]);
          }
        }
      }
    });

    $log.debug('Getting documents for profile with id: ' + id);
    profile.documents = [];
    StubFactory.getDocumentsData().then(function(result) {
      for(i = 0; i < profile.documentMapper.length; i++) {
        for(var j = 0; j < result.data.documents.length; j++) {
          if(profile.documentMapper[i] === result.data.documents[j].id) {
            profile.documents.push(result.data.documents[j]);
          }
        }
      }
    });
    $log.debug('Completed load for profile with id: ' + id);
    $log.info(profile);
    return profile;
  });
}
</code>```

StubFactory

```<code>function getContactsData() {
  return $http.get('data/contacts.json');

}

function getProfileData() {
  return $http.get('data/profiles.json');
}

function getDocumentsData() {
  return $http.get('data/documents.json');
}
</code>```

Logs are as follows...

```<code>[Warning] Unexpected CSS token: : (main.css, line 4919)
[Warning] Unexpected CSS token: : (main.css, line 8199)
[Warning] Unexpected CSS token: : (main.css, line 8207)
[Debug] Getting profile with id: 1 (angular.js, line 14326)
[Error] Error: undefined is not an object (evaluating 'ProfileService.getProfile(1).then')
loadProfile@http://localhost:9000/scripts/controllers/profile.js:17:35
http://localhost:9000/scripts/controllers/profile.js:22:19
$controllerInit@http://localhost:9000/bower_components/angular/angular.js:10717:40
nodeLinkFn@http://localhost:9000/bower_components/angular/angular.js:9594:45
compositeLinkFn@http://localhost:9000/bower_components/angular/angular.js:8903:23
publicLinkFn@http://localhost:9000/bower_components/angular/angular.js:8768:45
link@http://localhost:9000/bower_components/angular-route/angular-route.js:1222:11
invokeLinkFn@http://localhost:9000/bower_components/angular/angular.js:10274:15
nodeLinkFn@http://localhost:9000/bower_components/angular/angular.js:9663:23
compositeLinkFn@http://localhost:9000/bower_components/angular/angular.js:8903:23
publicLinkFn@http://localhost:9000/bower_components/angular/angular.js:8768:45
update@http://localhost:9000/bower_components/angular-route/angular-route.js:1171:36
$broadcast@http://localhost:9000/bower_components/angular/angular.js:18343:33
http://localhost:9000/bower_components/angular-route/angular-route.js:733:40
processQueue@http://localhost:9000/bower_components/angular/angular.js:16689:39
http://localhost:9000/bower_components/angular/angular.js:16733:39
$digest@http://localhost:9000/bower_components/angular/angular.js:17827:36
$apply@http://localhost:9000/bower_components/angular/angular.js:18125:31
done@http://localhost:9000/bower_components/angular/angular.js:12233:53
completeRequest@http://localhost:9000/bower_components/angular/angular.js:12459:15
requestLoaded@http://localhost:9000/bower_components/angular/angular.js:12387:24 – "<div ng-view=\"\" class=\"ng-scope\">"
    (anonymous function) (angular.js:10859)
    invokeLinkFn (angular.js:10276)
    nodeLinkFn (angular.js:9663)
    compositeLinkFn (angular.js:8903)
    publicLinkFn (angular.js:8768)
    update (angular-route.js:1171)
    $broadcast (angular.js:18343)
    (anonymous function) (angular-route.js:733)
    processQueue (angular.js:16689)
    (anonymous function) (angular.js:16733)
    $digest (angular.js:17827)
    $apply (angular.js:18125)
    done (angular.js:12233)
    completeRequest (angular.js:12459)
    requestLoaded (angular.js:12387)
[Debug] Getting contacts for profile with id: 1 (angular.js, line 14326)
[Debug] Getting documents for profile with id: 1 (angular.js, line 14326)
[Debug] Completed load for profile with id: 1 (angular.js, line 14326)
[Info] {id: 1, firstName: "Robert", lastName: "Emery", address: "95 Guild Street, London, N14 3UF", type: "tenant", …} (profile.js, line 115)
</code>```

profile.js, line 115 is the following line of code in ProfileService: $log.info(profile);.

答:
Your problem is related to async behavior of promise, which is good. So to get your data, you have 2 ways:

first way is to chain .then events and call a callbackfunction from last promise result.
Code is shown below :

ProfileController

```<code>vm.user = {};
vm.loadProfile = function() {
     ProfileService.getProfile(1, callBackfunc); // pass callback function
};

function callBackfunc(profileData){
     vm.user = profileData;
}
vm.loadProfile();
</code>```

ProfileService

```<code>function getProfile(id, callBackfunc) {
      var profile = [];
      // chain .then events
      $log.debug('Getting profile with id: ' + id);
      StubFactory.getProfileData().then(function(result) {
        for(var i = 0; i < result.data.profiles.length; i++) {
          if(result.data.profiles[i].id === id) {
            profile = result.data.profiles[i];
          }
        }

        $log.debug('Getting contacts for profile with id: ' + id);
        profile.contacts = [];
        StubFactory.getContactsData().then(function(result) {
          for(i = 0; i < profile.contactMapper.length; i++) {
            for(var j = 0; j < result.data.contacts.length; j++) {
              if(profile.contactMapper[i] === result.data.contacts[j].id) {
                profile.contacts.push(result.data.contacts[j]);
              }
            }
          }

        $log.debug('Getting documents for profile with id: ' + id);
        profile.documents = [];
        StubFactory.getDocumentsData().then(function(result) {
          for(i = 0; i < profile.documentMapper.length; i++) {
            for(var j = 0; j < result.data.documents.length; j++) {
              if(profile.documentMapper[i] === result.data.documents[j].id) {
                profile.documents.push(result.data.documents[j]);
              }
            }
          }
        $log.debug('Completed load for profile with id: ' + id);
        $log.info(profile);
        callBackfunc(profile); // callback function called.
        });
      });
    });
}
</code>```

Second way is to use $q service and utilize it's $q.all() method.

then your code will be like :

```<code>let promises = [promisegetProfileData(), promisegetContactsData(), promisegetDocumentsData()];

$q.all(promises).then((values) => {
    var profile = [];
    // assign ProfileData values[0]
    // assign ContactData values[1]
    // assign DocumentData values[2]

    callBackFunc(profile);
});
</code>```

Read more here for $q

Body:
Trying to load data in from a service and I get the following error message: Error: undefined is not an object (evaluating 'ProfileService.getProfile(1).then.

ProfileController

Error happens here...

vm.user = {};

vm.loadProfile = function() {
  ProfileService.getProfile(1).then(function(profileData) {
    console.log(profileData);
    vm.user = profileData;
  })
};

vm.loadProfile()

ProfileService

function getProfile(id) {
  var profile = [];

  $log.debug('Getting profile with id: ' + id);
  StubFactory.getProfileData().then(function(result) {
    for(var i = 0; i < result.data.profiles.length; i++) {
      if(result.data.profiles[i].id === id) {
        profile = result.data.profiles[i];
      }
    }

    $log.debug('Getting contacts for profile with id: ' + id);
    profile.contacts = [];
    StubFactory.getContactsData().then(function(result) {
      for(i = 0; i < profile.contactMapper.length; i++) {
        for(var j = 0; j < result.data.contacts.length; j++) {
          if(profile.contactMapper[i] === result.data.contacts[j].id) {
            profile.contacts.push(result.data.contacts[j]);
          }
        }
      }
    });

    $log.debug('Getting documents for profile with id: ' + id);
    profile.documents = [];
    StubFactory.getDocumentsData().then(function(result) {
      for(i = 0; i < profile.documentMapper.length; i++) {
        for(var j = 0; j < result.data.documents.length; j++) {
          if(profile.documentMapper[i] === result.data.documents[j].id) {
            profile.documents.push(result.data.documents[j]);
          }
        }
      }
    });
    $log.debug('Completed load for profile with id: ' + id);
    $log.info(profile);
    return profile;
  });
}

StubFactory

function getContactsData() {
  return $http.get('data/contacts.json');

}

function getProfileData() {
  return $http.get('data/profiles.json');
}

function getDocumentsData() {
  return $http.get('data/documents.json');
}

Logs are as follows...

[Warning] Unexpected CSS token: : (main.css, line 4919)
[Warning] Unexpected CSS token: : (main.css, line 8199)
[Warning] Unexpected CSS token: : (main.css, line 8207)
[Debug] Getting profile with id: 1 (angular.js, line 14326)
[Error] Error: undefined is not an object (evaluating 'ProfileService.getProfile(1).then')
loadProfile@http://localhost:9000/scripts/controllers/profile.js:17:35
http://localhost:9000/scripts/controllers/profile.js:22:19
$controllerInit@http://localhost:9000/bower_components/angular/angular.js:10717:40
nodeLinkFn@http://localhost:9000/bower_components/angular/angular.js:9594:45
compositeLinkFn@http://localhost:9000/bower_components/angular/angular.js:8903:23
publicLinkFn@http://localhost:9000/bower_components/angular/angular.js:8768:45
link@http://localhost:9000/bower_components/angular-route/angular-route.js:1222:11
invokeLinkFn@http://localhost:9000/bower_components/angular/angular.js:10274:15
nodeLinkFn@http://localhost:9000/bower_components/angular/angular.js:9663:23
compositeLinkFn@http://localhost:9000/bower_components/angular/angular.js:8903:23
publicLinkFn@http://localhost:9000/bower_components/angular/angular.js:8768:45
update@http://localhost:9000/bower_components/angular-route/angular-route.js:1171:36
$broadcast@http://localhost:9000/bower_components/angular/angular.js:18343:33
http://localhost:9000/bower_components/angular-route/angular-route.js:733:40
processQueue@http://localhost:9000/bower_components/angular/angular.js:16689:39
http://localhost:9000/bower_components/angular/angular.js:16733:39
$digest@http://localhost:9000/bower_components/angular/angular.js:17827:36
$apply@http://localhost:9000/bower_components/angular/angular.js:18125:31
done@http://localhost:9000/bower_components/angular/angular.js:12233:53
completeRequest@http://localhost:9000/bower_components/angular/angular.js:12459:15
requestLoaded@http://localhost:9000/bower_components/angular/angular.js:12387:24 – "
"
    (anonymous function) (angular.js:10859)
    invokeLinkFn (angular.js:10276)
    nodeLinkFn (angular.js:9663)
    compositeLinkFn (angular.js:8903)
    publicLinkFn (angular.js:8768)
    update (angular-route.js:1171)
    $broadcast (angular.js:18343)
    (anonymous function) (angular-route.js:733)
    processQueue (angular.js:16689)
    (anonymous function) (angular.js:16733)
    $digest (angular.js:17827)
    $apply (angular.js:18125)
    done (angular.js:12233)
    completeRequest (angular.js:12459)
    requestLoaded (angular.js:12387)
[Debug] Getting contacts for profile with id: 1 (angular.js, line 14326)
[Debug] Getting documents for profile with id: 1 (angular.js, line 14326)
[Debug] Completed load for profile with id: 1 (angular.js, line 14326)
[Info] {id: 1, firstName: "Robert", lastName: "Emery", address: "95 Guild Street, London, N14 3UF", type: "tenant", …} (profile.js, line 115)

profile.js, line 115 is the following line of code in ProfileService: $log.info(profile);.

Body:
Your problem is related to async behavior of promise, which is good. So to get your data, you have 2 ways:

first way is to chain .then events and call a callbackfunction from last promise result.
Code is shown below :

ProfileController

vm.user = {};
vm.loadProfile = function() {
     ProfileService.getProfile(1, callBackfunc); // pass callback function
};

function callBackfunc(profileData){
     vm.user = profileData;
}
vm.loadProfile();

ProfileService

function getProfile(id, callBackfunc) {
      var profile = [];
      // chain .then events
      $log.debug('Getting profile with id: ' + id);
      StubFactory.getProfileData().then(function(result) {
        for(var i = 0; i < result.data.profiles.length; i++) {
          if(result.data.profiles[i].id === id) {
            profile = result.data.profiles[i];
          }
        }

        $log.debug('Getting contacts for profile with id: ' + id);
        profile.contacts = [];
        StubFactory.getContactsData().then(function(result) {
          for(i = 0; i < profile.contactMapper.length; i++) {
            for(var j = 0; j < result.data.contacts.length; j++) {
              if(profile.contactMapper[i] === result.data.contacts[j].id) {
                profile.contacts.push(result.data.contacts[j]);
              }
            }
          }

        $log.debug('Getting documents for profile with id: ' + id);
        profile.documents = [];
        StubFactory.getDocumentsData().then(function(result) {
          for(i = 0; i < profile.documentMapper.length; i++) {
            for(var j = 0; j < result.data.documents.length; j++) {
              if(profile.documentMapper[i] === result.data.documents[j].id) {
                profile.documents.push(result.data.documents[j]);
              }
            }
          }
        $log.debug('Completed load for profile with id: ' + id);
        $log.info(profile);
        callBackfunc(profile); // callback function called.
        });
      });
    });
}

Second way is to use $q service and utilize it's $q.all() method.

then your code will be like :

let promises = [promisegetProfileData(), promisegetContactsData(), promisegetDocumentsData()];

$q.all(promises).then((values) => {
    var profile = [];
    // assign ProfileData values[0]
    // assign ContactData values[1]
    // assign DocumentData values[2]

    callBackFunc(profile);
});

Read more here for $q