问:
Access the attributes of a sister child via the parent model
So I've been looking all over and can't seem to find the correct conceptual explanation/technical process for this, and quite possibly am approaching it incorrectly.

I have 2 child models, connected by the same parent, I want to access the attributes of CHILD B from an Index view on CHILD A :THROUGH an instance of the parent.

High level overview

```<code>    Property
   /        \
Order      Owner
</code>```

Basically I have an index page showing all the open Orders, each Order must have a Property(parent) and every Property has an owner. So I'm in the Orders index page and I want to see the first_name of the Property's Owner, how can I access that?

If I do something like:

```<code>@order.property.owners.first_name
</code>```

I get a an error undefined method, however if I do:

```<code>@order.property.owners
</code>```

I don't receive an error but rather:

```<code>    #<Owner::ActiveRecord_Associations_CollectionProxy:0x007f8a85368988>
</code>```

shows up in my view, along with all the other correct information.

Models

```<code>Property
has_many :orders
has_many :owners
accepts_nested_attributes_for :owners

Owner
belongs_to :property

Orders
belongs_to :property
has_many :owners, through: :property
accepts_nested_attributes_for :owners
</code>```

Orders Controller

```<code>  def open_orders
@open_orders = Order.where(status: "Open").paginate(page: params[:page], per_page: 15)
###@orders = Order.all
###@properties = Property.find(@orders.property.id)
###@owners = Owner.find(@properties.owners.id)
render 'orders/open'
</code>```

end

^ Commented out stuff I was trying but was not working, including it incase I'm just a little bit off somewhere.

Open_orders View

```<code><% @open_orders.each do |order| %>
  <tr>
    <td><%= order.client_id %></td>
    <td><%= order.order_number %></td>
    <td><%= order.property.address1 %></td>
    <td><%= order.property.owners %></td>
    <td><%= order.order_update ? "Yes" : "No" %></td>
    <td><%= order.status %></td>
    <td><%= order.task %></td>
    <td><%= order.created_at %></td>
    <td><%= link_to fa_icon("edit"), edit_property_order_path(order, order.property.id), class: "m-r-xs", remote: true, data: { 'data-toggle' => "modal", 'data-target' => '#orders-modal'} %></td>
  </tr>
</code>```

答:
As per your model definition, an order has multiple owners..thus you are getting active record collection of owners instead of single object.

There are 2 ways to handle this,

Loop through the collection and get the names

Pluck all the owner names, which is I think you are looking for

You must preload the owners to avoid n+1 queries

In your controller

```<code>@open_orders = Order.where(status: "Open").includes(:owners).paginate(page: params[:page], per_page: 15)
</code>```

In your view

```<code><td><%= order.owners.pluck(:first_name).join(',') %></td>
</code>```

Update

To get the full_name of the owner, you can define a method in your owner.rb as

```<code>def full_name
  "#{first_name} #{last_name}"
end
</code>```

In your view

```<code><td><%= order.owners.map(&:full_name).join(',') %></td>
</code>```

Body:
So I've been looking all over and can't seem to find the correct conceptual explanation/technical process for this, and quite possibly am approaching it incorrectly.

I have 2 child models, connected by the same parent, I want to access the attributes of CHILD B from an Index view on CHILD A :THROUGH an instance of the parent.

High level overview

    Property
   /        \
Order      Owner

Basically I have an index page showing all the open Orders, each Order must have a Property(parent) and every Property has an owner. So I'm in the Orders index page and I want to see the first_name of the Property's Owner, how can I access that?

If I do something like:

@order.property.owners.first_name

I get a an error undefined method, however if I do:

@order.property.owners

I don't receive an error but rather:

    #<Owner::ActiveRecord_Associations_CollectionProxy:0x007f8a85368988>

shows up in my view, along with all the other correct information.

Models

Property
has_many :orders
has_many :owners
accepts_nested_attributes_for :owners

Owner
belongs_to :property

Orders
belongs_to :property
has_many :owners, through: :property
accepts_nested_attributes_for :owners

Orders Controller

  def open_orders
@open_orders = Order.where(status: "Open").paginate(page: params[:page], per_page: 15)
###@orders = Order.all
###@properties = Property.find(@orders.property.id)
###@owners = Owner.find(@properties.owners.id)
render 'orders/open'

end

^ Commented out stuff I was trying but was not working, including it incase I'm just a little bit off somewhere.

Open_orders View

<% @open_orders.each do |order| %>

    <%= order.client_id %>
    <%= order.order_number %>
    <%= order.property.address1 %>
    <%= order.property.owners %>
    <%= order.order_update ? "Yes" : "No" %>
    <%= order.status %>
    <%= order.task %>
    <%= order.created_at %>
    <%= link_to fa_icon("edit"), edit_property_order_path(order, order.property.id), class: "m-r-xs", remote: true, data: { 'data-toggle' => "modal", 'data-target' => '#orders-modal'} %>

Body:
As per your model definition, an order has multiple owners..thus you are getting active record collection of owners instead of single object.

There are 2 ways to handle this,

Loop through the collection and get the names

Pluck all the owner names, which is I think you are looking for

You must preload the owners to avoid n+1 queries

In your controller

@open_orders = Order.where(status: "Open").includes(:owners).paginate(page: params[:page], per_page: 15)

In your view

<td><%= order.owners.pluck(:first_name).join(',') %></td>

Update

To get the full_name of the owner, you can define a method in your owner.rb as

def full_name
  "#{first_name} #{last_name}"
end

In your view

<td><%= order.owners.map(&:full_name).join(',') %></td>


来源: stackexchange

问:
ImmutableJS: Return unchanged List after push
With ImmutableJS is there a way to push an "empty" value onto a List, returning the same unchanged List? For example, if I have a List xs and an Option a, I'd like to do something like:

```<code>xs.push(a.getOrElse(null)) // doesn't work as intended
</code>```

equivalent to:

```<code>xs.concat(a.map(a => [a]).getOrElse([])) // works as intended
</code>```

I'd like to use the cleaner syntax and O(1) efficiency of push though.

答:
The push method in ImmutableJS takes zero or more arguments, so you should be able to use the spread operator on an empty array to get the functionality you're looking for.

```<code>xs.push(...a.getOrElse([]))
</code>```

The caveat to this is that whatever result you get from getOrElse would need to be in array format.

ContentLicense: CC BY-SA 3.0

Body:
With ImmutableJS is there a way to push an "empty" value onto a List, returning the same unchanged List? For example, if I have a List xs and an Option a, I'd like to do something like:

xs.push(a.getOrElse(null)) // doesn't work as intended

equivalent to:

xs.concat(a.map(a => [a]).getOrElse([])) // works as intended

I'd like to use the cleaner syntax and O(1) efficiency of push though.

Body:
The push method in ImmutableJS takes zero or more arguments, so you should be able to use the spread operator on an empty array to get the functionality you're looking for.

xs.push(...a.getOrElse([]))

The caveat to this is that whatever result you get from getOrElse would need to be in array format.


问:
Is it possible to format code in Visual Studio Team Services
Is there a means to format code snippets in any way, ideally a Markdown like syntax, in Visual Studio Team Services (formerly Visual Studio Online)?

Using italics just doesn't sit right with me.

答:
Just found this extension from the feature request @eddie linked.

Markdown

Markdown is a custom work item form control, that allows you to edit the rich text fields on your work items with a Markdown enabled editor.


问:
Pick up lines from a file based on line numbers in another file
I have two files - one contains the addresses (line numbers) and the other one data, like this:

address file:

```<code>2
4
6
7
1
3
5
</code>```

data file

```<code>1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396
</code>```

I want to randomize the data file based on the numbers of address files
so I get:

```<code>2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874
</code>```

I want to do it either in python or in bash, but didn't yet find any solution.

答:
With awk:

```<code>awk 'NR==FNR {a[NR]=$0; next} {print a[$0]}' data.txt addr.txt
</code>```

NR==FNR {a[NR]=$0; next} creates an associative array a with keys being the record (line) number and values being the whole record, this would be applicable only for the first file (NR==FNR), which is data.txt. next makes awk to go to the next line without processing the record any further

{print a[$0]} prints the value from the array with keys being the currect file's (addr.txt) line (record) number

Example:

```<code>% cat addr.txt
2
4
6
7
1
3
5

% cat data.txt
1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396

% awk 'NR==FNR {a[NR]=$0; next} {print a[$0]}' data.txt addr.txt
2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874
</code>```

Body:
I have two files - one contains the addresses (line numbers) and the other one data, like this:

address file:

2
4
6
7
1
3
5

data file

1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396

I want to randomize the data file based on the numbers of address files
so I get:

2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874

I want to do it either in python or in bash, but didn't yet find any solution.

Body:
With awk:

awk 'NR==FNR {a[NR]=$0; next} {print a[$0]}' data.txt addr.txt

NR==FNR {a[NR]=$0; next} creates an associative array a with keys being the record (line) number and values being the whole record, this would be applicable only for the first file (NR==FNR), which is data.txt. next makes awk to go to the next line without processing the record any further

{print a[$0]} prints the value from the array with keys being the currect file's (addr.txt) line (record) number

Example:

% cat addr.txt
2
4
6
7
1
3
5

% cat data.txt
1.000451451
2.000589214
3.117892278
4.479511994
5.484514874
6.784499874
7.021239396

% awk 'NR==FNR {a[NR]=$0; next} {print a[$0]}' data.txt addr.txt
2.000589214
4.479511994
6.784499874
7.021239396
1.000451451
3.117892278
5.484514874


问:
Extracting a selected item in a ListBox c#
I have a list box that displays members of a List<Student> where Student is a class that has some properties like name etc.. I also have a list box that displays members of a 'ListwherePaperis similar toStudent`.

How do I get the selected Student and Paper and add them to a dict {Paper.Name:Student.Name} when a button is clicked ?

I have tried
Form2

selectedStudent_Form2 = studentListBox_Form2.SelectedItem;

But I get an error saying

Cannot implicitly convert type 'object' to 'TestProjectForProject5.Student'.

答:
ListBox.SelectedItem always returns object type value. So you cant directly assign that selectedItem to student. You need to cast it. But you can't simple cast anything into student type. If you have set student as displayValue then only you can cast selectedItem as student. But I do not think you have set displayValue as student, you may have set displayValue as student's Name.

so what you can do, is to set displayValue of both listBox (student as well as paper) to respectively student's name and Paper's Name.
now you will get studentName by studentListBox_Form2.SelectedItem.ToString() and
Papername by paperListBox_Form2.SelectedItem.ToString().

Now you can use them as key and value pair to add into dictionary


问:
Child position absolute parent relative doesn't work
I’m trying to implement something like a web page navbar. I have code like this:

nav {
  position: relative;
  display: inline-block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav></code>```

I have known that an absolute element is positioned to its first positioned (not static) ancestor element. I have set position property of element nav as absolute, but it looks like the
 run out of the  range.  In other word  i'm confused about why nav'height  is  less than  ul's   Thanks a  lot.

答:
Try This :

nav {
  position: relative;
}

.nav-right {
  display: inline-block;
  position: absolute;
  top: 0px;
  right: 0px;
  list-style: none;
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav> </code>```

Body:
I’m trying to implement something like a web page navbar. I have code like this:

nav {
  position: relative;
  display: inline-block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  list-style: none;
}

My First Website

Home

About

Contact

I have known that an absolute element is positioned to its first positioned (not static) ancestor element. I have set position property of element nav as absolute, but it looks like the
 run out of the  range.  In other word  i'm confused about why nav'height  is  less than  ul's   Thanks a  lot.

Body:
Try This :

nav {
  position: relative;
}

.nav-right {
  display: inline-block;
  position: absolute;
  top: 0px;
  right: 0px;
  list-style: none;
}

 <nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>


问:
New To PHP = Investment Calculator feedback
I'm new to php and I'm wondering if I set this up right, for a question I have to do. I have to set up a loop that does $amount * (1 + $interest / 100) to find the number of years up to  $1000000. The initial amount is $10000, but I'm not quite sure if I set up my if statement correctly.

```<code><?php //Script investment.php

    //Address error handling.
    ini_set('display_errors',1);
    error_reporting(E_ALL & ~E_NOTICE);

    // In case register_globals is disabled.
    $return = 10000*(1+(15/100));
    $total = 1000000;

    if ($year=$total/$return/12){
        echo "number of years is : ".$year;
    }
?>
</code>```

答:
I don't know the exact formula, but I think you're looking for something like this (Probably needs some tweaking):

```<code><?php

$investment = 10000;
$interest = 15;
$totalInvestmentDesired = 100000;
$year = 0;

while(true) {
    if($investment >= $totalInvestmentDesired) break;
    $year++;
    $investment = $investment*(1+$interest/100);
    echo "Year: " . $year . " Investment: " . round($investment,2) . "<br>\n";
}

echo "\n<br>Investment: " . round($investment, 2). " Number of years: ".$year;
</code>```

Yields:

Year: 1 Investment: 11500

Year: 2 Investment: 13225

Year: 3 Investment: 15208.75

Year: 4 Investment: 17490.06

Year: 5 Investment: 20113.57

Year: 6 Investment: 23130.61

Year: 7 Investment: 26600.2

Year: 8 Investment: 30590.23

Year: 9 Investment: 35178.76

Year: 10 Investment: 40455.58

Year: 11 Investment: 46523.91

Year: 12 Investment: 53502.5

Year: 13 Investment: 61527.88

Year: 14 Investment: 70757.06

Year: 15 Investment: 81370.62

Year: 16 Investment: 93576.21

Year: 17 Investment: 107612.64

Investment: 107612.64 Number of years: 17

http://sandbox.onlinephpfunctions.com/code/7cf9f868ed86a9fc24e3ae76dcf73896675d7261

Body:
I'm new to php and I'm wondering if I set this up right, for a question I have to do. I have to set up a loop that does $amount * (1 + $interest / 100) to find the number of years up to  $1000000. The initial amount is $10000, but I'm not quite sure if I set up my if statement correctly.

<?php //Script investment.php

    //Address error handling.
    ini_set('display_errors',1);
    error_reporting(E_ALL & ~E_NOTICE);

    // In case register_globals is disabled.
    $return = 10000*(1+(15/100));
    $total = 1000000;

    if ($year=$total/$return/12){
        echo "number of years is : ".$year;
    }
?>

Body:
I don't know the exact formula, but I think you're looking for something like this (Probably needs some tweaking):

<?php

$investment = 10000;
$interest = 15;
$totalInvestmentDesired = 100000;
$year = 0;

while(true) {
    if($investment >= $totalInvestmentDesired) break;
    $year++;
    $investment = $investment*(1+$interest/100);
    echo "Year: " . $year . " Investment: " . round($investment,2) . "<br>\n";
}

echo "\n<br>Investment: " . round($investment, 2). " Number of years: ".$year;

Yields:

Year: 1 Investment: 11500

Year: 2 Investment: 13225

Year: 3 Investment: 15208.75

Year: 4 Investment: 17490.06

Year: 5 Investment: 20113.57

Year: 6 Investment: 23130.61

Year: 7 Investment: 26600.2

Year: 8 Investment: 30590.23

Year: 9 Investment: 35178.76

Year: 10 Investment: 40455.58

Year: 11 Investment: 46523.91

Year: 12 Investment: 53502.5

Year: 13 Investment: 61527.88

Year: 14 Investment: 70757.06

Year: 15 Investment: 81370.62

Year: 16 Investment: 93576.21

Year: 17 Investment: 107612.64

Investment: 107612.64 Number of years: 17

http://sandbox.onlinephpfunctions.com/code/7cf9f868ed86a9fc24e3ae76dcf73896675d7261


问:
Swipe card view undo card item in Android
I need some help. I am using  swipe card library like Tinder app in Android and I am removing the cards by using cross button and Now I want undo options also on the click of back option. Can anyone please tell me what is the method used for that ? I really appreciate that.
Thanks!</p>

答:
I wrote a library some time ago, has achieved this function, I hope to help you
https://github.com/adgvcxz/CardLayoutManager</p>


问:
Laravel /public/home 500 (Internal Server Error)
My local laravel project starts with a

/public/home 500 (Internal Server Error)

in place of load all the view. Any suggestion?
I tried git stash to last commit, .htaccess modifications, clear view and caches but it's continues.

答:
Did you give your tmp folder 777 permission? Or delete

```<code>**storage/meta/compiled.php**
</code>```

Or try

```<code>ph**p artisan optimize**
</code>```

in your app's directory

Body:
Did you give your tmp folder 777 permission? Or delete

**storage/meta/compiled.php**

Or try

ph**p artisan optimize**

in your app's directory


问:
How good is Oracle Universal Connection Pool (UCP)
Does anybody have experience with using Oracle UCP under real production load?
Does it handle database reconnects well?
Are there any multi-threading issues?
Has anybody compared it with C3P0 or Apache DBCP?</p>

答:
I evaluated UCP 11.2.0.1 as a replacement for our legacy connection pool and I cannot recommend it:

it does not fully support jdk 6 / ojdbc6.jar. For example the use of statement caching and jmx-support does not work with java 6 and throws exceptions.

no internal statement cache - it relies on the jdbc driver's statement cache (setPoolable())

I submitted both issues to oracle, they confirmed it and will probably fix it when oracle 12.0 will be released. But even that's not for sure.

Too few releases (2 releases in 3 years), too less community support.

Not Open-Source

Hardly extensible. Only a few callbacks with an horrible interface design.

Example: You want to be notified when a Connection exceeds its TTL? Prepare for a wrapper DataSource and a mass usage of internal/proprietary UCP APIs. The official documentation (last update: 2008) remains silent how to achive this.

Fat design (almost a 0,5 MB jar) - many classes with similar names/function (e.g. there's a PoolDataSource and a ConnectionPool - both are related but invoked differently and provide slightly different functionality.)

java.util.logging only

UPDATE 1 (April 2014):

Although slightly off-topic: As a result of my evaluation I decided to go with the new tomcat jdbc-pool - and it is working almost perfectly since a year in several production systems. It's very well designed, updated regularly, extensible and the apache tomcat team does a good job in responding to questions/fixing issues.

UPDATE 2 (July 2016):

I can now highly recommend HikariCP which I'm currently favoring over all other connection pools.
Its architecture, focus on correctness and performance is just amazing.

ContentLicense: CC BY-SA 2.5


问:
How can I conditionally use either [href] or [routerLink] on an anchor?
I need for the same anchor link to be pointed conditionally locally or to external resource. I tried

test
```

But it doesn't work. I don't get any errors, but it points to the same local page and ignores the external URL. Any ideas?

Another option would be to construct the link, but I can't find any docs how to access routerLink inside a service

Edit: I know I can clone the whole link with *ngIf but I don't want to do it, my link contains a video tag with a buch of options

答:
The simplest way would be to use *ngIf / else:

```<code><ng-container *ngIf="outside; else internalBlock">
  <a [href]="externalUrl">External</a>
</ng-container>

<ng-template #internalBlock>
  <a [routerLink]="['/route', id]">Internal</a>
</ng-template>
</code>```

EDIT#1: (Ugly workaround)

Since you don't want to use *ngIf (I still don't understand why), you can do this:

Template:

```<code><a href="javascript:void(0)" (click)="handleClick(outside, '/route', id, externalUrl)">Link</a>
</code>```

Component:

```<code>handleClick(outside: boolean, internalUrl: string, internalId: string, externalUrl: string): void {
  if (outside) {
    window.location.href = externalUrl;
    // You can also use Location class of Angular
  } else {
    this.router.navigate([`${internalUrl}/${internalId}`]);
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need for the same anchor link to be pointed conditionally locally or to external resource. I tried

test

But it doesn't work. I don't get any errors, but it points to the same local page and ignores the external URL. Any ideas?

Another option would be to construct the link, but I can't find any docs how to access routerLink inside a service

Edit: I know I can clone the whole link with *ngIf but I don't want to do it, my link contains a video tag with a buch of options

Body:
The simplest way would be to use *ngIf / else:

<ng-container *ngIf="outside; else internalBlock">
  <a [href]="externalUrl">External</a>
</ng-container>

<ng-template #internalBlock>
  <a [routerLink]="['/route', id]">Internal</a>
</ng-template>

EDIT#1: (Ugly workaround)

Since you don't want to use *ngIf (I still don't understand why), you can do this:

Template:

<a href="javascript:void(0)" (click)="handleClick(outside, '/route', id, externalUrl)">Link</a>

Component:

handleClick(outside: boolean, internalUrl: string, internalId: string, externalUrl: string): void {
  if (outside) {
    window.location.href = externalUrl;
    // You can also use Location class of Angular
  } else {
    this.router.navigate([`${internalUrl}/${internalId}`]);
  }
}


问:
Spring Security 4.2.2 - Using Password To Decrypt Surrogate Key
Greetings StackOverflow!  Longtime reader, first time contributor.

I'm working on a personal project that will allow a logged-in user to store encrypted notes to themselves or family members.  After much research, I decided to implement a surrogate key approach, where each user is assigned a surrogate key upon creation of their account.

This surrogate key is encrypted and stored in the database... and is decrypted using the user's password upon login.  The resulting clear surrogate key is then used for all encryption activity in their profile.

My issue is capturing the user's password during login while using an implementation of Spring Security per this tutorial:

Spring Boot MVC Spring Security Tutorial

My SecurityConfig class looks like this:

```<code>    /*
 * (non-Javadoc)
 *
 * @see org.springframework.security.config.annotation.web.configuration.
 * WebSecurityConfigurerAdapter#configure(org.springframework.security.
 * config.annotation.web.builders.HttpSecurity)
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/login").permitAll()
            .antMatchers("/registration").permitAll().antMatchers("/accountverification/**").permitAll()
            .antMatchers("/secure/**").hasAuthority("MEMBER").anyRequest().authenticated().and().formLogin()
            .loginPage("/login").failureUrl("/login?error=true").defaultSuccessUrl("/secure/notes")
            .usernameParameter("email").passwordParameter("password").and().logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
            .exceptionHandling().accessDeniedPage("/access-denied");
}
</code>```

And my login.html page like this (the important part):

```<code><form th:action="@{/login}" method="POST" class="form-signin">
</code>```

If I'm understanding things correctly, the login.html page is posting to /login, which is defined in my SecurityConfig class (above).  Login itself works wonderfully.

However, this automatically bypasses the part of my flow where I'd decrypt that surrogate key.  So, I first tried posting to a separate controller then forwarding that request on to /login.  No dice.

I then tried extending HandleInterceptorAdapter, but found that the password at this point was still always null.  That led me to this post:

UserDetails getPassword returns null in spring security 3.1...

... but that struck me as hackey.

So, in the end, I'm still wondering how I might go about grabbing the password during the post of a login screen for temporary use of decrypting a user's surrogate key... then when the decryption is done and login completes... destroying it.

Any help is appreciated!

答:
I knew this would happen... as soon as I post some fancy question on StackOverflow I'd figure it out.

I'm not sure it's the most elegant solution, but it works.  I'm certainly open to alternatives.

I added this method to my login controller:

```<code>/**
 * @return
 */
@RequestMapping(value = { "/loginProcessor" }, method = RequestMethod.POST)
public String loginProcessor(@ModelAttribute Login login) {
    System.out.println("PASSWORD: " + login.getPassword());
    return "forward:/login";
}
</code>```

I then adjusted login.html to post to it, instead of to /login:

```<code><form th:action="@{/loginProcessor}" method="POST" class="form-signin">
</code>```

And I updated my SecurityConfig to accommodate both paths:

```<code>/*
 * (non-Javadoc)
 *
 * @see org.springframework.security.config.annotation.web.configuration.
 * WebSecurityConfigurerAdapter#configure(org.springframework.security.
 * config.annotation.web.builders.HttpSecurity)
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/loginProcessor").permitAll()
            .antMatchers("/login").permitAll().antMatchers("/registration").permitAll()
            .antMatchers("/accountverification/**").permitAll().antMatchers("/secure/**").hasAuthority("MEMBER")
            .anyRequest().authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error=true")
            .defaultSuccessUrl("/secure/notes").usernameParameter("email").passwordParameter("password").and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
            .exceptionHandling().accessDeniedPage("/access-denied");
}
</code>```

Et, voila!  The password printed, I was logged in and redirected to my profile page.  Is there a better way?

Body:
Greetings StackOverflow!  Longtime reader, first time contributor.

I'm working on a personal project that will allow a logged-in user to store encrypted notes to themselves or family members.  After much research, I decided to implement a surrogate key approach, where each user is assigned a surrogate key upon creation of their account.

This surrogate key is encrypted and stored in the database... and is decrypted using the user's password upon login.  The resulting clear surrogate key is then used for all encryption activity in their profile.

My issue is capturing the user's password during login while using an implementation of Spring Security per this tutorial:

Spring Boot MVC Spring Security Tutorial

My SecurityConfig class looks like this:

    /*
 * (non-Javadoc)
 *
 * @see org.springframework.security.config.annotation.web.configuration.
 * WebSecurityConfigurerAdapter#configure(org.springframework.security.
 * config.annotation.web.builders.HttpSecurity)
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/login").permitAll()
            .antMatchers("/registration").permitAll().antMatchers("/accountverification/**").permitAll()
            .antMatchers("/secure/**").hasAuthority("MEMBER").anyRequest().authenticated().and().formLogin()
            .loginPage("/login").failureUrl("/login?error=true").defaultSuccessUrl("/secure/notes")
            .usernameParameter("email").passwordParameter("password").and().logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
            .exceptionHandling().accessDeniedPage("/access-denied");
}

And my login.html page like this (the important part):

<form th:action="@{/login}" method="POST" class="form-signin">

If I'm understanding things correctly, the login.html page is posting to /login, which is defined in my SecurityConfig class (above).  Login itself works wonderfully.

However, this automatically bypasses the part of my flow where I'd decrypt that surrogate key.  So, I first tried posting to a separate controller then forwarding that request on to /login.  No dice.

I then tried extending HandleInterceptorAdapter, but found that the password at this point was still always null.  That led me to this post:

UserDetails getPassword returns null in spring security 3.1...

... but that struck me as hackey.

So, in the end, I'm still wondering how I might go about grabbing the password during the post of a login screen for temporary use of decrypting a user's surrogate key... then when the decryption is done and login completes... destroying it.

Any help is appreciated!

Body:
I knew this would happen... as soon as I post some fancy question on StackOverflow I'd figure it out.

I'm not sure it's the most elegant solution, but it works.  I'm certainly open to alternatives.

I added this method to my login controller:

/**
 * @return
 */
@RequestMapping(value = { "/loginProcessor" }, method = RequestMethod.POST)
public String loginProcessor(@ModelAttribute Login login) {
    System.out.println("PASSWORD: " + login.getPassword());
    return "forward:/login";
}

I then adjusted login.html to post to it, instead of to /login:

<form th:action="@{/loginProcessor}" method="POST" class="form-signin">

And I updated my SecurityConfig to accommodate both paths:

/*
 * (non-Javadoc)
 *
 * @see org.springframework.security.config.annotation.web.configuration.
 * WebSecurityConfigurerAdapter#configure(org.springframework.security.
 * config.annotation.web.builders.HttpSecurity)
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/loginProcessor").permitAll()
            .antMatchers("/login").permitAll().antMatchers("/registration").permitAll()
            .antMatchers("/accountverification/**").permitAll().antMatchers("/secure/**").hasAuthority("MEMBER")
            .anyRequest().authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error=true")
            .defaultSuccessUrl("/secure/notes").usernameParameter("email").passwordParameter("password").and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
            .exceptionHandling().accessDeniedPage("/access-denied");
}

Et, voila!  The password printed, I was logged in and redirected to my profile page.  Is there a better way?


问:
Splitting a list element by a separator | 'Can't convert 'list' object to str implicitly' error (Python)
I have a list json_data:

```<code>> print(json_data)
> ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']
</code>```

I need to split those elements with '/', '&' or 'and' into two different elements. The result I am looking for should look like this:

```<code>>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc' , 'osc']
</code>```

The code is:

```<code>separators = ['/', 'and', '&']

titles = []
for i in json_data:
    titles.extend([t.strip() for t in i.split(separators)
                  if i.strip() != ''])
</code>```

When running it, I am getting an error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-d0db85078f05> in <module>()
      5 titles = []
      6 for i in json_data:
----> 7     titles.extend([t.strip() for t in i.split(separators)
      8                   if i.strip() != ''])

TypeError: Can't convert 'list' object to str implicitly
</code>```

How can this be fixed?

答:
Regex is your friend:

```<code>>>> import re
>>> pat = re.compile("[/&]|and")
>>> json_data = ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']
>>> titles = []
>>> for i in json_data:
...   titles.extend([x.strip() for x in pat.split(i)])
...
>>> titles
['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc', 'osc']
</code>```

This line noise: re.compile("[/&]|and") means "create a regular expression matching either [/&] or the word 'and'". [/&] of course matches either / or &.
Having that in hand, pat.split(i) just splits the string i on anything matching pat.

LATE EDIT:
Realized that of course we can skip the strip() step by complicating the regex a little. If we have the regex "\s[/&]\s|\sand\s" then of course we match any whitespace before or after the basic matched elements. This means that splitting on this pattern removes the excess whitespace, and in addition it prevents us from splitting in the middle of a word like "sandwich", should that happen to appear in our data:

```<code>>>> pat = re.compile("\s[/&]\s|\sand\s")
>>> pat.split("beans and rice and sandwiches")
['beans', 'rice', 'sandwiches']
>>>
</code>```

This simplifies the construction of the list, since we no longer need to strip the whitespace from the results of the split, which incidentally saves us some looping. Given the new pattern, we can write it this way:

```<code>>>> titles = []
>>> for i in json_data:
...   titles.extend(pat.split(i))
...
</code>```

Body:
I have a list json_data:

> print(json_data)
> ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']

I need to split those elements with '/', '&' or 'and' into two different elements. The result I am looking for should look like this:

>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc' , 'osc']

The code is:

separators = ['/', 'and', '&']

titles = []
for i in json_data:
    titles.extend([t.strip() for t in i.split(separators)
                  if i.strip() != ''])

When running it, I am getting an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-d0db85078f05> in <module>()
      5 titles = []
      6 for i in json_data:
----> 7     titles.extend([t.strip() for t in i.split(separators)
      8                   if i.strip() != ''])

TypeError: Can't convert 'list' object to str implicitly

How can this be fixed?

Body:
Regex is your friend:

>>> import re
>>> pat = re.compile("[/&]|and")
>>> json_data = ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']
>>> titles = []
>>> for i in json_data:
...   titles.extend([x.strip() for x in pat.split(i)])
...
>>> titles
['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc', 'osc']

This line noise: re.compile("[/&]|and") means "create a regular expression matching either [/&] or the word 'and'". [/&] of course matches either / or &.
Having that in hand, pat.split(i) just splits the string i on anything matching pat.

LATE EDIT:
Realized that of course we can skip the strip() step by complicating the regex a little. If we have the regex "\s[/&]\s|\sand\s" then of course we match any whitespace before or after the basic matched elements. This means that splitting on this pattern removes the excess whitespace, and in addition it prevents us from splitting in the middle of a word like "sandwich", should that happen to appear in our data:

>>> pat = re.compile("\s[/&]\s|\sand\s")
>>> pat.split("beans and rice and sandwiches")
['beans', 'rice', 'sandwiches']
>>>

This simplifies the construction of the list, since we no longer need to strip the whitespace from the results of the split, which incidentally saves us some looping. Given the new pattern, we can write it this way:

>>> titles = []
>>> for i in json_data:
...   titles.extend(pat.split(i))
...


问:
Azure Media Services Stream Partial Content
I'm thinking to use Azure Media Services to store media files, mainly songs.
I then want to stream only the first 20-30 seconds of the songs to users.

Can this be done?

Thanks for your help

答:
The answer is Filters and dynamic manifests

You can define filters for your assets with Media Services. Starting with 2.11 release, Media Services enables you to define filters for your assets. These filters are server-side rules that help your customers do things like play a specific section of a video or specify a subset of audio and video renditions that your customer's device can handle (instead of all the renditions that are associated with the asset).

This filtering is achieved through dynamic manifests that are created when your customer requests to stream a video based on one or more specified filters.

For more information, see Filters and dynamic manifests:

https://learn.microsoft.com/en-us/azure/media-services/media-services-dynamic-manifest-overview

Also, you can use Media Services .NET SDK to create, update, and delete filters.

Note: if you update a filter, it can take up to 2 minutes for streaming endpoint to refresh the rules. If the content was served using this filter (and cached in proxies and CDN caches), updating this filter can result in player failures. It is recommending to clear the cache after updating the filter. If this option is not possible, consider using a different filter.

Create/Update/Read/Delete global filters

The following code shows how to use .NET to create, update,read, and delete asset filters.

```<code>string filterName = "GlobalFilter_" + Guid.NewGuid().ToString();

List<FilterTrackSelectStatement> filterTrackSelectStatements = new List<FilterTrackSelectStatement>();

FilterTrackSelectStatement filterTrackSelectStatement = new FilterTrackSelectStatement();
filterTrackSelectStatement.PropertyConditions = new List<IFilterTrackPropertyCondition>();
filterTrackSelectStatement.PropertyConditions.Add(new FilterTrackNameCondition("Track Name", FilterTrackCompareOperator.NotEqual));
filterTrackSelectStatement.PropertyConditions.Add(new FilterTrackBitrateRangeCondition(new FilterTrackBitrateRange(0, 1), FilterTrackCompareOperator.NotEqual));
filterTrackSelectStatement.PropertyConditions.Add(new FilterTrackTypeCondition(FilterTrackType.Audio, FilterTrackCompareOperator.NotEqual));
filterTrackSelectStatements.Add(filterTrackSelectStatement);

// Create
IStreamingFilter filter = _context.Filters.Create(filterName, new PresentationTimeRange(), filterTrackSelectStatements);

// Update
filter.PresentationTimeRange = new PresentationTimeRange(timescale: 500);
filter.Update();

// Read
var filterUpdated = _context.Filters.FirstOrDefault();
Console.WriteLine(filterUpdated.Name);

// Delete
filter.Delete();
</code>```

Create/Update/Read/Delete asset filters

The following code shows how to use .NET to create, update,read, and delete asset filters.

```<code>string assetName = "AssetFilter_" + Guid.NewGuid().ToString();
var asset = _context.Assets.Create(assetName, AssetCreationOptions.None);

string filterName = "AssetFilter_" + Guid.NewGuid().ToString();

// Create
IStreamingAssetFilter filter = asset.AssetFilters.Create(filterName,
                                    new PresentationTimeRange(),
                                    new List<FilterTrackSelectStatement>());

// Update
filter.PresentationTimeRange =
        new PresentationTimeRange(start: 6000000000, end: 72000000000);

filter.Update();

// Read
asset = _context.Assets.Where(c => c.Id == asset.Id).FirstOrDefault();
var filterUpdated = asset.AssetFilters.FirstOrDefault();
Console.WriteLine(filterUpdated.Name);

// Delete
filterUpdated.Delete();
</code>```

For more information please refer: https://learn.microsoft.com/en-us/azure/media-services/media-services-dotnet-dynamic-manifest

Body:
The answer is Filters and dynamic manifests

You can define filters for your assets with Media Services. Starting with 2.11 release, Media Services enables you to define filters for your assets. These filters are server-side rules that help your customers do things like play a specific section of a video or specify a subset of audio and video renditions that your customer's device can handle (instead of all the renditions that are associated with the asset).

This filtering is achieved through dynamic manifests that are created when your customer requests to stream a video based on one or more specified filters.

For more information, see Filters and dynamic manifests:

https://learn.microsoft.com/en-us/azure/media-services/media-services-dynamic-manifest-overview

Also, you can use Media Services .NET SDK to create, update, and delete filters.

Note: if you update a filter, it can take up to 2 minutes for streaming endpoint to refresh the rules. If the content was served using this filter (and cached in proxies and CDN caches), updating this filter can result in player failures. It is recommending to clear the cache after updating the filter. If this option is not possible, consider using a different filter.

Create/Update/Read/Delete global filters

The following code shows how to use .NET to create, update,read, and delete asset filters.

string filterName = "GlobalFilter_" + Guid.NewGuid().ToString();

List<FilterTrackSelectStatement> filterTrackSelectStatements = new List<FilterTrackSelectStatement>();

FilterTrackSelectStatement filterTrackSelectStatement = new FilterTrackSelectStatement();
filterTrackSelectStatement.PropertyConditions = new List<IFilterTrackPropertyCondition>();
filterTrackSelectStatement.PropertyConditions.Add(new FilterTrackNameCondition("Track Name", FilterTrackCompareOperator.NotEqual));
filterTrackSelectStatement.PropertyConditions.Add(new FilterTrackBitrateRangeCondition(new FilterTrackBitrateRange(0, 1), FilterTrackCompareOperator.NotEqual));
filterTrackSelectStatement.PropertyConditions.Add(new FilterTrackTypeCondition(FilterTrackType.Audio, FilterTrackCompareOperator.NotEqual));
filterTrackSelectStatements.Add(filterTrackSelectStatement);

// Create
IStreamingFilter filter = _context.Filters.Create(filterName, new PresentationTimeRange(), filterTrackSelectStatements);

// Update
filter.PresentationTimeRange = new PresentationTimeRange(timescale: 500);
filter.Update();

// Read
var filterUpdated = _context.Filters.FirstOrDefault();
Console.WriteLine(filterUpdated.Name);

// Delete
filter.Delete();

Create/Update/Read/Delete asset filters

The following code shows how to use .NET to create, update,read, and delete asset filters.

string assetName = "AssetFilter_" + Guid.NewGuid().ToString();
var asset = _context.Assets.Create(assetName, AssetCreationOptions.None);

string filterName = "AssetFilter_" + Guid.NewGuid().ToString();

// Create
IStreamingAssetFilter filter = asset.AssetFilters.Create(filterName,
                                    new PresentationTimeRange(),
                                    new List<FilterTrackSelectStatement>());

// Update
filter.PresentationTimeRange =
        new PresentationTimeRange(start: 6000000000, end: 72000000000);

filter.Update();

// Read
asset = _context.Assets.Where(c => c.Id == asset.Id).FirstOrDefault();
var filterUpdated = asset.AssetFilters.FirstOrDefault();
Console.WriteLine(filterUpdated.Name);

// Delete
filterUpdated.Delete();

For more information please refer: https://learn.microsoft.com/en-us/azure/media-services/media-services-dotnet-dynamic-manifest


问:
Send data from Android app with email
I just started with Android development and my first project is to create app for packing and moving company. I've created the form and wanted to send data to the email of an employee. I used this code:

```<code>Intent i = new Intent(Intent.ACTION_SEND);
i.setData(Uri.parse("email"));
String[] s={"abc@gmail.com","xyz@gmail.com"};
i.putExtra(Intent.EXTRA_EMAIL,s);
i.putExtra(Intent.EXTRA_SUBJECT,"This is a Subject");
i.putExtra(Intent.EXTRA_TEXT,"Hii This is the Email Body");
i.setType("message/rfc822");
Intent chooser = Intent.createChooser(i,"Launch Email");
startActivity(chooser);
</code>```

But the problem is user is prompted with option gmail and email and at last he/she also needs to click on send button. But I don't want that. Instead I want the data to be sent without any prompt. Please help!

答:
GmailBackground is small library to send an email in background without user interaction :

Usage:

```<code>    BackgroundMail.newBuilder(this)
            .withUsername("username@gmail.com")
            .withPassword("password12345")
            .withMailto("toemail@gmail.com")
            .withType(BackgroundMail.TYPE_PLAIN)
            .withSubject("this is the subject")
            .withBody("this is the body")
            .withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
                @Override
                public void onSuccess() {
                    //do some magic
                }
            })
            .withOnFailCallback(new BackgroundMail.OnFailCallback() {
                @Override
                public void onFail() {
                    //do some magic
                }
            })
            .send();
</code>```

Source

(I've tested it myself)

Title: Send data from Android app with email

Body:
I just started with Android development and my first project is to create app for packing and moving company. I've created the form and wanted to send data to the email of an employee. I used this code:

Intent i = new Intent(Intent.ACTION_SEND);
i.setData(Uri.parse("email"));
String[] s={"abc@gmail.com","xyz@gmail.com"};
i.putExtra(Intent.EXTRA_EMAIL,s);
i.putExtra(Intent.EXTRA_SUBJECT,"This is a Subject");
i.putExtra(Intent.EXTRA_TEXT,"Hii This is the Email Body");
i.setType("message/rfc822");
Intent chooser = Intent.createChooser(i,"Launch Email");
startActivity(chooser);

But the problem is user is prompted with option gmail and email and at last he/she also needs to click on send button. But I don't want that. Instead I want the data to be sent without any prompt. Please help!

Body:
GmailBackground is small library to send an email in background without user interaction :

Usage:

    BackgroundMail.newBuilder(this)
            .withUsername("username@gmail.com")
            .withPassword("password12345")
            .withMailto("toemail@gmail.com")
            .withType(BackgroundMail.TYPE_PLAIN)
            .withSubject("this is the subject")
            .withBody("this is the body")
            .withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
                @Override
                public void onSuccess() {
                    //do some magic
                }
            })
            .withOnFailCallback(new BackgroundMail.OnFailCallback() {
                @Override
                public void onFail() {
                    //do some magic
                }
            })
            .send();

Source

(I've tested it myself)


问:
invoking angular 2 ionic 2 app from another native app
we are having an app built using a mobile framework called MAF. we have another app built using angular 2/ionic 2. We want to launch this ng2/ionice 2 app from the app built using MAF.

For standard apps like instagram, facebook you can register a custom schema url like fb:// in your xcode. So the question is what do i do for my angular2 app which i will be using as custom schema to launch from MAF app?

答:
i found the answer here https://css-tricks.com/create-url-scheme/
all i did is just went to xcode version and added the custom url scheme</p>


问:
How to enumerate network interfaces and IP address on my mobile device
I am building a codenameone java client to communicate with a Java RMI server.
Can you advise how to enumerate the interfaces and Wi-Fi IP address on my destination mobile device?

I am looking for more details on what codenameone libs to use that provides the usual java.net methods, like
    Enumeration nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)) {
                String str = displayInterfaceInformation(netint);
                String IP1 = inc.getRowFromDelimitedStringSafe(str, 2, '~');
                System.out.println("IP = "+IP+" str = "+str);
            }

答:
Codename One doesn't support RMI. Mobile devices don't have the network interface API either as a mobile device won't have an ethernet port to choose from.

It's highly recommended you use HTTPS for communication or WebSockets since the mobile devices connect via cellular networks that might fail or filter "odd" traffic.


答:
You can try updating the permissions and ownership with the following commands from the projects root directory.

On Nginx / Homestead:

```<code>sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
</code>```

On Mac:

```<code>sudo chgrp -R _www storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
</code>```

If all else fails:

```<code>sudo chmod -R 777 storage bootstrap/cache
</code>```

Title: Laravel /public/home 500 (Internal Server Error)

Body:
My local laravel project starts with a

/public/home 500 (Internal Server Error)

in place of load all the view. Any suggestion?
I tried git stash to last commit, .htaccess modifications, clear view and caches but it's continues.

Body:
You can try updating the permissions and ownership with the following commands from the projects root directory.

On Nginx / Homestead:

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

On Mac:

sudo chgrp -R _www storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

If all else fails:

sudo chmod -R 777 storage bootstrap/cache


问:
My code gets the error expected ')'
I have tried to look for any curly brackets or parenthesis that don't have a pair but I can't find anything. Please let me know if you find the error or any other errors. The code is supposed to take the amount of minutes you take in the shower and turn it into the amount of bottles or water you used.

```<code>#include <stdio.h>
#include <cs50.h>

int main(void)

{
printf("Minutes: ");
int minutes = get_int();

if (minutes >0)
{
    int bottles = (128*(1.5*minutes)/16);
    printf("Bottles:%i \n "bottles);
}
else
{
    printf("Please type in a positive integer\n");
}

}
</code>```

Thanks for your help! :)

答:
Do u miss something in this line?</p>

```<code>    printf("Bottles:%i \n "bottles);
</code>```

Title: My code gets the error expected ')'

Body:
I have tried to look for any curly brackets or parenthesis that don't have a pair but I can't find anything. Please let me know if you find the error or any other errors. The code is supposed to take the amount of minutes you take in the shower and turn it into the amount of bottles or water you used.

#include <stdio.h>
#include <cs50.h>

int main(void)

{
printf("Minutes: ");
int minutes = get_int();

if (minutes >0)
{
    int bottles = (128*(1.5*minutes)/16);
    printf("Bottles:%i \n "bottles);
}
else
{
    printf("Please type in a positive integer\n");
}

}

Thanks for your help! :)

Body:
Do u miss something in this line?

    printf("Bottles:%i \n "bottles);


问:
Java Spring Boot Integration Tests Database Modification and Authentication
I have an integration test that tests a controller. I pass in a request and get a response back and the test passes. I however, before making the request, have to make a request to the /authenticate endpoint to retrieve a token so I can put it in the header of the request. I have 2 questions

The username and password I use locally validates against a dev LDAP server. As the application gets deployed to higher environments the LDAP endpoint changes to the respective level. So in environments higher than DEV the integration test will fail because that username/password combo won't work. So what is the best way to source the username/password to match the environment? Is there a better way to do this like forcing spring to forget about authentication entirely?

The integration test tests all the controller's endpoints like /add, /get etc. This unfortunately actually modifies the database (expected). Is there any way to run these tests but not actually modify the database?

答:
1) In your Unit test class, Use @TestPropertySource(properties = {"security.basic.enabled=false"}) to override your security setting or @TestPropertySource(locations="classpath:test.properties") if you want to use a totally different properties file testing.

2) You could use mocks, or if you don't want to use mocks in your integration tests, then you will have to clean the database after each test using something like this:

```<code>@After
public void tearDown() {
     cleanupDatabase();
 }
</code>```

Body:
1) In your Unit test class, Use @TestPropertySource(properties = {"security.basic.enabled=false"}) to override your security setting or @TestPropertySource(locations="classpath:test.properties") if you want to use a totally different properties file testing.

2) You could use mocks, or if you don't want to use mocks in your integration tests, then you will have to clean the database after each test using something like this:

@After
public void tearDown() {
     cleanupDatabase();
 }


问:
PDO json_encode in ternary operator
I am checking if the users information is in the database using

```<code>$usernameQuery->rowCount();
</code>```

but, I am also putting this code in a ternary operator and echoing the result, which is "false if its there and true if its not",  in json but its not working. I researched it and the information i found didn't help and doesn't have the ternary operator. Here is the code

PHP

```<code><?php

if($_SERVER['REQUEST_METHOD'] =="POST"){

    $email = $_POST['email'];
    $username = $_POST['username'];

    //if email and username is empty then do this
    if(!empty($email) && !empty($username)){

        //Connect to database
        try{

        // new php data object
        $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
        //ATTR_ERRMODE set to exception
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }catch(PDOException $e){
        die("There was an error connecting to the database");

    }

        //find email and username and Prepare
        $emailQuery = $handler->prepare( "SELECT * FROM app_signup WHERE email = ?");
        $usernameQuery = $handler->prepare("SELECT * FROM app_signup WHERE username = ?");

        //Execute;
        $emailQuery->execute(array($email));
        $usernameQuery->execute(array($username));

        //Check if the email is empty
        if(!empty($email)){

            echo "Test";
        }else{

            $nullResult = array();
            $nullResult['Email'] = (!empty($email))? "empty" : "";
            $nullResult['Username'] = ($usernameQuery->rowCount())? false: true;
            echo json_encode($nullResult);
            die("");
        }

    }else{

        $nullResult = array();
        $nullResult['Email'] = (empty($email))? "empty" : "";
        $nullResult['Username'] = (empty($username))? "empty" : "";
        echo json_encode($nullResult);
        exit();

    }

}

?>
</code>```

答:
Try this, i guess you are not checking the condition

```<code>$count = $usernameQuery->rowCount();

$nullResult['Username'] = (!empty($count)) ? true: false;
</code>```

And After Reading Your Question There is one thing also wrong, you are checking Two Column in Same table With Different Query, i think it should be like this if it's not required to be separate as your requirement

```<code>$data = $handler->prepare( "SELECT * FROM app_signup WHERE email = ? OR username = ?");

$data>execute(array($email,$username));
</code>```

Then Check

```<code>$nullResult = array();
$nullResult['Email'] = (!empty($data['email'])) ? $data['email'] : 'empty';
$nullResult['Username'] = (!empty($data->rowCount()) ? false : true;
</code>```

Here's a solution based on Detail you provided in Question, Hope this helps

```<code><?php

if($_SERVER['REQUEST_METHOD'] =="POST"){

    $email = $_POST['email'];
    $username = $_POST['username'];

    //if email and username is empty then do this
    if(!empty($email) && !empty($username)){

        //Connect to database
        try{

        // new php data object
        $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
        //ATTR_ERRMODE set to exception
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }catch(PDOException $e){
        die("There was an error connecting to the database");

    }

        //find email and username and Prepare
        $dataQuery = $handler->prepare( "SELECT * FROM app_signup WHERE email = ? OR username = ?");

        //Execute;
        $dataQuery->execute(array($email,$user));

        $count = $dataQuery->rowCount()
        //Check if the email is empty
        if(!empty($count)){
                echo "Test";
        }else{

            $nullResult = array();
            $nullResult['Email'] = (!empty($data['email'])) ? $data['email'] : 'empty';
            $nullResult['Username'] = (!empty($data->rowCount()) ? false : true;
            echo json_encode($nullResult);
            die("");
        }

    }else{

        $nullResult = array();
        $nullResult['Email'] = (empty($data['email']))? "empty" : "";
        $nullResult['Username'] = (empty($data['username']))? "empty" : "";
        echo json_encode($nullResult);
        exit();

    }

}
</code>```

Title: PDO json_encode in ternary operator

Body:
I am checking if the users information is in the database using

$usernameQuery->rowCount();

but, I am also putting this code in a ternary operator and echoing the result, which is "false if its there and true if its not",  in json but its not working. I researched it and the information i found didn't help and doesn't have the ternary operator. Here is the code

PHP

<?php

if($_SERVER['REQUEST_METHOD'] =="POST"){

    $email = $_POST['email'];
    $username = $_POST['username'];

    //if email and username is empty then do this
    if(!empty($email) && !empty($username)){

        //Connect to database
        try{

        // new php data object
        $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
        //ATTR_ERRMODE set to exception
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }catch(PDOException $e){
        die("There was an error connecting to the database");

    }

        //find email and username and Prepare
        $emailQuery = $handler->prepare( "SELECT * FROM app_signup WHERE email = ?");
        $usernameQuery = $handler->prepare("SELECT * FROM app_signup WHERE username = ?");

        //Execute;
        $emailQuery->execute(array($email));
        $usernameQuery->execute(array($username));

        //Check if the email is empty
        if(!empty($email)){

            echo "Test";
        }else{

            $nullResult = array();
            $nullResult['Email'] = (!empty($email))? "empty" : "";
            $nullResult['Username'] = ($usernameQuery->rowCount())? false: true;
            echo json_encode($nullResult);
            die("");
        }

    }else{

        $nullResult = array();
        $nullResult['Email'] = (empty($email))? "empty" : "";
        $nullResult['Username'] = (empty($username))? "empty" : "";
        echo json_encode($nullResult);
        exit();

    }

}

?>

Body:
Try this, i guess you are not checking the condition

$count = $usernameQuery->rowCount();

$nullResult['Username'] = (!empty($count)) ? true: false;

And After Reading Your Question There is one thing also wrong, you are checking Two Column in Same table With Different Query, i think it should be like this if it's not required to be separate as your requirement

$data = $handler->prepare( "SELECT * FROM app_signup WHERE email = ? OR username = ?");

$data>execute(array($email,$username));

Then Check

$nullResult = array();
$nullResult['Email'] = (!empty($data['email'])) ? $data['email'] : 'empty';
$nullResult['Username'] = (!empty($data->rowCount()) ? false : true;

Here's a solution based on Detail you provided in Question, Hope this helps

<?php

if($_SERVER['REQUEST_METHOD'] =="POST"){

    $email = $_POST['email'];
    $username = $_POST['username'];

    //if email and username is empty then do this
    if(!empty($email) && !empty($username)){

        //Connect to database
        try{

        // new php data object
        $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
        //ATTR_ERRMODE set to exception
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }catch(PDOException $e){
        die("There was an error connecting to the database");

    }

        //find email and username and Prepare
        $dataQuery = $handler->prepare( "SELECT * FROM app_signup WHERE email = ? OR username = ?");

        //Execute;
        $dataQuery->execute(array($email,$user));

        $count = $dataQuery->rowCount()
        //Check if the email is empty
        if(!empty($count)){
                echo "Test";
        }else{

            $nullResult = array();
            $nullResult['Email'] = (!empty($data['email'])) ? $data['email'] : 'empty';
            $nullResult['Username'] = (!empty($data->rowCount()) ? false : true;
            echo json_encode($nullResult);
            die("");
        }

    }else{

        $nullResult = array();
        $nullResult['Email'] = (empty($data['email']))? "empty" : "";
        $nullResult['Username'] = (empty($data['username']))? "empty" : "";
        echo json_encode($nullResult);
        exit();

    }

}


问:
identify the key in a dictionary that appears the maximum number of times, along with the number of times it appears
Hoping someone can help:
I created a dictionary named stat_pair, and am trying to return the key with the maximum number of occurrences, along with the number of times the key appears.
I'm new to Python & tried several approaches, but haven't been successful.
Any assistance would be appreciated.</p>

答:
Assuming that tied keys all count as the winner:</p>

```<code>keys_tied_for_most_occurences = [k for k in my_dict.keys()]
num_of_occurences = 1
</code>```

Body:
Assuming that tied keys all count as the winner:

keys_tied_for_most_occurences = [k for k in my_dict.keys()]
num_of_occurences = 1


问:
Detect smartphone type
I am building a web application that will manipulate images. ( crop and apply effects like sepia etc ).

Is there a library where i can detect ( front or backend ), the type of device the user is using ( middle level device or high end. ).

Example an ipad would be a high end device, a nexus 5 from 2013, would be a mid level device.

On an nexus 5 from 2013 i would compress the image in javascript so it is being handled without lag, however on an ipad there would be no reason to do that.

Thank you.

答:
The following link may be useful.

Refer to https://github.com/WhichBrowser/Parser

Title: Detect smartphone type


问:
How to change the Hello World Asterisk example to use TCP instead of UDP?
I setup Asterisk on a server.
I set up the basic "Hello, World" example (direct from the docs here) which entails having my extensions.conf file as:

```<code>[from-internal]
exten = 100,1,Answer()
same = n,Wait(1)
same = n,Playback(hello-world)
same = n,Hangup()
</code>```

and my pjsip.conf file as:

```<code>[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0

[6001]
type=endpoint
context=from-internal
disallow=all
allow=ulaw
auth=6001
aors=6001

[6001]
type=auth
auth_type=userpass
password=unsecurepassword
username=6001

[6001]
type=aor
max_contacts=1
</code>```

I have a simple Python script to make a call to the extension 100. This is direct from the docs here, where I call this script passing in the sip address sip:100@<my-sip-server-ip>:

```<code>import sys
import pjsua as pj

# Logging callback
def log_cb(level, str, len):
    print str,

# Callback to receive events from Call
class MyCallCallback(pj.CallCallback):
    def __init__(self, call=None):
        pj.CallCallback.__init__(self, call)

    # Notification when call state has changed
    def on_state(self):
        print "Call is ", self.call.info().state_text,
        print "last code =", self.call.info().last_code,
        print "(" + self.call.info().last_reason + ")"

    # Notification when call's media state has changed.
    def on_media_state(self):
        global lib
        if self.call.info().media_state == pj.MediaState.ACTIVE:
            # Connect the call to sound device
            call_slot = self.call.info().conf_slot
            lib.conf_connect(call_slot, 0)
            lib.conf_connect(0, call_slot)
            print "Hello world, I can talk!"

# Check command line argument
if len(sys.argv) != 2:
    print "Usage: simplecall.py <dst-URI>"
    sys.exit(1)

try:
    # Create library instance
    lib = pj.Lib()

    # Init library with default config
    lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))

    # Create UDP transport which listens to any available port
    transport = lib.create_transport(pj.TransportType.UDP)

    # Start the library
    lib.start()

    # Create local/user-less account
    acc = lib.create_account_for_transport(transport)

    # Make call
    call = acc.make_call(sys.argv[1], MyCallCallback())

    # Wait for ENTER before quitting
    print "Press <ENTER> to quit"
    input = sys.stdin.readline().rstrip("\r\n")

    # We're done, shutdown the library
    lib.destroy()
    lib = None

except pj.Error, e:
    print "Exception: " + str(e)
    lib.destroy()
    lib = None
    sys.exit(1)
</code>```

This all works fine, I call the SIP server, and hear the "Hello, World" recording.

What do I need to change so that I can have this communication occur over TCP?
So far I have tried changing my pjsip.conf file by changing the protocol to tcp in the following part:

```<code>[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0
</code>```

, adding ;transport=tcp to the URI of my server that I pass in to the Python script, and also changing the line in the Python script that creates a Transport to

```<code># Create UDP transport which listens to any available port
transport = lib.create_transport(pj.TransportType.UDP)
</code>```

What happens is in the Python script I get

```<code>pjsua_acc.c !...SIP registration failed, status=408 (Request Timeout)
</code>```

And on the server I don't see the request at all.

答:
Are you sure that your Asterisk is using pjsip? Old versions (below v.11) are using sip.conf and not pjsip.conf.

You need to enable tcp globally in sip.conf:

```<code>[general]
tcpenable=yes
tcpbindaddr=0.0.0.0
</code>```

If you are on a new Asterisk, then add this to pjsip.conf:

```<code>[transport-tcp]
type=transport
protocol=tcp
bind=0.0.0.0:5060

[transport-tcp-out]
type=transport
protocol=tcp
bind=0.0.0.0:5060
#local_net=192.168.X.X/XX   //you might also set this
</code>```

Body:
I setup Asterisk on a server.
I set up the basic "Hello, World" example (direct from the docs here) which entails having my extensions.conf file as:

[from-internal]
exten = 100,1,Answer()
same = n,Wait(1)
same = n,Playback(hello-world)
same = n,Hangup()

and my pjsip.conf file as:

[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0

[6001]
type=endpoint
context=from-internal
disallow=all
allow=ulaw
auth=6001
aors=6001

[6001]
type=auth
auth_type=userpass
password=unsecurepassword
username=6001

[6001]
type=aor
max_contacts=1

I have a simple Python script to make a call to the extension 100. This is direct from the docs here, where I call this script passing in the sip address sip:100@<my-sip-server-ip>:

import sys
import pjsua as pj

# Logging callback
def log_cb(level, str, len):
    print str,

# Callback to receive events from Call
class MyCallCallback(pj.CallCallback):
    def __init__(self, call=None):
        pj.CallCallback.__init__(self, call)

    # Notification when call state has changed
    def on_state(self):
        print "Call is ", self.call.info().state_text,
        print "last code =", self.call.info().last_code,
        print "(" + self.call.info().last_reason + ")"

    # Notification when call's media state has changed.
    def on_media_state(self):
        global lib
        if self.call.info().media_state == pj.MediaState.ACTIVE:
            # Connect the call to sound device
            call_slot = self.call.info().conf_slot
            lib.conf_connect(call_slot, 0)
            lib.conf_connect(0, call_slot)
            print "Hello world, I can talk!"

# Check command line argument
if len(sys.argv) != 2:
    print "Usage: simplecall.py <dst-URI>"
    sys.exit(1)

try:
    # Create library instance
    lib = pj.Lib()

    # Init library with default config
    lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))

    # Create UDP transport which listens to any available port
    transport = lib.create_transport(pj.TransportType.UDP)

    # Start the library
    lib.start()

    # Create local/user-less account
    acc = lib.create_account_for_transport(transport)

    # Make call
    call = acc.make_call(sys.argv[1], MyCallCallback())

    # Wait for ENTER before quitting
    print "Press <ENTER> to quit"
    input = sys.stdin.readline().rstrip("\r\n")

    # We're done, shutdown the library
    lib.destroy()
    lib = None

except pj.Error, e:
    print "Exception: " + str(e)
    lib.destroy()
    lib = None
    sys.exit(1)

This all works fine, I call the SIP server, and hear the "Hello, World" recording.

What do I need to change so that I can have this communication occur over TCP?
So far I have tried changing my pjsip.conf file by changing the protocol to tcp in the following part:

[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0

, adding ;transport=tcp to the URI of my server that I pass in to the Python script, and also changing the line in the Python script that creates a Transport to

# Create UDP transport which listens to any available port
transport = lib.create_transport(pj.TransportType.UDP)

What happens is in the Python script I get

pjsua_acc.c !...SIP registration failed, status=408 (Request Timeout)

And on the server I don't see the request at all.

Body:
Are you sure that your Asterisk is using pjsip? Old versions (below v.11) are using sip.conf and not pjsip.conf.

You need to enable tcp globally in sip.conf:

[general]
tcpenable=yes
tcpbindaddr=0.0.0.0

If you are on a new Asterisk, then add this to pjsip.conf:

[transport-tcp]
type=transport
protocol=tcp
bind=0.0.0.0:5060

[transport-tcp-out]
type=transport
protocol=tcp
bind=0.0.0.0:5060
#local_net=192.168.X.X/XX   //you might also set this


问:
position absolute with content below
I want the div class content always visible no matter what height of the  div class banner-text-container on all screens. banner-text-container got dynamic contents inside so its height is not fixed. The requirement is those blue boxes are half on the img-banner-container div and half on the content div. Is there any way to deal with it by css or js?

h1,
h2 {
  text-align: center;
}

.img-banner-container {
  position: relative;
  color: #ffffff!important;
  /*margin-bottom: 200px;*/
  background-image: linear-gradient( rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url("http://www.lanlinglaurel.com/data/out/162/5403600-wallpaper-hd.jpeg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  /*height: auto;*/
  width: 100%;
  height: 1000px;
}

.banner-text-container {
  position: absolute;
  top: 40%;
  z-index: 10;
}

.banner-text-content {
  padding: 0 20%;
  margin-bottom: 30px;
}

/*.content-with-nav-boxes {*/

/*background-color: white;*/

/*position: relative;*/

/*padding: 0 10%;*/

/*margin-bottom: 50px;*/

/*height: 500px;*/

/*width: 100%;*/

/*overflow-x: hidden;*/

/*}*/

.small-nav-boxes {
  /*padding: 0 10%;*/
  /*clear: both;*/
  width: 100%;
}

.small-nav-boxes .single-nav-box {
  text-align: center;
  color: white;
  width: 33.33%!important;
  float: left!important;
}

.single-nav-box {
  padding: 10px 0;
  cursor: pointer;
  height: 300px;
  overflow: hidden;
  background-color: #0091CF;
}

.content {
  background-color: #4C4145;
  color: white;
}

@media screen and (max-width: 1024px) {
  .small-nav-boxes .single-nav-box {
    width: 100%!important;
    float: none!important;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img-banner-container">
  <div class="banner-text-container">
    <h1 class="banner-text-title">
      Lorem Ipsum
    </h1>
    <div class="banner-text-content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. In purus leo, blandit sit amet hendrerit non, lobortis id arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam tempor eu urna vitae aliquam. Donec convallis
      ullamcorper massa. Nam interdum pulvinar libero, a lobortis nunc congue eu. Vestibulum vel elit et metus feugiat faucibus. Ut aliquet dui leo, quis imperdiet quam tincidunt sit amet. Etiam sed nibh efficitur, tincidunt justo a, dapibus dui. In quam
      ipsum, dapibus id convallis vulputate, porttitor et erat. Vivamus eget tellus sit amet nulla aliquet pharetra. Cras sed lorem euismod, maximus urna non, condimentum lacus. Nullam eleifend nunc eget magna ultrices eleifend.
      <br/> Aliquam vel porta quam. Sed a blandit purus. Proin non magna in enim aliquam mollis. Quisque lacus ex, ultrices id nulla scelerisque, suscipit congue risus. Mauris tincidunt gravida semper. Fusce a consectetur lorem. Praesent molestie consequat
      leo, vel egestas mi mollis eu. Quisque non pharetra orci, vitae dapibus sem. Sed pharetra facilisis interdum. Aenean a posuere lorem, et bibendum augue. Vestibulum quis auctor tortor. Suspendisse porta facilisis erat et dignissim. Nulla commodo
      enim tellus, eget vestibulum felis bibendum vel. In semper erat id lacus venenatis tincidunt. Sed a nulla quis leo porttitor porta.
      <br/> Proin erat ipsum, vestibulum ac lacus a, luctus gravida arcu. Curabitur tincidunt varius finibus. Suspendisse at nibh erat. Sed in lobortis mi, in lobortis felis. Phasellus tincidunt tincidunt porta. Nulla non ipsum ullamcorper, egestas dui
      in, rhoncus orci. Nulla malesuada mauris nec nibh porta facilisis. Etiam finibus purus non ex accumsan, accumsan lacinia lectus rutrum. Etiam molestie neque id lectus condimentum ullamcorper. Quisque nunc nisl, venenatis vel diam vitae, facilisis
      pharetra massa. Curabitur fringilla mollis vulputate. Donec fermentum lorem felis.
      <br/>
    </div>
    <div class="small-nav-boxes">
      <div class="single-nav-box">
        <p>What is Lorem Ipsum?</p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
        survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
        publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      </div>
      <div class="single-nav-box">
        <p>Why do we use it?</p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
        survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
        publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      </div>
      <div class="single-nav-box">
        <p>What is Lorem Ipsum?</p>
        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here,
        content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various
        versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
      </div>
    </div>
  </div>
</div>

<div class="content">
  <h2>Where does it come from?</h2>
  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
  one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
  et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
  1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English
  versions from the 1914 translation by H. Rackham.
</div></code>```

答:
Your question is a little vague, but I understood more from looking at your code directly.

It seems to me that you're using absolute positioning where is not needed, and also using way too many !important declarations when you should almost-never use them.

I modified your code to keep the "content" block present at all times. If the content above it will change its size due to dynamically generated content, then it should grow naturally and follow the flow of the page. No need to set heights or use absolute positioning.

Here is your CSS, modified: https://jsfiddle.net/ronaldpoi/e434hy5w/

EDIT: With more information about the desired outcome, I updated the code. In this scenario you do have to use absolute positioning to control the elements. You'll also need to add html markup to make it possible. I updated my code in the Jsfiddle.

Here is the second modification: https://jsfiddle.net/ronaldpoi/e434hy5w/1/

* {
  box-sizing: border-box;
}

h1,
h2 {
  text-align: center;
}

.img-banner-container {
  color: #fff;
  background-image: linear-gradient( rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url("http://www.lanlinglaurel.com/data/out/162/5403600-wallpaper-hd.jpeg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  padding-bottom: 180px;
}

.banner-text-container {
  padding: 20px;
  max-width: 960px;
  margin: 0 auto;
}

.small-nav-boxes-container {
  position: relative;
  height: 0;
}

.small-nav-boxes {
  max-width: 960px;
  margin: 0 auto;
  position: absolute;
  left: 50%;
  margin-left: -480px;
  transform: translateY(-50%);
}

.single-nav-box {
  text-align: center;
  width: 33%;
  background-color: #0091CF;
  overflow: hidden;
  display: inline-block;
  padding: 20px;
}

.content {
  background-color: #4C4145;
  color: #fff;
  padding-top: 180px;
}```

Title: position absolute with content below

Body:
I want the div class content always visible no matter what height of the  div class banner-text-container on all screens. banner-text-container got dynamic contents inside so its height is not fixed. The requirement is those blue boxes are half on the img-banner-container div and half on the content div. Is there any way to deal with it by css or js?

h1,
h2 {
  text-align: center;
}

.img-banner-container {
  position: relative;
  color: #ffffff!important;
  /*margin-bottom: 200px;*/
  background-image: linear-gradient( rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url("http://www.lanlinglaurel.com/data/out/162/5403600-wallpaper-hd.jpeg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  /*height: auto;*/
  width: 100%;
  height: 1000px;
}

.banner-text-container {
  position: absolute;
  top: 40%;
  z-index: 10;
}

.banner-text-content {
  padding: 0 20%;
  margin-bottom: 30px;
}

/*.content-with-nav-boxes {*/

/*background-color: white;*/

/*position: relative;*/

/*padding: 0 10%;*/

/*margin-bottom: 50px;*/

/*height: 500px;*/

/*width: 100%;*/

/*overflow-x: hidden;*/

/*}*/

.small-nav-boxes {
  /*padding: 0 10%;*/
  /*clear: both;*/
  width: 100%;
}

.small-nav-boxes .single-nav-box {
  text-align: center;
  color: white;
  width: 33.33%!important;
  float: left!important;
}

.single-nav-box {
  padding: 10px 0;
  cursor: pointer;
  height: 300px;
  overflow: hidden;
  background-color: #0091CF;
}

.content {
  background-color: #4C4145;
  color: white;
}

@media screen and (max-width: 1024px) {
  .small-nav-boxes .single-nav-box {
    width: 100%!important;
    float: none!important;
  }
}

      Lorem Ipsum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. In purus leo, blandit sit amet hendrerit non, lobortis id arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam tempor eu urna vitae aliquam. Donec convallis
      ullamcorper massa. Nam interdum pulvinar libero, a lobortis nunc congue eu. Vestibulum vel elit et metus feugiat faucibus. Ut aliquet dui leo, quis imperdiet quam tincidunt sit amet. Etiam sed nibh efficitur, tincidunt justo a, dapibus dui. In quam
      ipsum, dapibus id convallis vulputate, porttitor et erat. Vivamus eget tellus sit amet nulla aliquet pharetra. Cras sed lorem euismod, maximus urna non, condimentum lacus. Nullam eleifend nunc eget magna ultrices eleifend.

 Aliquam vel porta quam. Sed a blandit purus. Proin non magna in enim aliquam mollis. Quisque lacus ex, ultrices id nulla scelerisque, suscipit congue risus. Mauris tincidunt gravida semper. Fusce a consectetur lorem. Praesent molestie consequat
      leo, vel egestas mi mollis eu. Quisque non pharetra orci, vitae dapibus sem. Sed pharetra facilisis interdum. Aenean a posuere lorem, et bibendum augue. Vestibulum quis auctor tortor. Suspendisse porta facilisis erat et dignissim. Nulla commodo
      enim tellus, eget vestibulum felis bibendum vel. In semper erat id lacus venenatis tincidunt. Sed a nulla quis leo porttitor porta.

 Proin erat ipsum, vestibulum ac lacus a, luctus gravida arcu. Curabitur tincidunt varius finibus. Suspendisse at nibh erat. Sed in lobortis mi, in lobortis felis. Phasellus tincidunt tincidunt porta. Nulla non ipsum ullamcorper, egestas dui
      in, rhoncus orci. Nulla malesuada mauris nec nibh porta facilisis. Etiam finibus purus non ex accumsan, accumsan lacinia lectus rutrum. Etiam molestie neque id lectus condimentum ullamcorper. Quisque nunc nisl, venenatis vel diam vitae, facilisis
      pharetra massa. Curabitur fringilla mollis vulputate. Donec fermentum lorem felis.

What is Lorem Ipsum?

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
        survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
        publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
        survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
        publishing software like Aldus PageMaker including versions of Lorem Ipsum.

What is Lorem Ipsum?

        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here,
        content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various
        versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?

  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
  one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
  et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
  1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English
  versions from the 1914 translation by H. Rackham.


问:
Missing pages in woocommerce
When I click on "install all missing woocommerce pages" in System status it gives me an ERROR: options page not found.
https://www.freshmorrow.com/wp-admin/options.php</p>

答:
That url (/wp-admin/options.php) isn't going to do much without a login.

Can you ftp into your directory and check if they are there?

It should be somewhere like:

```<code>/wp-content/plugins/woocommerce
</code>```

You also could delete the plugin and reinstall it?

Edit: didn't read close enough.

make sure the file /wp-admin/options.php exists as well

Title: Missing pages in woocommerce

Body:
That url (/wp-admin/options.php) isn't going to do much without a login.

Can you ftp into your directory and check if they are there?

It should be somewhere like:

/wp-content/plugins/woocommerce

You also could delete the plugin and reinstall it?

Edit: didn't read close enough.

make sure the file /wp-admin/options.php exists as well


问:
Change Date format MM-DD-YYYY to MM/DD/YYYY in macro VBA
I tried using format function as below

let the startdate = "06-05-2017"

End Date = format (startdate," MM/DD/YYYY"), but it is not getting changed.
End Date is still showing as 06-05-2017.
Please help me know what is wrong here.

Thanks !!

答:
Excel probably does not recognise the start date as a date, but as text. You need to work out what your system's default date format is. To do that, you can type this in the immediate window:

```<code>?date
</code>```

The returned result shows in the date format you need to use to assign a value to your start date variable. On my computer I need to use dd/mm/yyyy, so for me, this code works:

```<code>Sub test()
Dim startdate As Date
Dim enddate As String
startdate = "24/12/2017"
enddate = Format(startdate, "mm/dd/yyy")
Debug.Print enddate ' will show as 12/24/2017
End Sub
</code>```

Body:
Excel probably does not recognise the start date as a date, but as text. You need to work out what your system's default date format is. To do that, you can type this in the immediate window:

?date

The returned result shows in the date format you need to use to assign a value to your start date variable. On my computer I need to use dd/mm/yyyy, so for me, this code works:

Sub test()
Dim startdate As Date
Dim enddate As String
startdate = "24/12/2017"
enddate = Format(startdate, "mm/dd/yyy")
Debug.Print enddate ' will show as 12/24/2017
End Sub


问:
Get error year by using NSDateFormatter transform NSDate to NSString
```<code>NSDate *date = [NSDate date];
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = NSLocalizedString(@"yyyy-MM-dd", nil);
return [formatter stringFromDate:date];
</code>```

Today is "2017-06-09", but the result is "0029-06-09" on the user's iphone. How can I fix it?

答:
Try to set your local to NSDateFormatter</p>

```<code>    [formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:"jp"];
</code>```

Body:
NSDate *date = [NSDate date];
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = NSLocalizedString(@"yyyy-MM-dd", nil);
return [formatter stringFromDate:date];

Today is "2017-06-09", but the result is "0029-06-09" on the user's iphone. How can I fix it?

Body:
Try to set your local to NSDateFormatter

    [formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:"jp"];


问:
Buttons shift downwards in android studio when text excedes 1 line
I am trying to put a bunch of buttons in a Grid Layout, and all of the buttons look fine until I put enough text in one for the text to move on to another line. The button that has 2 lines of text shifts down 10dp.

Button is shifted down

The first button is one that is in the right spot, the second is shifted down.

```<code><Button
    android:id="@+id/flavButt2"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginEnd="10dp"
    android:layout_marginRight="10dp"
    android:text="Flavor2" />

<Button
    android:id="@+id/flavButt3"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginEnd="10dp"
    android:layout_marginRight="10dp"
    android:text="Cookies n Cream" />
</code>```

I was able to get the button to go back to the right spot by setting the top margin to -10dp, but that becomes a pain if I need to change the text on the buttons.

Why is the location even changing? I am still new to Android Studio.

答:
Try to give it a layout_gravity; This kind of gravity is to set it in relation to its parent. There's other kind, and its gravity... so when you use a gravity attribute, its gonna be applied just to its children.

```<code>        <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="top"
        android:text="Lorem ipsum dolor sit amet. lorem...."/>
</code>```

Body:
I am trying to put a bunch of buttons in a Grid Layout, and all of the buttons look fine until I put enough text in one for the text to move on to another line. The button that has 2 lines of text shifts down 10dp.

Button is shifted down

The first button is one that is in the right spot, the second is shifted down.

<Button
    android:id="@+id/flavButt2"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginEnd="10dp"
    android:layout_marginRight="10dp"
    android:text="Flavor2" />

<Button
    android:id="@+id/flavButt3"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginEnd="10dp"
    android:layout_marginRight="10dp"
    android:text="Cookies n Cream" />

I was able to get the button to go back to the right spot by setting the top margin to -10dp, but that becomes a pain if I need to change the text on the buttons.

Why is the location even changing? I am still new to Android Studio.

Body:
Try to give it a layout_gravity; This kind of gravity is to set it in relation to its parent. There's other kind, and its gravity... so when you use a gravity attribute, its gonna be applied just to its children.

        <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="top"
        android:text="Lorem ipsum dolor sit amet. lorem...."/>


问:
missing a temporary folder wordpress upload
I have a wordpress installed . Host provider is 1&1. Now if i tried to upload media file it show me the error missing a temporary folder . I also define a path fpr temp directory . I refer this link link . And created the php.ini file in the home directory . My php.ini file content is

```<code>upload_max_filesize = 16M
upload_tmp_dir = on
upload_tmp_dir = /epigram.co.uk/tmp
</code>```

I also tried to change wp-config file and added this

```<code>define('WP_TEMP_DIR','/epigram.co.uk/tmp');
</code>```

Also tried with full path . like

```<code>define('WP_TEMP_DIR',$_SERVER['DOCUMENT_ROOT'].'/tmp');
</code>```

Nothing helped me . any help will be appreciated .Thanks

答:
Add From Server plugin saved my time.
it's easy to use, just upload your image through ftp and use Add from sever plugin to import to your Media Library.</p>

Body:
I have a wordpress installed . Host provider is 1&1. Now if i tried to upload media file it show me the error missing a temporary folder . I also define a path fpr temp directory . I refer this link link . And created the php.ini file in the home directory . My php.ini file content is

upload_max_filesize = 16M
upload_tmp_dir = on
upload_tmp_dir = /epigram.co.uk/tmp

I also tried to change wp-config file and added this

define('WP_TEMP_DIR','/epigram.co.uk/tmp');

Also tried with full path . like

define('WP_TEMP_DIR',$_SERVER['DOCUMENT_ROOT'].'/tmp');

Nothing helped me . any help will be appreciated .Thanks