问:
Getting the "Loading" status from Elm's RemoteData package
Here is the simplest Elm program I can think of that uses the RemoteData package to better model server responses:

```<code>module App exposing (..)

import Http exposing (..)
import Html exposing (..)
import Html.Events exposing (..)
import RemoteData exposing (..)
import Debug exposing (..)

type alias Model = WebData String

init : (Model, Cmd Msg)
init = (RemoteData.NotAsked, Cmd.none)

type Msg = Ask | OnUpdate (WebData String)

view : Model -> Html Msg
view model =
    div []
        [ button [ onClick Ask ] [ text "ask" ]
        , text (toString model)
        ]

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        OnUpdate response -> (log (toString response) response, Cmd.none)
        Ask -> (model,
                Http.getString "https://api.ipify.org"
                    |> RemoteData.sendRequest
                    |> Cmd.map OnUpdate)

subscriptions : Model -> Sub Msg
subscriptions model = Sub.none

main : Program Never Model Msg
main =
    program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }
</code>```

Even though the package has the states of NotAsked, Loading, Success and Failure, I never see the Loading status. When does this package ever send this status and how would I use it?

答:
Actually, it's your job to put the loading status in the model when you send the command:

```<code>update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        OnUpdate response -> (log (toString response) response, Cmd.none)
        Ask -> (RemoteData.Loading,
                Http.getString "https://api.ipify.org"
                    |> RemoteData.sendRequest
                    |> Cmd.map OnUpdate)
</code>```

See also the example here: https://github.com/krisajenkins/remotedata/blob/4.3.0/src/RemoteData.elm#L72

Body:
Here is the simplest Elm program I can think of that uses the RemoteData package to better model server responses:

module App exposing (..)

import Http exposing (..)
import Html exposing (..)
import Html.Events exposing (..)
import RemoteData exposing (..)
import Debug exposing (..)

type alias Model = WebData String

init : (Model, Cmd Msg)
init = (RemoteData.NotAsked, Cmd.none)

type Msg = Ask | OnUpdate (WebData String)

view : Model -> Html Msg
view model =
    div []
        [ button [ onClick Ask ] [ text "ask" ]
        , text (toString model)
        ]

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        OnUpdate response -> (log (toString response) response, Cmd.none)
        Ask -> (model,
                Http.getString "https://api.ipify.org"
                    |> RemoteData.sendRequest
                    |> Cmd.map OnUpdate)

subscriptions : Model -> Sub Msg
subscriptions model = Sub.none

main : Program Never Model Msg
main =
    program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

Even though the package has the states of NotAsked, Loading, Success and Failure, I never see the Loading status. When does this package ever send this status and how would I use it?

Body:
Actually, it's your job to put the loading status in the model when you send the command:

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        OnUpdate response -> (log (toString response) response, Cmd.none)
        Ask -> (RemoteData.Loading,
                Http.getString "https://api.ipify.org"
                    |> RemoteData.sendRequest
                    |> Cmd.map OnUpdate)

See also the example here: https://github.com/krisajenkins/remotedata/blob/4.3.0/src/RemoteData.elm#L72


来源: stackexchange

问:
How to skip /dev/sda1: clean in booting system?
When I start system I see black display with message:

```<code>/dev/sda1: clean....blocks
</code>```

How to skip this step and run Ubuntu? It takes over 3 hours to check HDD 500 gb

答:
NOTE: Your question is off-topic for this site. It should be on Ask Ubuntu. But to make things easier, I will answer it here.

Use your favorite text editor to open /etc/fstab (WARNING: Be very careful when editing this file. It controls how your system mounts filesystems on boot).

Find the line for /dev/sda1 At the end of the line, you should see a 1, or 2. Change this to a 0. This tells the system to not run fsck whenever it boots.

ContentLicense: CC BY-SA 3.0

Body:
When I start system I see black display with message:

/dev/sda1: clean....blocks

How to skip this step and run Ubuntu? It takes over 3 hours to check HDD 500 gb


问:
Set button in vertical center of table view cell.
I have button and a label in my table view cell placing one after other vertically.

In my xib design i placed my button then below it placed my label.

if the string for label is  empty then i want to set the button as vertically center in table view cell and hide the label.

if have tried following code for my implementation but button does not come in vertical center position.

```<code>if([labelString isEqualToString:@""]){
    _label.hidden = YES;
    _button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
}
</code>```

it would be helpful if get suggestion for fixing this problem.

答:
One approach: use dynamic setting of constraints.

In InterfaceBuilder:

Put your button and label inside an enclosing wrapper view.

Constrain the wrapper view to be centered in the main view.

Constrain the button and the label to be of fixed height, and the top of the label to be constrained to the bottom of the button (with spacing if desired).

Constrain the top of the wrapper to the top of the button.

Constrain the bottom of the wrapper with two separate constraints: one to the bottom of the button (but make this inactive), and one to the bottom of the label (active.).

Make both of those constraints outlets so that you can access them in code.

Leave the wrapper height otherwise unconstrained. Thus it will "shrink-wrap" to the combined height of the button and label.

In code:

When the label is empty, activate the constraint that pins the wrapper to the button instead of to the label:

```<code>    BOOL hideLabel = [labelString isEqualToString:@""];
    _label.hidden = hideLabel;
    _wrapperToButtonConstraint.active = hideLabel;
    _wrapperToLabelConstraint.active = !hideLabel;
</code>```

Now the shrink-wrap effect will make the wrapper have the same height as the button, and since the wrapper is centered, so will the button be centered.

Body:
I have button and a label in my table view cell placing one after other vertically.

In my xib design i placed my button then below it placed my label.

if the string for label is  empty then i want to set the button as vertically center in table view cell and hide the label.

if have tried following code for my implementation but button does not come in vertical center position.

if([labelString isEqualToString:@""]){
    _label.hidden = YES;
    _button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
}

it would be helpful if get suggestion for fixing this problem.

Body:
One approach: use dynamic setting of constraints.

In InterfaceBuilder:

Put your button and label inside an enclosing wrapper view.

Constrain the wrapper view to be centered in the main view.

Constrain the button and the label to be of fixed height, and the top of the label to be constrained to the bottom of the button (with spacing if desired).

Constrain the top of the wrapper to the top of the button.

Constrain the bottom of the wrapper with two separate constraints: one to the bottom of the button (but make this inactive), and one to the bottom of the label (active.).

Make both of those constraints outlets so that you can access them in code.

Leave the wrapper height otherwise unconstrained. Thus it will "shrink-wrap" to the combined height of the button and label.

In code:

When the label is empty, activate the constraint that pins the wrapper to the button instead of to the label:

    BOOL hideLabel = [labelString isEqualToString:@""];
    _label.hidden = hideLabel;
    _wrapperToButtonConstraint.active = hideLabel;
    _wrapperToLabelConstraint.active = !hideLabel;

Now the shrink-wrap effect will make the wrapper have the same height as the button, and since the wrapper is centered, so will the button be centered.


问:
Remove rows based specific condition
I have this data:

```<code>  name   keyword1  keyword2  keyword3
  artA      0         1         0
  artA      1         1         0
  artB      0         0         1
  artB      1         1         0
  artC      1         1         0
  artD      0         0         0
  artD      0         0         0
</code>```

How is it possible to remove SUM rows  based on column name?

Expression:

```<code>df <- df$name[rowSums(df$name != 0)>0,]
</code>```

Expected results:

```<code>name keyword1  keyword2  keyword3
artA    0         1         0
artA    1         1         0
artB    0         0         1
artB    1         1         0
artC    1         1         0
</code>```

答:
We can do this with Reduce

```<code>df1[Reduce(`|`, df1[-1]),]
#    name keyword1 keyword2 keyword3
#1 artA        0        1        0
#2 artA        1        1        0
#3 artB        0        0        1
#4 artB        1        1        0
#5 artC        1        1        0
</code>```

Title: Remove rows based specific condition

Body:
I have this data:

  name   keyword1  keyword2  keyword3
  artA      0         1         0
  artA      1         1         0
  artB      0         0         1
  artB      1         1         0
  artC      1         1         0
  artD      0         0         0
  artD      0         0         0

How is it possible to remove SUM rows  based on column name?

Expression:

df <- df$name[rowSums(df$name != 0)>0,]

Expected results:

name keyword1  keyword2  keyword3
artA    0         1         0
artA    1         1         0
artB    0         0         1
artB    1         1         0
artC    1         1         0

Body:
We can do this with Reduce

df1[Reduce(`|`, df1[-1]),]
#    name keyword1 keyword2 keyword3
#1 artA        0        1        0
#2 artA        1        1        0
#3 artB        0        0        1
#4 artB        1        1        0
#5 artC        1        1        0


问:
Is it possible to have a Jquery Draggable object under an other div
I'm attempting to create a template system where an uploaded jpg is then placed on a template.

Test example:

http://www.silverink.com/TEMP/jqueryTest/

The problem is that I want to have a mask on the top most layer but be able to click and drag the lower layer. At present I'm having to either click the area to bring it to the fore then drag or have it at the fore transparent.

Any ideas or suggestions most welcome!!

答:
You are using a transparent png file for faded masking so I it's not possible to do what you are trying to. Even png is transparent in the middle still it's a part of image and block the layers below.

But you may cut that png into 4 different files and place them around this http://jsbin.com/etale4/2/edit

ContentLicense: CC BY-SA 2.5


问:
Unity - Navigation for performance on mobile
In case of a Unity mobile app, would it be good (at all) for performance, to deactivate the navigation through canvas objects like TextFields and Buttons?

When selecting e.g. a Button or TextField in the sceneview, the inspector shows the option "Navigation", which can be set to different things and can also be visualized. This feature is usually used to tab through input fields, like you would expect it on a website. On my mobile game I don't need this "tabbing". Would there be any sort of performance increase if I deactivated it everywhere?

答: I can confirm, that deactivating the navigation of UI elements has no performance influence. Behind the scenes there's just a handler, that gets triggered, when you hit "tab" on pc, or analogeously on mobile.</p>


问:
Passing a Varible through a form
I am still new to PHP but I have been making good progress on my site. However I seem to have hit a bit of a roadblock. I have a page that has a URL and in that URL there is a category Identifier. so it looks like;

```<code>www.website.com/createpage?cat=1
</code>```

Now in the previous pages I have been passing the variable from page to page doing the following;

```<code>$cat = $_GET['cat'];
<a href="nextpage.php?cat=$cat">
</code>```

However I have now come to the point where I need to use a form to process the information. I have a special script that runs on submit using the action= attribute.

If I try amending the link there to like the ones above, it just passes a string '$cat' through. I have read on several topics here that I can achieve the same thing by creating a hidden field in a form and calling it out on the new page like I would with the rest of the information. But in both cases it only passes a string through. If I echo the variable on the form before submission it reports the correct number, and if I put the processing script on the same page as the form it gets further than it does without (i have an error somewhere at the bottom of my script but I was expecting that)

Is there anything special about passing through values on forms that I am missing? Everyone post I read makes it sound simple, but I am struggling to replicate it on my own script.

I can post the script, but it is a hell of a long one.

```<code>echo '<form action="topic_process.php" method="POST">
    <p>Topic Subject:<input name="topic_subject" type="text"></p><br>
    <p>Post: <textarea name="post_content"></textarea></p><br>
    <input type="hidden" name="cat" value="$cat">
    <p><input type="submit" value="Create"></p>';
</code>```

答:
Since your form string is delimited by single-quotes, you're sending $cat as a string, you have to concatenate it :

```<code>echo '<form action="topic_process.php" method="POST">
    <p>Topic Subject:<input name="topic_subject" type="text"></p><br>
    <p>Post: <textarea name="post_content"></textarea></p><br>
    <input type="hidden" name="cat" value="' . $cat . '">
    <p><input type="submit" value="Create"></p>';
</code>```

Please read this thread to understand your error

Title: Passing a Varible through a form

Body:
I am still new to PHP but I have been making good progress on my site. However I seem to have hit a bit of a roadblock. I have a page that has a URL and in that URL there is a category Identifier. so it looks like;

www.website.com/createpage?cat=1

Now in the previous pages I have been passing the variable from page to page doing the following;

$cat = $_GET['cat'];

However I have now come to the point where I need to use a form to process the information. I have a special script that runs on submit using the action= attribute.

If I try amending the link there to like the ones above, it just passes a string '$cat' through. I have read on several topics here that I can achieve the same thing by creating a hidden field in a form and calling it out on the new page like I would with the rest of the information. But in both cases it only passes a string through. If I echo the variable on the form before submission it reports the correct number, and if I put the processing script on the same page as the form it gets further than it does without (i have an error somewhere at the bottom of my script but I was expecting that)

Is there anything special about passing through values on forms that I am missing? Everyone post I read makes it sound simple, but I am struggling to replicate it on my own script.

I can post the script, but it is a hell of a long one.

echo '<form action="topic_process.php" method="POST">

Topic Subject:<input name="topic_subject" type="text">

Post: <textarea name="post_content"></textarea>

    <input type="hidden" name="cat" value="$cat">

<input type="submit" value="Create">
';

Body:
Since your form string is delimited by single-quotes, you're sending $cat as a string, you have to concatenate it :

echo '<form action="topic_process.php" method="POST">
    <p>Topic Subject:<input name="topic_subject" type="text"></p><br>
    <p>Post: <textarea name="post_content"></textarea></p><br>
    <input type="hidden" name="cat" value="' . $cat . '">
    <p><input type="submit" value="Create"></p>';

Please read this thread to understand your error


问:
How to create alter script from two mysqldump files
I'm trying to figure out how to implement migration between two databases. My plan is

Create mysqldump --no-data of source DB

Create mysqldump --no-data of target DB

Create alterscript based on 2 created mysqldump files

Run alter script on target DB to migrate new changes

However I haven't found a way to compare 2 mysqldumps and create alter script from that. Is there any tools for that?

-kari

答:
Looks like this tool does what I need. http://search.cpan.org/dist/MySQL-Diff/bin/mysqldiff

I can compare Databases and mysqldumps and it creates alter script from differences.

Example:

```<code>mysqldump -uroot --no-data db1 > db1.sql
mysqldump -uroot --no-data db2 > db2.sql
mysqldiff --user=root db1.sql db2.sql
</code>```

Body:
Looks like this tool does what I need. http://search.cpan.org/dist/MySQL-Diff/bin/mysqldiff

I can compare Databases and mysqldumps and it creates alter script from differences.

Example:

mysqldump -uroot --no-data db1 > db1.sql
mysqldump -uroot --no-data db2 > db2.sql
mysqldiff --user=root db1.sql db2.sql


问:
React JS maintain array inside state
I have been using React state to maintain some data. For ints and strings it's working well, but unfortunately arrays are not working.

In my component constructor, I have

```<code>constructor(props) {
    super(props);

    this.state = {
        terms: 5,
        myArray: []
    }
</code>```

and then, I am trying to maintain it in componentDidUpdate

```<code>componentDidUpdate() {
    this.state = {
        terms: this.state.terms,
        myArray: this.state.myArray
    }
</code>```

but myArray: this.state.myArray is not working. However terms: this.state.terms is working perfectly.

Can someone help!

答:
You cannot set state directly like that since its an array you will have to append the value or else push the value.

try something like

```<code>var newArray = this.state.myArray.slice();
newArray.push("new value");
this.setState({myArray:newArray})
</code>```

here i sliced to make it immutable.

Title: React JS maintain array inside state

Body:
I have been using React state to maintain some data. For ints and strings it's working well, but unfortunately arrays are not working.

In my component constructor, I have

constructor(props) {
    super(props);

    this.state = {
        terms: 5,
        myArray: []
    }

and then, I am trying to maintain it in componentDidUpdate

componentDidUpdate() {
    this.state = {
        terms: this.state.terms,
        myArray: this.state.myArray
    }

but myArray: this.state.myArray is not working. However terms: this.state.terms is working perfectly.

Can someone help!

Body:
You cannot set state directly like that since its an array you will have to append the value or else push the value.

try something like

var newArray = this.state.myArray.slice();
newArray.push("new value");
this.setState({myArray:newArray})

here i sliced to make it immutable.


问:
SonarQube compare versions of the same project
i'd like to compare code coverage and other metrics between two different versions of my project, but using the leaking period mechanism i was not able to get the view i want.

I would like to compare version metrics like this:

On my researches i've read something similar was possible on older versions of sonar.

Can someone give a tip on how to do it?

答:
With recent versions of SonarQube, you don't have built-in tables that show you a list of metrics over different versions of your project.

Still, you can see the evolution of each metric over the past versions when you go to "Measures > [select the metric] > History". You will see something like:


问:
Continuous build and deployment of Angular-cli using TeamCity and Octopus
I have developed my Angular 2 application using angular-cli. Now I am planning to deploy the application through Team City and Octopus Deploy. At present all the projects in Team City are ASP.NET MVC so there is no reference to use.

After searching I found that TeamCity.Node plugin is required on Team City to build this app. Are there any other approaches?

答:
You have three options:

Install Node.js and npm on each build agent.

Install Team City plugin that adds a support for npm (like TeamCity.Node that you've mentioned).

Put angular-cli files (and any other required npm packages) into your source control, thus eliminating the need for npm.


问:
Zend framework fckeditor integration
I have done integration of fckeditor with zend framework.

have using custom view helper.

and its calling fckeditor class now

my problem is that it's (fckeditor class)  using iframe to show fckeditor. Here Zend  frame work url not working.

Iframe link built by eckeditor class is :

```<code>/mysite/public/js/fckeditor/editor/fckeditor.html?InstanceName=page_text_details
</code>```

it's giving below error due to iframe link to fckeditor.html

```<code>Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (js)' in /var/www/html/......
</code>```

Please help me how can i remove this.

Even i have used htacces to rewrite URL

my htaccess file is :

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule !\.(htm|html|txt|swf|js|ico|gif|jpg|png|css|php|xml|pdf|cab)$ index.php [NC,L]
</code>```

答:
I think you need to add a rewritebase rule in your htaccess :

```<code>RewriteBase /mysite/public
</code>```

You may want to verify that your 'js' folder exists (and its fckeditor dependances) under the public folder

Title: Zend framework fckeditor integration

Body:
I have done integration of fckeditor with zend framework.

have using custom view helper.

and its calling fckeditor class now

my problem is that it's (fckeditor class)  using iframe to show fckeditor. Here Zend  frame work url not working.

Iframe link built by eckeditor class is :

/mysite/public/js/fckeditor/editor/fckeditor.html?InstanceName=page_text_details

it's giving below error due to iframe link to fckeditor.html

Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (js)' in /var/www/html/......

Please help me how can i remove this.

Even i have used htacces to rewrite URL

my htaccess file is :

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule !\.(htm|html|txt|swf|js|ico|gif|jpg|png|css|php|xml|pdf|cab)$ index.php [NC,L]

Body:
I think you need to add a rewritebase rule in your htaccess :

RewriteBase /mysite/public

You may want to verify that your 'js' folder exists (and its fckeditor dependances) under the public folder


问:
What exactly does this WSO2 ESB echo endpoint?
I am very new in WSO2 and I have the following doubt related to an ESB project on which I am working.

In this ESB application I am sending a message to a named endopoint mediator, something like this:

```<code><send>
    <endpoint key="echoEndpoint"/>
</send>
</code>```

This is the contend of the related echoEndpoint.xml file in my project:

```<code><?xml version="1.0" encoding="UTF-8"?>
<endpoint name="echoEndpoint" xmlns="http://ws.apache.org/ns/synapse">
    <address format="soap11" statistics="enable" trace="enable" uri="http://localhost:8280/services/echo"/>
</endpoint>
</code>```

So what exactly does this endpoint? The http://localhost:8280/services/echo is something like a predefined endopoined provided natively by WSO2? or what?

答: This is a service that by default is already displayed when you run the ESB. Echo.aar is located in the path repository\deployment\server\axis2services . And wsdl you can see https://localhost:your_Port/services/echo?wsdl</p>

Body:
I am very new in WSO2 and I have the following doubt related to an ESB project on which I am working.

In this ESB application I am sending a message to a named endopoint mediator, something like this:

<send>
    <endpoint key="echoEndpoint"/>
</send>

This is the contend of the related echoEndpoint.xml file in my project:

<?xml version="1.0" encoding="UTF-8"?>
<endpoint name="echoEndpoint" xmlns="http://ws.apache.org/ns/synapse">
    <address format="soap11" statistics="enable" trace="enable" uri="http://localhost:8280/services/echo"/>
</endpoint>

So what exactly does this endpoint? The http://localhost:8280/services/echo is something like a predefined endopoined provided natively by WSO2? or what?


问:
Difference between two structure variable declaration?
I am doing hash implementation. I have sample program below.

```<code>#define HASHSIZE 25

struct HashTable {
        char key[50];
        char val[50];
};

int main() {

        struct HashTable *hashtab[HASHSIZE];  // declaration - 1

        struct HashTable hashtab2[HASHSIZE];  // declaration - 2
}
</code>```

declaration-1:

```<code>struct HashTable *hashtab[HASHSIZE];
</code>```

declaration-2:

```<code>struct HashTable hashtab2[HASHSIZE];
</code>```

As per my understanding, both declarations are seems to be doing same in memory layout of allocation. Like, allocating HASHSIZE of array of struct HashTable and variable pointing to the [0]th element of array of structs.

But, Still I feel that there is some difference that I might not be able to get it.

I want to know if there is a difference, how does one differ from another in memory layout (OR) allocation/accessing.

答:
cdecl is an useful online tool to help beginners get used to complicated declarations.

```<code>struct HashTable *hashtab[25];
</code>```

declare hashtab as array 25 of pointer to struct HashTable

```<code>struct HashTable hashtab[25];
</code>```

declare hashtab as array 25 of struct HashTable

Body:
I am doing hash implementation. I have sample program below.

#define HASHSIZE 25

struct HashTable {
        char key[50];
        char val[50];
};

int main() {

        struct HashTable *hashtab[HASHSIZE];  // declaration - 1

        struct HashTable hashtab2[HASHSIZE];  // declaration - 2
}

declaration-1:

struct HashTable *hashtab[HASHSIZE];

declaration-2:

struct HashTable hashtab2[HASHSIZE];

As per my understanding, both declarations are seems to be doing same in memory layout of allocation. Like, allocating HASHSIZE of array of struct HashTable and variable pointing to the [0]th element of array of structs.

But, Still I feel that there is some difference that I might not be able to get it.

I want to know if there is a difference, how does one differ from another in memory layout (OR) allocation/accessing.

Body:
cdecl is an useful online tool to help beginners get used to complicated declarations.

struct HashTable *hashtab[25];

declare hashtab as array 25 of pointer to struct HashTable

struct HashTable hashtab[25];

declare hashtab as array 25 of struct HashTable


问:
order by id on firebase database android
what i wanna do is sort out the data by id. I know i should use booksInstance.orderByChild("id"). i tried doing that and nothing has changed because i don't know where should i be using it in the code. here is how i am displaying the data.

```<code>private void getData(){
        firebaseDatabaseInstance = FirebaseDatabase.getInstance();
        // get reference to 'users' node
        booksInstance = firebaseDatabaseInstance.getReference("a3lamAlda3wa");
        books.clear();
        books.addAll(db.getAllA3());
        adapter = new BookGridAdapter(this, books);
        gridView.setAdapter(adapter);
        if (books.isEmpty()) {
            Constants.showLoadingDialog(this);
        }
        booksInstance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                storeData(dataSnapshot);
            }
            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
        booksInstance.orderByChild("id").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                BookData book = new BookData(

                        (String) dataSnapshot.child("id").getValue(),
                        (String) dataSnapshot.child("book_name").getValue(),
                        (String)dataSnapshot.child("book_path").getValue(),
                        (String)dataSnapshot.child("book_path2").getValue(),
                        "",
                        (String)dataSnapshot.child("image_path").getValue(),
                        (String)dataSnapshot.child("image_path2").getValue(),
                        ""
                );
                db.insertA3(book);
                reloadData();
            }
        });
    }
       private void storeData(DataSnapshot snapshot) {
        books.clear();
        for (DataSnapshot alert: snapshot.getChildren()) {
            BookData book = new BookData(
                    (String)alert.child("id").getValue(),
                    (String)alert.child("book_name").getValue(),
                    (String)alert.child("book_path").getValue(),
                    (String)alert.child("book_path2").getValue(),
                    "",
                    (String)alert.child("image_path").getValue(),
                    (String)alert.child("image_path2").getValue(),
                    ""
            );
            db.insertBook(book);
        }
        books.addAll(db.getAllBook());
        adapter.notifyDataSetChanged();
    }
</code>```

This is how my database looks like

```<code> "books" : [ null, {
        "book_name" : "book 1",
        "book_path" : "gs://appspot.com/books/1.pdf",
        "book_path2" : "https://firebasestorage.googleapis.com",
        "id" : "a-1",
        "image_path" : "gs://mostsharabdallah-c0c65.appspot.com",
        "image_path2" : "https://firebasestorage.googleapis.com"
      }
</code>```

答:
Instead of attaching your listener to the location of books, you attach it to the ordered query. So:

```<code>booksInstance.orderByChild("id").addChildEventListener(new ChildEventListener() {
</code>```

Out of curiosity: since your books have IDs already, why don't you simple store them under their ID as key?

Body:
what i wanna do is sort out the data by id. I know i should use booksInstance.orderByChild("id"). i tried doing that and nothing has changed because i don't know where should i be using it in the code. here is how i am displaying the data.

private void getData(){
        firebaseDatabaseInstance = FirebaseDatabase.getInstance();
        // get reference to 'users' node
        booksInstance = firebaseDatabaseInstance.getReference("a3lamAlda3wa");
        books.clear();
        books.addAll(db.getAllA3());
        adapter = new BookGridAdapter(this, books);
        gridView.setAdapter(adapter);
        if (books.isEmpty()) {
            Constants.showLoadingDialog(this);
        }
        booksInstance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                storeData(dataSnapshot);
            }
            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
        booksInstance.orderByChild("id").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                BookData book = new BookData(

                        (String) dataSnapshot.child("id").getValue(),
                        (String) dataSnapshot.child("book_name").getValue(),
                        (String)dataSnapshot.child("book_path").getValue(),
                        (String)dataSnapshot.child("book_path2").getValue(),
                        "",
                        (String)dataSnapshot.child("image_path").getValue(),
                        (String)dataSnapshot.child("image_path2").getValue(),
                        ""
                );
                db.insertA3(book);
                reloadData();
            }
        });
    }
       private void storeData(DataSnapshot snapshot) {
        books.clear();
        for (DataSnapshot alert: snapshot.getChildren()) {
            BookData book = new BookData(
                    (String)alert.child("id").getValue(),
                    (String)alert.child("book_name").getValue(),
                    (String)alert.child("book_path").getValue(),
                    (String)alert.child("book_path2").getValue(),
                    "",
                    (String)alert.child("image_path").getValue(),
                    (String)alert.child("image_path2").getValue(),
                    ""
            );
            db.insertBook(book);
        }
        books.addAll(db.getAllBook());
        adapter.notifyDataSetChanged();
    }

This is how my database looks like

 "books" : [ null, {
        "book_name" : "book 1",
        "book_path" : "gs://appspot.com/books/1.pdf",
        "book_path2" : "https://firebasestorage.googleapis.com",
        "id" : "a-1",
        "image_path" : "gs://mostsharabdallah-c0c65.appspot.com",
        "image_path2" : "https://firebasestorage.googleapis.com"
      }

Body:
Instead of attaching your listener to the location of books, you attach it to the ordered query. So:

booksInstance.orderByChild("id").addChildEventListener(new ChildEventListener() {

Out of curiosity: since your books have IDs already, why don't you simple store them under their ID as key?


问:
Object.toString() -> [object Object]
The following code send by using Ajax a json :

```<code>var geojson = new Object();
geojson["type"] = "FeatureCollection";
geojson["zone_type"] = "Zone";
$.ajax({
  url : url,
  type : 'POST',
  data : geojson,
  dataType : 'json',
});
</code>```

However, when I ask in the console "geojson" and when I look the request in the network :

```<code>geojson = "[object Object]"
</code>```

Actually, I should have the object :

```<code>geojson = {type:FeatureCollection,zone_type:Zone}
</code>```

Shouldn't I ?

答:
```<code>var geojson = new Object();
geojson["type"] = "FeatureCollection";
geojson["zone_type"] = "Zone";
$.ajax({
  url : url,
  type : 'POST',
  data : JSON.stringify(geojson),
  dataType : 'json',
});
</code>```

If I add JSON.stringify(geojson) indeed, I get correctly :

```<code>geojson = {"type":"FeatureCollection","zone_type":"warning_zone"}
</code>```

Thank you very much @SLYcee

Title: Object.toString() -> [object Object]

Body:
The following code send by using Ajax a json :

var geojson = new Object();
geojson["type"] = "FeatureCollection";
geojson["zone_type"] = "Zone";
$.ajax({
  url : url,
  type : 'POST',
  data : geojson,
  dataType : 'json',
});

However, when I ask in the console "geojson" and when I look the request in the network :

geojson = "[object Object]"

Actually, I should have the object :

geojson = {type:FeatureCollection,zone_type:Zone}

Shouldn't I ?

Body:
var geojson = new Object();
geojson["type"] = "FeatureCollection";
geojson["zone_type"] = "Zone";
$.ajax({
  url : url,
  type : 'POST',
  data : JSON.stringify(geojson),
  dataType : 'json',
});

If I add JSON.stringify(geojson) indeed, I get correctly :

geojson = {"type":"FeatureCollection","zone_type":"warning_zone"}

Thank you very much @SLYcee


问:
Shell - how i can use a variable in sed command
I'm having a problem when use a variable in sed command.

My script:

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

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {
        set req.backend_hint = $host;
        return (pass);
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste
</code>```

The error:

```<code>sed: -e expression #1, char 53: unknown option to `s'
</code>```

答:
You need add \n\\ to each line of varnish_config. shell will expand this to "new line" and \. If in the end of line will be \ sed will concatenate next line to current one.

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

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {\n\\
        set req.backend_hint = $host;\n\\
        return (pass);\n\\
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste
</code>```

Body:
I'm having a problem when use a variable in sed command.

My script:

#!/bin/sh

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {
        set req.backend_hint = $host;
        return (pass);
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste

The error:

sed: -e expression #1, char 53: unknown option to `s'

Body:
You need add \n\\ to each line of varnish_config. shell will expand this to "new line" and \. If in the end of line will be \ sed will concatenate next line to current one.

#!/bin/sh

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {\n\\
        set req.backend_hint = $host;\n\\
        return (pass);\n\\
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste


问:
SQL BACKUP Query
how can i backup data from a query with MSSQL. I think about something like this:

```<code>BACKUP DATABASE 'sourceDB'
Select * from Table1 where Day = '12.01.2010';
TO DISK = 'F:\Program Files\Microsoft SQL Server\MSSQL\Backup\sourceDB.bak' WITH FORMAT
</code>```

Thank you for your support!

Cheers

Stefan

答:
If you have access to Management Studio, you can save query results to a file quite easily:

Open a query window. One way to do
this is by right-clicking on the
database name in the Object Explorer.

You might want to write the query and
run it there first, to test that it
is producing the desired results.

When you are ready to run the query and save it to file, on the menu choose Query, then Results To, and finally Results to File.

Now, when you run the query (F5), you will get a dialog box to indicate the filename and folder to save the data.

That's all there is to it.

Title: SQL BACKUP Query

Body:
how can i backup data from a query with MSSQL. I think about something like this:

BACKUP DATABASE 'sourceDB'
Select * from Table1 where Day = '12.01.2010';
TO DISK = 'F:\Program Files\Microsoft SQL Server\MSSQL\Backup\sourceDB.bak' WITH FORMAT

Thank you for your support!

Cheers

Stefan


问:
date of birth input mask react
I am using this react input mask.

The input mask is being used for a user's date of birth. This works, however, the issue I am having is that a user can enter 54/54/2017 into the input box. I want to prevent this. One way I can do this is by entering a 0 before the first input if less than 10. However, if it is then 12 a 0 is put first.

Does anyone know a way I can solve this issue?

My code is as follows:

```<code>import InputMask from 'react-input-mask';

class Date extends Component {

  constructor(props) {
    this.state = {
        date_of_birth: ''
    };
    this.handleDateOfBirth = this.handleDateOfBirth.bind(this);

  }

  handleDateOfBirth(e) {

    this.setState({
      date_of_birth: e.target.value
    });

    }

  render() {
    const = {this.state};
    return <InputMask value={date_of_birth} mask="99/99/9999" onChange={this.handleDateOfBirth} />;
  }

}
</code>```

答:
before setting the date value you better try to parse the string in date object like

var valid_date = new Date(e.target.value)

This will return "Invalid Date" response if your date is not valid using this response you can put a if condition and prevent the further operation

Hope this Helps :)

Title: date of birth input mask react

Body:
I am using this react input mask.

The input mask is being used for a user's date of birth. This works, however, the issue I am having is that a user can enter 54/54/2017 into the input box. I want to prevent this. One way I can do this is by entering a 0 before the first input if less than 10. However, if it is then 12 a 0 is put first.

Does anyone know a way I can solve this issue?

My code is as follows:

import InputMask from 'react-input-mask';

class Date extends Component {

  constructor(props) {
    this.state = {
        date_of_birth: ''
    };
    this.handleDateOfBirth = this.handleDateOfBirth.bind(this);

  }

  handleDateOfBirth(e) {

    this.setState({
      date_of_birth: e.target.value
    });

    }

  render() {
    const = {this.state};
    return <InputMask value={date_of_birth} mask="99/99/9999" onChange={this.handleDateOfBirth} />;
  }

}


问:
Make a if else return in one line
I have a function which takes 4 parameters.

```<code>function fillTheText (selector, arrText, arrEl, j) {
  if (j >= 0) {
    return document.querySelector(selector + [j]).innerHTML = arrText[arrEl][j];
  } else {
    return document.querySelector(selector).innerHTML = arrText[arrEl];
  }
}
</code>```

The above function is invoked three times

```<code>function startQuiz (question) {
  fillTheText('#question', question[i], 'text');
  for (let j = 0; j < question[i].choices.length; j++) {
    fillTheText('#choice', question[i], 'choices', j)
  }
}
</code>```

I want to make changes so that fillTheText returns a single line but have no idea how can I make [j] optional. I tried conditional (ternary) operators but did not succeed.

答:
Not one line, but still an improvement, I think.

```<code>function fillTheText (selector, arrText, arrEl, j) {
  var selector = j >= 0 ? selector + [j] : selector;
  var value = j >= 0 ? arrText[arrEl][j] : arrText[arrEl];

  document.querySelector(selector).innerHTML = value;
}
</code>```

Or, perhaps, this

```<code>function fillTheText (selector, arrText, arrEl, j) {
  var value = arrText[arrEl];

  if (j >= 0) {
    selector = selector + [j];
    value = value[j];
  }

  document.querySelector(selector).innerHTML = value;
}
</code>```

Title: Make a if else return in one line

Body:
I have a function which takes 4 parameters.

function fillTheText (selector, arrText, arrEl, j) {
  if (j >= 0) {
    return document.querySelector(selector + [j]).innerHTML = arrText[arrEl][j];
  } else {
    return document.querySelector(selector).innerHTML = arrText[arrEl];
  }
}

The above function is invoked three times

function startQuiz (question) {
  fillTheText('#question', question[i], 'text');
  for (let j = 0; j < question[i].choices.length; j++) {
    fillTheText('#choice', question[i], 'choices', j)
  }
}

I want to make changes so that fillTheText returns a single line but have no idea how can I make [j] optional. I tried conditional (ternary) operators but did not succeed.

Body:
Not one line, but still an improvement, I think.

function fillTheText (selector, arrText, arrEl, j) {
  var selector = j >= 0 ? selector + [j] : selector;
  var value = j >= 0 ? arrText[arrEl][j] : arrText[arrEl];

  document.querySelector(selector).innerHTML = value;
}

Or, perhaps, this

function fillTheText (selector, arrText, arrEl, j) {
  var value = arrText[arrEl];

  if (j >= 0) {
    selector = selector + [j];
    value = value[j];
  }

  document.querySelector(selector).innerHTML = value;
}


问:
how to add listbox items to datagridview as it is in loop?
I am sorry if the topic and my problem is missmatching but it is the best I can do.Anyways, I have 2 listboxes , 2 datagridviews, a chart,start and stop button and stopwatch. When I click start button listboxes getting datas(listbox1=data coming from serial port and listbox2=time(elapsed)) and real time charting is starting. When I push stop button all the values in listboxes copying to datagridview as seperated columns. Then If I click the start button again I want to clear all the previous data(from listboxes and datagridviews) to start with refreshed and new start.Then I start to get new data again as the same procedure (I mentioned before) until I click stop button. However there is a problem;when I click the stop button.In the new data(copied to datagirdview) I face that first row of the datagridview2 is the lastest row of the previous one. I mean in twice time of the measurement, It is saving the lastest row of the previous data (even I write to clear it) and adding it as a first row of the new measurement.In third measurement it gets the lastest row of the second one as a first row and it is going like that in every measurment.I dont know where the problem is? Can you help me?</p>

```<code>    private void btnStart_Click(object sender, EventArgs e)
    {

        btnOpenFile.Enabled = false;
        btnStore.Enabled = false;
        btnSend.Enabled = false;
        btnStopReceiving.Enabled = true;
        btnStart.Enabled = false;
        btnTrig.Enabled = true;
        watch.Reset();
        watch.Start();
        zaman.Enabled = true;
        timer1.Enabled = true;
        listBox1.Items.Clear();
        listBox2.Items.Clear();
        dataGridView1.Rows.Clear();
        dataGridView2.Rows.Clear();

        foreach (var series in chrtAcq.Series)
        {
            series.Points.Clear();
        }
    }

    private void btnStopReceiving_Click(object sender, EventArgs e)
    {
        watch.Stop();
        zaman.Enabled = false;
        timer1.Enabled = false;

        btnSend.Enabled = true;
        btnOpenFile.Enabled = true;
        btnStopReceiving.Enabled = false;
        btnStart.Enabled = true;

        btnStore.Enabled = true;
        btnSend.Enabled = false;
        foreach (var item in listBox1.Items)
        {
            dataGridView1.Rows.Add();
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = item;

        }

        foreach (var item2 in listBox2.Items)
        {
            dataGridView2.Rows.Add();
            dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[0].Value = item2;
        }
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            for (int j = 1; j < dataGridView1.Columns.Count; j++)
            {
                dataGridView2.Rows[i].Cells[j].Value =
                    dataGridView1.Rows[i].Cells[j].Value;
            }

        }
    }
</code>```

答:
Try binding the ListBox items to a BindingSource, then bind the BindingSource to the DataGridView.  This will update the DataGridView rows in real time as the ListBox items change.

Try replacing your foreach loops in the btnStopReceiving_Click method with this:

```<code>BindingSource bs = new BindingSource();
bs.DataSource = listBox1.Items;
bs.ResetBindings(false);
dataGridView1.DataSource = bs;
</code>```

Body:
I am sorry if the topic and my problem is missmatching but it is the best I can do.Anyways, I have 2 listboxes , 2 datagridviews, a chart,start and stop button and stopwatch. When I click start button listboxes getting datas(listbox1=data coming from serial port and listbox2=time(elapsed)) and real time charting is starting. When I push stop button all the values in listboxes copying to datagridview as seperated columns. Then If I click the start button again I want to clear all the previous data(from listboxes and datagridviews) to start with refreshed and new start.Then I start to get new data again as the same procedure (I mentioned before) until I click stop button. However there is a problem;when I click the stop button.In the new data(copied to datagirdview) I face that first row of the datagridview2 is the lastest row of the previous one. I mean in twice time of the measurement, It is saving the lastest row of the previous data (even I write to clear it) and adding it as a first row of the new measurement.In third measurement it gets the lastest row of the second one as a first row and it is going like that in every measurment.I dont know where the problem is? Can you help me?

    private void btnStart_Click(object sender, EventArgs e)
    {

        btnOpenFile.Enabled = false;
        btnStore.Enabled = false;
        btnSend.Enabled = false;
        btnStopReceiving.Enabled = true;
        btnStart.Enabled = false;
        btnTrig.Enabled = true;
        watch.Reset();
        watch.Start();
        zaman.Enabled = true;
        timer1.Enabled = true;
        listBox1.Items.Clear();
        listBox2.Items.Clear();
        dataGridView1.Rows.Clear();
        dataGridView2.Rows.Clear();

        foreach (var series in chrtAcq.Series)
        {
            series.Points.Clear();
        }
    }

    private void btnStopReceiving_Click(object sender, EventArgs e)
    {
        watch.Stop();
        zaman.Enabled = false;
        timer1.Enabled = false;

        btnSend.Enabled = true;
        btnOpenFile.Enabled = true;
        btnStopReceiving.Enabled = false;
        btnStart.Enabled = true;

        btnStore.Enabled = true;
        btnSend.Enabled = false;
        foreach (var item in listBox1.Items)
        {
            dataGridView1.Rows.Add();
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = item;

        }

        foreach (var item2 in listBox2.Items)
        {
            dataGridView2.Rows.Add();
            dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[0].Value = item2;
        }
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            for (int j = 1; j < dataGridView1.Columns.Count; j++)
            {
                dataGridView2.Rows[i].Cells[j].Value =
                    dataGridView1.Rows[i].Cells[j].Value;
            }

        }
    }

Body:
Try binding the ListBox items to a BindingSource, then bind the BindingSource to the DataGridView.  This will update the DataGridView rows in real time as the ListBox items change.

Try replacing your foreach loops in the btnStopReceiving_Click method with this:

BindingSource bs = new BindingSource();
bs.DataSource = listBox1.Items;
bs.ResetBindings(false);
dataGridView1.DataSource = bs;


问:
How can I get my SpatialPolygonsDataFrame to plot correctly over my RasterLayer
I've got a problem when I try to plot the following.

I've created a mask of my study area with raster cell ID's and a shapefile with the country outlines of my study area.
The shapefile was created by merging the shapefiles of the countries, and then cropping it to the study area. (which was needed because the world countries shapefile wasn't detailed enough)

```<code>R version 3.3.3 (2017-03-06) -- "Another Canoe"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)
library(raster)
library(maptools)
library(rgdal)

#load Mask
sa.ID <- raster("Masks/sa.ID.asc")
proj4string(sa.ID) <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
sa.ID

class       : RasterLayer
dimensions  : 177, 266, 47082  (nrow, ncol, ncell)
resolution  : 0.08333333, 0.08333333  (x, y)
extent      : 118.8333, 141, -9.166667, 5.583333  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : ....\Masks\sa.ID.asc
names       : sa.ID

#load countries shapefile
countries.ra <- readOGR(dsn="diva-gis/Adm areas", layer="countries.ra")
countries.ra

class       : SpatialPolygonsDataFrame
features    : 4
extent      : 118.8, 141, -9.2, 5.6  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
variables   : 70
names       : GADMID, ISO,  NAME_ENGLI,    NAME_ISO,    NAME_FAO,  NAME_LOCAL,                                                                                NAME_OBSOL,                  NAME_VARIA, NAME_NONLA,                   NAME_FRENC,     NAME_SPANI,            NAME_RUSSI,          NAME_ARABI, NAME_CHINE, WASPARTOF, ...
min values  :    103, IDN,  East Timor,   INDONESIA,   Indonesia,   Indonesia,                                                      British New Guinea|German New Guinea|New Britain|New Guinea, East Timor|Portuguese Timor,         NA,                   IndonÃ©sie,      Filipinas, ????? Â— ????? ??????, ????? ????? ???????,        ???,        NA, ...
max values  :    222, TLS, Philippines, TIMOR-LESTE, Timor-Leste, Timor-Leste, Dutch Borneo|Dutch East Indies|Dutch New Guinea|East Indies|Netherlands Indies|West New Guinea|Nederlands IndiÃ«,                 Philippines,         NA, Timor-Leste (Timor Oriental), Timor Oriental,       ????????? ?????,           ?????????,    ???????,        NA, ...
</code>```

Now I try to plot the mask with the country layer on top

```<code>plot(sa.ID, xlim=c(118.8,141), ylim=c(-9.2,5.6), axes=TRUE)
plot(countries.ra, add=T)
</code>```

Initially, the plot I get looks fine, but when the extent of the plot window is changed, or when I try to save it, the countries shape changes with it instead of staying where it should be (see sa.ID )

but somehow, when I change it around and plot

```<code>plot(sa.ID, xlim=c(118.8,141), ylim=c(-9.2,5.6), axes=TRUE)
plot(countries.ra, add=T)
</code>```

the countries shape does stay put (see sa.ID.inverse).
However, as I need the clear lines on top, I really need the first one to work.

Can anybody help me? Because I really can't see what I might be doing wrong...

eta: I have the same problem with my range mask (which has values for every raster cell) and with the world country shapefile

答:
Following on @Bastien's comment, I think you might try using:

```<code>plot.window(xlim, ylim, log = "", asp = NA, ...)
</code>```

to designate the dimensions of your plot window. I'm not sure what how you want your plots to appear, but something to the effect of:

```<code>plot.window(xlim=c(118.8333, 141), ylim=( -9.166667, 5.583333))
</code>```

If you designate these values, it should force R to redraw the plot window correctly each time.

Body:
I've got a problem when I try to plot the following.

I've created a mask of my study area with raster cell ID's and a shapefile with the country outlines of my study area.
The shapefile was created by merging the shapefiles of the countries, and then cropping it to the study area. (which was needed because the world countries shapefile wasn't detailed enough)

R version 3.3.3 (2017-03-06) -- "Another Canoe"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)
library(raster)
library(maptools)
library(rgdal)

#load Mask
sa.ID <- raster("Masks/sa.ID.asc")
proj4string(sa.ID) <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
sa.ID

class       : RasterLayer
dimensions  : 177, 266, 47082  (nrow, ncol, ncell)
resolution  : 0.08333333, 0.08333333  (x, y)
extent      : 118.8333, 141, -9.166667, 5.583333  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : ....\Masks\sa.ID.asc
names       : sa.ID

#load countries shapefile
countries.ra <- readOGR(dsn="diva-gis/Adm areas", layer="countries.ra")
countries.ra

class       : SpatialPolygonsDataFrame
features    : 4
extent      : 118.8, 141, -9.2, 5.6  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
variables   : 70
names       : GADMID, ISO,  NAME_ENGLI,    NAME_ISO,    NAME_FAO,  NAME_LOCAL,                                                                                NAME_OBSOL,                  NAME_VARIA, NAME_NONLA,                   NAME_FRENC,     NAME_SPANI,            NAME_RUSSI,          NAME_ARABI, NAME_CHINE, WASPARTOF, ...
min values  :    103, IDN,  East Timor,   INDONESIA,   Indonesia,   Indonesia,                                                      British New Guinea|German New Guinea|New Britain|New Guinea, East Timor|Portuguese Timor,         NA,                   IndonÃ©sie,      Filipinas, ????? Â— ????? ??????, ????? ????? ???????,        ???,        NA, ...
max values  :    222, TLS, Philippines, TIMOR-LESTE, Timor-Leste, Timor-Leste, Dutch Borneo|Dutch East Indies|Dutch New Guinea|East Indies|Netherlands Indies|West New Guinea|Nederlands IndiÃ«,                 Philippines,         NA, Timor-Leste (Timor Oriental), Timor Oriental,       ????????? ?????,           ?????????,    ???????,        NA, ...

Now I try to plot the mask with the country layer on top

plot(sa.ID, xlim=c(118.8,141), ylim=c(-9.2,5.6), axes=TRUE)
plot(countries.ra, add=T)

Initially, the plot I get looks fine, but when the extent of the plot window is changed, or when I try to save it, the countries shape changes with it instead of staying where it should be (see sa.ID )

but somehow, when I change it around and plot

plot(sa.ID, xlim=c(118.8,141), ylim=c(-9.2,5.6), axes=TRUE)
plot(countries.ra, add=T)

the countries shape does stay put (see sa.ID.inverse).
However, as I need the clear lines on top, I really need the first one to work.

Can anybody help me? Because I really can't see what I might be doing wrong...

eta: I have the same problem with my range mask (which has values for every raster cell) and with the world country shapefile

Body:
Following on @Bastien's comment, I think you might try using:

plot.window(xlim, ylim, log = "", asp = NA, ...)

to designate the dimensions of your plot window. I'm not sure what how you want your plots to appear, but something to the effect of:

plot.window(xlim=c(118.8333, 141), ylim=( -9.166667, 5.583333))

If you designate these values, it should force R to redraw the plot window correctly each time.


问:
Do I need test method that is inside the test class
So I have a sample method that I give him a day and it returns me the first and last day of a week in which the day:

```<code>public static final DatePeriod thisWeek(LocalDate date) {

    TemporalField dayOfWeek = WeekFields.of(Locale.FRANCE).dayOfWeek();
    LocalDate mon = date.with(dayOfWeek, 1);
    LocalDate sun = date.with(dayOfWeek, 7);

    return new DatePeriod(mon, sun);
}
</code>```

I have to write a JUnit test (and I did it):

```<code>@Test
public void testThisMonth_LocalDate() throws ParseException {
    System.out.println("thisMonth");
    for (String[] date : VALID_TEST_DATES) {
        LocalDate dateLocal = dateToLocal(date[0]);
        DatePeriod expResult = new DatePeriod(dateToLocal(date[5]), dateToLocal(date[6]));
        DatePeriod result = JavaTimeUtils.thisMonth(dateLocal);
        assertEquals(expResult.getLeft(), result.getLeft());
        assertEquals(expResult.getRight(), result.getRight());
    }
}
</code>```

So, because I used code in dateToLocal() multiple times, I decided to make it in method like this:

```<code>public LocalDate dateToLocal(String dateString) throws ParseException {   // Calendar to LocalDate
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Calendar cal = Calendar.getInstance();
    Date initDate = df.parse(dateString);
    cal.setTime(initDate);
    LocalDate dateLocal = LocalDate.of(cal.get(Calendar.YEAR), Month.of(cal.get(Calendar.MONTH)+1), cal.get(Calendar.DAY_OF_MONTH));

    return dateLocal;
}
</code>```

And it works.
But that is not my question.
I was wondering is this the correct way to do things like this (method in this JUnit test), do I need to make Test for this method, do I have to move it in other class (outside the tests)? I know this is strange question, I've already searching in google, unsuccessfully. (maybe I can't  ask google right).
Thanks :)

答: It is totally acceptable to have helper methods in test classes. In fact, when testing things of any large complexity it's hard not to. Unless the test helper method is in a utility class used across multiple tests in multiple projects (and thus being in the main jar of a different project) I don't typically consider it useful to write tests for the test helper methods (otherwise, taken to the logical conclusion, it'd be nearly impossible to have any code reuse and fully tested classes).</p>

Body:
So I have a sample method that I give him a day and it returns me the first and last day of a week in which the day:

public static final DatePeriod thisWeek(LocalDate date) {

    TemporalField dayOfWeek = WeekFields.of(Locale.FRANCE).dayOfWeek();
    LocalDate mon = date.with(dayOfWeek, 1);
    LocalDate sun = date.with(dayOfWeek, 7);

    return new DatePeriod(mon, sun);
}

I have to write a JUnit test (and I did it):

@Test
public void testThisMonth_LocalDate() throws ParseException {
    System.out.println("thisMonth");
    for (String[] date : VALID_TEST_DATES) {
        LocalDate dateLocal = dateToLocal(date[0]);
        DatePeriod expResult = new DatePeriod(dateToLocal(date[5]), dateToLocal(date[6]));
        DatePeriod result = JavaTimeUtils.thisMonth(dateLocal);
        assertEquals(expResult.getLeft(), result.getLeft());
        assertEquals(expResult.getRight(), result.getRight());
    }
}

So, because I used code in dateToLocal() multiple times, I decided to make it in method like this:

public LocalDate dateToLocal(String dateString) throws ParseException {   // Calendar to LocalDate
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Calendar cal = Calendar.getInstance();
    Date initDate = df.parse(dateString);
    cal.setTime(initDate);
    LocalDate dateLocal = LocalDate.of(cal.get(Calendar.YEAR), Month.of(cal.get(Calendar.MONTH)+1), cal.get(Calendar.DAY_OF_MONTH));

    return dateLocal;
}

And it works.
But that is not my question.
I was wondering is this the correct way to do things like this (method in this JUnit test), do I need to make Test for this method, do I have to move it in other class (outside the tests)? I know this is strange question, I've already searching in google, unsuccessfully. (maybe I can't  ask google right).
Thanks :)


问:
Recurrence Approach : How can we generate all possibilities on braces?
How can we generate all possibilities on braces  ?

N value has given to us and we have to  generate all possibilities.

Examples:

1) if N == 1,  then only one possibility () .

2) if N==2, then possibilities are (()), ()()

3) if N==3, then possibilities are ((())), (())(),()()(), ()(()) ...

Note: left and right braces should match. I mean )( is INVALID for the N==1

Can we solve this problem by using recurrence approach ?

答:
For a given N we always have to start with an open brace. Now consider where it's corresponding closing brace is. It can be in the middle like in ()() or at the end like (()) for N=2.

Now consider N=3:

It can be at the end: (()()) and ((())).

Or in the middle: ()(()) and ()()() where it's in position 2. Then it can also be in position 4: (())().

Now we can essentially combine the 2 cases by realising the case where the closing brace is at the end is the same as it being at the middle, but with all the possibilities for N=0 added to the end.

Now to solve it you can work out all the possibilities for n between the begin and end brace and similarly you can work out all the possibilities for m after the end brace. (Note m+n+1 = N) Then you can just combine all possible combinations, append them to your list of possibilities and move on to the next possible location for the end brace.

Just be warned an easy mistake to make with these types of problems, is to find all the possibilities for i and for N-i and just combine them, but this for N=3 would double count ()()() or at least print it twice.

Here is some Python 2.x code that solves the problem:

```<code>memoise = {}
memoise[0] = [""]
memoise[1] = ["()"]

def solve(N, doprint=True):
    if N in memoise:
        return memoise[N]

    memoise[N] = []

    for i in xrange(1,N+1):
        between = solve(i-1, False)
        after   = solve(N-i, False)
        for b in between:
           for a in after:
               memoise[N].append("("+b+")"+a)

    if doprint:
        for res in memoise[N]:
            print res

    return memoise[N]
</code>```

Body:
For a given N we always have to start with an open brace. Now consider where it's corresponding closing brace is. It can be in the middle like in ()() or at the end like (()) for N=2.

Now consider N=3:

It can be at the end: (()()) and ((())).

Or in the middle: ()(()) and ()()() where it's in position 2. Then it can also be in position 4: (())().

Now we can essentially combine the 2 cases by realising the case where the closing brace is at the end is the same as it being at the middle, but with all the possibilities for N=0 added to the end.

Now to solve it you can work out all the possibilities for n between the begin and end brace and similarly you can work out all the possibilities for m after the end brace. (Note m+n+1 = N) Then you can just combine all possible combinations, append them to your list of possibilities and move on to the next possible location for the end brace.

Just be warned an easy mistake to make with these types of problems, is to find all the possibilities for i and for N-i and just combine them, but this for N=3 would double count ()()() or at least print it twice.

Here is some Python 2.x code that solves the problem:

memoise = {}
memoise[0] = [""]
memoise[1] = ["()"]

def solve(N, doprint=True):
    if N in memoise:
        return memoise[N]

    memoise[N] = []

    for i in xrange(1,N+1):
        between = solve(i-1, False)
        after   = solve(N-i, False)
        for b in between:
           for a in after:
               memoise[N].append("("+b+")"+a)

    if doprint:
        for res in memoise[N]:
            print res

    return memoise[N]


问:
Pass test data to table-valued parameter within SQL
Is it possible, and if so how, to pass data to a table-valued parameter of a stored function using SQL EXEC?

I know how to pass in data from C#. One of my four stored procs using table-valued parameters is not producing the expected results. I'd like to execute my proc from SQL server management studio for debugging purposes, but I am unable to find the correct syntax for doing so, if such a syntax even exists. I haven't found anything relevant in the docs.

My type table:

```<code>CREATE TYPE [MyNameSpace].[MyTypeTable] AS TABLE(
//... all my fields
)
</code>```

My stored proc:

```<code>//... bunch of stuff
ALTER PROCEDURE [MyNameSpace].[MyStoredProc]
@MyTypeTableVar MyTypeTable READONLY
AS
BEGIN
//Do a bunch of stuff
//Want to test the stuff in here
END
</code>```

I have tried:

```<code>IF OBJECT_ID('tempdb.dbo.#MyTempTable') IS NOT NULL DROP TABLE tempdb.dbo.#MyTempTable;
select top 0 *
into #MyTempTable
//existing table with structure that matches the table-valued param
from MyNameSpace.MyTable;

//...Long insert statement assigning test data to #MyTempTable

EXECUTE MyNameSpace.MyStoredProc @MyTypeTableVar = #MyTempTable;
</code>```

which throws:

Operand type clash: nvarchar is incompatible with MyTypeTable

答:
Here's a working example:</p>

```<code>-- Declare a table parameter
DECLARE @registryUpdates AS typ_KeyValuePairStringTable;
-- Insert one row
INSERT INTO @registryUpdates
VALUES ('Hello', 'World');
-- Call Stored Procedure
EXEC prc_UpdateRegistry @registryUpdates
</code>```

Body:
Is it possible, and if so how, to pass data to a table-valued parameter of a stored function using SQL EXEC?

I know how to pass in data from C#. One of my four stored procs using table-valued parameters is not producing the expected results. I'd like to execute my proc from SQL server management studio for debugging purposes, but I am unable to find the correct syntax for doing so, if such a syntax even exists. I haven't found anything relevant in the docs.

My type table:

CREATE TYPE [MyNameSpace].[MyTypeTable] AS TABLE(
//... all my fields
)

My stored proc:

//... bunch of stuff
ALTER PROCEDURE [MyNameSpace].[MyStoredProc]
@MyTypeTableVar MyTypeTable READONLY
AS
BEGIN
//Do a bunch of stuff
//Want to test the stuff in here
END

I have tried:

IF OBJECT_ID('tempdb.dbo.#MyTempTable') IS NOT NULL DROP TABLE tempdb.dbo.#MyTempTable;
select top 0 *
into #MyTempTable
//existing table with structure that matches the table-valued param
from MyNameSpace.MyTable;

//...Long insert statement assigning test data to #MyTempTable

EXECUTE MyNameSpace.MyStoredProc @MyTypeTableVar = #MyTempTable;

which throws:

Operand type clash: nvarchar is incompatible with MyTypeTable

Body:
Here's a working example:

-- Declare a table parameter
DECLARE @registryUpdates AS typ_KeyValuePairStringTable;
-- Insert one row
INSERT INTO @registryUpdates
VALUES ('Hello', 'World');
-- Call Stored Procedure
EXEC prc_UpdateRegistry @registryUpdates


问:
ValidateAsync Identity Server 4 passing dbConnection
I have already set up a dbConnection singleton in my Startup.cs

```<code>var dbConection = new SqlConnection(Configuration.GetConnectionString("MyDatabase"));
services.AddSingleton(dbConection);
</code>```

Now I want to get the dbConnection in my ValidateAsync method, but I can not pass it:

```<code>public Task ValidateAsync(ResourceOwnerPasswordValidationContext context, SqlConnection dbConnection)
</code>```

because it is not a proper interface for the ResourceOwnerPasswordValidator

How can I receive or read the dbConnection inside ValidateAsync?

答: If we pass the SqlConnection then where is the context with its data?</p>

Body:
I have already set up a dbConnection singleton in my Startup.cs

var dbConection = new SqlConnection(Configuration.GetConnectionString("MyDatabase"));
services.AddSingleton(dbConection);

Now I want to get the dbConnection in my ValidateAsync method, but I can not pass it:

public Task ValidateAsync(ResourceOwnerPasswordValidationContext context, SqlConnection dbConnection)

because it is not a proper interface for the ResourceOwnerPasswordValidator

How can I receive or read the dbConnection inside ValidateAsync?


问:
php mail() not sent with slim 3 getParams() data

I am doing a mail sent function from a contact form inside a Slim 3 project.

I get the name, email and message field data from $request->getParams() and then place it to an $email_message to send the information directly to my email. And the email was not delivered.
Funny thing is, without the getParams() data (I just replace it with any string), the email is delivered and i receive it. So probably the mail syntax is right and email is enabled on my hosting.

And if i echoed the message right before the mail() code, it print out the message correctly, so data from the form is received.
So I could not figure out what is going wrong here.

I try to use print_r(error_get_last()) but it only returns a blank page.

Please somebody can help? Thanks a lot!

My code:

```<code>$data = $request->getParams();
$name = $data['name'];
$email_from = $data['email'];
$message = $data['message'];

$email_message = "Name: ".$name."Message: ".$message;

$email_to = "myemail@email.com";
$email_subject = "Message from website";

$headers = 'From: '.$email_from."\r\n".
           'Reply-To: '.$email_from."\r\n" .
           'X-Mailer: PHP/' . phpversion();
$send = mail($email_to, $email_subject, $email_message, $headers);
if($send)
    {
       echo 'Sent!';
    } else {
       print_r(error_get_last());
    }
die();
</code>```

UPDATED: now it prints out 'Sent!', and still i don't get any email to my email address.

For someone that mark this as duplicate, i also read that answer but not successful. This issue is different because it DID send email successully without data passed from the contact form, it only gets problem when there is data from getParams() added. So i hope somebody who is experience in Slim or PHP can help. Please don't just mark as duplicate if you don't really understand the question.

答:
99.9% of people trying to mail with PHP giving up.

PHP only does half of the work for you, it formats the outgoing email, however it does not do the actual sending. What does? Well it depends on the OS you're using, and even then, it depends on what mail server you want to use.

I've only set this environment up for Debian/Linux. I'd install postfix (apt install postfix), configure it, and start the process. Only then does the mail function work. HOWEVER it still maybe rejected from some email servers (ie, gmail) because it's unencrypted.

Best of luck.

Body:
I am doing a mail sent function from a contact form inside a Slim 3 project.

I get the name, email and message field data from $request->getParams() and then place it to an $email_message to send the information directly to my email. And the email was not delivered.
Funny thing is, without the getParams() data (I just replace it with any string), the email is delivered and i receive it. So probably the mail syntax is right and email is enabled on my hosting.

And if i echoed the message right before the mail() code, it print out the message correctly, so data from the form is received.
So I could not figure out what is going wrong here.

I try to use print_r(error_get_last()) but it only returns a blank page.

Please somebody can help? Thanks a lot!

My code:

$data = $request->getParams();
$name = $data['name'];
$email_from = $data['email'];
$message = $data['message'];

$email_message = "Name: ".$name."Message: ".$message;

$email_to = "myemail@email.com";
$email_subject = "Message from website";

$headers = 'From: '.$email_from."\r\n".
           'Reply-To: '.$email_from."\r\n" .
           'X-Mailer: PHP/' . phpversion();
$send = mail($email_to, $email_subject, $email_message, $headers);
if($send)
    {
       echo 'Sent!';
    } else {
       print_r(error_get_last());
    }
die();

UPDATED: now it prints out 'Sent!', and still i don't get any email to my email address.

For someone that mark this as duplicate, i also read that answer but not successful. This issue is different because it DID send email successully without data passed from the contact form, it only gets problem when there is data from getParams() added. So i hope somebody who is experience in Slim or PHP can help. Please don't just mark as duplicate if you don't really understand the question.


问:
Unity performance drain of non-visible UI
I've got a game with lots of menus. The menus have their own scripts which I don't neccessarily want to stop, just because the user can't see the menu.

This is why I currently just translate the canvases off the screen, so the user can't see them and the scripts can continue to do their thing.

Can anyone say something about the performance drain of non-visible UI? Does it cost much to have let's say 200 labels, 50 images and 50 buttons active but off screen, or is it all culled away immediately and does basically nothing performance wise?

In this context I'm also curious, if it is ok to have multiple fullscreen menus in the same canvas as I do currently, or would it be way better to give each menu it's own canvas? If non-visible UI drains a lot of performance while not visible, I would do the latter option to deactivate the canvas, but keep the script running. Would that be the way to go?

答: I can confirm, that there was a huge performance increase after deactivating the UI elements, that are not shown. To keep scripts on them alive, one can just write a little function, that checks if there are any scripts on a GameObject that is about to be deactivated.</p>


问:
How to avoid overfitting Recurrent Neural Network
I have been training Bidirectional LSTM based RNN for Speech Recognition, and the network appears to forget the old context as soon as a new context arrives. I am unsure how to explain its behaviour though; it appears that the network is being overfit such that it remembers only one specific case at a time.

The link to code is https://github.com/rajkumarcm15/Speech-Recognition/blob/master/MFCC_SWN_BN_Affine/train.py and its output in https://github.com/rajkumarcm15/Speech-Recognition/blob/master/MFCC_SWN_BN_Affine/Results.pdf.

Need some help in understanding its output pattern.

答:
Are you doing a validation step at every epoch (for instance) to check that this behavior is indeed due to overfitting?

If not, you should be doing so, and check if there is a certain training step at which the loss for the validation set starts increasing and the loss for the training set is still decreasing.


问:
how to insert group checkbox values with PHP?
PHP code

```<code>$sql = "INSERT INTO user_details (check_box)
VALUES ('$_POST[check_box]')";
</code>```

Below is my html code

```<code><input type="checkbox" name="check_box[]" value="1"> Group 1<br>
<input type="checkbox" name="check_box[]" value="2"> Group 2<br>
<input type="checkbox" name="check_box[]" value="3"> Group 3<br>
</code>```

答:
This can be done in this way:

```<code>$sql =  "INSERT INTO user_details (check_box) VALUES ("
        . implode('), (',$_POST[check_box])
        . ")";
</code>```

this is open to mysql injections!! Better do

$clean = array_map('intval',$_POST[check_box]);

before using it.

Body:
PHP code

$sql = "INSERT INTO user_details (check_box)
VALUES ('$_POST[check_box]')";

Below is my html code

<input type="checkbox" name="check_box[]" value="1"> Group 1

<input type="checkbox" name="check_box[]" value="2"> Group 2

<input type="checkbox" name="check_box[]" value="3"> Group 3

Body:
This can be done in this way:

$sql =  "INSERT INTO user_details (check_box) VALUES ("
        . implode('), (',$_POST[check_box])
        . ")";

this is open to mysql injections!! Better do

$clean = array_map('intval',$_POST[check_box]);

before using it.


问:
Bit Error Rate SIMO
What is the general formula of  BER in SIMO systems.
My system uses BPSK and my channel is AWGN.

I found many formulas but for specific cases and no generic one!.

An example of how i can find BER with Rx=10 is appreciated.

Thanks.

答:
The generic formula can be written as :

p = 1/2 - 1/2*(1+1./power(10,SNRdB/10)).^(-1/2);

theoryBer= 0;

for k=0:1:NumOfRec-1
theoryBer = theoryBer + nchoosek(NumOfRec-1+k,k).*(1-p).^k;
  end
Note: Do not forget to specify number of receivers!.

Title: Bit Error Rate SIMO


问:
Modelica - join connectors after some distance
In modelica I need to connect two spaces and pass an object, lets say a ball, between them after some distance. In my example I have two spaces one which is free space (no forces) and suddenly we enter near earth space (gravity) which acts on the ball. I need to be able to pass the ball from the first space to the second but I can't get it. Here is a minimal example.

```<code>model Ball
  Real[2] position;
  Real[2] velocity;
  parameter Real mass=1;
equation
  der(position) = velocity;
end Ball;

connector Flange
  Real p;
  flow Ball b;
end Flange;

model FreeSpace
  Ball ball;
  parameter Real length;
  Flange f;
equation
  // need to do something, probably here, to end the first space when ball is at length
end FreeSpace;

model NearEarth
  extends FreeSpace;
  parameter Real[2] g={0,-9.8};
equation
  der(ball.velocity) = g;
end NearEarth;

model PassBall
  FreeSpace free(ball.velocity={5,0},ball.position={0,10});
  NearEarth near;
equation
  connect(free.f,near.f);
end Equation;
</code>```

Perhaps I am doing something very wrong, but this is where I am. (In the real problem I have an electron pulse propagating through spaces which inherit from a FreeSpace, but have different forces acting in each.) Any suggestions would be great!

答:
If I understand your goal, you want to have two different "environments" and then pass objects between these two environments?

This is problematic in Modelica.  Modelica is designed for systems that have static topologies.  By this I mean that all connections are present at the start of the simulation and no connections are added or removed during the simulation.  Of course, it would be nice to have more dynamic features, but things can quickly become overwhelming if you add too many features/capabilities.

As to your issue, one thing you can do would be to have a FreeSpaceInteraction class to describe the interaction between the ball and a FreeSpace object and a NearEarthInteraction class to describe the interaction between the ball and the NearEarth object.  Then you can have a boolean signal to both indicating which should be active at any given time (based on distance).

I could work out an example if you'd like.  A very similar example is present in "Introduction to Physical Modeling with Modelica" (if you have a copy) that involves planets and gravitational attraction.  One issue that occurs there is that you get into some combinatorial issues when you have lots of bodies all acting on one another.

Updates:

Joel, Google Books is your friend here.  I did a search of "Modelica gravity Tiller" and came up with this link.  I hope it works for you.  If not, let me know and I can try and paste a copy of the model in here.

Glad to hear UI had my book...that's where I got my Ph.D.  I'd like to think it was because I was an alum, but I doubt it.

The key to this is that you have "FixedSpace" has-a "Ball".  That isn't the way I modeled it (because the has-a relationship would be transient).  In the orbital model, I create a "solar system" which has a bunch of "planets" and then I create a whole network of many-to-many "gravitational pull" objects connecting everything to everything.  For your case, you might want to create a similar "forces" kind of object and connect it the ball and each environment and then have it figure out how it could behaves based on its position.  That is at least, conceptually, one way to do it.

Body:
In modelica I need to connect two spaces and pass an object, lets say a ball, between them after some distance. In my example I have two spaces one which is free space (no forces) and suddenly we enter near earth space (gravity) which acts on the ball. I need to be able to pass the ball from the first space to the second but I can't get it. Here is a minimal example.

model Ball
  Real[2] position;
  Real[2] velocity;
  parameter Real mass=1;
equation
  der(position) = velocity;
end Ball;

connector Flange
  Real p;
  flow Ball b;
end Flange;

model FreeSpace
  Ball ball;
  parameter Real length;
  Flange f;
equation
  // need to do something, probably here, to end the first space when ball is at length
end FreeSpace;

model NearEarth
  extends FreeSpace;
  parameter Real[2] g={0,-9.8};
equation
  der(ball.velocity) = g;
end NearEarth;

model PassBall
  FreeSpace free(ball.velocity={5,0},ball.position={0,10});
  NearEarth near;
equation
  connect(free.f,near.f);
end Equation;

Perhaps I am doing something very wrong, but this is where I am. (In the real problem I have an electron pulse propagating through spaces which inherit from a FreeSpace, but have different forces acting in each.) Any suggestions would be great!


问:
How to find & replace regular expressions from a text file?
I have a huge .txt file in which i want to find the regular expression (^.+$)\n   and replace it with \1\n. Currently i'm doing it manually.

how can i automate this using batch script?

答:
If I understand your expression properly:

```<code>^  - Start of Line.
.+ - Any character, possibly repeated
$  - End of Line
\n - Followed by a blank line
</code>```

And you want to replace it with:

```<code>Everything you Captured
\n
</code>```

That looks like it does not accomplish anything.

Doesn't that just replace each line with the same line?

Can you clarify your intent?

Body:
If I understand your expression properly:

^  - Start of Line.
.+ - Any character, possibly repeated
$  - End of Line
\n - Followed by a blank line

And you want to replace it with:

Everything you Captured
\n

That looks like it does not accomplish anything.

Doesn't that just replace each line with the same line?

Can you clarify your intent?


问:
Store the output of a loop inside a function into a vector or data.frame
I have a data frame df that looks like the following:

```<code>structure(list(sequence = c("CSPPPPSPSPHPRPP", "GEGSPTSPTSPKQPG",
"EAGAPAGSGAPPPAD", "PAPPKPKESKEPENA", "AKPKQQDEDPDGAAE", "GDRGGGTGNEDDDYE"
), group = c("BP", "BP", "BP", "BP", "BP", "BP")), .Names = c("sequence",
"group"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

For all the character variables underdf$sequence I want to get all the possible sub-sets of 7 characters, shifting one character to the right after each iteration.
For that, I created a function called scan_core_OLpeptides. If I apply the following function:

```<code>scan_core_OLpeptides <- function(x) {
  for(i in seq_len(nchar(x)-7+1)){
    print(str_sub(string = x, start = i, end = i+6))
}}
</code>```

I get the following output:

```<code>[1] "CSPPPPS" "GEGSPTS" "EAGAPAG" "PAPPKPK" "AKPKQQD" "GDRGGGT"
[1] "SPPPPSP" "EGSPTSP" "AGAPAGS" "APPKPKE" "KPKQQDE" "DRGGGTG"
[1] "PPPPSPS" "GSPTSPT" "GAPAGSG" "PPKPKES" "PKQQDED" "RGGGTGN"
[1] "PPPSPSP" "SPTSPTS" "APAGSGA" "PKPKESK" "KQQDEDP" "GGGTGNE"
[1] "PPSPSPH" "PTSPTSP" "PAGSGAP" "KPKESKE" "QQDEDPD" "GGTGNED"
[1] "PSPSPHP" "TSPTSPK" "AGSGAPP" "PKESKEP" "QDEDPDG" "GTGNEDD"
[1] "SPSPHPR" "SPTSPKQ" "GSGAPPP" "KESKEPE" "DEDPDGA" "TGNEDDD"
[1] "PSPHPRP" "PTSPKQP" "SGAPPPA" "ESKEPEN" "EDPDGAA" "GNEDDDY"
[1] "SPHPRPP" "TSPKQPG" "GAPPPAD" "SKEPENA" "DPDGAAE" "NEDDDYE"
</code>```

Which is exactly what I want. However, I wanted to store this output into an object, preferably into a vector or into a data.frame.
I thought about storing into a list but it did not work.

答:
I 'd use zoo package for this,

```<code>library(zoo)
sapply(strsplit(df1$sequence, ''), function(i) rollapply(i, 7, by = 1,
                                                   function(i)paste0(i, collapse = '')))
</code>```

Body:
I have a data frame df that looks like the following:

structure(list(sequence = c("CSPPPPSPSPHPRPP", "GEGSPTSPTSPKQPG",
"EAGAPAGSGAPPPAD", "PAPPKPKESKEPENA", "AKPKQQDEDPDGAAE", "GDRGGGTGNEDDDYE"
), group = c("BP", "BP", "BP", "BP", "BP", "BP")), .Names = c("sequence",
"group"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))

For all the character variables underdf$sequence I want to get all the possible sub-sets of 7 characters, shifting one character to the right after each iteration.
For that, I created a function called scan_core_OLpeptides. If I apply the following function:

scan_core_OLpeptides <- function(x) {
  for(i in seq_len(nchar(x)-7+1)){
    print(str_sub(string = x, start = i, end = i+6))
}}

I get the following output:

[1] "CSPPPPS" "GEGSPTS" "EAGAPAG" "PAPPKPK" "AKPKQQD" "GDRGGGT"
[1] "SPPPPSP" "EGSPTSP" "AGAPAGS" "APPKPKE" "KPKQQDE" "DRGGGTG"
[1] "PPPPSPS" "GSPTSPT" "GAPAGSG" "PPKPKES" "PKQQDED" "RGGGTGN"
[1] "PPPSPSP" "SPTSPTS" "APAGSGA" "PKPKESK" "KQQDEDP" "GGGTGNE"
[1] "PPSPSPH" "PTSPTSP" "PAGSGAP" "KPKESKE" "QQDEDPD" "GGTGNED"
[1] "PSPSPHP" "TSPTSPK" "AGSGAPP" "PKESKEP" "QDEDPDG" "GTGNEDD"
[1] "SPSPHPR" "SPTSPKQ" "GSGAPPP" "KESKEPE" "DEDPDGA" "TGNEDDD"
[1] "PSPHPRP" "PTSPKQP" "SGAPPPA" "ESKEPEN" "EDPDGAA" "GNEDDDY"
[1] "SPHPRPP" "TSPKQPG" "GAPPPAD" "SKEPENA" "DPDGAAE" "NEDDDYE"

Which is exactly what I want. However, I wanted to store this output into an object, preferably into a vector or into a data.frame.
I thought about storing into a list but it did not work.

Body:
I 'd use zoo package for this,

library(zoo)
sapply(strsplit(df1$sequence, ''), function(i) rollapply(i, 7, by = 1,
                                                   function(i)paste0(i, collapse = '')))


问:
ARMv8A AArch64 vmlal_high_s8 Intrinsics
I'm looking for the intrinsic corresponding to the operation 'SMLAL2 Vd.8H,Vn.16B,Vm.16B', which according to ARM's own documentation (ARM Neon Intrinsics Ref) should be something like

```<code>int16x8_t vmlal_high_s8 (int16x8_t a,int8x16_t b,int8x16_t c)
</code>```

however in the arm_neon.h that is included in ARM's GNU Toolchain doesn't have anything corresponding to it. So my question would be if I have to just include something else or otherwise can somehow circumvent this problem.

Thanks in advance!

答: For anyone else hitting this problem: I had chosen the ARM embedded tool chain instead of the linaro one, which is suitable for aarch64</p>

Title: ARMv8A AArch64 vmlal_high_s8 Intrinsics

Body:
I'm looking for the intrinsic corresponding to the operation 'SMLAL2 Vd.8H,Vn.16B,Vm.16B', which according to ARM's own documentation (ARM Neon Intrinsics Ref) should be something like

int16x8_t vmlal_high_s8 (int16x8_t a,int8x16_t b,int8x16_t c)

however in the arm_neon.h that is included in ARM's GNU Toolchain doesn't have anything corresponding to it. So my question would be if I have to just include something else or otherwise can somehow circumvent this problem.

Thanks in advance!


问:
How to retrieve the records based on a condition from a Hbase table?
I have a Hbase table: employeedetails with column families:cols-personaldetails: firstname, lastname, professionaldetails: cols-company, empid
and it has the following data in it.

```<code> 1    column=personaldetails:firstname, timestamp=1490959927100, value=Steven
 1    column=personaldetails:lastname, timestamp=1490959947478, value=Gerrard
 1    column=professionaldetails:company, timestamp=1490959968846, value=ABC
 1    column=professionaldetails:empid, timestamp=1490959978542, value=02429O
 2    column=personaldetails:firstname, timestamp=1490960007427, value=Sidhartha
 2    column=personaldetails:lastname, timestamp=1490960054615, value=Bobby
 2    column=professionaldetails:company, timestamp=1490960074243, value=DEF
 2    column=professionaldetails:empid, timestamp=1490960103882, value=02429N
 3    column=personaldetails:company, timestamp=1490960175772, value=WES
 3    column=personaldetails:empid, timestamp=1490960187863, value=987789
 3    column=personaldetails:firstname, timestamp=1490960128896, value=Sunny
 3    column=personaldetails:lastname, timestamp=1490960142031, value=Smith
</code>```

Is there a way to write a command to retrieve the records whose first name starts with 'S'.

答:
The best thing you can do is that you can create an external table in Hive with the same schema mapping to the HBase table and you can run hive queries on the top of the HBase table.

You can use conditions in the Hive queries which runs on the top of the HBase table data.

You can refer to this blog for integrating hive with HBase and running Hive queries on the top of HBase table.

Body:
I have a Hbase table: employeedetails with column families:cols-personaldetails: firstname, lastname, professionaldetails: cols-company, empid
and it has the following data in it.

 1    column=personaldetails:firstname, timestamp=1490959927100, value=Steven
 1    column=personaldetails:lastname, timestamp=1490959947478, value=Gerrard
 1    column=professionaldetails:company, timestamp=1490959968846, value=ABC
 1    column=professionaldetails:empid, timestamp=1490959978542, value=02429O
 2    column=personaldetails:firstname, timestamp=1490960007427, value=Sidhartha
 2    column=personaldetails:lastname, timestamp=1490960054615, value=Bobby
 2    column=professionaldetails:company, timestamp=1490960074243, value=DEF
 2    column=professionaldetails:empid, timestamp=1490960103882, value=02429N
 3    column=personaldetails:company, timestamp=1490960175772, value=WES
 3    column=personaldetails:empid, timestamp=1490960187863, value=987789
 3    column=personaldetails:firstname, timestamp=1490960128896, value=Sunny
 3    column=personaldetails:lastname, timestamp=1490960142031, value=Smith

Is there a way to write a command to retrieve the records whose first name starts with 'S'.


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答:
You could overload the stream out operator (<<) and stream out each individual field (and vice versa)

EDIT: here is a complete example...

```<code>#include <iostream>
#include <fstream>
#include <map>

using namespace std;

template <typename T>
void serialize(ostream& str, const T& field)
{
  str.rdbuf()->sputn(reinterpret_cast<const char*>(&field), sizeof(T));
}

template <typename T>
void deserialize(istream& str, T& field)
{
  str.rdbuf()->sgetn(reinterpret_cast<char*>(&field), sizeof(T));
}

class MyGame
{
public:
 MyGame() : a(), b() {}
 MyGame(int av, int bv) : a(av), b(bv) {}

 friend ostream& operator<<(ostream& str, MyGame const& game);
 friend istream& operator>>(istream& str, MyGame& game);

  int getA() const { return a; }
  int getB() const { return b; }

private:
 int a;
 int b;
};

ostream& operator<<(ostream& str, MyGame const& game)
{
  serialize(str, game.a);
  serialize(str, game.b);
  return str;
}

istream& operator>>(istream& str, MyGame& game)
{
  deserialize(str, game.a);
  deserialize(str, game.b);
  return str;
}

int main(void)
{
  {
    ofstream fout("test.bin", ios::binary);
    MyGame game(10, 11);
    fout << game;
  }

  {
    ifstream fin("test.bin", ios::binary);
    MyGame game;
    fin >> game;
    cout << "game.a: " << game.getA() << ", game.b: " << game.getB() << endl;
  }

  return 0;
}
</code>```

You must understand the issues with this approach though, such as the resulting file will be platform specific (i.e. non-portable) etc.

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

Body:
You could overload the stream out operator (<<) and stream out each individual field (and vice versa)

EDIT: here is a complete example...

#include <iostream>
#include <fstream>
#include <map>

using namespace std;

template <typename T>
void serialize(ostream& str, const T& field)
{
  str.rdbuf()->sputn(reinterpret_cast<const char*>(&field), sizeof(T));
}

template <typename T>
void deserialize(istream& str, T& field)
{
  str.rdbuf()->sgetn(reinterpret_cast<char*>(&field), sizeof(T));
}

class MyGame
{
public:
 MyGame() : a(), b() {}
 MyGame(int av, int bv) : a(av), b(bv) {}

 friend ostream& operator<<(ostream& str, MyGame const& game);
 friend istream& operator>>(istream& str, MyGame& game);

  int getA() const { return a; }
  int getB() const { return b; }

private:
 int a;
 int b;
};

ostream& operator<<(ostream& str, MyGame const& game)
{
  serialize(str, game.a);
  serialize(str, game.b);
  return str;
}

istream& operator>>(istream& str, MyGame& game)
{
  deserialize(str, game.a);
  deserialize(str, game.b);
  return str;
}

int main(void)
{
  {
    ofstream fout("test.bin", ios::binary);
    MyGame game(10, 11);
    fout << game;
  }

  {
    ifstream fin("test.bin", ios::binary);
    MyGame game;
    fin >> game;
    cout << "game.a: " << game.getA() << ", game.b: " << game.getB() << endl;
  }

  return 0;
}

You must understand the issues with this approach though, such as the resulting file will be platform specific (i.e. non-portable) etc.