问:
Attribute not saving to Model in boot method
When creating a new model instance, the 'slug' attribute is not being saved. I checked that the creating event in the boot method is being called. However, in tinker, I can see that there is no 'slug' key in the attributes. What gives? For the life of me, I can't find my mistake.

Tinker:

```<code>App\Models\TicketType::create(['title'=>'My title']);

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'slug' doesn't have a default value (SQL: insert into `ticket_types` (`title`, `updated_at`, `created_at`) values (my title, 2017-11-16 08:13:17, 2017-11-16 08:13:17))'
</code>```

TicketType.php

```<code>namespace App\Models;

use App\Models\Abstracts\TypeModelAbstract;
use App\Models\Interfaces\TypeModelInterface;
use App\Traits\HasSlug;

class TicketType extends TypeModelAbstract implements TypeModelInterface {

    use HasSlug;

    protected $fillable = [
        'title',
        'slug',
        ...
    ];

    ...

    public static function boot() {

        parent::boot();

        static::creating(function ($item) {
            $item->sluggable();
            \Log::debug('slug is ' . $item->slug, $item->attributes);
            // Here $item->slug is correct, but the slug is not in the attributes array
        });
    }
</code>```

HasSlug.php

```<code>namespace App\Traits;

use Illuminate\Support\Facades\Cache;

trait HasSlug {

    public function sluggable() {
        if (!$this->getSlug()) {
            $slug = $this->buildSlug();
            $this->setSlug($slug);
        }
        return $this;
    }

    public function refreshSlug() {
        $this->setSlug($this->buildSlug());
        return $this;
    }

    protected function setSlug($slug) {
        // $save_to = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $save_to = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        $this->attributes[$save_to] = $slug;
        // $this->setAttribute($save_to, $slug);
        return $this;
    }

    /**
     * @return \Eloquent
     */
    public function getSlug() {
        // $save_to = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $save_to = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        // return $this->getAttribute($save_to);
        return $this->$save_to;
    }

    /**
     * @return string
     */
    protected static function getRand() {
        $length = 11;
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $size = strlen($chars);
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, $size - 1)];
        }
        return $str;
    }

    /**
     * @param string $str;
     * @return string;
     */
    protected function mod($str) {
        // if (static::$sluggable_uppercase ?? false ) {  -- PHP bug fixed in 7.0.19 and  7.1.5
        $uppercase = isset(static::$sluggable_uppercase) ? static::$sluggable_uppercase : false;
        if ( $uppercase ) {
            return strtoupper($str);
        } else {
            return $str;
        }
    }

    /**
     * @return string
     */
    protected function buildSlug() {
        // $attr = static::$sluggable_build_from_attribute ?? 'title'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $attr = isset(static::$sluggable_build_from_attribute) ? static::$sluggable_build_from_attribute : 'title';
        $string = $attr && $this->$attr ? $this->$attr : static::getRand();
        return $this->bestSlugFrom($string);
    }

    /**
     * @param string $string
     * @return string
     */
    public function bestSlugFrom($string) {
        $original = $slug = $this->mod(static::sluggify($string));
        $i = 1;
        while (static::findBySlug($slug, true)) {
            $slug = $original . '-' . $i;
            $i++;
        }
        return $slug;
    }

    /**
     * Sluggify a string
     * @param string $text
     * @return string
     */
    public static function sluggify($text) {
        $text = str_replace(array('#', 'ω'), array(' sharp', ' omega'), $text); // replace non letter or digits by -
        return str_slug($text);
    }

    /**
     * Get a model by the slug
     * @param string $slug
     * @param bool $includeTrashed
     * @return static
     */
    public static function findBySlug($slug, $includeTrashed = false ) {
        // $slugAttr = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $slugAttr = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        return Cache::remember( get_called_class() . "_bySlug_{$slug}_{$includeTrashed}", 1, function () use ($slug, $includeTrashed, $slugAttr) {
            $q = static::where($slugAttr ?? 'slug', $slug);
            if ( $includeTrashed && method_exists(get_called_class(), 'bootSoftDeletingTrait') ) {
                /* Make sure the model has soft deletes before calling this method */
                $q->withTrashed();
            }
            return $q->first();
        });
    }

}
</code>```

答: Doh! I had a getSlugAttribute($value) on an inherited trait. Thanks Hamoud!

Body:
When creating a new model instance, the 'slug' attribute is not being saved. I checked that the creating event in the boot method is being called. However, in tinker, I can see that there is no 'slug' key in the attributes. What gives? For the life of me, I can't find my mistake.

Tinker:

App\Models\TicketType::create(['title'=>'My title']);

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'slug' doesn't have a default value (SQL: insert into `ticket_types` (`title`, `updated_at`, `created_at`) values (my title, 2017-11-16 08:13:17, 2017-11-16 08:13:17))'

TicketType.php

namespace App\Models;

use App\Models\Abstracts\TypeModelAbstract;
use App\Models\Interfaces\TypeModelInterface;
use App\Traits\HasSlug;

class TicketType extends TypeModelAbstract implements TypeModelInterface {

    use HasSlug;

    protected $fillable = [
        'title',
        'slug',
        ...
    ];

    ...

    public static function boot() {

        parent::boot();

        static::creating(function ($item) {
            $item->sluggable();
            \Log::debug('slug is ' . $item->slug, $item->attributes);
            // Here $item->slug is correct, but the slug is not in the attributes array
        });
    }

HasSlug.php

namespace App\Traits;

use Illuminate\Support\Facades\Cache;

trait HasSlug {

    public function sluggable() {
        if (!$this->getSlug()) {
            $slug = $this->buildSlug();
            $this->setSlug($slug);
        }
        return $this;
    }

    public function refreshSlug() {
        $this->setSlug($this->buildSlug());
        return $this;
    }

    protected function setSlug($slug) {
        // $save_to = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $save_to = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        $this->attributes[$save_to] = $slug;
        // $this->setAttribute($save_to, $slug);
        return $this;
    }

    /**
     * @return \Eloquent
     */
    public function getSlug() {
        // $save_to = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $save_to = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        // return $this->getAttribute($save_to);
        return $this->$save_to;
    }

    /**
     * @return string
     */
    protected static function getRand() {
        $length = 11;
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $size = strlen($chars);
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, $size - 1)];
        }
        return $str;
    }

    /**
     * @param string $str;
     * @return string;
     */
    protected function mod($str) {
        // if (static::$sluggable_uppercase ?? false ) {  -- PHP bug fixed in 7.0.19 and  7.1.5
        $uppercase = isset(static::$sluggable_uppercase) ? static::$sluggable_uppercase : false;
        if ( $uppercase ) {
            return strtoupper($str);
        } else {
            return $str;
        }
    }

    /**
     * @return string
     */
    protected function buildSlug() {
        // $attr = static::$sluggable_build_from_attribute ?? 'title'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $attr = isset(static::$sluggable_build_from_attribute) ? static::$sluggable_build_from_attribute : 'title';
        $string = $attr && $this->$attr ? $this->$attr : static::getRand();
        return $this->bestSlugFrom($string);
    }

    /**
     * @param string $string
     * @return string
     */
    public function bestSlugFrom($string) {
        $original = $slug = $this->mod(static::sluggify($string));
        $i = 1;
        while (static::findBySlug($slug, true)) {
            $slug = $original . '-' . $i;
            $i++;
        }
        return $slug;
    }

    /**
     * Sluggify a string
     * @param string $text
     * @return string
     */
    public static function sluggify($text) {
        $text = str_replace(array('#', 'ω'), array(' sharp', ' omega'), $text); // replace non letter or digits by -
        return str_slug($text);
    }

    /**
     * Get a model by the slug
     * @param string $slug
     * @param bool $includeTrashed
     * @return static
     */
    public static function findBySlug($slug, $includeTrashed = false ) {
        // $slugAttr = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $slugAttr = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        return Cache::remember( get_called_class() . "_bySlug_{$slug}_{$includeTrashed}", 1, function () use ($slug, $includeTrashed, $slugAttr) {
            $q = static::where($slugAttr ?? 'slug', $slug);
            if ( $includeTrashed && method_exists(get_called_class(), 'bootSoftDeletingTrait') ) {
                /* Make sure the model has soft deletes before calling this method */
                $q->withTrashed();
            }
            return $q->first();
        });
    }

}


来源: stackexchange

问:
How to make responsive table and header fixed both on same html table
Here is the code pen https://codepen.io/shaswat/pen/EbwPNK

I have made an html table responsive by making all the columns getting repeated and show the correspondent row value up when its mobile display -- so the responsive part is done

Now having trouble to make the header fixed in this html table while scrolling the tbody - so tbody can have fixed height and that time scrolling header should be fixed -- applicable only for the resolutions greater than mobile display
--need help in this

HTML

```<code><h1>Some more Header information</h1>
<h2>Some more Header information</h2>
<h3>Header</h3>

<div class='rg-container'>
    <div class='rg-content'>
        <table class='rg-table'>
            <thead>
                <tr>
                    <th class='text '>id </th>
                    <th class='text '>somcol</th>
                    <th class='text '>biggger id</th>
                    <th class='text '>another id</th>
                    <th class='text '>med col</th>
                    <th class='text '>med col</th>
                    <th class='text '>sheet</th>
                    <th class='text '>sheet</th>
                    <th class='text '>anotherbigcoloumn</th>
                    <th class='text '>small</th>
                    <th class='text '>anotherbigcoloumn</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>small col</th>
                    <th class='text '>dateformat</th>
                    <th class='text '>averybigcolumnssssss</th>
                    <th class='text '>mediumclolumnss</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class='text' data-title='id'>id</td>
                    <td class='text' data-title='somcol'>somcol</td>
                    <td class='text' data-title='biggger id'>biggger id</td>
                    <td class='text' data-title='another id'>another id</td>
                    <td class='text' data-title='med col'>med col</td>
                    <td class='text' data-title='med col'>med col</td>
                    <td class='text' data-title='sheet'>sheet</td>
                    <td class='text' data-title='sheet'>sheet</td>
                    <td class='text' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text' data-title='small'>small</td>
                    <td class='text' data-title='anotherbigcoloumn'>another big coloumn</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='small col'>small col</td>
                    <td class='text' data-title='dateformat'>date format</td>
                    <td class='text' data-title='averybigcolumnssssss'>a very big columnssssss</td>
                    <td class='text' data-title='mediumclolumnss'>medium clolumnss</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

CSS

```<code>.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}

.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}
</code>```

答:
After trial and error I created this html table . which is responsive and table head is fixed

https://codepen.io/shaswat/pen/bYoagm

HTML

```<code><div class="gridContainer"><h1 class='deepshadow'>Table Fixed header Plus Responsive table</h1>

    <div class="tableWrapper">
        <div class="tableWrapper__head">
            <table class="responsiveTableLayout">
                <thead>
                    <tr>
                        <th>small_1</th>
                        <th>small_2</th>
                        <th>Medium_1</th>
                        <th>Medium_2</th>
                        <th>Medium_3</th>
                        <th>Medium_4</th>
                        <th>Medium_5</th>

                        <th>BigColumn_1</th>
                        <th>BigColumn_2</th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="tableWrapper__body">
            <table class="responsiveTableLayout">

                <tbody>
                    <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_1'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

CSS

```<code>h1 {
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  font-size: 20px;
  padding: 12px 12px;
  text-align: center;
  text-transform: uppercase;
  text-rendering: optimizeLegibility;
}
h1.deepshadow {
  color: #e0dfdc;
  background-color: #333;
  letter-spacing: .1em;
  text-shadow: 0 -1px 0 #fff, 0 1px 0 #2e2e2e, 0 1px 0 #2c2c2c, 0 2px 0 #2a2a2a, 0 2px 0 #282828, 0 2px 0 #262626, 0 2px 0 #242424, 0 2px 0 #222, 0 4px 0 #202020, 0 4px 0 #1e1e1e, 0 10px 0 #1c1c1c, 0 11px 0 #1a1a1a, 0 12px 0 #181818, 0 13px 0 #161616, 0 14px 0 #141414, 0 15px 0 #121212, 0 22px 30px rgba(0, 0, 0, 0.9);
}

table {
  border-collapse: collapse;
  table-layout: fixed;
  width: 100%;
  background: white;
}

td, th {
  border: 1px solid lightgray;
  padding: 2px;
  text-align: left;
}

td:first-child {
  width: 75px;
}
td:nth-child(2) {
  width: 75px;
}
td:last-child {
  text-align: right;
  width: 120px;
}

th:first-child {
  width: 75px;
}
th:nth-child(2) {
  width: 75px;
}

th:last-child {
  text-align: right;
  width: 135px;
}

th {
  background: #333;
  color: white;
  text-transform: uppercase;
  font-weight: normal;
  height:30px;
}

table tr:first-child td {
  border-top: none;
}

.gridContainer {
  background: #ccc;
  width: 100%;
  padding: 4px;
  box-sizing: border-box;
}

.tableWrapper {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.tableWrapper__head{

}
.tableWrapper__body {
  max-height :300px;
  overflow-y: scroll;
}

/* media queries */
@media screen and (max-width: 1000px) {
    .gridContainer {
        max-width: 1000px;
        margin: 0 auto;
    }

    table.responsiveTableLayout {
        width: 100%;

    }

        table.responsiveTableLayout thead {
            display: none;
        }

        table.responsiveTableLayout tbody {
            width: 100%;
        }

        table.responsiveTableLayout tr, table.responsiveTableLayout th, table.responsiveTableLayout td {
            display: block;
            padding: 0;
        }
        table.responsiveTableLayout th:nth-child(n), table.responsiveTableLayout td:nth-child(n) {
            width:auto;
        }

        table.responsiveTableLayout tr {
            border-bottom: none;
            margin: 0 0 10px 0;
            /*padding: 1px;*/
        }

        table.responsiveTableLayout td {
            /*padding: 4px 0 4px 0;*/
            border-bottom: 1px dotted #ccc;
            text-align: right;
        }

            table.responsiveTableLayout td[data-title]:before {
                content: attr(data-title);
                font-weight: bold;
                display: inline-block;
                content: attr(data-title);
                float: left;
              color:teal;
                /*margin-right: 0.5em;
                font-size: 0.95em;*/
            }

            table.responsiveTableLayout td:last-child {
                padding-right: 0;
              padding-bottom:5px;
                border-bottom: 2px solid #ccc;

            }

            table.responsiveTableLayout td:empty {
                display: none;
            }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is the code pen https://codepen.io/shaswat/pen/EbwPNK

I have made an html table responsive by making all the columns getting repeated and show the correspondent row value up when its mobile display -- so the responsive part is done

Now having trouble to make the header fixed in this html table while scrolling the tbody - so tbody can have fixed height and that time scrolling header should be fixed -- applicable only for the resolutions greater than mobile display
--need help in this

HTML

Some more Header information

Some more Header information

Header

                    id
                    somcol
                    biggger id
                    another id
                    med col
                    med col
                    sheet
                    sheet
                    anotherbigcoloumn
                    small
                    anotherbigcoloumn
                    dateformat
                    dateformat
                    small col
                    dateformat
                    averybigcolumnssssss
                    mediumclolumnss

                    id
                    somcol
                    biggger id
                    another id
                    med col
                    med col
                    sheet
                    sheet
                    another big coloumn
                    small
                    another big coloumn
                    date format
                    date format
                    small col
                    date format
                    a very big columnssssss
                    medium clolumnss

CSS

.rg-container {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.4;
    margin: 0;
    padding: 1em 0.5em;
    color: #222;
}
.rg-header {
    margin-bottom: 1em;
    text-align: left;
}

.rg-header > * {
    display: block;
}

/* table */
table.rg-table {
    width: 100%;
    margin-bottom: 0.5em;
    font-size: 1em;
    border-collapse: collapse;
    border-spacing: 0;
  overflow:scroll;
}
table.rg-table tr {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    text-align: left;
    color: #333;
}
table.rg-table thead {
    border-bottom: 3px solid #ddd;
  background:black;
}

table.rg-table tr {
    border-bottom: 1px solid #ddd;
    color: #222;
}
table.rg-table tr.highlight {
    background-color: #dcf1f0 !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table th {
    font-weight: bold;
    padding: 0.35em;
    font-size: 0.9em;
  color:white;
}
table.rg-table td {
    padding: 0.35em;
    font-size: 0.9em;
}
table.rg-table .highlight td {
    font-weight: bold;
}
table.rg-table th.number, td.number {
    text-align: right;
}

/* media queries */
@media screen and (max-width: 800px) {
.rg-container {
    max-width: 800px;
    margin: 0 auto;
}
table.rg-table {
    width: 100%;
}
table.rg-table tr.hide-mobile, table.rg-table th.hide-mobile, table.rg-table td.hide-mobile {
    display: none;
}
table.rg-table thead {
    display: none;
}
table.rg-table tbody {
    width: 100%;

}
table.rg-table tr, table.rg-table th, table.rg-table td {
    display: block;
    padding: 0;
}
table.rg-table tr {
    border-bottom: none;
    margin: 0 0 1em 0;
    padding: 0.5em;
}
table.rg-table tr.highlight {
    background-color: inherit !important;
}
table.rg-table.zebra tr:nth-child(even) {
    background-color: none;
}
table.rg-table.zebra td:nth-child(even) {
    background-color: #f6f6f6;
}
table.rg-table tr:nth-child(even) {
    background-color: none;
}
table.rg-table td {
    padding: 0.5em 0 0.25em 0;
    border-bottom: 1px dotted #ccc;
    text-align: right;
}
table.rg-table td[data-title]:before {
    content: attr(data-title);
    font-weight: bold;
    display: inline-block;
    content: attr(data-title);
    float: left;
    margin-right: 0.5em;
    font-size: 0.95em;
}
table.rg-table td:last-child {
    padding-right: 0;
    border-bottom: 2px solid #ccc;
}
table.rg-table td:empty {
    display: none;
}
table.rg-table .highlight td {
    background-color: inherit;
    font-weight: normal;
}

Body:
After trial and error I created this html table . which is responsive and table head is fixed

https://codepen.io/shaswat/pen/bYoagm

HTML

<div class="gridContainer"><h1 class='deepshadow'>Table Fixed header Plus Responsive table</h1>

    <div class="tableWrapper">
        <div class="tableWrapper__head">
            <table class="responsiveTableLayout">
                <thead>
                    <tr>
                        <th>small_1</th>
                        <th>small_2</th>
                        <th>Medium_1</th>
                        <th>Medium_2</th>
                        <th>Medium_3</th>
                        <th>Medium_4</th>
                        <th>Medium_5</th>

                        <th>BigColumn_1</th>
                        <th>BigColumn_2</th>
                    </tr>
                </thead>
            </table>
        </div>
        <div class="tableWrapper__body">
            <table class="responsiveTableLayout">

                <tbody>
                    <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_1'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                  <tr>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Small_2'>1</td>
                        <td data-title='Medium_1'>Some values</td>
                        <td data-title='Medium_2'>Some values</td>
                        <td data-title='Medium_3'>Some values</td>
                        <td data-title='Medium_4'>Some values</td>
                        <td data-title='Medium_5'>Some values</td>
                        <td data-title='BigColumn_1'>Big Value</td>
                        <td data-title='BigColumn_2'>Big Value</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

CSS

h1 {
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  font-size: 20px;
  padding: 12px 12px;
  text-align: center;
  text-transform: uppercase;
  text-rendering: optimizeLegibility;
}
h1.deepshadow {
  color: #e0dfdc;
  background-color: #333;
  letter-spacing: .1em;
  text-shadow: 0 -1px 0 #fff, 0 1px 0 #2e2e2e, 0 1px 0 #2c2c2c, 0 2px 0 #2a2a2a, 0 2px 0 #282828, 0 2px 0 #262626, 0 2px 0 #242424, 0 2px 0 #222, 0 4px 0 #202020, 0 4px 0 #1e1e1e, 0 10px 0 #1c1c1c, 0 11px 0 #1a1a1a, 0 12px 0 #181818, 0 13px 0 #161616, 0 14px 0 #141414, 0 15px 0 #121212, 0 22px 30px rgba(0, 0, 0, 0.9);
}

table {
  border-collapse: collapse;
  table-layout: fixed;
  width: 100%;
  background: white;
}

td, th {
  border: 1px solid lightgray;
  padding: 2px;
  text-align: left;
}

td:first-child {
  width: 75px;
}
td:nth-child(2) {
  width: 75px;
}
td:last-child {
  text-align: right;
  width: 120px;
}

th:first-child {
  width: 75px;
}
th:nth-child(2) {
  width: 75px;
}

th:last-child {
  text-align: right;
  width: 135px;
}

th {
  background: #333;
  color: white;
  text-transform: uppercase;
  font-weight: normal;
  height:30px;
}

table tr:first-child td {
  border-top: none;
}

.gridContainer {
  background: #ccc;
  width: 100%;
  padding: 4px;
  box-sizing: border-box;
}

.tableWrapper {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.tableWrapper__head{

}
.tableWrapper__body {
  max-height :300px;
  overflow-y: scroll;
}

/* media queries */
@media screen and (max-width: 1000px) {
    .gridContainer {
        max-width: 1000px;
        margin: 0 auto;
    }

    table.responsiveTableLayout {
        width: 100%;

    }

        table.responsiveTableLayout thead {
            display: none;
        }

        table.responsiveTableLayout tbody {
            width: 100%;
        }

        table.responsiveTableLayout tr, table.responsiveTableLayout th, table.responsiveTableLayout td {
            display: block;
            padding: 0;
        }
        table.responsiveTableLayout th:nth-child(n), table.responsiveTableLayout td:nth-child(n) {
            width:auto;
        }

        table.responsiveTableLayout tr {
            border-bottom: none;
            margin: 0 0 10px 0;
            /*padding: 1px;*/
        }

        table.responsiveTableLayout td {
            /*padding: 4px 0 4px 0;*/
            border-bottom: 1px dotted #ccc;
            text-align: right;
        }

            table.responsiveTableLayout td[data-title]:before {
                content: attr(data-title);
                font-weight: bold;
                display: inline-block;
                content: attr(data-title);
                float: left;
              color:teal;
                /*margin-right: 0.5em;
                font-size: 0.95em;*/
            }

            table.responsiveTableLayout td:last-child {
                padding-right: 0;
              padding-bottom:5px;
                border-bottom: 2px solid #ccc;

            }

            table.responsiveTableLayout td:empty {
                display: none;
            }
}


问:
Error while calling a .sql script from shell script
Folks,

I am trying to call an sql script with 1 parameter from shell script. My scripts are as follows

tab.sql

```<code>set lines 500
col file_name for a80

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&TAB_NAME');
/
</code>```

and my shell script is test.sh is

```<code>#!/bin/bash

LOC=`pwd`

echo -n "Enter the name of the Tablespace: "
read -r TAB_NAME

sqlplus "/ as sysdba" <<- EOF
@$LOC/tab.sql $TAB_NAME
EOF

exit
</code>```

When I execute the script this is what I am getting

```<code>sh test.sh
Enter the name of the Tablespace: users

SQL*Plus: Release 11.2.0.4.0 Production on Thu Nov 16 14:17:45 2017

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

Connected.
SQL> Enter value for tab_name:
SP2-0546: User requested Interrupt or EOF detected.
Enter value for tab_name:
SP2-0546: User requested Interrupt or EOF detected.
SQL> Disconnected
</code>```

Can anyone tell me what is wrong here? I searched on net regarding this SP2-0546 but didn't resolved my issue. I am using 11.2.0.4 db on OLE-6

Thanks

答:
You're mixing up named and positional substitution variables, and possibly confusing them with shell variables a bit too. You can refer to the argument passed on the SQL*Plus command line positionally:

```<code>select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&1');
/
</code>```

If you wanted to you could define a named substitution variable; possibly overkill here but can be useful for clarity in bigger scripts:

```<code>define TAB_NAME=&1

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&TAB_NAME');
/
</code>```

or to simplify later references a bit:

```<code>define TAB_NAME=upper('&1')

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=&TAB_NAME;
/
</code>```

Note that in this version the reference to &TAB_NAME is not enclosed in single quotes, as they are applied during the substitution.

I can be helpful to set verify on while testing/debugging, then set verify off for real use to hide the noise. You might also find it useful to include the -s flag in the sqlplus call to hide the banner text. You don't even need a heredoc in this case, you can run the script directly from the command line too:

```<code>sqlplus -s "/ as sysdba" @$LOC/tab.sql $TAB_NAME
</code>```

(Connecting as sys for routine queries isn't ideal; it would be better to have a normal user with privileges to see the data dictionary tables you need to query, but that's a different topic...)

Body:
Folks,

I am trying to call an sql script with 1 parameter from shell script. My scripts are as follows

tab.sql

set lines 500
col file_name for a80

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&TAB_NAME');
/

and my shell script is test.sh is

#!/bin/bash

LOC=`pwd`

echo -n "Enter the name of the Tablespace: "
read -r TAB_NAME

sqlplus "/ as sysdba" <<- EOF
@$LOC/tab.sql $TAB_NAME
EOF

exit

When I execute the script this is what I am getting

sh test.sh
Enter the name of the Tablespace: users

SQL*Plus: Release 11.2.0.4.0 Production on Thu Nov 16 14:17:45 2017

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

Connected.
SQL> Enter value for tab_name:
SP2-0546: User requested Interrupt or EOF detected.
Enter value for tab_name:
SP2-0546: User requested Interrupt or EOF detected.
SQL> Disconnected

Can anyone tell me what is wrong here? I searched on net regarding this SP2-0546 but didn't resolved my issue. I am using 11.2.0.4 db on OLE-6

Thanks

Body:
You're mixing up named and positional substitution variables, and possibly confusing them with shell variables a bit too. You can refer to the argument passed on the SQL*Plus command line positionally:

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&1');
/

If you wanted to you could define a named substitution variable; possibly overkill here but can be useful for clarity in bigger scripts:

define TAB_NAME=&1

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=upper('&TAB_NAME');
/

or to simplify later references a bit:

define TAB_NAME=upper('&1')

select file_name,bytes/1024/1024,maxbytes/1024/1024
  from dba_data_files
 where tablespace_name=&TAB_NAME;
/

Note that in this version the reference to &TAB_NAME is not enclosed in single quotes, as they are applied during the substitution.

I can be helpful to set verify on while testing/debugging, then set verify off for real use to hide the noise. You might also find it useful to include the -s flag in the sqlplus call to hide the banner text. You don't even need a heredoc in this case, you can run the script directly from the command line too:

sqlplus -s "/ as sysdba" @$LOC/tab.sql $TAB_NAME

(Connecting as sys for routine queries isn't ideal; it would be better to have a normal user with privileges to see the data dictionary tables you need to query, but that's a different topic...)


问:
Correction about list elements in one line (str to int)
I have something like this:-

```<code>List = [["a","1"],["b","2"]]
</code>```

and what I wanna do is keep single letter integers as integers.
so output should be like

```<code>List =  [["a",1],["b",2]]
</code>```

答:
Changed question before rollback: Sort heterogeneous list

It seems that you completely changed your question after people answered the first version. Please don't do that. You could simply ask a new question.

If you want to sort a heterogeneous list, you can provide a custom key which returns a tuple. The first element is 0 for strings and 1 for integers. This way, the strings would appear before the integers.
If the object is an integer, the second element is set to -x in order to sort the integers in decreasing order:

```<code>def custom_order(x):
    if isinstance(x, int):
        return (1, -x)
    else:
        return (0, x)

print(sorted([1,2,3,4,5,"a","b","c","d"], key=custom_order))
# ['a', 'b', 'c', 'd', 5, 4, 3, 2, 1]
</code>```

This code should work on Python2 and Python3. It will fail on Python3 if an element is neither a string nor an int.

Original question: convert nested strings to ints

You could use a nested list comprehension with a ternary operator to check if the string looks like an integer:

```<code>>>> data = [["a","1"],["b","2"]]
>>> [[int(s) if s.isdecimal() else s for s in l] for l in data]
[['a', 1], ['b', 2]]
</code>```

As a bonus, it would work in any order and with sub-lists of any size:

```<code>>>> data = [["a","1"],["b","2"],["3", "c"], ["4", "5", "d"]]
>>> [[int(s) if s.isdecimal() else s for s in l] for l in data]
[['a', 1], ['b', 2], [3, 'c'], [4, 5, 'd']]
</code>```

Body:
I have something like this:-

List = [["a","1"],["b","2"]]

and what I wanna do is keep single letter integers as integers.
so output should be like

List =  [["a",1],["b",2]]

Body:
Changed question before rollback: Sort heterogeneous list

It seems that you completely changed your question after people answered the first version. Please don't do that. You could simply ask a new question.

If you want to sort a heterogeneous list, you can provide a custom key which returns a tuple. The first element is 0 for strings and 1 for integers. This way, the strings would appear before the integers.
If the object is an integer, the second element is set to -x in order to sort the integers in decreasing order:

def custom_order(x):
    if isinstance(x, int):
        return (1, -x)
    else:
        return (0, x)

print(sorted([1,2,3,4,5,"a","b","c","d"], key=custom_order))
# ['a', 'b', 'c', 'd', 5, 4, 3, 2, 1]

This code should work on Python2 and Python3. It will fail on Python3 if an element is neither a string nor an int.

Original question: convert nested strings to ints

You could use a nested list comprehension with a ternary operator to check if the string looks like an integer:

>>> data = [["a","1"],["b","2"]]
>>> [[int(s) if s.isdecimal() else s for s in l] for l in data]
[['a', 1], ['b', 2]]

As a bonus, it would work in any order and with sub-lists of any size:

>>> data = [["a","1"],["b","2"],["3", "c"], ["4", "5", "d"]]
>>> [[int(s) if s.isdecimal() else s for s in l] for l in data]
[['a', 1], ['b', 2], [3, 'c'], [4, 5, 'd']]


问:
How do I get the last value in a string separated by commas?
I have this string

```<code>let data = 123,456,7,8,9,10
</code>```

I want to extract the last value separated by a "," which in this case would  be 10, and its not necessarily a two digit value.

I tried this:

```<code>var data = 123,456,7,8,9,10
data = data.last!
</code>```

答:
Use String method data.components(separatedBy:)

```<code>let data = "123,456,7,8,9,10"
let lastComponent = data.components(separatedBy: ",").last
print(lastComponent)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this string

let data = 123,456,7,8,9,10

I want to extract the last value separated by a "," which in this case would  be 10, and its not necessarily a two digit value.

I tried this:

var data = 123,456,7,8,9,10
data = data.last!

Body:
Use String method data.components(separatedBy:)

let data = "123,456,7,8,9,10"
let lastComponent = data.components(separatedBy: ",").last
print(lastComponent)


问:
How to initialize model class from JSON with custom type attribute
I know I can create failable initializer for my model class to initialize from JSON data by :

```<code>struct Person {
    let firstName: String
    let middleName: String?

    init?(JSONData data:[String:AnyObject]) {
        guard let firstName = data["firstName"] as? String else { return nil }
        self.firstName = firstName
        self.middleName = data["middleName"] as? String
    }
}
</code>```

But what if I have another attribute in Person which is another model class type? For example:

```<code>struct Person {
   let firstName: String
   let car: Car

   init?(JSONData data:[String: AnyObject]) {
      guard let firstName = data["firstName"] as! String,
            let car = data["car"] as! Car // this line doesn't work I guess
       else {return nil}
      self.firstName = firstName
      self.car = car
   }

}
</code>```

Car looks like this:

```<code>struct Car {
    let year: Int
    let brand: String
}
</code>```

What is the proper way to make the failable initializer above work with custom type Car for JSON data parsing?

e.g. JSON:

```<code>{“firstName”: “John”,
 “car”: {
        “year”: 2009,
        “brand”: “BMW”
       }}
</code>```

答:
As Swift 4+ introduces Codable For Encoding & decoding with external representation(JSON,Plist)

JsonData -

```<code>    let jsonExample = """
{
    "firstName": "John",
      "car": {
            "year": 2009,
            "brand": "BMW"
      }

}
""".data(using: .utf8)!
</code>```

Struct with Codable protocol-

```<code> struct UserData: Codable{
        var firstName: String
        var car: CarData
    }
    struct CarData: Codable{
        var year: Int
        var brand: String
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            year = try values.decode(Int.self, forKey: .year)
            brand = try values.decode(String.self, forKey: .brand)
        }
    }
</code>```

Usage-

```<code>  let jsonDecoder = JSONDecoder()
        do {
            let modelResult = try jsonDecoder.decode(UserData.self,from: jsonExample)
            print("firstName is \(modelResult.firstName)")//prints John
            print("car brand is \(modelResult.car.brand)")//Prints BMW

        } catch {
            print(error)
        }
</code>```

If of Json is with diffrent keys respective of your struct then use CodingKeys

Example-

```<code>let jsonExample = """
{
    "firstNameOfBuyer": "John",
      "car": {
            "year-of-made": 2009,
            "brand-name": "BMW"
      }

}
""".data(using: .utf8)!
    struct UserData: Codable {
        var firstName: String
        var car: CarData
        private enum CodingKeys: String, CodingKey {
            case firstName = "firstNameOfBuyer"
            case car
        }

    }
    struct CarData: Codable{
        var year: Int
        var brand: String
        private enum CodingKeys: String, CodingKey {
            case year = "year-of-made"
            case brand = "brand-name"

        }
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            year = try values.decode(Int.self, forKey: .year)
            brand = try values.decode(String.self, forKey: .brand)
        }
    }
</code>```

Body:
I know I can create failable initializer for my model class to initialize from JSON data by :

struct Person {
    let firstName: String
    let middleName: String?

    init?(JSONData data:[String:AnyObject]) {
        guard let firstName = data["firstName"] as? String else { return nil }
        self.firstName = firstName
        self.middleName = data["middleName"] as? String
    }
}

But what if I have another attribute in Person which is another model class type? For example:

struct Person {
   let firstName: String
   let car: Car

   init?(JSONData data:[String: AnyObject]) {
      guard let firstName = data["firstName"] as! String,
            let car = data["car"] as! Car // this line doesn't work I guess
       else {return nil}
      self.firstName = firstName
      self.car = car
   }

}

Car looks like this:

struct Car {
    let year: Int
    let brand: String
}

What is the proper way to make the failable initializer above work with custom type Car for JSON data parsing?

e.g. JSON:

{“firstName”: “John”,
 “car”: {
        “year”: 2009,
        “brand”: “BMW”
       }}

Body:
As Swift 4+ introduces Codable For Encoding & decoding with external representation(JSON,Plist)

JsonData -

    let jsonExample = """
{
    "firstName": "John",
      "car": {
            "year": 2009,
            "brand": "BMW"
      }

}
""".data(using: .utf8)!

Struct with Codable protocol-

 struct UserData: Codable{
        var firstName: String
        var car: CarData
    }
    struct CarData: Codable{
        var year: Int
        var brand: String
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            year = try values.decode(Int.self, forKey: .year)
            brand = try values.decode(String.self, forKey: .brand)
        }
    }

Usage-

  let jsonDecoder = JSONDecoder()
        do {
            let modelResult = try jsonDecoder.decode(UserData.self,from: jsonExample)
            print("firstName is \(modelResult.firstName)")//prints John
            print("car brand is \(modelResult.car.brand)")//Prints BMW

        } catch {
            print(error)
        }

If of Json is with diffrent keys respective of your struct then use CodingKeys

Example-

let jsonExample = """
{
    "firstNameOfBuyer": "John",
      "car": {
            "year-of-made": 2009,
            "brand-name": "BMW"
      }

}
""".data(using: .utf8)!
    struct UserData: Codable {
        var firstName: String
        var car: CarData
        private enum CodingKeys: String, CodingKey {
            case firstName = "firstNameOfBuyer"
            case car
        }

    }
    struct CarData: Codable{
        var year: Int
        var brand: String
        private enum CodingKeys: String, CodingKey {
            case year = "year-of-made"
            case brand = "brand-name"

        }
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            year = try values.decode(Int.self, forKey: .year)
            brand = try values.decode(String.self, forKey: .brand)
        }
    }


问:
WPF Add KeyBinding events with umlaut characters in XAML
Can anyone tell me why keybinding events do not work with umlaut characters like this?

Trying in xaml

```<code><Grid.InputBindings>
    <KeyBinding Key="Ü" ... />
</Grid.InputBindings>
</code>```

Will throw error:

Cannot convert string value 'Ü' to type System.Windows.Input.Key

答:
I've made a small test program to find out which Key is what. Make new WPF project and add to main window cs-file:

```<code>public MainWindow()
{
    InitializeComponent();
    var skip = new[] { Key.None, Key.DeadCharProcessed };
    foreach (Key value in Enum.GetValues(typeof(Key)))
        if (!skip.Contains(value))
            InputBindings.Add(new KeyBinding { Command = new MyCommand(value.ToString()), Key = value });
}

public class MyCommand : ICommand
{
    public event EventHandler CanExecuteChanged;

    public string Text { get; }

    public MyCommand(string text) { Text = text; }

    public bool CanExecute(object parameter) => true;
    public void Execute(object parameter) => MessageBox.Show(Text);
}
</code>```

To save you time:

```<code>Ü = Key.Oem1
Ö = Key.Oem3
Ä = Key.OemQuotes
</code>```

Body:
Can anyone tell me why keybinding events do not work with umlaut characters like this?

Trying in xaml

<Grid.InputBindings>
    <KeyBinding Key="Ü" ... />
</Grid.InputBindings>

Will throw error:

Cannot convert string value 'Ü' to type System.Windows.Input.Key

Body:
I've made a small test program to find out which Key is what. Make new WPF project and add to main window cs-file:

public MainWindow()
{
    InitializeComponent();
    var skip = new[] { Key.None, Key.DeadCharProcessed };
    foreach (Key value in Enum.GetValues(typeof(Key)))
        if (!skip.Contains(value))
            InputBindings.Add(new KeyBinding { Command = new MyCommand(value.ToString()), Key = value });
}

public class MyCommand : ICommand
{
    public event EventHandler CanExecuteChanged;

    public string Text { get; }

    public MyCommand(string text) { Text = text; }

    public bool CanExecute(object parameter) => true;
    public void Execute(object parameter) => MessageBox.Show(Text);
}

To save you time:

Ü = Key.Oem1
Ö = Key.Oem3
Ä = Key.OemQuotes


问:
Ajax jQuery with FormData and string values
Is it possible to pass a jQuery AJAX request that contains both a FormData object as well as a string value? Below are my unsuccessful attempts so far. I keep getting the same error:

Undefined index: check

when I attempt to fetch the value like this:

```<code>$test = $_POST['check'];
echo $test;
</code>```

My two attempts are as seen below:

```<code>var formData = new FormData(document.getElementById('#form1'));
var bar = "salesReport";

$.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : {
                        formData,
                        check : bar
                            },
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })
</code>```

or this:

```<code>var formData = new FormData(document.getElementById('#form1'));

formData.append("check", "salesReport");

$.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })
</code>```

答:
If you have a php backend you may have to parse it from the input stream

```<code>$request_body = file_get_contents('php://input');
$_POST = (array)(json_decode($request_body, true));
</code>```

then you can use the $_POST again

Body:
Is it possible to pass a jQuery AJAX request that contains both a FormData object as well as a string value? Below are my unsuccessful attempts so far. I keep getting the same error:

Undefined index: check

when I attempt to fetch the value like this:

$test = $_POST['check'];
echo $test;

My two attempts are as seen below:

var formData = new FormData(document.getElementById('#form1'));
var bar = "salesReport";

$.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : {
                        formData,
                        check : bar
                            },
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })

or this:

var formData = new FormData(document.getElementById('#form1'));

formData.append("check", "salesReport");

$.ajax({
        type        : 'POST',
        url         : 'process.php',
        data        : formData,
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })

Body:
If you have a php backend you may have to parse it from the input stream

$request_body = file_get_contents('php://input');
$_POST = (array)(json_decode($request_body, true));

then you can use the $_POST again


问:
How to use css vertically centered title?
How to use css vertically centered title?

<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>test page</title>

       title title title title
      title title title title title title title title title title title title title

    posttime:2017-11-11 11:21

```

答:
Add Img tag CSS

```<code>vertical-align: middle;
</code>```

<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>test page</title>

       title title title title
      title title title title title title title title title title title title title

    posttime:2017-11-11 11:21

```

Body:
Add Img tag CSS

vertical-align: middle;

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>test page</title>

</head>

<body>
  <div style="padding: 8px 8px 10px;border-bottom: 1px solid #e8e8e8;">

    <a href="#" style="overflow-x: hidden;text-overflow: ellipsis;white-space: nowrap;width: 154px;display: inline-block;">
      <img src="http://i.ytimg.com/p/PL-o37YO_uwcLPmR8QBTegC2BoJ03I3tqe/mqdefault.jpg" style="display: inline-block;width: 30px;height: 30px;border: 1px solid #ddd;border-radius: 50%;overflow: hidden;vertical-align: middle;"> title title title title
      title title title title title title title title title title title title title </a>

    <span style="ctitle;vertical-align: 10px">posttime:2017-11-11 11:21</span> </div>

</body>

</html>


问:
MS Bluetooth stack documentation
I want to develop a Bluetooth application for Windows 7. Where could I find a proper documentation, tutorials and so on? My intention is to use Microsoft stack.

The MSDN is sterile about this topic, in the sense that they have a long list of Windows API functions for Bluetooth with brief descriptions, but with no logical start and end. Until now the best valuable resource found by me is a web tutorial:

http://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedotherprotocol4j.html

Any other ideas?

Thnx

答: If you want some examples of the MS stack in action, check out the source for the BlueCove project.  It's a complete implementation of JSR-82 (the Java BT interface) written to use a variety of stacks, including MS.  For example, this file exercises lots of the stack.</p>

ContentLicense: CC BY-SA 2.5

Title: MS Bluetooth stack documentation


问:
"The parameter is incorrect" error using "netsh http add sslcert"
Following the instructions in How to: Configure a Port with an SSL Certificate, I entered this command on the command line (duh):

```<code>netsh http add sslcert ipport:10.141.146.227:7001 certhash=5d48e604007b867ae8a69260a4ad318d2c05d8ff appid={EDE3C891-306C-40fe-BAD4-895B236A1CC8}
</code>```

Output:

```<code>The parameter is incorrect.
</code>```

My certhash thumbprint was taken from the certificate in Certificates (Local Computer) → Personal → Certificates folder.

The appid GUID was generated.

What else is wrong that I need to fix to get this to work?

答:
I was trying to add an IP address and port with the hostnameport parameter, so I got this parameter error.

netsh http add sslcert hostnameport="10.0.0.120:443"

Instead of:

netsh http add sslcert ipport="10.0.0.120:443"

Body:
Following the instructions in How to: Configure a Port with an SSL Certificate, I entered this command on the command line (duh):

netsh http add sslcert ipport:10.141.146.227:7001 certhash=5d48e604007b867ae8a69260a4ad318d2c05d8ff appid={EDE3C891-306C-40fe-BAD4-895B236A1CC8}

Output:

The parameter is incorrect.

My certhash thumbprint was taken from the certificate in Certificates (Local Computer) → Personal → Certificates folder.

The appid GUID was generated.

What else is wrong that I need to fix to get this to work?


问:
CocoaPods issues while adding a new pod
My CocoaPods works fine until I try to install a new one.

If I try to install a new pod, then there are several issues in charts pod, else it works fine.

How do I fix it?

The errors show up as below:

My podfile is as below:

```<code># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
use_frameworks!

target 'Tranquil' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks

# Pods for TranquillocationText
pod 'GooglePlaces'
pod 'UICircularProgressRing'
pod 'Alamofire', '~> 4.0' . //if i try to add this pod then error occurs
pod 'Charts'
end
</code>```

答: Go to build settings of the target 'Tranquil' then to the section 'Swift Language Version' and set it to 'Swift 4.0'. Next, reinstall your pods with a command 'pod install'. Next, rebuild your project.</p>

Title: CocoaPods issues while adding a new pod

Body:
My CocoaPods works fine until I try to install a new one.

If I try to install a new pod, then there are several issues in charts pod, else it works fine.

How do I fix it?

The errors show up as below:

My podfile is as below:

# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
use_frameworks!

target 'Tranquil' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks

# Pods for TranquillocationText
pod 'GooglePlaces'
pod 'UICircularProgressRing'
pod 'Alamofire', '~> 4.0' . //if i try to add this pod then error occurs
pod 'Charts'
end


问:
Writing a Multi-threaded C# application
I need to write an application in c# that keeps track of multiple tasks, each being implemented as a class instance running on its own thread. A user interface will be used to display the status of each task instance depending on which task I select from tree view which will display the list of tasks.

An idea I have is to create some other class, called PropertyClass which will have an instance of the TaskClass and some properties relating to this TaskClass instance. Then whenever the TaskClass instance changes its state the related property in the PropertyClass instance will get updated and then the UI will be updated with these property values from the PropertyClass when the task is selected from the Tree View list.

There will probably be hundreds of these tasks running which will be communicating with a service on a remote machine.

How else can I go about coding this solution in an efficient way?

答: Read this document from the MSDN on the Task Parallel Library first.</p>

Title: Writing a Multi-threaded C# application


问:
Change contents of a Border control with a Data Trigger
I have a Grid named "Popup" that has its visibility bound to a Bool in the viewmodel using a BoolToVisibilityConverter.

This works perfectly, but I want to re-use it for multiple UserControls by setting the content of the Border control depending on another Bool in the viewmodel, also using a BoolToVisibilityConverter.

This is what I have so far but obviously it isn't working, and I can't find any answers online. Does anyone have any ideas?

```<code><Grid x:Name="PopUp" Visibility="{Binding ShowPopUp, Converter={StaticResource BoolToVisibilityConverter}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Border Grid.Column="1" Grid.Row="1">
            <Border.Style>
                <Style>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ShowView1}" Value="true">
                            <Setter Property="ContentControl.Content">
                                <Setter.Value>
                                    <view:View1/>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
        </Border>
    </Grid>
</code>```

答:
I figured it out, using this post as inspiration.

I had to create a ContentControl, then used a DataTrigger to set the Template to a Border containing my UserControl, much in the same way that I was trying to do before.

```<code><Grid x:Name="PopUp" Visibility="{Binding ShowPopUp, Converter={StaticResource BoolToVisibilityConverter}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ContentControl Grid.Row="1" Grid.Column="1">
            <ContentControl.Style>
                <Style TargetType="ContentControl">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ShowView1}" Value="true">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate>
                                        <Border>
                                            <view:View1/>
                                        </Border>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentControl.Style>
        </ContentControl>

    </Grid>
</code>```

Body:
I have a Grid named "Popup" that has its visibility bound to a Bool in the viewmodel using a BoolToVisibilityConverter.

This works perfectly, but I want to re-use it for multiple UserControls by setting the content of the Border control depending on another Bool in the viewmodel, also using a BoolToVisibilityConverter.

This is what I have so far but obviously it isn't working, and I can't find any answers online. Does anyone have any ideas?

<Grid x:Name="PopUp" Visibility="{Binding ShowPopUp, Converter={StaticResource BoolToVisibilityConverter}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Border Grid.Column="1" Grid.Row="1">
            <Border.Style>

                </Style>
            </Border.Style>
        </Border>
    </Grid>

Body:
I figured it out, using this post as inspiration.

I had to create a ContentControl, then used a DataTrigger to set the Template to a Border containing my UserControl, much in the same way that I was trying to do before.

<Grid x:Name="PopUp" Visibility="{Binding ShowPopUp, Converter={StaticResource BoolToVisibilityConverter}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ContentControl Grid.Row="1" Grid.Column="1">
            <ContentControl.Style>
                <Style TargetType="ContentControl">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ShowView1}" Value="true">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate>
                                        <Border>
                                            <view:View1/>
                                        </Border>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentControl.Style>
        </ContentControl>

    </Grid>


问:
Extract text from html tags using reduce in Javascript
I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:

// JS
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a, b) => a + ", " + b.innerHTML));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p></code>```

And here's the (wrong) output:

[object HTMLParagraphElement], Strawberry, Banana

What am I doing wrong?

Many thanks for your help!

答:
reduce function takes a 2nd argument which is the initial value for the accumulator.

By default, it's the first item in the array.

To have the desired result you should write your code like this:

```<code>let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a,b)=>a+", "+b.innerHTML, ""));
</code>```

Here is a document on reduce function from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a

Body:
I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:

// JS
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a, b) => a + ", " + b.innerHTML));

Apple

Strawberry

Banana

And here's the (wrong) output:

[object HTMLParagraphElement], Strawberry, Banana

What am I doing wrong?

Many thanks for your help!

Body:
reduce function takes a 2nd argument which is the initial value for the accumulator.

By default, it's the first item in the array.

To have the desired result you should write your code like this:

let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a,b)=>a+", "+b.innerHTML, ""));

Here is a document on reduce function from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a


问:
Excel use range name as an argument to excel function

Let suppose I have several named ranges, P2017.01, P2017.02 and so on. These ranges hold values from year 2017 month 01, month 02, and so on.
I want to sum the month values one-by-one. I want to construct the names of the ranges, and use these constructed names as a function argument. Example: the prefix 'P2017' is in B3, the index of the month is in C3. I concatenate B3&'.'&C3 and store the value to D3.

In E3 I want to =SUM(INDEX(P2017.01;0;2)), but instead of writing the name P2017.01 I want to acquire the name from the value of cell D3.

What should I write to E3 to do that?

答:
Try following formula...

```<code>=SUM(INDEX(INDIRECT(D3),0,2))
</code>```

Comma (,) or semicolon (;) depens on regional settings.

Body:
Try following formula...

=SUM(INDEX(INDIRECT(D3),0,2))

Comma (,) or semicolon (;) depens on regional settings.


问:
How to get a Control byId from a SAPUI5 Fragment
I have a dialog which is in a Fragment. So after entering the details into it and clicking the submit button, the text which was filled into the input should be displayed as a MessageToast. But I am getting the error : ' Cannot read property 'getValue' of undefined '.

Below is the code :

```<code>    onAddMovie: function() {
        var view = this.getView();
        var createDialog = view.byId("CreateDialog");
        var oDummyController = {
            // This is when I clicked the Submit button in dialog
            submitDialog: function() {
            var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();
                MessageToast.show(user);
                createDialog.close();
            },
            closeDialog: function() {
                createDialog.close();
            }
        };

        if (!createDialog) {
            createDialog = sap.ui.xmlfragment(view.getId(), "Admin.view.Dialog", oDummyController);
        }
        view.addDependent(createDialog);
        createDialog.open();
        if (!createDialog.isOpen()) {
            //do sth
        }
    },
</code>```

Above is the function in which the dialog is getting displayed and after pressing submit button , the text in the input should be displayed in a MessageToast.

XML :

```<code>        <core:FragmentDefinition  xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">

        <Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
            <l:VerticalLayout class="sapUiContentPadding" width="100%">
            <l:content>
                <Input width="100%" placeholder="Movie Name" id="movie_name"/>
                <HBox alignItems="Center" renderType="Bare">
                    <Label text="Year of Release" width="50%"/>
                    <ActionSelect selectedItem="Element sap.ui.core.ListItem#__item0" selectedKey="item1" class="sapUiLargeMarginBegin" selectedItemId="__item0" id="__select0" width="50%">
                        <items>
                            <core:ListItem text="2017" key="item1" id="__item0"/>
                            <core:ListItem text="2016" key="item2" id="__item1"/>
                            <core:ListItem text="2015" key="item3" id="__item2"/></items>
                    </ActionSelect>
                </HBox>
                <HBox alignItems="Center" renderType="Bare">
                    <Label text="Date of Screening" width="50%"/>
                    <DatePicker class="sapUiLargeMarginBegin" width="50%" id="__picker0"/>
                </HBox>
                <HBox alignItems="Center">
                    <Label text="Movie Rating"/>
                    <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="__group0">
                        <buttons>
                            <RadioButton selected="true" groupName="__group0" text="Universal" id="__button0"/>
                            <RadioButton groupName="__group0" text="Adult" id="__button1"/>
                            <RadioButton groupName="__group0" text="U/A" id="__button2"/></buttons>
                    </RadioButtonGroup>
                </HBox>
                        <HBox alignItems="Center" width="100%" renderType="Bare">
                    <Label text="Enable Booking" width="70%"/>
                <CheckBox id="__box0" width="30%" textDirection="LTR"/>
            </HBox>
                <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">

                    <SegmentedButton selectedButton="__button3" id="__button21">
                            <buttons>
                                <Button text="Submit" id="__submit" press="submitDialog"/>
                                <Button text="Cancel" id="__button41" press="closeDialog"/></buttons>
                        </SegmentedButton>
                            </FlexBox>
                </l:content>
            </l:VerticalLayout>
        </Dialog>

    </core:FragmentDefinition>
</code>```

答:
Instead of using :

```<code> var view = this.getView();
var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();
</code>```

I used :

```<code> var view = this.getView();
 var user = view.byId("movie_name").getValue();
                MessageToast.show(user);
</code>```

And it worked !!

Body:
I have a dialog which is in a Fragment. So after entering the details into it and clicking the submit button, the text which was filled into the input should be displayed as a MessageToast. But I am getting the error : ' Cannot read property 'getValue' of undefined '.

Below is the code :

    onAddMovie: function() {
        var view = this.getView();
        var createDialog = view.byId("CreateDialog");
        var oDummyController = {
            // This is when I clicked the Submit button in dialog
            submitDialog: function() {
            var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();
                MessageToast.show(user);
                createDialog.close();
            },
            closeDialog: function() {
                createDialog.close();
            }
        };

        if (!createDialog) {
            createDialog = sap.ui.xmlfragment(view.getId(), "Admin.view.Dialog", oDummyController);
        }
        view.addDependent(createDialog);
        createDialog.open();
        if (!createDialog.isOpen()) {
            //do sth
        }
    },

Above is the function in which the dialog is getting displayed and after pressing submit button , the text in the input should be displayed in a MessageToast.

XML :

        <core:FragmentDefinition  xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">

        <Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
            <l:VerticalLayout class="sapUiContentPadding" width="100%">
            <l:content>
                <Input width="100%" placeholder="Movie Name" id="movie_name"/>
                <HBox alignItems="Center" renderType="Bare">

                    <ActionSelect selectedItem="Element sap.ui.core.ListItem#__item0" selectedKey="item1" class="sapUiLargeMarginBegin" selectedItemId="__item0" id="__select0" width="50%">
                        <items>
                            <core:ListItem text="2017" key="item1" id="__item0"/>
                            <core:ListItem text="2016" key="item2" id="__item1"/>
                            <core:ListItem text="2015" key="item3" id="__item2"/></items>
                    </ActionSelect>
                </HBox>
                <HBox alignItems="Center" renderType="Bare">

                    <DatePicker class="sapUiLargeMarginBegin" width="50%" id="__picker0"/>
                </HBox>
                <HBox alignItems="Center">

                    <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="__group0">
                        <buttons>
                            <RadioButton selected="true" groupName="__group0" text="Universal" id="__button0"/>
                            <RadioButton groupName="__group0" text="Adult" id="__button1"/>
                            <RadioButton groupName="__group0" text="U/A" id="__button2"/></buttons>
                    </RadioButtonGroup>
                </HBox>
                        <HBox alignItems="Center" width="100%" renderType="Bare">

                <CheckBox id="__box0" width="30%" textDirection="LTR"/>
            </HBox>
                <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">

                    <SegmentedButton selectedButton="__button3" id="__button21">
                            <buttons>
                                <Button text="Submit" id="__submit" press="submitDialog"/>
                                <Button text="Cancel" id="__button41" press="closeDialog"/></buttons>
                        </SegmentedButton>
                            </FlexBox>
                </l:content>
            </l:VerticalLayout>
        </Dialog>

    </core:FragmentDefinition>

Body:
Instead of using :

 var view = this.getView();
var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();

I used :

 var view = this.getView();
 var user = view.byId("movie_name").getValue();
                MessageToast.show(user);

And it worked !!


问:
Exporting CALayer with implicit animation via AVExportSession
I'm trying to export an animation for my custom CALayer with a custom property via AVExportSession, please find the setup below:

```<code>class CustomAnimatable: CALayer
{
    @NSManaged var brightness: CGFloat

    override init(layer: Any) {
        super.init(layer: layer);

        if let l = layer as? CustomAnimatable {
            self.brightness = l.brightness;
        }
    }

    override func action(forKey event: String) -> CAAction?
    {
        if event == "brightness" {
            let animation = CABasicAnimation(keyPath: event);
            animation.fromValue = presentation()?.brightness ?? self.brightness;
            return animation;
        }

        return super.action(forKey: event);
    }

    override class func needsDisplay(forKey key: String) -> Bool
    {
        if key == "brightness" {
            return true;
        }

        return super.needsDisplay(forKey: key);
    }

    override func display()
    {
        print("\(self) \(presentation()?.brightness) \(self.brightness)")
    }
}
</code>```

Here's the export session pre-setup:

```<code>func render()
{
     ......

    let parentLayer = CALayer();
    let videoLayer = CALayer();
    let animationLayer = CustomAnimatable()

    parentLayer.frame = frame;
    videoLayer.frame = frame;
    animationLayer.frame = frame;

    parentLayer.addSublayer(videoLayer);
    parentLayer.addSublayer(animationLayer);

    CATransaction.begin()
    CATransaction.setAnimationDuration(2.2);
    CATransaction.setDisableActions(true);
    CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear))

    let anim = CABasicAnimation(keyPath: "brightness");

    anim.fromValue = 1.0;
    anim.fillMode = kCAFillModeBoth;
    anim.beginTime = AVCoreAnimationBeginTimeAtZero;
    anim.repeatCount = 1;
    anim.toValue = 0.0;
    anim.isRemovedOnCompletion = false;

    animationLayer.add(anim, forKey: "anim")

    CATransaction.commit()

    let videoComposition = AVMutableVideoComposition();

    videoComposition.renderSize = CGSize(width: width, height: height);
    videoComposition.instructions = [mainInstruction];
    videoComposition.frameDuration = CMTimeMake(1, 30);
    videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer);

     ....
}
</code>```

The issue is that the brightness value in the resulting video goes from 1 to 0 without animation. If I attempt to animate CALayer's native properties, e.g. opacity - the exported animation video is totally fine, the opacity smoothly fades from 1 to 0.

Am I doing it wrong for custom property?

Things I've considered:

wrapping the explicit animation into CATransaction to disable implicit actions

setting animation begin time to AVCoreAnimationBeginTimeAtZero and isRemovedOnCompletion to false as per "Editing Media with AV Foundation" session (Core Animation Gotchas section)

I'm a bit confused by the fact that native CALayer properties animate fine, thus the export session setup seems to be correct.

Besides that, if I add the custom layer to a view and animate the brightness property - it also animates fine. So the issue seems to be specific to rendering custom property animation w/ AVExportSession.

答:
I'm not entirely sure why you have added both class videoLayer and animationLayer in parentLayer?.

```<code>parentLayer.addSublayer(videoLayer);
parentLayer.addSublayer(animationLayer);
</code>```

Use following code Hope will helpful to you!

```<code>parentLayer.addSublayer(videoLayer);
videoLayer.addSublayer(animationLayer);
</code>```

Body:
I'm trying to export an animation for my custom CALayer with a custom property via AVExportSession, please find the setup below:

class CustomAnimatable: CALayer
{
    @NSManaged var brightness: CGFloat

    override init(layer: Any) {
        super.init(layer: layer);

        if let l = layer as? CustomAnimatable {
            self.brightness = l.brightness;
        }
    }

    override func action(forKey event: String) -> CAAction?
    {
        if event == "brightness" {
            let animation = CABasicAnimation(keyPath: event);
            animation.fromValue = presentation()?.brightness ?? self.brightness;
            return animation;
        }

        return super.action(forKey: event);
    }

    override class func needsDisplay(forKey key: String) -> Bool
    {
        if key == "brightness" {
            return true;
        }

        return super.needsDisplay(forKey: key);
    }

    override func display()
    {
        print("\(self) \(presentation()?.brightness) \(self.brightness)")
    }
}

Here's the export session pre-setup:

func render()
{
     ......

    let parentLayer = CALayer();
    let videoLayer = CALayer();
    let animationLayer = CustomAnimatable()

    parentLayer.frame = frame;
    videoLayer.frame = frame;
    animationLayer.frame = frame;

    parentLayer.addSublayer(videoLayer);
    parentLayer.addSublayer(animationLayer);

    CATransaction.begin()
    CATransaction.setAnimationDuration(2.2);
    CATransaction.setDisableActions(true);
    CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear))

    let anim = CABasicAnimation(keyPath: "brightness");

    anim.fromValue = 1.0;
    anim.fillMode = kCAFillModeBoth;
    anim.beginTime = AVCoreAnimationBeginTimeAtZero;
    anim.repeatCount = 1;
    anim.toValue = 0.0;
    anim.isRemovedOnCompletion = false;

    animationLayer.add(anim, forKey: "anim")

    CATransaction.commit()

    let videoComposition = AVMutableVideoComposition();

    videoComposition.renderSize = CGSize(width: width, height: height);
    videoComposition.instructions = [mainInstruction];
    videoComposition.frameDuration = CMTimeMake(1, 30);
    videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer);

     ....
}

The issue is that the brightness value in the resulting video goes from 1 to 0 without animation. If I attempt to animate CALayer's native properties, e.g. opacity - the exported animation video is totally fine, the opacity smoothly fades from 1 to 0.

Am I doing it wrong for custom property?

Things I've considered:

wrapping the explicit animation into CATransaction to disable implicit actions

setting animation begin time to AVCoreAnimationBeginTimeAtZero and isRemovedOnCompletion to false as per "Editing Media with AV Foundation" session (Core Animation Gotchas section)

I'm a bit confused by the fact that native CALayer properties animate fine, thus the export session setup seems to be correct.

Besides that, if I add the custom layer to a view and animate the brightness property - it also animates fine. So the issue seems to be specific to rendering custom property animation w/ AVExportSession.

Body:
I'm not entirely sure why you have added both class videoLayer and animationLayer in parentLayer?.

parentLayer.addSublayer(videoLayer);
parentLayer.addSublayer(animationLayer);

Use following code Hope will helpful to you!

parentLayer.addSublayer(videoLayer);
videoLayer.addSublayer(animationLayer);


问:
How do you tamper AuthLogic to show me the "last" last_login_at?
I would like to code the progress of events that have changed since someone had last logged in.

Authlogic provides a last_login_at, but that is the datetime of when the user logged in even though he may be currently still logged on.

I'm trying to find the time when they were logged in before that. So that when a user logs in, I have a log of the last time they were logged in, and I can show them all the things that have changed since then.

I looked into AuthLogic::Session::MagicColumns which is the method that supports last_login_at, but was unable to find anything useful.

Any ideas?

答: I haven't read anything like this relating to Authlogic. It seems like you are going to have to write some custom session code to store that datetime you want. You could override the method in Authlogic that sets last_login_at and migrate the old value over to your new database column.


问:
mongoose - increment a value inside an array
I have the following schema:

```<code>var mySchema = new Schema({
  "name": String,
  "users": [
     {
       "user_id": ObjectId,
       "counter": Number
     }]
});
</code>```

example of a document:

```<code>{
   "name": "Test",
   "users": [
       {
          "user_id": "aaaaaa",
          "counter": 2
       },
       {
          "user_id": "bbbbbb",
          "counter": 3
       }]
}
</code>```

How can i findOneAndUpdate a specific user_id and increment counter?

For example: how can i find Test and update the counterof user_id: bbbbb in a single action?

答:
```<code>mongoose.model('MySchema', mySchema); //is this line superflous??
var MySchema = mongoose.model('MySchema');

MySchema.update({"name": "Test", "users.user_id" : "aaaaaa" } ,
                {$inc : {"users.$.counter" : 1} },
                function() {...});
</code>```

So with first object you are finding object that you want to update. Second parameter is what you want to update, where $ is used to change only currently selected object in query. Last parameter is callback.

Body:
I have the following schema:

var mySchema = new Schema({
  "name": String,
  "users": [
     {
       "user_id": ObjectId,
       "counter": Number
     }]
});

example of a document:

{
   "name": "Test",
   "users": [
       {
          "user_id": "aaaaaa",
          "counter": 2
       },
       {
          "user_id": "bbbbbb",
          "counter": 3
       }]
}

How can i findOneAndUpdate a specific user_id and increment counter?

For example: how can i find Test and update the counterof user_id: bbbbb in a single action?

Body:
mongoose.model('MySchema', mySchema); //is this line superflous??
var MySchema = mongoose.model('MySchema');

MySchema.update({"name": "Test", "users.user_id" : "aaaaaa" } ,
                {$inc : {"users.$.counter" : 1} },
                function() {...});

So with first object you are finding object that you want to update. Second parameter is what you want to update, where $ is used to change only currently selected object in query. Last parameter is callback.


问:
How to multiply seperate cells in excel 2016?
I am doing a Controlled assessment, and I'm trying to multiply 2 seperate cells to get a value. I tried =g2*e2, but it says #VALUE!, can anyone help me please?

A screenshot is available

答: Lol mate, you need to make it a number value, like harun24hr said.</p>


问:
Correction about list elements in one line (str to int)
I have something like this:-

```<code>List = [["a","1"],["b","2"]]
</code>```

and what I wanna do is keep single letter integers as integers.
so output should be like

```<code>List =  [["a",1],["b",2]]
</code>```

答:
Assuming that you stored that in a list called "data", you can do the following.

```<code>new_data = [[k,int(v)] for k,v in data]
</code>```

Refer below for details:

```<code>data =  [["a","1"],["b","2"]]
new_data = [[k,int(v)] for k,v in data]

print new_data
</code>```

Output:

```<code>[['a', 1], ['b', 2]]
</code>```

Body:
I have something like this:-

List = [["a","1"],["b","2"]]

and what I wanna do is keep single letter integers as integers.
so output should be like

List =  [["a",1],["b",2]]

Body:
Assuming that you stored that in a list called "data", you can do the following.

new_data = [[k,int(v)] for k,v in data]

Refer below for details:

data =  [["a","1"],["b","2"]]
new_data = [[k,int(v)] for k,v in data]

print new_data

Output:

[['a', 1], ['b', 2]]


问:
MySQL Regular expression search
Iam struck with a search query in mysql, where i want to show a user's name like John-Chow, if i enter the search string in my textbox as John Chow.

How to do this with mysql regular expression search ?

答:
How about this:

explode the textbox string in words

use the following regex :
    words1.*?words2....*?wordsN

Title: MySQL Regular expression search


问:
Finding correlation between numeric encoded categorical variables?
So I have a data set which has categorical variables. I have encoded each category from 0:x depending on the amount of categories x. I am trying to find the correlation between the variables (both numeric and categorical) to the target variable (which is also categorical, but has been coded to 0 for no and 1 for yes).

I have been able to run this code for the correlation(s) for all the variables (there are about 17) and it does seem to work, but I question whether the correlations are correct. I haven't calculated the correlation with categorical variables in my data set before, just want to ensure that I am going about this the right way:

```<code>print(df['previous'].corr(df['y']))
</code>```

Any help would be great!

答: Correlation analogue for categorical data is called cross tabulation (you get a contingency table for your data). You can do it in pandas using pandas.crosstab.</p>

Body:
So I have a data set which has categorical variables. I have encoded each category from 0:x depending on the amount of categories x. I am trying to find the correlation between the variables (both numeric and categorical) to the target variable (which is also categorical, but has been coded to 0 for no and 1 for yes).

I have been able to run this code for the correlation(s) for all the variables (there are about 17) and it does seem to work, but I question whether the correlations are correct. I haven't calculated the correlation with categorical variables in my data set before, just want to ensure that I am going about this the right way:

print(df['previous'].corr(df['y']))

Any help would be great!


问:
Rails :Can't save audio file (paperclip)
I can't save audio file, so can you tell me how to save about audio file .
I use gem paperclip !

log is
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-1bal5v0.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.1ms)  begin transaction
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-wh10af.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.2ms)  rollback transaction
Redirected to http://localhost:3000/listings/new
Completed 302 Found in 128ms (ActiveRecord: 3.0ms)

show you model listing.rb

```<code>class Listing < ApplicationRecord
     belongs_to :user
     has_many :photos
     has_many :likes
     has_many :customers
     has_many :reviews
     validates :listing_title, presence: true

    has_attached_file  :file,  :storage => :s3,
                               :s3_credentials => "#{Rails.root}/config/s3.yml"

   validates_attachment :file, content_type: { content_type: ['file/mp3'] }

 end
</code>```

show you view new.html.erb

```<code><%= form_for @listing do |f| %>
    <div class="row">
     <div class="col-md-12 select">
       <div class="form-group">
        <label>タイトル</label>
           <%= f.text_field :listing_title, autofocus: true, :placeholder => "タイトル", :class => 'form-control', required: "true" %>
       </div>
      </div>
     </div>
     <br>

     <div class="row">
      <div class="col-md-12 select">
       <div class="form-group">
        <label>ファイル</label>
          <%= f.file_field :file, :class => 'form-control' %>
       </div>
      </div>
     </div>
     <br>

     <div class="actions">
       <%= f.submit "Save", class: "btn btn-danger" %>
     </div>
<% end %>
</code>```

Controller is nothing problem! I set params!
What should I need I success to save audio file?
Please tell me!

答:
MP3 audio files has mime typed "audio/mpeg"

Change your content type to "audio/mpeg"

Body:
I can't save audio file, so can you tell me how to save about audio file .
I use gem paperclip !

log is
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-1bal5v0.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.1ms)  begin transaction
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-wh10af.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.2ms)  rollback transaction
Redirected to http://localhost:3000/listings/new
Completed 302 Found in 128ms (ActiveRecord: 3.0ms)

show you model listing.rb

class Listing < ApplicationRecord
     belongs_to :user
     has_many :photos
     has_many :likes
     has_many :customers
     has_many :reviews
     validates :listing_title, presence: true

    has_attached_file  :file,  :storage => :s3,
                               :s3_credentials => "#{Rails.root}/config/s3.yml"

   validates_attachment :file, content_type: { content_type: ['file/mp3'] }

 end

show you view new.html.erb

<%= form_for @listing do |f| %>

        タイトル
           <%= f.text_field :listing_title, autofocus: true, :placeholder => "タイトル", :class => 'form-control', required: "true" %>

        ファイル
          <%= f.file_field :file, :class => 'form-control' %>

       <%= f.submit "Save", class: "btn btn-danger" %>

<% end %>

Controller is nothing problem! I set params!
What should I need I success to save audio file?
Please tell me!