问:
Cannot add a new method to an Angular TypeScript class (FormGroup)
I am trying to add an additional method to Angular's FormGroup class which will set the state of the group + set error state from the server.

I have the following code in a form-helper.ts file in my Angular4 app.

```<code>import { FormGroup } from '@angular/forms';

export interface FormGroup {
  setValueAndErrors(state: any, memberErrors: any);
}

FormGroup.prototype.setValueAndErrors = (state: any, memberErrors: any) => {
  this.setValue(state);
  // do some stuff with the memberErrors parameter
}
</code>```

But the compiler throws an error on the FormGroup.prototype.setValueAndErrors line.

ERROR in C:/dev/AppName/AppName-Client/src/app/shared/utils/form-helper.ts (3,21): Property 'setValueAndErrors' does not exist on type 'FormGroup'.

答:
The following compiles for me:

```<code>declare module "@angular/forms/src/model" {
  interface FormGroup {
    setValueAndErrors(this: FormGroup, state: any, memberErrors: any): void;
  }
}

FormGroup.prototype.setValueAndErrors = function(this: FormGroup, state: any, memberErrors: any): void {
  this.setValue(state);
}
</code>```

The key seems to be using the module name that refers to the actual module/file that contains the FormGroup.

Also, you will need to address your usage of this.

Body:
I am trying to add an additional method to Angular's FormGroup class which will set the state of the group + set error state from the server.

I have the following code in a form-helper.ts file in my Angular4 app.

import { FormGroup } from '@angular/forms';

export interface FormGroup {
  setValueAndErrors(state: any, memberErrors: any);
}

FormGroup.prototype.setValueAndErrors = (state: any, memberErrors: any) => {
  this.setValue(state);
  // do some stuff with the memberErrors parameter
}

But the compiler throws an error on the FormGroup.prototype.setValueAndErrors line.

ERROR in C:/dev/AppName/AppName-Client/src/app/shared/utils/form-helper.ts (3,21): Property 'setValueAndErrors' does not exist on type 'FormGroup'.

Body:
The following compiles for me:

declare module "@angular/forms/src/model" {
  interface FormGroup {
    setValueAndErrors(this: FormGroup, state: any, memberErrors: any): void;
  }
}

FormGroup.prototype.setValueAndErrors = function(this: FormGroup, state: any, memberErrors: any): void {
  this.setValue(state);
}

The key seems to be using the module name that refers to the actual module/file that contains the FormGroup.

Also, you will need to address your usage of this.


来源: stackexchange

问:
Set version to latest version including prereleases in Gemfile
How do I specify a version constraint in a Gemfile, such that it always take the latest release including pre-releases of a gem.

Currently the library I work with has the latest stable release 2.0.0, and the latest pre-release 2.1.0.alpha.pre.171.

I could set the version constraint to >=2.1.0.alpha.pre.171 or just >=2.1.0.a, as I understand it. But would that also include future pre releases such as >=2.2.0.alpha.pre.1 or even >=3.0.0.alpha.pre.1 as well as future stable versions such as 3.0.0? And would that always resolve to the latest version?

Disclaimer:
To not be misunderstood, this is not for any productive dependency management. The idea is to have a demo up an running, which should always include the latest features and as well should crash if the latest pre-release is broken.

答:
This is a very bad idea in a nutshell, but it’s very easy to check:

```<code>%w|2.1.0.alpha.pre.171
   2.1.0
   2.2.0.alpha.pre.1
   3.0.0.alpha.pre.1|.map(&Gem::Version.method(:new)).sort
#⇒ [
#   [0] #<Gem::Version "2.1.0.alpha.pre.171">,
#   [1] #<Gem::Version "2.1.0">,
#   [2] #<Gem::Version "2.2.0.alpha.pre.1">,
#   [3] #<Gem::Version "3.0.0.alpha.pre.1">
# ]
</code>```

So, yes, >= will work for any new release, including 2.1.0.

ContentLicense: CC BY-SA 3.0

Body:
This is a very bad idea in a nutshell, but it’s very easy to check:

%w|2.1.0.alpha.pre.171
   2.1.0
   2.2.0.alpha.pre.1
   3.0.0.alpha.pre.1|.map(&Gem::Version.method(:new)).sort
#⇒ [
#   [0] #<Gem::Version "2.1.0.alpha.pre.171">,
#   [1] #<Gem::Version "2.1.0">,
#   [2] #<Gem::Version "2.2.0.alpha.pre.1">,
#   [3] #<Gem::Version "3.0.0.alpha.pre.1">
# ]

So, yes, >= will work for any new release, including 2.1.0.


问:
SQLIte how to insert unique data on change of column value
I am using SQLite Database for my application. I have 4 columns-  Student_Name,Student_Enroll, Student_Mob, Student_Address in my database. Now I can add new record if and only if one of four column value is different or all values are different. If all column values are same then no new record should be generated.
Can you please guide me to solve this issue?</p>

答: During Create Database line insert UNIQUE ...for each column to insert only unique record.</p>


问:
Add script to file in powershell
I am having long script that need to be added to created file, problem is its a script and it contains lots of special chars.

And I am getting a lot of error, I've put script in '' but it did not work as i expected.

Is there an easy way to do it, like taking a text and just adding it to file, somehow with special chars?

```<code>powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 - 'Function Press-Button
{
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.SendKeys]::SendWait('~');
}

Function Resize-Window
{
    $pshost = get-host
    $pswindow = $pshost.ui.rawui

    $newsize = $pswindow.buffersize
    $newsize.height = 300
    $newsize.width = 128
    $pswindow.buffersize = $newsize

    $newsize = $pswindow.windowsize
    $newsize.height = 5
    $newsize.width = 128
    $pswindow.windowsize = $newsize
}

Function Run-Tool
{
    $ps = new-object System.Diagnostics.Process
    $ps.StartInfo.Filename = "C:\Testing\bin.exe"
    $ps.StartInfo.RedirectStandardInput = $true
    $ps.StartInfo.UseShellExecute = $false

    $ps.start()

    while ( ! $ps.HasExited ) {
        Start-Sleep -s 5
        write-host "I will press button now..."
        Press-Button
    }

    Write-Output "Default key was pressed"
    Write-Output "exit code: $($ps.ExitCode)"
}

Resize-Window
Run-Tool'
</code>```

答:
You would want to use a Here String to define the block of text. You begin a here-string by using @" and end it by using "@.

The @" must be the last thing on the first line and the closing "@ must be the first two characters on the next line:

```<code>$a = @"
This is a here-string. I can type "anything" I want,
even carriage returns, and it will all be preserved.
No need to escape!
"@
</code>```

Using it with your script would look like this:

```<code>powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 @"
Function Press-Button
{
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.SendKeys]::SendWait('~');
}

Function Resize-Window
{
    $pshost = get-host
    $pswindow = $pshost.ui.rawui

    $newsize = $pswindow.buffersize
    $newsize.height = 300
    $newsize.width = 128
    $pswindow.buffersize = $newsize

    $newsize = $pswindow.windowsize
    $newsize.height = 5
    $newsize.width = 128
    $pswindow.windowsize = $newsize
}

Function Run-Tool
{
    $ps = new-object System.Diagnostics.Process
    $ps.StartInfo.Filename = "C:\Testing\bin.exe"
    $ps.StartInfo.RedirectStandardInput = $true
    $ps.StartInfo.UseShellExecute = $false

    $ps.start()

    while ( ! $ps.HasExited ) {
        Start-Sleep -s 5
        write-host "I will press button now..."
        Press-Button
    }

    Write-Output "Default key was pressed"
    Write-Output "exit code: $($ps.ExitCode)"
}

Resize-Window
Run-Tool
"@
</code>```

Title: Add script to file in powershell

Body:
I am having long script that need to be added to created file, problem is its a script and it contains lots of special chars.

And I am getting a lot of error, I've put script in '' but it did not work as i expected.

Is there an easy way to do it, like taking a text and just adding it to file, somehow with special chars?

powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 - 'Function Press-Button
{
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.SendKeys]::SendWait('~');
}

Function Resize-Window
{
    $pshost = get-host
    $pswindow = $pshost.ui.rawui

    $newsize = $pswindow.buffersize
    $newsize.height = 300
    $newsize.width = 128
    $pswindow.buffersize = $newsize

    $newsize = $pswindow.windowsize
    $newsize.height = 5
    $newsize.width = 128
    $pswindow.windowsize = $newsize
}

Function Run-Tool
{
    $ps = new-object System.Diagnostics.Process
    $ps.StartInfo.Filename = "C:\Testing\bin.exe"
    $ps.StartInfo.RedirectStandardInput = $true
    $ps.StartInfo.UseShellExecute = $false

    $ps.start()

    while ( ! $ps.HasExited ) {
        Start-Sleep -s 5
        write-host "I will press button now..."
        Press-Button
    }

    Write-Output "Default key was pressed"
    Write-Output "exit code: $($ps.ExitCode)"
}

Resize-Window
Run-Tool'

Body:
You would want to use a Here String to define the block of text. You begin a here-string by using @" and end it by using "@.

The @" must be the last thing on the first line and the closing "@ must be the first two characters on the next line:

$a = @"
This is a here-string. I can type "anything" I want,
even carriage returns, and it will all be preserved.
No need to escape!
"@

Using it with your script would look like this:

powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 @"
Function Press-Button
{
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.SendKeys]::SendWait('~');
}

Function Resize-Window
{
    $pshost = get-host
    $pswindow = $pshost.ui.rawui

    $newsize = $pswindow.buffersize
    $newsize.height = 300
    $newsize.width = 128
    $pswindow.buffersize = $newsize

    $newsize = $pswindow.windowsize
    $newsize.height = 5
    $newsize.width = 128
    $pswindow.windowsize = $newsize
}

Function Run-Tool
{
    $ps = new-object System.Diagnostics.Process
    $ps.StartInfo.Filename = "C:\Testing\bin.exe"
    $ps.StartInfo.RedirectStandardInput = $true
    $ps.StartInfo.UseShellExecute = $false

    $ps.start()

    while ( ! $ps.HasExited ) {
        Start-Sleep -s 5
        write-host "I will press button now..."
        Press-Button
    }

    Write-Output "Default key was pressed"
    Write-Output "exit code: $($ps.ExitCode)"
}

Resize-Window
Run-Tool
"@


问:
Change telegram bot owner
We have created telegram bot which has many difficult operations. Bot was created by one developer using his phone number. Is it possible change bot's owner or add another user as admin to bot? </p>

答:
Please see Bekorchi's answer, it's possible to transfer bots since 2020 October.

Out-dated:

Not possible to transfer by @BotFather command at this time (2017 July).

You can contact human supporter @BotSupport, they may have permission to transfer that.

Title: Change telegram bot owner

ContentLicense: CC BY-SA 4.0


问:
Application Project has not been registered
I am trying to run my react native app on my device .
So I am running react-native start
everything looks fine.

and when running react-native run-android I get this error

otherwise, I get this error in my device

答: Delete / uninstall first the APP installed and then do a clean install of it and see if it works.</p>


问:
ajax post method not working in vb.net
I am using jquery so using ajax to post data, but for some reason when i click on submit, the page doesnt go from aspx to aspx.vb on the back side.
here's my code -

```<code> $(document).ready(function() {
      $("#btnsave").click(function() {
          var firstname = $("#" + '<%=firstname.ClientID%>').val();
          $.ajax({
              type: "POST",
              url: "student.aspx/new_class",
              data: "firstname="+ firstname + ";",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function() {
              }
          });
      });
  });
</code>```

new_class is my webmethod in the vb.net side. Now if i put an alert in the btnsave onclick function, i see the firstname value in the alert. But the page does not call the new_class function after that.
Any ideas where i'm going wrong?

答:
That URL is incorrect for mapping to a method on the server-side code.

I assume you're trying to call a method called new_class in student.aspx.vb.  Is this correct?

What you'll want to do is create a separate page for this request.  Maybe something like student_ajax.aspx or something of that nature.  How you organize it is up to you.  The simplest way to go about doing what you're trying to do is to have the new_class logic be the Page_Load logic in the new page.  In that method you'll generate the JSON (which I'm assuming you're doing manually and correctly, but that's for a different question if it comes up) to return to the client.

Note, however, that in that page you'll need to do some trickery.  First, get rid of all of the HTML in the page itself.  You want to return only JSON, not wrapped in any HTML.  Then, when you're generating the response string in the code-behind logic, you'll want to set the header to the proper headers and output the string:

```<code>Response.Clear()
Response.ContentType = "application/json"
Response.Write(myJSONString)
Response.End()
</code>```

Note that this was all freehand, so there may be a detail or two missing in this implementation.  And I know there are more elegant ways to do this.  I'm sure you can find a tutorial or two on Google.  Essentially what you're trying to do is create a custom handler on the server for an AJAX request which returns JSON data.

ContentLicense: CC BY-SA 2.5

Title: ajax post method not working in vb.net

Body:
I am using jquery so using ajax to post data, but for some reason when i click on submit, the page doesnt go from aspx to aspx.vb on the back side.
here's my code -

 $(document).ready(function() {
      $("#btnsave").click(function() {
          var firstname = $("#" + '<%=firstname.ClientID%>').val();
          $.ajax({
              type: "POST",
              url: "student.aspx/new_class",
              data: "firstname="+ firstname + ";",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function() {
              }
          });
      });
  });

new_class is my webmethod in the vb.net side. Now if i put an alert in the btnsave onclick function, i see the firstname value in the alert. But the page does not call the new_class function after that.
Any ideas where i'm going wrong?

Body:
That URL is incorrect for mapping to a method on the server-side code.

I assume you're trying to call a method called new_class in student.aspx.vb.  Is this correct?

What you'll want to do is create a separate page for this request.  Maybe something like student_ajax.aspx or something of that nature.  How you organize it is up to you.  The simplest way to go about doing what you're trying to do is to have the new_class logic be the Page_Load logic in the new page.  In that method you'll generate the JSON (which I'm assuming you're doing manually and correctly, but that's for a different question if it comes up) to return to the client.

Note, however, that in that page you'll need to do some trickery.  First, get rid of all of the HTML in the page itself.  You want to return only JSON, not wrapped in any HTML.  Then, when you're generating the response string in the code-behind logic, you'll want to set the header to the proper headers and output the string:

Response.Clear()
Response.ContentType = "application/json"
Response.Write(myJSONString)
Response.End()

Note that this was all freehand, so there may be a detail or two missing in this implementation.  And I know there are more elegant ways to do this.  I'm sure you can find a tutorial or two on Google.  Essentially what you're trying to do is create a custom handler on the server for an AJAX request which returns JSON data.


问:
How to embed image link in drupal?
I want to add image from remote server. I have image link such as http://www.qygjxz.com/data/out/114/5095827-image.jpg
But drupal is giving only upload image option. I don't want to store image. I want to display it without storing.</p>

答:
You cannot do this with the default image field. (Assuming you are using Drupal 8)

What you can do is use a plain text field to input and store the image URL and use the field value later in your template files as image source.

Alternatively you can use ck-editor directly to upload image or use external image urls, to use external URLs only you will need to uncheck "Enable image uploads" option in admin > configuration > text formats and editors > configure(your desired text format basic/full/restricted etc).

Title: How to embed image link in drupal?


问:
Changing Custom Property on hover || VUEJS
Trying to become friends with VUEJS. Got stuck on some simple stuff, couldn't google it. So I'm using MuseUi framework in my App. Well I want to do a simple thing, change the value of the property for each specific element on hover

```<code> <mu-paper :zDepth="1" v-on:mouseover=" ???? " class="searchBox">
</code>```

I need to change:zDepth to 3 for example, on hover of the element. How could I achieve that?

full code snippet

```<code><template>
<div>
    <div class="column is-one-quarter">
        <mu-paper :zDepth="paperHover" v-on:mouseover="changePaper" class="searchBox">
            <mu-text-field fullWidth="true" :hintText="searchHint" v-model="query" class="demo-radio"/><br/>
                <mu-radio label="Name" name="group" nativeValue="1" v-model="selected" class="demo-radio"/>
                <mu-radio label="Manager" name="group" nativeValue="2" v-model="selected" class="demo-radio"/>
                <mu-radio label="Department" name="group" nativeValue="3" v-model="selected" class="demo-radio"/>
                <mu-radio label="Stage" name="group" nativeValue="4" v-model="selected" class="demo-radio"/>
                <mu-radio label="Deadline" name="group" nativeValue="5" v-model="selected" class="demo-radio"/>
                <mu-radio label="Start Date" name="group" nativeValue="6" v-model="selected" class="demo-radio"/>
        </mu-paper>
    </div>
    <div class="column is-one-column">
        <mu-float-button icon="add" v-on:click="openModal"/>
    </div>
    <div class="column">
        <draggable v-model="projects" @start="drag=true" @end="drag=false">
            <transition-group name="list-complete staggered-fade" tad="ul" :css="false" :before-enter="beforeEnter" :enter="enter" :leave="leave">
                <li v-for="(project, index) in projectsComputed"  :key="project.name" :data-index="index" class="column is-one-third list-complete-item">
                    <mu-paper :zDepth="3">
                        <mu-icon-button icon="delete" class="delete-button"></mu-icon-button>
                        <article class="media">
                            <div class="media-content">
                                <div class="content">
                                    <div class="project-name has-text-centered">
                                        <span>{{project.name}}</span>
                                    </div>
                                    <mu-badge :content="project.stage.name" primary slot="right"/>
                                    <!--<div class="project-status has-text-centered">-->
                                        <!--<span>{{project.stage.name}}</span>-->
                                    <!--</div>-->
                                    <div class="project-desc-list has-text left">
                                        <span>Manager: </span> <span>{{project.manager.name}}</span>
                                    </div>
                                    <div class="project-desc-list has-text left">
                                        <span>Department: </span> <span>{{project.department.name}}</span>
                                    </div>
                                    <div class="project-desc-list has-text left">
                                        <span>Start Date: </span> <span>{{project.started_from}}</span>
                                    </div>
                                    <div class="project-desc-list has-text left">
                                        <span>Dealine: </span> <span>{{project.deadline}}</span>
                                    </div>
                                    <p class="project-description">
                                        {{project.description}}
                                    </p>
                                </div>
                            </div>
                        </article>
                    </mu-paper>
                </li>
            </transition-group>
        </draggable>
    </div>
    <div id="modal-ter"  :class="[isActive ? activeClass : '', modal]">
        <div class="modal-background" v-on:click="openModal"></div>
        <div class="modal-card">
            <header class="modal-card-head">
                <p class="modal-card-title">Add New Project</p>
                <button v-on:click="openModal" class="delete"></button>
            </header>
            <section class="modal-card-body">
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Project Name</label>
                        <p class="control">
                            <input class="input" v-model="newProject.name" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Project Description</label>
                        <p class="control">
                            <input class="input" v-model="newProject.description" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Start Date</label>
                        <p class="control">
                            <input class="input" v-model="newProject.started_from" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Deadline</label>
                        <p class="control">
                            <input class="input" v-model="newProject.deadline" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Manager</label>
                        <p class="control">
                            <input class="input" v-model="newProject.manager.name" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Department</label>
                        <p class="control">
                            <input class="input" v-model="newProject.department.name" type="text" placeholder="Text input">
                        </p>
                    </div>
                </div>
                <div class="column is-one-third">
                    <div class="field">
                        <label class="label">Stage</label>
                        <p class="control">
                            <input class="input" type="text" v-model="newProject.stage.name" placeholder="Text input">
                        </p>
                    </div>
                </div>
            </section>
            <footer class="modal-card-foot">
                <a v-on:click="createProject" class="button is-success">Save changes</a>
                <a class="button">Cancel</a>
            </footer>
        </div>
    </div>
</div>
</template>
<style scoped>
    .demo-radio {
        min-width: 8em;
    }
    .searchBox {
        padding: 2em;
    }
    .project-status {
        position: absolute;
        top: 0.3em;
        left: 0.3em;
        background-color: #ffdb57;
        padding: 0.2em;
        padding-left: 0.5em;
        padding-right: 0.5em;
        border-radius: 0.3em;
    }
    .project-name {
        font-weight: 900;
    }
    .project-description {
        margin-top: 0.5em;
        padding-top: 1em;
        border-top: 1px solid lightgrey;
    }
    .project-desc-list span:first-of-type{
        font-weight: 900;
    }
    .box {
        position: relative;
    }
    .project-name {
        text-align: center;
    }
    .delete-button {
        background-color: rgba(255, 8, 8, 0.4);
        transition: all .25s ease-in;
        float: right;
        position: absolute;
        right: 0.3em;
        top: 0.3em;
    }

    .delete-button:hover, .delete-button:focus{
        background-color: rgba(255, 0, 0, 0.68);
    }

    .column{
        display: inline-block;
        padding: 1em;
    }

    .list-complete-item {
        transition: all 1s;
    }

    .list-complete-enter, .list-complete-leave-active {
        opacity: 0;
    }
</style>
<script >
    export default {
        data(){
            return {
                loading: false,
                isActive: false,
                paperHover: 3,
                modal: 'modal',
                searchHint: 'Search by ...',
                activeClass: 'is-active',
                query: "",
                selected: "",
                projects: [],
                newProject: {
                    name: '',
                    description: '',
                    started_from: '',
                    deadline: '',
                    manager: {
                        name: ''
                    },
                    department: {
                        name: ''
                    },
                    stage: {
                        name: ''
                    }
                },
            }
        },
        options: {
            segmentShowStroke: false
        },
        mounted() {
            this.getData();
        },
        computed: {
            projectsComputed: function () {
               var vm = this;
               if(this.selected == '1' || this.selected == ""){
                   this.searchHint = "Search by Name";
                   return this.projects.filter(function (project) {
                       return project.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '2'){
                   this.searchHint = "Search by Manager";
                   return this.projects.filter(function (project) {
                       return project.manager.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '3'){
                   this.searchHint = "Search by Department";
                   return this.projects.filter(function (project) {
                       return project.department.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '4'){
                   this.searchHint = "Search by Stage";
                   return this.projects.filter(function (project) {
                       return project.stage.name.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '5'){
                   this.searchHint = "Search by Deadline";
                   return this.projects.filter(function (project) {
                       return project.deadline.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }else if(this.selected == '6'){
                   this.searchHint = "Search by Start Date";
                   return this.projects.filter(function (project) {
                       return project.started_from.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1;
                   })
               }

            }
        },
        methods: {
            changePaper: function () {
              this.paperHover = 6 ;
            },
            beforeEnter: function (el) {
                el.style.opacity = 0
                el.style.height = 0
            },
            enter: function (el, done) {
                var delay = el.dataset.index * 150
                setTimeout(function () {
                    Velocity(
                        el,
                        { opacity: 1, height: '1.6em' },
                        { complete: done }
                    )
                }, delay)
            },
            leave: function (el, done) {
                var delay = el.dataset.index * 150
                setTimeout(function () {
                    Velocity(
                        el,
                        { opacity: 0, height: 0 },
                        { complete: done }
                    )
                }, delay)
            },
            getData() {
                this.loading = true;
                axios.get('/project/').then(({data}) => this.projects = data).then(() => this.loading = false)
            },
            openModal: function(){
                if(this.isActive){
                    this.isActive = false;
                }else {
                    this.isActive = true;
                }
            },
            createProject() {
                axios.post('project/store', this.newProject)
            }
        }
    }
</script>
enter code here
</code>```

答:
I'm not familiar with MuseUI. However, I've written a Vue.js training course. In Vue, the area where your "????" are, should be a JavaScript expression. A typical practice is to call a method on your Vue instance that would then update the value of the property for the specific element. Without more details, it's hard to provide specifics.

The bottom line is, the "????" can be a JavaScript expression.

Body:
Trying to become friends with VUEJS. Got stuck on some simple stuff, couldn't google it. So I'm using MuseUi framework in my App. Well I want to do a simple thing, change the value of the property for each specific element on hover

 <mu-paper :zDepth="1" v-on:mouseover=" ???? " class="searchBox">

I need to change:zDepth to 3 for example, on hover of the element. How could I achieve that?

full code snippet

<template>

        <mu-paper :zDepth="paperHover" v-on:mouseover="changePaper" class="searchBox">
            <mu-text-field fullWidth="true" :hintText="searchHint" v-model="query" class="demo-radio"/>

                <mu-radio label="Name" name="group" nativeValue="1" v-model="selected" class="demo-radio"/>
                <mu-radio label="Manager" name="group" nativeValue="2" v-model="selected" class="demo-radio"/>
                <mu-radio label="Department" name="group" nativeValue="3" v-model="selected" class="demo-radio"/>
                <mu-radio label="Stage" name="group" nativeValue="4" v-model="selected" class="demo-radio"/>
                <mu-radio label="Deadline" name="group" nativeValue="5" v-model="selected" class="demo-radio"/>
                <mu-radio label="Start Date" name="group" nativeValue="6" v-model="selected" class="demo-radio"/>
        </mu-paper>

        <mu-float-button icon="add" v-on:click="openModal"/>

        <draggable v-model="projects" @start="drag=true" @end="drag=false">
            <transition-group name="list-complete staggered-fade" tad="ul" :css="false" :before-enter="beforeEnter" :enter="enter" :leave="leave">

                    <mu-paper :zDepth="3">
                        <mu-icon-button icon="delete" class="delete-button"></mu-icon-button>

                                        {{project.name}}

                                    <mu-badge :content="project.stage.name" primary slot="right"/>

                                        Manager:  {{project.manager.name}}

                                        Department:  {{project.department.name}}

                                        Start Date:  {{project.started_from}}

                                        Dealine:  {{project.deadline}}

                                        {{project.description}}

                    </mu-paper>

            </transition-group>
        </draggable>

Add New Project

                <button v-on:click="openModal" class="delete"></button>

                        Project Name

                            <input class="input" v-model="newProject.name" type="text" placeholder="Text input">

                        Project Description

                            <input class="input" v-model="newProject.description" type="text" placeholder="Text input">

                        Start Date

                            <input class="input" v-model="newProject.started_from" type="text" placeholder="Text input">

                        Deadline

                            <input class="input" v-model="newProject.deadline" type="text" placeholder="Text input">

                        Manager

                            <input class="input" v-model="newProject.manager.name" type="text" placeholder="Text input">

                        Department

                            <input class="input" v-model="newProject.department.name" type="text" placeholder="Text input">

                        Stage

                            <input class="input" type="text" v-model="newProject.stage.name" placeholder="Text input">

                Save changes
                Cancel

</template>

enter code here


问:
Reading between certain lines
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!</p>

```<code># DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789
</code>```

答:
Edit4: With those comments, here's the hopefully final version:</p>

```<code>use strict;
use warnings;
use 5.010;
use Data::Dumper;

my %counter_vals;

{
    local $/ = "\n\n\n";

    while (<DATA>) {
        my ($date) = /(
                     \p{L}{3}
                     \s+
                     (?:3[0-1]|[1-2][0-9]|[1-9]))
                        .*?
                     Stats1/msxg or next;
        my @counter_vals = /counter[0-9]+:\s+([0-9]+)/g;
        push @{$counter_vals{$date}}, @counter_vals;
    }
}
say Dumper \%counter_vals;
</code>```

Title: Reading between certain lines

Body:
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!

# DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Body:
Edit4: With those comments, here's the hopefully final version:

use strict;
use warnings;
use 5.010;
use Data::Dumper;

my %counter_vals;

{
    local $/ = "\n\n\n";

    while (<DATA>) {
        my ($date) = /(
                     \p{L}{3}
                     \s+
                     (?:3[0-1]|[1-2][0-9]|[1-9]))
                        .*?
                     Stats1/msxg or next;
        my @counter_vals = /counter[0-9]+:\s+([0-9]+)/g;
        push @{$counter_vals{$date}}, @counter_vals;
    }
}
say Dumper \%counter_vals;


问:
Changing legend location seaborn factorplot
```<code>g = sns.factorplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
</code>```

In seaborn, is there a way to plot the legend in the first sub-plot instead of second? This example is from here: https://seaborn.pydata.org/generated/seaborn.factorplot.html?highlight=factor#seaborn.factorplot

答:
There is an even easier way:

```<code>g = sns.factorplot(x="time", y="pulse", hue="kind", col="diet",
                   data=exercise, legend_out=False)
</code>```

Body:
g = sns.factorplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)

In seaborn, is there a way to plot the legend in the first sub-plot instead of second? This example is from here: https://seaborn.pydata.org/generated/seaborn.factorplot.html?highlight=factor#seaborn.factorplot

Body:
There is an even easier way:

g = sns.factorplot(x="time", y="pulse", hue="kind", col="diet",
                   data=exercise, legend_out=False)


问:
How to chain in javascript yet get value in between
ok weird title, I know. However the question is simple. In a class I want to be able to do these two things:

invoice.getAmount(); // returns 1000

and

invoice.getAmount().asCurrency(); // returns $1000.00

I can do either, just don't know how to get both to work.

What I have for now for the second idea:

```<code>getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}
</code>```

That's an ugly copy of what I really have but the concept is represented...

Any idea?

Thanks

答:
You can use Number.prototype.toLocaleString():

function getAmount() {
   return 1000;
}

var result = getAmount().toLocaleString('en-EN', {style: 'currency', currency: 'USD'});

console.log(result);```

Body:
ok weird title, I know. However the question is simple. In a class I want to be able to do these two things:

invoice.getAmount(); // returns 1000

and

invoice.getAmount().asCurrency(); // returns $1000.00

I can do either, just don't know how to get both to work.

What I have for now for the second idea:

getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}

That's an ugly copy of what I really have but the concept is represented...

Any idea?

Thanks


问:
Case insensitive unique multidimensional array loop
I'm trying to loop through a multidimensional array and retreive unique values(case insensitive), can anyone help me?

```<code>$shop = array(
            array(
                'Title' => "General enquiries",
                'Phone' => 02085237289,
            ),
            array(
                'Title' => "general enquiries",
                'email' => 'something@gmail.com',
            ),
            array(
                'Title' => "not enquiries",
                'Phone' => 02039303039,
            ),
            array(
                'Title' => "Not enquiries",
                'email' => 'blah@gmail.com',
            )
        );
</code>```

This what i'm trying to create:

```<code>General Enquiries
02085237289
something@gmail.com

Not enquiries
blah@gmail.com
02039303039
</code>```

What I've tried so far:

```<code>$res = array();
foreach ($shop as $each) {
    array_push($res,strtolower($each['Title']));
    array_push($res,$each['email']);
    array_push($res,$each['Phone']);
}

$test =  array_unique($res);

foreach($test as $t){
    //echo $t;
}
</code>```

答:
I figured things out in the end thanks to Rasclatt and  Haotian Liu. I thought I should put it up just in case people were curious.
Thanks guys!

I changed the array a bit, this is how it looked:

```<code>Array
(
    [0] => Array
        (
            [contact_description] => Employment support
            [contact_type] => Phone
            [contact] => 0300 456 8110
        )

    [1] => Array
        (
            [contact_description] => General enquiries
            [contact_type] => Phone
            [contact] => 0300 456 8052
        )

    [2] => Array
        (
            [contact_description] => employment support
            [contact_type] => Email
            [contact] => employmentservices.osc@remploy.co.u
        )

    [3] => Array
        (
            [contact_description] => general enquiries
            [contact_type] => Email
            [contact] => info@remploy.co.uk
        )

)

 $res = array();
 foreach ($shop as $each) {
      $lcValue = strtolower($each['Title']);
       if (isset($res[$lcValue]))
           array_push($res[$lcValue], $each['contact']);
       else
          $res[$lcValue] = array($each['contact']);
   }

foreach ($res as $name => $contact) {
                    echo '<h5 class="mb-0">' . ucwords($name) . '</h5>';
                    foreach ($contact as $contact) {
                        if (1 === preg_match('~[0-9]~', $contact)) {
                            // Phone Number
                            echo '<li class="work_number"><a href="tel:' . $contact . '">' . $contact . '</a></li>';
                        } elseif (strpos($contact, '@') !== false) {
                            //Email
                            echo '<li class="email"><a href="mailto:' . $contact . '" target="_blank">' . $contact . '</a></li>';
                        } else {
                            echo '<li><a>' . $contact . '</a></li>';
                        }
                    }

                }
</code>```

Body:
I'm trying to loop through a multidimensional array and retreive unique values(case insensitive), can anyone help me?

$shop = array(
            array(
                'Title' => "General enquiries",
                'Phone' => 02085237289,
            ),
            array(
                'Title' => "general enquiries",
                'email' => 'something@gmail.com',
            ),
            array(
                'Title' => "not enquiries",
                'Phone' => 02039303039,
            ),
            array(
                'Title' => "Not enquiries",
                'email' => 'blah@gmail.com',
            )
        );

This what i'm trying to create:

General Enquiries
02085237289
something@gmail.com

Not enquiries
blah@gmail.com
02039303039

What I've tried so far:

$res = array();
foreach ($shop as $each) {
    array_push($res,strtolower($each['Title']));
    array_push($res,$each['email']);
    array_push($res,$each['Phone']);
}

$test =  array_unique($res);

foreach($test as $t){
    //echo $t;
}

Body:
I figured things out in the end thanks to Rasclatt and  Haotian Liu. I thought I should put it up just in case people were curious.
Thanks guys!

I changed the array a bit, this is how it looked:

Array
(
    [0] => Array
        (
            [contact_description] => Employment support
            [contact_type] => Phone
            [contact] => 0300 456 8110
        )

    [1] => Array
        (
            [contact_description] => General enquiries
            [contact_type] => Phone
            [contact] => 0300 456 8052
        )

    [2] => Array
        (
            [contact_description] => employment support
            [contact_type] => Email
            [contact] => employmentservices.osc@remploy.co.u
        )

    [3] => Array
        (
            [contact_description] => general enquiries
            [contact_type] => Email
            [contact] => info@remploy.co.uk
        )

)

 $res = array();
 foreach ($shop as $each) {
      $lcValue = strtolower($each['Title']);
       if (isset($res[$lcValue]))
           array_push($res[$lcValue], $each['contact']);
       else
          $res[$lcValue] = array($each['contact']);
   }

foreach ($res as $name => $contact) {
                    echo '<h5 class="mb-0">' . ucwords($name) . '</h5>';
                    foreach ($contact as $contact) {
                        if (1 === preg_match('~[0-9]~', $contact)) {
                            // Phone Number
                            echo '<li class="work_number"><a href="tel:' . $contact . '">' . $contact . '</a></li>';
                        } elseif (strpos($contact, '@') !== false) {
                            //Email
                            echo '<li class="email"><a href="mailto:' . $contact . '" target="_blank">' . $contact . '</a></li>';
                        } else {
                            echo '<li><a>' . $contact . '</a></li>';
                        }
                    }

                }


问:
SerialPort.ReadLine() slow compared to manual method?
I've recently implemented a small program which reads data coming from a sensor and plotting it as diagram.

The data comes in as chunks of 5 bytes, roughly every 500 µs (baudrate: 500000). Around 3000 chunks make up a complete line. So the total transmission time is around 1.5 s.

As I was looking at the live diagram I noticed a severe lag between what is shown and what is currently measured. Investigating, it all boiled down to:

```<code>SerialPort.ReadLine();
</code>```

It takes around 0.5 s more than the line to be transmitted. So each line read takes around 2 s. Interestingly no data is lost, it just lags behind even more with each new line read. This is very irritating for the user, so I couldn't leave it like that.

I've implemented my own variant and it shows a consistent time of around 1.5 s, and no lag occurs. I'm not really proud of my implementation (more or less polling the BaseStream) and I'm wondering if there is a way to speed up the ReadLine function of the SerialPort class. With my implementation I'm also getting some corrupted lines, and haven't found the exact issue yet.

I've tried changing the ReadTimeout to 1600, but that just produced a TimeoutException. Although the data arrived.

Any explanation as of why it is slow or a way to fix it is appreciated.

As a side-note: I've tried this on a Console application with only SerialPort.ReadLine() as well and the result is the same, so I'm ruling out my own application affecting the SerialPort.

I'm not sure this is relevant, but my implementation looks like this:

```<code>LineSplitter lineSplitter = new LineSplitter();
async Task<string> SerialReadLineAsync(SerialPort serialPort)
{
    byte[] buffer = new byte[5];
    string ret = string.Empty;

    while (true)
    {
        try
        {
            int bytesRead = await serialPort.BaseStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
            byte[] line = lineSplitter.OnIncomingBinaryBlock(this, buffer, bytesRead);
            if (null != line)
            {
                return Encoding.ASCII.GetString(line).TrimEnd('\r', '\n');
            }
        }
        catch
        {
            return string.Empty;
        }
    }
}
</code>```

With LineSplitter being the following:

```<code>class LineSplitter
{
    // based on: http://www.sparxeng.com/blog/software/reading-lines-serial-port
    public byte Delimiter = (byte)'\n';
    byte[] leftover;

    public byte[] OnIncomingBinaryBlock(object sender, byte[] buffer, int bytesInBuffer)
    {
        leftover = ConcatArray(leftover, buffer, 0, bytesInBuffer);
        int newLineIndex = Array.IndexOf(leftover, Delimiter);
        if (newLineIndex >= 0)
        {
            byte[] result = new byte[newLineIndex+1];
            Array.Copy(leftover, result, result.Length);
            byte[] newLeftover = new byte[leftover.Length - result.Length];
            Array.Copy(leftover, newLineIndex + 1, newLeftover, 0, newLeftover.Length);
            leftover = newLeftover;

            return result;
        }
        return null;
    }

    static byte[] ConcatArray(byte[] head, byte[] tail, int tailOffset, int tailCount)
    {
        byte[] result;
        if (head == null)
        {
            result = new byte[tailCount];
            Array.Copy(tail, tailOffset, result, 0, tailCount);
        }
        else
        {
            result = new byte[head.Length + tailCount];
            head.CopyTo(result, 0);
            Array.Copy(tail, tailOffset, result, head.Length, tailCount);
        }

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

答:
I ran into this issue in 2008 talking to GPS modules. Essentially the blocking functions are flaky and the solution is to use APM.

Here are the gory details in another Stack Overflow answer: How to do robust SerialPort programming with .NET / C#?

You may also find this of interest: How to kill off a pending APM operation

Body:
I've recently implemented a small program which reads data coming from a sensor and plotting it as diagram.

The data comes in as chunks of 5 bytes, roughly every 500 µs (baudrate: 500000). Around 3000 chunks make up a complete line. So the total transmission time is around 1.5 s.

As I was looking at the live diagram I noticed a severe lag between what is shown and what is currently measured. Investigating, it all boiled down to:

SerialPort.ReadLine();

It takes around 0.5 s more than the line to be transmitted. So each line read takes around 2 s. Interestingly no data is lost, it just lags behind even more with each new line read. This is very irritating for the user, so I couldn't leave it like that.

I've implemented my own variant and it shows a consistent time of around 1.5 s, and no lag occurs. I'm not really proud of my implementation (more or less polling the BaseStream) and I'm wondering if there is a way to speed up the ReadLine function of the SerialPort class. With my implementation I'm also getting some corrupted lines, and haven't found the exact issue yet.

I've tried changing the ReadTimeout to 1600, but that just produced a TimeoutException. Although the data arrived.

Any explanation as of why it is slow or a way to fix it is appreciated.

As a side-note: I've tried this on a Console application with only SerialPort.ReadLine() as well and the result is the same, so I'm ruling out my own application affecting the SerialPort.

I'm not sure this is relevant, but my implementation looks like this:

LineSplitter lineSplitter = new LineSplitter();
async Task<string> SerialReadLineAsync(SerialPort serialPort)
{
    byte[] buffer = new byte[5];
    string ret = string.Empty;

    while (true)
    {
        try
        {
            int bytesRead = await serialPort.BaseStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
            byte[] line = lineSplitter.OnIncomingBinaryBlock(this, buffer, bytesRead);
            if (null != line)
            {
                return Encoding.ASCII.GetString(line).TrimEnd('\r', '\n');
            }
        }
        catch
        {
            return string.Empty;
        }
    }
}

With LineSplitter being the following:

class LineSplitter
{
    // based on: http://www.sparxeng.com/blog/software/reading-lines-serial-port
    public byte Delimiter = (byte)'\n';
    byte[] leftover;

    public byte[] OnIncomingBinaryBlock(object sender, byte[] buffer, int bytesInBuffer)
    {
        leftover = ConcatArray(leftover, buffer, 0, bytesInBuffer);
        int newLineIndex = Array.IndexOf(leftover, Delimiter);
        if (newLineIndex >= 0)
        {
            byte[] result = new byte[newLineIndex+1];
            Array.Copy(leftover, result, result.Length);
            byte[] newLeftover = new byte[leftover.Length - result.Length];
            Array.Copy(leftover, newLineIndex + 1, newLeftover, 0, newLeftover.Length);
            leftover = newLeftover;

            return result;
        }
        return null;
    }

    static byte[] ConcatArray(byte[] head, byte[] tail, int tailOffset, int tailCount)
    {
        byte[] result;
        if (head == null)
        {
            result = new byte[tailCount];
            Array.Copy(tail, tailOffset, result, 0, tailCount);
        }
        else
        {
            result = new byte[head.Length + tailCount];
            head.CopyTo(result, 0);
            Array.Copy(tail, tailOffset, result, head.Length, tailCount);
        }

        return result;
    }
}


问:
Pandas Series boxplot not showing correctly
I have a Pandas Series named a, and a.describe() gives this

```<code>count    1116.000
mean      211.495
std      1241.612
min         1.000
25%        16.000
50%        20.000
75%        57.000
max     23220.000
</code>```

I'd like to create a boxplot out of it so I did a.plot(kind='box'), there is what I get：

The first few entries of the series look like this:

```<code>338.000
17.000
9.000
20.000
68.000
288.000
18.000
25.000
</code>```

Why isn't the boxplot showing up correctly?

The maximum value indeed makes this plot unreadable. I decide to hide the outliers by doing this:

```<code>plt.boxplot(a, showfliers=False)
</code>```

答: Actually, regarding to your values, your box plot is showing up 'correctly' because of your max value : 23220.000. Try playing with xlim and ylim arguments of Pandas plot function</p>

Body:
I have a Pandas Series named a, and a.describe() gives this

count    1116.000
mean      211.495
std      1241.612
min         1.000
25%        16.000
50%        20.000
75%        57.000
max     23220.000

I'd like to create a boxplot out of it so I did a.plot(kind='box'), there is what I get：

The first few entries of the series look like this:

338.000
17.000
9.000
20.000
68.000
288.000
18.000
25.000

Why isn't the boxplot showing up correctly?

The maximum value indeed makes this plot unreadable. I decide to hide the outliers by doing this:

plt.boxplot(a, showfliers=False)


问:
Cannot read property '.then' of undefined when testing async action creators with redux and react
I'm trying to write some test using react, redux-mock-store and redux, but I keep getting and error. Maybe because my Promise has not yet been resolved?

The fetchListing() action creator actually works when I try it on dev and production, but I'm having problems making the test pass.

error message

```<code>(node:19143) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): SyntaxError
(node:19143) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
 FAIL  src/actions/__tests__/action.test.js
  ● async actions › creates "FETCH_LISTINGS" when fetching listing has been done

    TypeError: Cannot read property 'then' of undefined

      at Object.<anonymous> (src/actions/__tests__/action.test.js:44:51)
          at Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:169:7)

  async actions
    ✕ creates "FETCH_LISTINGS" when fetching listing has been done (10ms)
</code>```

action/index.js

```<code>// actions/index.js
import axios from 'axios';

import { FETCH_LISTINGS } from './types';

export function fetchListings() {

  const request = axios.get('/5/index.cfm?event=stream:listings');

  return (dispatch) => {
    request.then(( { data } ) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
};
</code>```

action.test.js

```<code>// actions/__test__/action.test.js

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { applyMiddleware } from 'redux';
import nock from 'nock';
import expect from 'expect';

import * as actions from '../index';
import * as types from '../types';

const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
})

it('creates "FETCH_LISTINGS" when fetching listing has been done', () => {
  nock('http://example.com/')
    .get('/listings')
    .reply(200, { body: { listings: [{ 'corpo_id': 5629, id: 1382796, name: 'masm' }] } })

    const expectedActions = [
      { type: types.FETCH_LISTINGS }, { body: { listings: [{ 'corpo_id': 5629, id: 1382796, name: 'masm' }] }}
    ]

    const store = mockStore({ listings: [] })

    return store.dispatch(actions.fetchListings()).then((data) => {
      expect(store.getActions()).toEqual(expectedActions)
    })
  })
})
</code>```

答:
store.dispatch(actions.fetchListings()) returns undefined. You can't call .then on that.

See redux-thunk code. It executes the function you return and returns that. The function you return in fetchListings returns nothing, i.e. undefined.

Try

```<code>return (dispatch) => {
    return request.then( (data) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
</code>```

After that you will still have another problem. You don't return anything inside your then, you only dispatch. That means the next then gets undefined argument

Body:
I'm trying to write some test using react, redux-mock-store and redux, but I keep getting and error. Maybe because my Promise has not yet been resolved?

The fetchListing() action creator actually works when I try it on dev and production, but I'm having problems making the test pass.

error message

(node:19143) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): SyntaxError
(node:19143) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
 FAIL  src/actions/__tests__/action.test.js
  ● async actions › creates "FETCH_LISTINGS" when fetching listing has been done

    TypeError: Cannot read property 'then' of undefined

      at Object.<anonymous> (src/actions/__tests__/action.test.js:44:51)
          at Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:169:7)

  async actions
    ✕ creates "FETCH_LISTINGS" when fetching listing has been done (10ms)

action/index.js

// actions/index.js
import axios from 'axios';

import { FETCH_LISTINGS } from './types';

export function fetchListings() {

  const request = axios.get('/5/index.cfm?event=stream:listings');

  return (dispatch) => {
    request.then(( { data } ) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
};

action.test.js

// actions/__test__/action.test.js

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { applyMiddleware } from 'redux';
import nock from 'nock';
import expect from 'expect';

import * as actions from '../index';
import * as types from '../types';

const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
})

it('creates "FETCH_LISTINGS" when fetching listing has been done', () => {
  nock('http://example.com/')
    .get('/listings')
    .reply(200, { body: { listings: [{ 'corpo_id': 5629, id: 1382796, name: 'masm' }] } })

    const expectedActions = [
      { type: types.FETCH_LISTINGS }, { body: { listings: [{ 'corpo_id': 5629, id: 1382796, name: 'masm' }] }}
    ]

    const store = mockStore({ listings: [] })

    return store.dispatch(actions.fetchListings()).then((data) => {
      expect(store.getActions()).toEqual(expectedActions)
    })
  })
})

Body:
store.dispatch(actions.fetchListings()) returns undefined. You can't call .then on that.

See redux-thunk code. It executes the function you return and returns that. The function you return in fetchListings returns nothing, i.e. undefined.

Try

return (dispatch) => {
    return request.then( (data) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }

After that you will still have another problem. You don't return anything inside your then, you only dispatch. That means the next then gets undefined argument


问:
MSSQL Query Not Returning Null Columns/Results
I'm kind of new to SQL queries so this is probably something easily fixed, but I can't seem to find any answers.

I've got a bunch of related tables. E.g.
SPClients contains iClientID and sName, SPDocTypes contains iDocTypeID and sName, SPCreditor contains iCreditorID and sName

and then

SPDocIndex contains iIndexID, and then foreign keys to iClientID, iDocTypeID and iCreditorID listed above.

If I do a simple SELECT * FROM SPDocIndex I get all results, with just the IDs being displayed, which isn't much use when bound to a datagrid. So I use an inner join so the actual names appear rather than just their IDs, like so:

```<code>SELECT * FROM SPDocIndex
INNER JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
INNER JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
INNER JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID
</code>```

And the query "works" but it only returns rows that have data in all three columns. If the iCreditorID column of SPDocIndex is null, then that row is NOT returned...but I would like all rows to be returned irrespective of whether the columns are null or not.

答:
Benny - some of the others responded in the comments, that you'll need to adjust your join to a left join instead of an inner join; indeed,  that is the case here. Please check out this link for a quick tutorial on the differences between SQL joins.

https://www.w3schools.com/sql/sql_join.asp

Body:
I'm kind of new to SQL queries so this is probably something easily fixed, but I can't seem to find any answers.

I've got a bunch of related tables. E.g.
SPClients contains iClientID and sName, SPDocTypes contains iDocTypeID and sName, SPCreditor contains iCreditorID and sName

and then

SPDocIndex contains iIndexID, and then foreign keys to iClientID, iDocTypeID and iCreditorID listed above.

If I do a simple SELECT * FROM SPDocIndex I get all results, with just the IDs being displayed, which isn't much use when bound to a datagrid. So I use an inner join so the actual names appear rather than just their IDs, like so:

SELECT * FROM SPDocIndex
INNER JOIN SPClients ON SPDocIndex.iClientID=SPClients.iClientID
INNER JOIN SPDocType ON SPDocIndex.iDocTypeID=SPDocType.iDocTypeID
INNER JOIN SPCreditor ON SPDocIndex.iCreditorID=SPCreditor.iCreditorID

And the query "works" but it only returns rows that have data in all three columns. If the iCreditorID column of SPDocIndex is null, then that row is NOT returned...but I would like all rows to be returned irrespective of whether the columns are null or not.


问:
path param in URL in GO without any web framework
While developing a REST api in Go, how can we use path params? meaning to say what will be the format of the URI?

```<code>http://localhost:8765/myapp/{param1}/entries/{param2}
</code>```

I tried using something like this to create the route but the handler function is not getting invoked.

Please note that, i intent to use only the net/http package , not any other web framework like gorilla mux.

答:
What I tend to do is nested handlers. "/" is handled by the root handler. It pops the first part of the path, assigns the rest back to req.URL.Path (effectively acting like StripPrefix), determines which handler handles routes by that prefix (if any), then chains the appropriate handler. If that handler needs to parse an ID out of the path, it can, by the same mechansim - pop the first part of the path, parse it as necessary, then act.

This not only has no external dependencies, but it is faster than any router could ever be, because the routing is hard-coded rather than dynamic. Unless routing changes at runtime (which would be pretty unusual), there is no need for routing to be handled dynamically.

Body:
While developing a REST api in Go, how can we use path params? meaning to say what will be the format of the URI?

http://localhost:8765/myapp/{param1}/entries/{param2}

I tried using something like this to create the route but the handler function is not getting invoked.

Please note that, i intent to use only the net/http package , not any other web framework like gorilla mux.


问:
Can I get the url of current page from xslt?
Is is possible to get the URL of the page in XSL similar to javascript's location.href ?</p>

答: In XSLT 2.0 you have access to all XPath 2.0 functions https://www.w3.org/TR/xpath-functions/ and there you will find https://www.w3.org/TR/xpath-functions/#func-document-uri e.g document-uri(/) and https://www.w3.org/TR/xpath-functions/#func-base-uri. Whether that helps to "get the URL of the page" I am not sure because I am not sure what you consider "the page". An XSLT document processes various input documents and you can find the URI of the currently processed one using document-uri(/).


问:
Rspec - How to clean the database after each test
I have a feature spec with Capybara for a login page, and I am using FactoryGirl + DatabaseCleaner

```<code>require 'rails_helper'

feature 'Admin signs in' do

  background do
    FactoryGirl.create(:user)
  end

  scenario 'with valid credentials' do
    visit admin_root_path
    fill_in 'user_email', :with => 'email@email.com'
    fill_in 'user_password', :with => 'testpassword'
    click_button 'Sign in'
    expect(page).to have_content('Dashboard')
  end

  scenario 'with invalid credentials' do
    visit admin_root_path
    fill_in 'user_email', :with => 'email@email.com'
    fill_in 'user_password', :with => 'wrongpassword'
    click_button 'Sign in'
    expect(page).to have_content('Admin Login')
  end

end
</code>```

running the test, I get the following error:

```<code>1) Admin signs in test with invalid credentials
 Failure/Error: FactoryGirl.create(:user)
 ActiveRecord::RecordInvalid:
   Validation failed: Email has already been taken
</code>```

I thought DatabaseCleaner would revert the changes, but it looks like the user record persist in the database till the second scenario block.

How can I make sure that the database is cleaned after the first scenario?

I configured Database cleaner following this post

```<code># support/database_cleaner_spec.rb

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end
</code>```

I have also updated the spec helper file with:

```<code>config.use_transactional_fixtures = false
</code>```

答:
```<code>  config.before(:example) do
    DatabaseCleaner.clean_with(:truncation)
  end
</code>```

worked for me!

Body:
I have a feature spec with Capybara for a login page, and I am using FactoryGirl + DatabaseCleaner

require 'rails_helper'

feature 'Admin signs in' do

  background do
    FactoryGirl.create(:user)
  end

  scenario 'with valid credentials' do
    visit admin_root_path
    fill_in 'user_email', :with => 'email@email.com'
    fill_in 'user_password', :with => 'testpassword'
    click_button 'Sign in'
    expect(page).to have_content('Dashboard')
  end

  scenario 'with invalid credentials' do
    visit admin_root_path
    fill_in 'user_email', :with => 'email@email.com'
    fill_in 'user_password', :with => 'wrongpassword'
    click_button 'Sign in'
    expect(page).to have_content('Admin Login')
  end

end

running the test, I get the following error:

1) Admin signs in test with invalid credentials
 Failure/Error: FactoryGirl.create(:user)
 ActiveRecord::RecordInvalid:
   Validation failed: Email has already been taken

I thought DatabaseCleaner would revert the changes, but it looks like the user record persist in the database till the second scenario block.

How can I make sure that the database is cleaned after the first scenario?

I configured Database cleaner following this post

# support/database_cleaner_spec.rb

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end

I have also updated the spec helper file with:

config.use_transactional_fixtures = false

Body:
  config.before(:example) do
    DatabaseCleaner.clean_with(:truncation)
  end

worked for me!


问:
Excel VBA - append formatted text to cell
I need to add a "padding-bottom" to a cell in VBA.

A way to get what I need might be to append to a cell a char  with smaller font size (let's say a small dot) in a new line.

How can I achieve this in VBA?

答:
The following will insert "my text" into range A1, you can adapt it as you need.

It works as follows:

Get the current number of characters in Range A1 (lOldTextLen)

Insert two line breaks and "my text" into Range A1

Update the characters in Range A1 to font size 8, starting from the end of the previous text (using lOldTextLen)

```<code>Dim sText As String
Dim lOldTextLen As Long

sText = "my text"
lOldTextLen = Len(Range("a1"))

Range("a1").Value = Range("a1").Value & vbNewLine & vbNewLine & sText

Range("a1").Characters(lOldTextLen + 1).Font.Size = 8
</code>```

Body:
The following will insert "my text" into range A1, you can adapt it as you need.

It works as follows:

Get the current number of characters in Range A1 (lOldTextLen)

Insert two line breaks and "my text" into Range A1

Update the characters in Range A1 to font size 8, starting from the end of the previous text (using lOldTextLen)

Dim sText As String
Dim lOldTextLen As Long

sText = "my text"
lOldTextLen = Len(Range("a1"))

Range("a1").Value = Range("a1").Value & vbNewLine & vbNewLine & sText

Range("a1").Characters(lOldTextLen + 1).Font.Size = 8


问:
TYPO3 6.2 suddenly extreme slow (only frontend!)
We run several TYPO3 websites on Apache (Linux 3.16, mysql 5.6, PHP 5.6). One of our websites (TYPO3 6.2.19) is suddenly extremely slowly but only the frontend. Loading time is always more than 60s but maximum 1.8 min. Site did always run smooth and fast. No changes in server settings were made since the past days.

I already tried to restart apache and sql server, cleared all TYPO3 caches... no changes in frontend.

Any ideas what could cause this error?

答:
Can you activate the scheduler extension and execute garbage collection tasks?
Then see, if that helps

Do you have access to the server and can you restart services?
Then try restarting apache

I had a similar situation once, the issue was based on wrong permissions and php session files that could not be deleted. Switching to memcache session handling for php solved the issue.


问:
How to get check with multiple value to one input
This is my code to get value from check field..

```<code>$(document).ready(function(){
    $(document).on("change keyup mouseup", "#title", function(){
        $("#alias").val($("#title").val())
    });
});
</code>```

https://jsfiddle.net/javasalden/vf4uzjhp/

How to complete this code to show:

If i check "HONDA" and "AUDI":

Output: Toyota, Honda, Audi

If i uncheck Honda

Output: Toyota, Audi

答:
Check the below code. You need to get all the checked and append the values in the input field:

var checkboxes = $(".has-value");
checkboxes.on("change", function() {
  $("#alias").val(
    checkboxes.filter(":checked").map(function() {
      return this.value;
    }).get().join(", ")
  );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="has-value m-r" id="title" value="Toyota," type="checkbox">Toyota
<input class="has-value m-r" value="Honda," type="checkbox">Honda
<input class="has-value m-r" value="Honda," type="checkbox">Audi
<br><br>
<input class="  " name="alias" id="alias">
<br><br> if i check "HONDA" and "AUDI"<br><br> result input will like this Toyota, Honda, Audi
<br><br><br> if i Uncheck Honda
<br><br> result will like this Toyota, Audi</code>```

Body:
This is my code to get value from check field..

$(document).ready(function(){
    $(document).on("change keyup mouseup", "#title", function(){
        $("#alias").val($("#title").val())
    });
});

https://jsfiddle.net/javasalden/vf4uzjhp/

How to complete this code to show:

If i check "HONDA" and "AUDI":

Output: Toyota, Honda, Audi

If i uncheck Honda

Output: Toyota, Audi

Body:
Check the below code. You need to get all the checked and append the values in the input field:

var checkboxes = $(".has-value");
checkboxes.on("change", function() {
  $("#alias").val(
    checkboxes.filter(":checked").map(function() {
      return this.value;
    }).get().join(", ")
  );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="has-value m-r" id="title" value="Toyota," type="checkbox">Toyota
<input class="has-value m-r" value="Honda," type="checkbox">Honda
<input class="has-value m-r" value="Honda," type="checkbox">Audi
<br><br>
<input class="  " name="alias" id="alias">
<br><br> if i check "HONDA" and "AUDI"<br><br> result input will like this Toyota, Honda, Audi
<br><br><br> if i Uncheck Honda
<br><br> result will like this Toyota, Audi


问:
Unable to route to child resource - Nested routes
I've been banging my head against this one for few days now ......

my routes.rb file looks like this:

```<code>resources :vehicles do
 member do
   resources :services
 end
end
</code>```

my service.rb file shows:

```<code>class Service < ActiveRecord::Base
  belongs_to :vehicle
end
</code>```

my vehicle.rb file shows:

```<code>class Vehicle < ActiveRecord::Base
  has_many :services, :dependent => :destroy
end
</code>```

Here is services_controller.rb

```<code>class ServicesController < ApplicationController

  def index
    @vehicle = Vehicle.find(params[:id])
    @services = @vehicle.services.order('created_at DESC')
  end

  def show
    @vehicle = Vehicle.find(params[:id])
    @service = Vehicle.services.find(params[:service_id])
  end

  def new
    @vehicle = Vehicle.find(params[:id])
    @service = @vehicle.services.new
  end

  def create
    @vehicle = Vehicle.find(params[:id])
    @service = @vehicle.services.build(service_params)
    if @service.save
      redirect_to @vehicle
    else
      render :new
    end
  end

  private
    def service_params
       params.require(:service).permit(:service_option, :odometer,
   :current_service, :price, :comments, :next_service)
  end

end
</code>```

And here is the services#index

```<code><h1>Services</h1>

<% @services.each do |s| %>
  <%= link_to "Details", service_path(s) %>
  <%= s.created_at %>
  <%= s.service_option %>
  <%= s.odometer %><br>
<% end %>
</code>```

Clicking on the "Details" link or manually entering the URL

http://localhost:3000/vehicles/2/services/7

gives my systematically the same routing error:

ActiveRecord::RecordNotFound in ServicesController#show
    Couldn't find Vehicle with 'id'=7

```<code>Extracted source (around line #10):

def show
   @vehicle = Vehicle.find(params[:id])
   @service = Vehicle.services.find(params[:service_id])
end
</code>```

It passes a SERVICE ID to a vehicle objet / variable and I don't know why!

Thanks a million!

答:
In your services#show method you are fetching the vehicle and service with wrong params. Also Vehicle.services is wrong, it should be @vehicle.services

```<code>def show
  @vehicle = Vehicle.find(params[:vehicle_id])
  @service = @vehicle.services.find(params[:id])
end
</code>```

Update:

You should remove member in the routes, else it will produce the routes like

```<code>service GET  /vehicles/:id/services/:id(.:format)  services#show
</code>```

which are irrelevant

```<code>resources :vehicles do
  resources :services
end
</code>```

So now you will have routes like

```<code>service GET  /vehicles/:vehicle_id/services/:id(.:format)  services#show
</code>```

which are relevant and you can fetch the vehicle with params[:vehicle_id] and service with params[:id]

Don't forget to change the route helpers. For instance service_path will become vehicle_service_path

```<code><%= link_to "Details", vehicle_service_path(@vehicle,s) %>
</code>```

Body:
I've been banging my head against this one for few days now ......

my routes.rb file looks like this:

resources :vehicles do
 member do
   resources :services
 end
end

my service.rb file shows:

class Service < ActiveRecord::Base
  belongs_to :vehicle
end

my vehicle.rb file shows:

class Vehicle < ActiveRecord::Base
  has_many :services, :dependent => :destroy
end

Here is services_controller.rb

class ServicesController < ApplicationController

  def index
    @vehicle = Vehicle.find(params[:id])
    @services = @vehicle.services.order('created_at DESC')
  end

  def show
    @vehicle = Vehicle.find(params[:id])
    @service = Vehicle.services.find(params[:service_id])
  end

  def new
    @vehicle = Vehicle.find(params[:id])
    @service = @vehicle.services.new
  end

  def create
    @vehicle = Vehicle.find(params[:id])
    @service = @vehicle.services.build(service_params)
    if @service.save
      redirect_to @vehicle
    else
      render :new
    end
  end

  private
    def service_params
       params.require(:service).permit(:service_option, :odometer,
   :current_service, :price, :comments, :next_service)
  end

end

And here is the services#index

Services

<% @services.each do |s| %>
  <%= link_to "Details", service_path(s) %>
  <%= s.created_at %>
  <%= s.service_option %>
  <%= s.odometer %>

<% end %>

Clicking on the "Details" link or manually entering the URL

http://localhost:3000/vehicles/2/services/7

gives my systematically the same routing error:

ActiveRecord::RecordNotFound in ServicesController#show
    Couldn't find Vehicle with 'id'=7

Extracted source (around line #10):

def show
   @vehicle = Vehicle.find(params[:id])
   @service = Vehicle.services.find(params[:service_id])
end

It passes a SERVICE ID to a vehicle objet / variable and I don't know why!

Thanks a million!

Body:
In your services#show method you are fetching the vehicle and service with wrong params. Also Vehicle.services is wrong, it should be @vehicle.services

def show
  @vehicle = Vehicle.find(params[:vehicle_id])
  @service = @vehicle.services.find(params[:id])
end

Update:

You should remove member in the routes, else it will produce the routes like

service GET  /vehicles/:id/services/:id(.:format)  services#show

which are irrelevant

resources :vehicles do
  resources :services
end

So now you will have routes like

service GET  /vehicles/:vehicle_id/services/:id(.:format)  services#show

which are relevant and you can fetch the vehicle with params[:vehicle_id] and service with params[:id]

Don't forget to change the route helpers. For instance service_path will become vehicle_service_path

<%= link_to "Details", vehicle_service_path(@vehicle,s) %>


问:
Swift - How to change the color of an accessoryType (disclosureIndicator)?
I have question about the accessoryType of cells. I am using a cell with an disclosureIndicator as accessoryType and I want to change it's color but I can't.
Does anyone know if this is a bug or if Apple forces me to use the grey color?
Actually I can change the colors of other accessoryType.

My code looks like this:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! customCell
cell.tintColor = UIColor.red
cell.accessoryType = .disclosureIndicator
</code>```

And my arrow is still grey. But if I use a checkmark accessoryType it becomes red.

Is there any way to fix this or do I have to use a colored image?

答:
You can do something like this

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.tintColor = UIColor.white

    let image = UIImage(named: "Arrow.png")
    let checkmark  = UIImageView(frame:CGRect(x:0, y:0, width:(image?.size.width)!, height:(image?.size.height)!));
    checkmark.image = image
    cell.accessoryView = checkmark

    let object = objects[indexPath.row] as! NSDate
    cell.textLabel!.text = object.description
    return cell
}
</code>```

Sample Arrow Images

Output

Body:
I have question about the accessoryType of cells. I am using a cell with an disclosureIndicator as accessoryType and I want to change it's color but I can't.
Does anyone know if this is a bug or if Apple forces me to use the grey color?
Actually I can change the colors of other accessoryType.

My code looks like this:

let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! customCell
cell.tintColor = UIColor.red
cell.accessoryType = .disclosureIndicator

And my arrow is still grey. But if I use a checkmark accessoryType it becomes red.

Is there any way to fix this or do I have to use a colored image?

Body:
You can do something like this

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.tintColor = UIColor.white

    let image = UIImage(named: "Arrow.png")
    let checkmark  = UIImageView(frame:CGRect(x:0, y:0, width:(image?.size.width)!, height:(image?.size.height)!));
    checkmark.image = image
    cell.accessoryView = checkmark

    let object = objects[indexPath.row] as! NSDate
    cell.textLabel!.text = object.description
    return cell
}

Sample Arrow Images

Output


问:
AngularJS $location.path() not reloading data of the destination view
In my angular project, when changing the path with $location.path('/foobar') the destination view is displayed but the data aren't reloaded (typically after saving an item and going back to the list, the list is not updated).

I tried to add $route.reload() or $scope.apply(), but nothing change.

I don't know what's wrong or missing to make this work.

UPDATE

$location.url() doesnt' work either

I'm using angular 1.2.26

UPDATE 2 - ANSWER

Ok, after a lot of comments and answers, I think it's time to end this.

I didn't think it would have been a so complicated question.

So, my conclusion, giving all you said is :

Giving simple example of @yvesmancera, the default behavior of the controller is to reload itself

In a complex controller with a resource factory and some REST calls, any save or update action should also manually update the list reference, or trigger a full reload of the list

All of you gave me some good advices, so thank you.

答:
```<code>$location.path("/login");
$timeout(() => $scope.$apply(), 1000);
</code>```

works for me

Body:
$location.path("/login");
$timeout(() => $scope.$apply(), 1000);

works for me


问:
How to solve this JNA issue?
I have application which use JNA and gets the audio and video. It works in my Linux box. But when i am testing it in Windows. It just never working. Because i am still learning, i will appreciate your suggestion how to fix it, i already spent few days and weeks only to work it out, but just dont get this why JAVA does not work simply, its a cross platform. Why should it require again System path or etc configuration.

I am totally lost now, why it works in Linux and it does not work in Windows XP ? How can i run it then ?

```<code>Inside the lib direcotry i have my JNA and Audio libraries.
C:\Documents and Settings\test\Desktop\test>dir
 Volume in drive C has no label.
 Volume Serial Number is 680F-0963

 Directory of C:\Documents and Settings\test\Desktop\test

19/12/2010  22:09    <DIR>          .
19/12/2010  22:09    <DIR>          ..
19/12/2010  22:09            51.791 Audio.jar
19/12/2010  22:09    <DIR>          lib
               1 File(s)         51.791 bytes
               3 Dir(s)     487.002.112 bytes free

Now trying to run Audio.jar, gets Fail 1:

C:\Documents and Settings\test\Desktop\test>java -Djava.library.path=~/jni -jar
Audio.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)

Fail 2:
C:\Documents and Settings\test\Desktop\test>java -Djna.library.path=. -jar Audio
.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)
</code>```

答:
For Fail 1: I don't believe that the ~/ syntax will work on Windows.  Try %HOME%\ instead.  The tilde expansion happens in Bash, so things are a bit different in Windows.

For Fail 2: It doesn't look like the .dll is in your test directory, and you're setting the jna.library.path to ..

If the .dll's are in your lib directory, then shouldn't the paths be set to that directory, instead of ~/jni and .?

Title: How to solve this JNA issue?

Body:
I have application which use JNA and gets the audio and video. It works in my Linux box. But when i am testing it in Windows. It just never working. Because i am still learning, i will appreciate your suggestion how to fix it, i already spent few days and weeks only to work it out, but just dont get this why JAVA does not work simply, its a cross platform. Why should it require again System path or etc configuration.

I am totally lost now, why it works in Linux and it does not work in Windows XP ? How can i run it then ?

Inside the lib direcotry i have my JNA and Audio libraries.
C:\Documents and Settings\test\Desktop\test>dir
 Volume in drive C has no label.
 Volume Serial Number is 680F-0963

 Directory of C:\Documents and Settings\test\Desktop\test

19/12/2010  22:09    <DIR>          .
19/12/2010  22:09    <DIR>          ..
19/12/2010  22:09            51.791 Audio.jar
19/12/2010  22:09    <DIR>          lib
               1 File(s)         51.791 bytes
               3 Dir(s)     487.002.112 bytes free

Now trying to run Audio.jar, gets Fail 1:

C:\Documents and Settings\test\Desktop\test>java -Djava.library.path=~/jni -jar
Audio.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)

Fail 2:
C:\Documents and Settings\test\Desktop\test>java -Djna.library.path=. -jar Audio
.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)


问:
Unity3D: Aspect ratio issue
In Unity3D I can't scale the game properly to remove the black bar.

I've added pictures for reference:

EDIT: I need to make the canvas scale to the whole screen instead of only a part of the screen.

答:
Set the screen resolution manually in the Start() of your code:

```<code>Screen.SetResolution(x, y, true)
</code>```

Title: Unity3D: Aspect ratio issue

Body:
Set the screen resolution manually in the Start() of your code:

Screen.SetResolution(x, y, true)


问:
Retrieving rows based on another column's aggregate values in MS SQL
I am trying to write a query for MS SQL Server which returns the container_parent_ids that have quantity of 0:

```<code>Container_id | Container_name | container_parent_id | quantity | alive
----------------------------------------------------------------------
1            | ContA          | 12345               | 2        | 1
2            | ContB          | 12345               | 1        | 1
3            | ContC          | 12345               | 0        | 1
4            | ContD          | 12345               | 1        | 1
5            | ContA          | 23456               | 1        | 1
6            | ContB          | 23456               | 0        | 1
7            | ContC          | 23456               | 1        | 1
8            | ContD          | 34567               | 0        | 1
9            | ContE          | 34567               | 0        | 1
</code>```

In the above data, only ContD and ContE should be returned for 34567.

If I group by container_parent_id and use WHERE quanity = 0, the result includes other rows.

This is what I have been trying:

```<code>SELECT count(), container_parent_id from Container where quantity = 0 GROUP BY container_parent_id HAVING count() > 0
</code>```

resulting in:

```<code>3 | ContC | 12345 | 0 | 1
6 | ContB | 23456 | 0 | 1
8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1
</code>```

Problem with running this query or what Renu/Stan suggested is, it returns those containers that have quantity as 0 - as a subset. But, I do not want the first two as they have other containers with quantities 1 or 2 for the same container_parent_id. My final output should just be:

```<code>8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1
</code>```

I.e. every container_parent_id that which has only records with quantity = 0.

答:
Simply Try this,</p>

```<code>SELECT container_parent_id FROM Container WHERE quantity=0
</code>```

Body:
I am trying to write a query for MS SQL Server which returns the container_parent_ids that have quantity of 0:

Container_id | Container_name | container_parent_id | quantity | alive
----------------------------------------------------------------------
1            | ContA          | 12345               | 2        | 1
2            | ContB          | 12345               | 1        | 1
3            | ContC          | 12345               | 0        | 1
4            | ContD          | 12345               | 1        | 1
5            | ContA          | 23456               | 1        | 1
6            | ContB          | 23456               | 0        | 1
7            | ContC          | 23456               | 1        | 1
8            | ContD          | 34567               | 0        | 1
9            | ContE          | 34567               | 0        | 1

In the above data, only ContD and ContE should be returned for 34567.

If I group by container_parent_id and use WHERE quanity = 0, the result includes other rows.

This is what I have been trying:

SELECT count(), container_parent_id from Container where quantity = 0 GROUP BY container_parent_id HAVING count() > 0

resulting in:

3 | ContC | 12345 | 0 | 1
6 | ContB | 23456 | 0 | 1
8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1

Problem with running this query or what Renu/Stan suggested is, it returns those containers that have quantity as 0 - as a subset. But, I do not want the first two as they have other containers with quantities 1 or 2 for the same container_parent_id. My final output should just be:

8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1

I.e. every container_parent_id that which has only records with quantity = 0.

Body:
Simply Try this,

SELECT container_parent_id FROM Container WHERE quantity=0


答:
Should do the trick.

```<code>     <input class="has-value m-r"  id="title"  value="Toyota" type="checkbox">Toyota
     <input class="has-value m-r"  value="Honda" type="checkbox">Honda
     <input class="has-value m-r"  value="Audi" type="checkbox">Audi
      <br><br>
   <input class="  " name="alias" id="alias" >
   <br><br>
   if i check "HONDA" and "AUDI"<br><br>

   result input will like this Toyota, Honda, Audi
   <br><br><br>
   if i Uncheck Honda
   <br><br>
   result will like this Toyota, Audi

$(document).ready(function(){
                $('.has-value').click(function() {
                        var t = "";

                     $('.has-value:checked').each(function() {
                         if( t== "") {
                            t = $(this).val();
                         }
                         else {
                           t = t + ","+ $(this).val();
                         }
                     });

                     $('#alias').val(t);

                })
            });
</code>```

Title: How to get check with multiple value to one input

Body:
Should do the trick.

     <input class="has-value m-r"  id="title"  value="Toyota" type="checkbox">Toyota
     <input class="has-value m-r"  value="Honda" type="checkbox">Honda
     <input class="has-value m-r"  value="Audi" type="checkbox">Audi
      <br><br>
   <input class="  " name="alias" id="alias" >
   <br><br>
   if i check "HONDA" and "AUDI"<br><br>

   result input will like this Toyota, Honda, Audi
   <br><br><br>
   if i Uncheck Honda
   <br><br>
   result will like this Toyota, Audi

$(document).ready(function(){
                $('.has-value').click(function() {
                        var t = "";

                     $('.has-value:checked').each(function() {
                         if( t== "") {
                            t = $(this).val();
                         }
                         else {
                           t = t + ","+ $(this).val();
                         }
                     });

                     $('#alias').val(t);

                })
            });


问:
SQL: Select distinct children ordered by property of related child
I've got a query where I want to retrieve distinct child2 rows, but ordered by a property of child1 rows that are related by a common parent. If I do the following, I get an error because the ORDERBY property is not in the DISTINCT list:

```<code>select
    distinct c2.Id, c2.Foo, c2.Bar
    from Child1 c1
    join Parent p on c1.parentId = p.Id
    join Child2 c2 on c2.parentId = p.Id
    order by c1.Id
</code>```

However, if I add c1.Id to the select list, I will lose distinctness of Child rows, as c1.Id makes them all distinct.

If I use a CTE or subquery to first do the ordering, and then select distinct rows from that, the outer query doesn't guarantee that it will maintain the order of the inner/cte query.

Is there a way to achieve this?

答:
I make rows distinct in cte using TOP(1) WITH TIES, then sort in query

```<code>WITH Data AS(
    SELECT TOP(1) WITH TIES
        g.id, g.foo, g.bar, p.createdDate
    FROM Parent p
    JOIN Child c on c.parentId = p.id
    JOIN Grandchild g on g.childId = c.id
    ORDER BY ROW_NUMBER() OVER(PARTITION BY g.id, g.foo, g.bar ORDER BY p.createdDate)
)
SELECT *
FROM Data
ORDER BY createdDate
</code>```

TOP(1) WITH TIES selects rows where ROW_NUMBER().. = 1. Because of PARTITION BY ... it selects one row per partition(group). It works similar to GROUP BY but allows to return all columns

Body:
I've got a query where I want to retrieve distinct child2 rows, but ordered by a property of child1 rows that are related by a common parent. If I do the following, I get an error because the ORDERBY property is not in the DISTINCT list:

select
    distinct c2.Id, c2.Foo, c2.Bar
    from Child1 c1
    join Parent p on c1.parentId = p.Id
    join Child2 c2 on c2.parentId = p.Id
    order by c1.Id

However, if I add c1.Id to the select list, I will lose distinctness of Child rows, as c1.Id makes them all distinct.

If I use a CTE or subquery to first do the ordering, and then select distinct rows from that, the outer query doesn't guarantee that it will maintain the order of the inner/cte query.

Is there a way to achieve this?

Body:
I make rows distinct in cte using TOP(1) WITH TIES, then sort in query

WITH Data AS(
    SELECT TOP(1) WITH TIES
        g.id, g.foo, g.bar, p.createdDate
    FROM Parent p
    JOIN Child c on c.parentId = p.id
    JOIN Grandchild g on g.childId = c.id
    ORDER BY ROW_NUMBER() OVER(PARTITION BY g.id, g.foo, g.bar ORDER BY p.createdDate)
)
SELECT *
FROM Data
ORDER BY createdDate

TOP(1) WITH TIES selects rows where ROW_NUMBER().. = 1. Because of PARTITION BY ... it selects one row per partition(group). It works similar to GROUP BY but allows to return all columns


问:
CKEditor - Image Too Wide for Editor Box
I've managed to configure CKEditor and CKFinder to work together in an in-house CMS and I'm coming to the closing stages.

One UI issue I'm having, however, concerns images in the editor WYSIWYG box.

My editor box is roughly 1000px wide, but some images are 1400px wide. They are obviously too big for the editor box and bring in a horizontal scrollbar.

I don't want to set a width on the actual image as this will change the final HTML code, so what are my options for reducing the size of the image ONLY when it's displayed in the CKEditor window?

答:
You can use CSS for this. CKEditor uses class cke_editable for the contents, so put the following line in config.js as the last line, after the definition of CKEDITOR.editorConfig

```<code>CKEDITOR.addCss('.cke_editable img { max-width: 100% !important; height: auto !important; }');
</code>```

Body:
You can use CSS for this. CKEditor uses class cke_editable for the contents, so put the following line in config.js as the last line, after the definition of CKEDITOR.editorConfig

CKEDITOR.addCss('.cke_editable img { max-width: 100% !important; height: auto !important; }');