问:
Determining subnet mask based on number of hosts
During preparation for an exam I came over two questions that didn't make sense to me.

"You are planning to subnet IPv4 addresses to use on a global network. The design must support creating two separate networks that allows for support up to 1000 hosts and maximize the number of networks that are avaible.

You need to identify the subnets that meet these requirements."

Network 1:

```<code> 1. 172.16.0.0/5
 2. 172.16.0.0/6
 3. 172.16.0.0/8
</code>```

Network 2:

```<code> 1. 10.0.0.0/14
 2. 10.0.0.0/16
 3. 10.0.0.0/20
</code>```

The correct answers are 2) for Network 1 and 1) for Network 2, but the calculations are not presented as a part of the solutions. I've been trying for a few days to work it out, but something in my brain seems to have crashed.

I'd be grateful if anyone could show me how to work from network ID, netmask and number hosts to determine which netmask is the best and provides the most subnets.

答:
10101100 00010000 00000000 000000
is the binary representation of the IP address 172.16.0.0.
the subnet must be done in such a way so that atleast 1000 hosts can be allocated.
We cannot touch the 172 and 16 address as it belongs to a different class.
now looking at

00 00 00 00 and 00 00 00 00

if we subnet the 1st 6 places it will leading to

11 11 11 00 00 00 00 00 to 11 11 11 11 11 11 11 11

which is 172.16.252.0 to 172.16.255.255 giving us 256*4 = approx 1000 hosts
hence we subnet using 172.16.0.0/6 but not others as it may lead to shortage or excess present available hosts
Hope its helpful for the other but consider class as the second question belong to different class

Body:
During preparation for an exam I came over two questions that didn't make sense to me.

"You are planning to subnet IPv4 addresses to use on a global network. The design must support creating two separate networks that allows for support up to 1000 hosts and maximize the number of networks that are avaible.

You need to identify the subnets that meet these requirements."

Network 1:

 1. 172.16.0.0/5
 2. 172.16.0.0/6
 3. 172.16.0.0/8

Network 2:

 1. 10.0.0.0/14
 2. 10.0.0.0/16
 3. 10.0.0.0/20

The correct answers are 2) for Network 1 and 1) for Network 2, but the calculations are not presented as a part of the solutions. I've been trying for a few days to work it out, but something in my brain seems to have crashed.

I'd be grateful if anyone could show me how to work from network ID, netmask and number hosts to determine which netmask is the best and provides the most subnets.


来源: stackexchange

问:
Firebase increment key to avoid push
i've little problem regarding firebase auto generated key via push().
i want to replace push auto generated key like in MySQL 0001,0002,0003,0004,0005

Here is image for firebase auto generated key Click this.

```<code>  public void onClick(View view) {
            Firebase ref=new Firebase(config_firebaseurl.FIREBASE_URL);

        String address=Address.getText().toString().trim();
            String license_no=licenseno.getText().toString().trim();

            personal_information per=new personal_information();
            per.setYear(getYear);
            per.setMonth(getMonth);
            per.setDay(getDate);
            per.setAddress(address);
            per.setState(state);
            per.setLicenseno(license_no);
            per.setFirstName(fname);
            per.setLastName(lname);
            per.setGender(getgender);
            per.setmobileNo(phoneno);

            ref.child("personal_information").push().setValue(per);
            Intent i=new Intent(personal_information_handler.this, means_of_transport_handler.class);
            startActivity(i);

            Toast.makeText(getApplicationContext(),"Information Added", Toast.LENGTH_LONG).show();
        }
</code>```

I want to auto generated key in 0001,0002,0003 in this form .

答:
I'd not recommned doing so, but as workaround you can store like this:

```<code>ref.child("personal_information").child(incrementedId).setValue(per)
</code>```

but in this case you need to know the last value each time you saving new data.

ContentLicense: CC BY-SA 3.0

Title: Firebase increment key to avoid push

Body:
i've little problem regarding firebase auto generated key via push().
i want to replace push auto generated key like in MySQL 0001,0002,0003,0004,0005

Here is image for firebase auto generated key Click this.

  public void onClick(View view) {
            Firebase ref=new Firebase(config_firebaseurl.FIREBASE_URL);

        String address=Address.getText().toString().trim();
            String license_no=licenseno.getText().toString().trim();

            personal_information per=new personal_information();
            per.setYear(getYear);
            per.setMonth(getMonth);
            per.setDay(getDate);
            per.setAddress(address);
            per.setState(state);
            per.setLicenseno(license_no);
            per.setFirstName(fname);
            per.setLastName(lname);
            per.setGender(getgender);
            per.setmobileNo(phoneno);

            ref.child("personal_information").push().setValue(per);
            Intent i=new Intent(personal_information_handler.this, means_of_transport_handler.class);
            startActivity(i);

            Toast.makeText(getApplicationContext(),"Information Added", Toast.LENGTH_LONG).show();
        }

I want to auto generated key in 0001,0002,0003 in this form .

Body:
I'd not recommned doing so, but as workaround you can store like this:

ref.child("personal_information").child(incrementedId).setValue(per)

but in this case you need to know the last value each time you saving new data.


问:
Service unavailable message in IIS
I have created a sample ASP.NET website and hosted it in IIS 6.0 . It is working fine , if the identity of the defalut app pool is "local system". But when i changed the identity with some other configurable user id then it is showing as "Service Unavailable".

The following message is found in the event viewver.

"The identity of application pool 'DefaultAppPool' is invalid, so the World Wide Web Publishing Service can not create a worker process to serve the application pool.  Therefore, the application pool has been disabled."

答:
FYI,

In a development environment you can use the default app pool to create your web applications.

In production environment you want to use lusrmgr.msc (Server 2008/R2/7 Ultimate and Pro) to create new users (and their credentials) on the machine and assign the users to the right group (IIS_IUSRS).

Also once you have created the user, you will want to give it access to your data source back-end (if sql is running on the same machine and using windows authentication to access SQL).

ContentLicense: CC BY-SA 2.5

Title: Service unavailable message in IIS


问:
ServiceNow Compare Servers Attributes
How can I get a diff between two servers taking all the attributes like OS Details, Patches installed, Load Balncer associated, Software installed etc.</p>

答:
You may want to check AvailabilityGuard. It's a ServiceNow Addon that allows Server Comparison as well as compliance standard checks and out of the box Downtime and Data-Loss risk assessment.

Another option is to check Symantec's CCS. More security oriented but potentially does something similar.

Mark.

Title: ServiceNow Compare Servers Attributes


问:
update table by getting a value from another view Yii
i'm using yii framework here. i need help, how to put a value to my textfield and update my table while the value that i take is from the other view.

i have a main table (A) where this table have id, proj_name, design_start_date, design_end_date. while my other table (B) have id, design_start, design_end. value of design_start_date will update by the minimum date from design_start and design_end_date will update by the maximum date from design_end

can anybody help me? thanks in advance

答:
i have found my solution, thanks..
if u need some maybe this could help

in my table A view:

```<code>$start_date = Yii::app()->db->createCommand("select * from (select design_start from B Order by design_start asc) where rownum = 1")->queryScalar();

$end_date = Yii::app()->db->createCommand("select * from (select design_end from B Order by design_end asc) where rownum = 1")->queryScalar();
</code>```

somehow the textfield u want to fill with that value:

```<code><?php echo $form->textfield($model, 'design_start_date', array('id'=>'designstartDate', 'value'=>$start_date))>
<?php echo $form->textfield($model, 'design_end_date', array('id'=>'designendDate', 'value'=>$end_date))>
</code>```

value will be generated in textfield but u still have to click the save button so it will save to table A

Body:
i have found my solution, thanks..
if u need some maybe this could help

in my table A view:

$start_date = Yii::app()->db->createCommand("select * from (select design_start from B Order by design_start asc) where rownum = 1")->queryScalar();

$end_date = Yii::app()->db->createCommand("select * from (select design_end from B Order by design_end asc) where rownum = 1")->queryScalar();

somehow the textfield u want to fill with that value:

<?php echo $form->textfield($model, 'design_start_date', array('id'=>'designstartDate', 'value'=>$start_date))>
<?php echo $form->textfield($model, 'design_end_date', array('id'=>'designendDate', 'value'=>$end_date))>

value will be generated in textfield but u still have to click the save button so it will save to table A


问:
Iterate over an array of Objects and get the key Angular 2
Hi I have a data structure as below:

```<code>list = [{id: "test", name: "name1"}, {id: "test1", name: "name2"}, ..]
</code>```

I want to display the keys (id and name) as th in my table. Since i didnt find any buitin pipes i created a custom one.

```<code>@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}
</code>```

But in my html, am getting only 0, 1 , 2, ... as keys. Any idea whats happening wrong here?

答:
Maybe this would help:  </p>

```<code>@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    Object.keys(value).forEach(function(key){
      keys.push({key: key, value: value['value']});
    });

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

Body:
Hi I have a data structure as below:

list = [{id: "test", name: "name1"}, {id: "test1", name: "name2"}, ..]

I want to display the keys (id and name) as th in my table. Since i didnt find any buitin pipes i created a custom one.

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

But in my html, am getting only 0, 1 , 2, ... as keys. Any idea whats happening wrong here?

Body:
Maybe this would help:

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    Object.keys(value).forEach(function(key){
      keys.push({key: key, value: value['value']});
    });

    return keys;
  }
}


问:
JTable multiple selection without using keyboard only using mouse
Here is my code. I want to select multiple rows in JTable, I am using the following line:

```<code>table.getColumnModel().getSelectionModel().setSelectionMode(
    javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
</code>```

With the above line I am able to select multiple rows using keyboard, but requirement is to select only using mouse.

Is there any thing other than this, that Java provides for multiple selection only using mouse without using keyboard?

答:
I finally used this code:

```<code>JTable table = new JTable(){
    @Override
    public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
        super.changeSelection(rowIndex, columnIndex, true, extend);
    }
};
</code>```

This way CTRL(toogle) is always pushed(true).

Body:
Here is my code. I want to select multiple rows in JTable, I am using the following line:

table.getColumnModel().getSelectionModel().setSelectionMode(
    javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

With the above line I am able to select multiple rows using keyboard, but requirement is to select only using mouse.

Is there any thing other than this, that Java provides for multiple selection only using mouse without using keyboard?

Body:
I finally used this code:

JTable table = new JTable(){
    @Override
    public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
        super.changeSelection(rowIndex, columnIndex, true, extend);
    }
};

This way CTRL(toogle) is always pushed(true).


问:
How can I do the opposite .include?
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!</p>

```<code>def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])
</code>```

答:
I have to do this using loops.

You approach is very creative. You have re-created an if statement using a while loop:

```<code>while expression do
  # ...
  break
end
</code>```

Is equivalent to:

```<code>if expression
  # ...
end
</code>```

With expression being something like array.include? element.

How can I do the opposite?

To invert a (boolean) expression, you just prepend !:

```<code>if !expression
  # ...
end
</code>```

Applied to your while-hack:

```<code>while !expression do
  # ...
  break
end
</code>```

The whole method would look like this:

```<code>def element_index(element, my_array)
  while my_array.include? element do
    puts my_array.index(element)
    break
  end

  while !my_array.include? element do
    puts -1
    break
  end
end

element_index("c", ["a","b","c"])
# prints 2
element_index("d", ["a","b","c"])
# prints -1
</code>```

As I said at the beginning, this approach is very "creative". You are probably supposed to find the index using a loop (see Schwern's answer) instead of calling the built-in index.

Title: How can I do the opposite .include?

Body:
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!

def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])

Body:
I have to do this using loops.

You approach is very creative. You have re-created an if statement using a while loop:

while expression do
  # ...
  break
end

Is equivalent to:

if expression
  # ...
end

With expression being something like array.include? element.

How can I do the opposite?

To invert a (boolean) expression, you just prepend !:

if !expression
  # ...
end

Applied to your while-hack:

while !expression do
  # ...
  break
end

The whole method would look like this:

def element_index(element, my_array)
  while my_array.include? element do
    puts my_array.index(element)
    break
  end

  while !my_array.include? element do
    puts -1
    break
  end
end

element_index("c", ["a","b","c"])
# prints 2
element_index("d", ["a","b","c"])
# prints -1

As I said at the beginning, this approach is very "creative". You are probably supposed to find the index using a loop (see Schwern's answer) instead of calling the built-in index.


问:
I can't remove the margin between two input fields
I'm trying to remove the margin between the search bar and the "Go!" button at the top of this page: http://beta.linksku.com/

I've tried removing all styles and adding margin:0;padding:0;border:none;, but there is still a margin between the two elements. I cannot replicate this problem on JSFiddle, but it occurs in all browsers on my website.

答:
One way is to remove space, but if you're not willing to have an unreadable one-line mess, you can use HTML comment:</p>

```<code><form id="search" method="get" action="http://beta.linksku.com/">
      <input type="text" name="s" tabindex="2"><!--
  !--><input type="submit" value="Go!" class="btn">
</form>
</code>```

Body:
One way is to remove space, but if you're not willing to have an unreadable one-line mess, you can use HTML comment:

<form id="search" method="get" action="http://beta.linksku.com/">
      <input type="text" name="s" tabindex="2"><!--
  !--><input type="submit" value="Go!" class="btn">
</form>


问:
Handle exceptions without crashing socket server?
I am attempting to run a threaded socket server that handles multiple clients simultaneously. However after I telnet into the server and then exit in a non-graceful way, say by closing the window.

The server crashes and returns System.out.println("Runnable terminating with exception: " + e ); with e being java.Lang.NullPointerException.

My question is how can I simply close the socket and keep the server running even if something goes wrong in handleSession(), so that others can connect?

I am new to exceptions so my understand is still elementary.

```<code>publc class ThreadedHandler implements Runnable {
    Socket incoming;
    BufferedReader in;
    PrintWriter out;
    SortedTopicList topics;

    ThreadedHandler(Socket s) {
        incoming = s;
    }
    public void run() {
        try {
            handleSession(incoming);
        }catch (Exception e) {
            System.out.println("Runnable terminating with exception: " + e );
        }
        }

    public void handleSession(Socket client) {
        try {
            //Code goes here
        } catch (IOException e) {
            System.err.println(e.getMessage());
        } finally {
            shutdown();
        }
    }

    public void shutdown() {
        try {
            in.close();
            out.close();
            incoming.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}
</code>```

My main method is as follows:

```<code>public class MessageBoardServer {

    public static void main(String[] args) {
        Thread t;
        try {
            ServerSocket ss = new ServerSocket(118118);
            while(true) {
                Socket session = ss.accept();
                t = new Thread(new ThreadedHandler(session));
                t.start();
            }

} catch (Exception e) {
    System.err.println(e.getMessage());
}
}
}
</code>```

答:
I would recommend to put while body inside a try/catch block, since any error there breaks the loop.

About the NPE - seems that you initialize BufferedReader in;, PrintWriter out; inside the handleSession method, in try. If something fails before is has initialized in and/or out, it will fail with NPE, since shutdown called in finally and closes in and out.

The code as it posted here doesn't break the main loop around accept on NPE in the run of the handler thread.

Body:
I am attempting to run a threaded socket server that handles multiple clients simultaneously. However after I telnet into the server and then exit in a non-graceful way, say by closing the window.

The server crashes and returns System.out.println("Runnable terminating with exception: " + e ); with e being java.Lang.NullPointerException.

My question is how can I simply close the socket and keep the server running even if something goes wrong in handleSession(), so that others can connect?

I am new to exceptions so my understand is still elementary.

publc class ThreadedHandler implements Runnable {
    Socket incoming;
    BufferedReader in;
    PrintWriter out;
    SortedTopicList topics;

    ThreadedHandler(Socket s) {
        incoming = s;
    }
    public void run() {
        try {
            handleSession(incoming);
        }catch (Exception e) {
            System.out.println("Runnable terminating with exception: " + e );
        }
        }

    public void handleSession(Socket client) {
        try {
            //Code goes here
        } catch (IOException e) {
            System.err.println(e.getMessage());
        } finally {
            shutdown();
        }
    }

    public void shutdown() {
        try {
            in.close();
            out.close();
            incoming.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

My main method is as follows:

public class MessageBoardServer {

    public static void main(String[] args) {
        Thread t;
        try {
            ServerSocket ss = new ServerSocket(118118);
            while(true) {
                Socket session = ss.accept();
                t = new Thread(new ThreadedHandler(session));
                t.start();
            }

} catch (Exception e) {
    System.err.println(e.getMessage());
}
}
}


问:
Windows Form Cancel Button Not Working
I have a Visual Studio, Visual Basic form that includes an OK button and a Cancel button.

What I want to do is have the OK button save the options that the user chooses and of course the Cancel button discarding them and returning them to their previous values.

But what I'm noticing is that as I'm debugging the form, the values are being saved regardless of whichever button I'm choosing. On the form's properties, I have declared that indeed the CancelBtn is the CancelBtn and that the OK button is the OK button, but the values are still being saved regardless.

Is there a better way to do what I would like this form to do?

EDIT:

Here's the code so far for the two buttons, both are being set to close the window. AcceptOption should save the values and CancelOption should just close the form. I'm sorry if this isn't done well but the FAQ's that I found only mention changing the properties of each button and nothing about the code.:

```<code>Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles AcceptOptionBtn.Click
    ' Save the Options
    Me.Close()
    ' Close the form
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles CancelOptionBtn.Click
    ' Close the form
    Me.Close()
End Sub
</code>```

答:
I was having the same issues. As soon as I use My.Settings.Blabla = Blabla.value, it gets saved even if I haven't used My.Settings.Save() which makes My.Settings.Save() completely pointless as far as I can tell.

I ended up taking up Jordell's advice: Don't change "the values" until the user clicks the Save button but it wasn't too clear for me how to go about it.

I ended up using temporary variables in all my settings subs instead of the user My.Settings.UserConfigs. Only when I was in the OK sub did I call

My.Settings.UserConfigSetting = temporary_UserCofigValue

Here is an example from the code I was working on:

```<code>Private Sub btnOptionsThemeLB_Back_Update_Click(sender As System.Object, e As System.EventArgs) Handles btnOptionsThemeLB_Back_Update.Click
    If (tempOptionsThemeLB_Back = Nothing) Then
        tempOptionsThemeLB_Back = Me.btnOptionsThemeLB_Back.BackColor
    End If
    tempOptionsThemeLB_Back = RGBToColor(txtbOptionsThemeLB_Back_Red.Text, txtbOptionsThemeLB_Back_Green.Text, txtbOptionsThemeLB_Back_Blue.Text, tempOptionsThemeLB_Back)
    Me.btnOptionsThemeLB_Back.BackColor = tempOptionsThemeLB_Back
End Sub
</code>```

And only withing the Ok sub did I call My.Settings.

```<code>'Theme Section
My.Settings.colorBtnBack = tempOptionsThemeLB_Back
</code>```

Title: Windows Form Cancel Button Not Working

Body:
I have a Visual Studio, Visual Basic form that includes an OK button and a Cancel button.

What I want to do is have the OK button save the options that the user chooses and of course the Cancel button discarding them and returning them to their previous values.

But what I'm noticing is that as I'm debugging the form, the values are being saved regardless of whichever button I'm choosing. On the form's properties, I have declared that indeed the CancelBtn is the CancelBtn and that the OK button is the OK button, but the values are still being saved regardless.

Is there a better way to do what I would like this form to do?

EDIT:

Here's the code so far for the two buttons, both are being set to close the window. AcceptOption should save the values and CancelOption should just close the form. I'm sorry if this isn't done well but the FAQ's that I found only mention changing the properties of each button and nothing about the code.:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles AcceptOptionBtn.Click
    ' Save the Options
    Me.Close()
    ' Close the form
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles CancelOptionBtn.Click
    ' Close the form
    Me.Close()
End Sub

Body:
I was having the same issues. As soon as I use My.Settings.Blabla = Blabla.value, it gets saved even if I haven't used My.Settings.Save() which makes My.Settings.Save() completely pointless as far as I can tell.

I ended up taking up Jordell's advice: Don't change "the values" until the user clicks the Save button but it wasn't too clear for me how to go about it.

I ended up using temporary variables in all my settings subs instead of the user My.Settings.UserConfigs. Only when I was in the OK sub did I call

My.Settings.UserConfigSetting = temporary_UserCofigValue

Here is an example from the code I was working on:

Private Sub btnOptionsThemeLB_Back_Update_Click(sender As System.Object, e As System.EventArgs) Handles btnOptionsThemeLB_Back_Update.Click
    If (tempOptionsThemeLB_Back = Nothing) Then
        tempOptionsThemeLB_Back = Me.btnOptionsThemeLB_Back.BackColor
    End If
    tempOptionsThemeLB_Back = RGBToColor(txtbOptionsThemeLB_Back_Red.Text, txtbOptionsThemeLB_Back_Green.Text, txtbOptionsThemeLB_Back_Blue.Text, tempOptionsThemeLB_Back)
    Me.btnOptionsThemeLB_Back.BackColor = tempOptionsThemeLB_Back
End Sub

And only withing the Ok sub did I call My.Settings.

'Theme Section
My.Settings.colorBtnBack = tempOptionsThemeLB_Back


问:
psql variable substitution for postgres script with functions
I have a Postgres script that I have that I intend to run against multiple databases. The sample SQL has functions and tables like

```<code>CREATE FUNCTION point() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.the_geom:=ST_SetSRID(geom, :CRS) ;
RETURN NEW;
END
$$;

CREATE TABLE admin (
gid integer NOT NULL,
geom geometry(Polygon,:CRS)
);
</code>```

I have put a variable inside so that I can substitute it on runtime as

 psql -d db -p 5432 -U username -h localhost -f test.sql --variable=CRS=3857

Why does the variable only get properly substituted in table definitions and not function definition

答:
https://www.postgresql.org/docs/current/static/app-psql.html#APP-PSQL-INTERPOLATION

Therefore, a construction such as ':foo' doesn't work to produce a
  quoted literal from a variable's value (and it would be unsafe if it
  did work, since it wouldn't correctly handle quotes embedded in the
  value).

a function definition is put between quotes - in your case $$ instead of ', so it fails. You can change ST_SetSRID(geom, :CRS) to ST_SetSRID(geom, $$:CRS) to see it start being handled again (of course ruining the function body)

As a workaround you can try using bash variable instead:

```<code>vao@vao-VirtualBox:~$ export CRS=33
vao@vao-VirtualBox:~$ psql t << EOF
> CREATE OR REPLACE FUNCTION point() RETURNS trigger
> LANGUAGE plpgsql
> AS \$\$
> BEGIN
> NEW.the_geom:=ST_SetSRID(geom, $CRS) ;
> RETURN NEW;
> END
> \$\$;
> \sf point()
> EOF
CREATE FUNCTION
CREATE OR REPLACE FUNCTION public.point()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
BEGIN
NEW.the_geom:=ST_SetSRID(geom, 33) ;
RETURN NEW;
END
$function$
</code>```

Of course it can be scripted to a file that you can call as bash with argument

Body:
I have a Postgres script that I have that I intend to run against multiple databases. The sample SQL has functions and tables like

CREATE FUNCTION point() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.the_geom:=ST_SetSRID(geom, :CRS) ;
RETURN NEW;
END
$$;

CREATE TABLE admin (
gid integer NOT NULL,
geom geometry(Polygon,:CRS)
);

I have put a variable inside so that I can substitute it on runtime as

 psql -d db -p 5432 -U username -h localhost -f test.sql --variable=CRS=3857

Why does the variable only get properly substituted in table definitions and not function definition

Body:
https://www.postgresql.org/docs/current/static/app-psql.html#APP-PSQL-INTERPOLATION

Therefore, a construction such as ':foo' doesn't work to produce a
  quoted literal from a variable's value (and it would be unsafe if it
  did work, since it wouldn't correctly handle quotes embedded in the
  value).

a function definition is put between quotes - in your case $$ instead of ', so it fails. You can change ST_SetSRID(geom, :CRS) to ST_SetSRID(geom, $$:CRS) to see it start being handled again (of course ruining the function body)

As a workaround you can try using bash variable instead:

vao@vao-VirtualBox:~$ export CRS=33
vao@vao-VirtualBox:~$ psql t << EOF
> CREATE OR REPLACE FUNCTION point() RETURNS trigger
> LANGUAGE plpgsql
> AS \$\$
> BEGIN
> NEW.the_geom:=ST_SetSRID(geom, $CRS) ;
> RETURN NEW;
> END
> \$\$;
> \sf point()
> EOF
CREATE FUNCTION
CREATE OR REPLACE FUNCTION public.point()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
BEGIN
NEW.the_geom:=ST_SetSRID(geom, 33) ;
RETURN NEW;
END
$function$

Of course it can be scripted to a file that you can call as bash with argument


问:
disabling horizontal scroll on an iPhone website
I am developing an iPhone version of a Wordpress driven website and I was wondering if there's any method to disable horizontal scrolling when the website is open in Safari for iPhone. Right now, I am half way through the development and just to check if I could disable horizontal scrolling, I have hidden any of the elements which were exceeding the screen width but still I can scroll horizontally to the right. I tried putting the following code inside the

答:
I was having the same issue with a mobile menu positioned outside the viewport area. overflow-x: hidden solved in Android phones, but not in iPhones. I solved by changing 'absolute' to 'fixed' position to the menu:

```<code>body { overflow-x: hidden; }
nav { position: absolute; width: 300px; right: -300px; }
</code>```

to:

```<code>body { overflow-x: hidden; }
nav { position: fixed; width: 300px; right: -300px; }
</code>```

Hope it helps.

Body:
I was having the same issue with a mobile menu positioned outside the viewport area. overflow-x: hidden solved in Android phones, but not in iPhones. I solved by changing 'absolute' to 'fixed' position to the menu:

body { overflow-x: hidden; }
nav { position: absolute; width: 300px; right: -300px; }

to:

body { overflow-x: hidden; }
nav { position: fixed; width: 300px; right: -300px; }

Hope it helps.


问:
Partial template specialization for specific type, c++
Using partial specialization of templates I would like to  create a function/method:

A) processing only one specific primitive type (int, double, float,...) of the formal parameter and for other types throwing exception

```<code>template <class T>
T min ( Point <T> p )
{
    /*if (T == int) continue;
    else throw exception*/
}
</code>```

B)  processing more non-primitive types (user defined types) of the formal parameter and for other types throwing exception...

Some code examples would be helpful (without c++ boost library). Thanks for your help.

答:
As mentioned in the comment by Alexender C., are you sure a compile error wouldn't be more suitable?

```<code>template <typename T> struct GateKeeper;

// Func we want to call
template <typename S, typename T> void foo (T t);

// Warpper that checks the type and forwards the call
template <typename T> inline void foo (T t)
{
  //
  // This call will fail for unless a specialization of
  // GateKeeper for `T` is defined with a member TYPE
  foo< typename GateKeeper<T>::TYPE, T > ( t );
}

//
// This declaration "allows" the type int.
template <> struct GateKeeper<int> { typedef int TYPE; };

void bar ()
{
  foo (0);   // Compiles
  foo (0.0); // Causes error in wrapping foo
}
</code>```

A partial specialization can be used to allow any specialization of a given template:

```<code>// Some template type
template <typename T>
class TmplType
{
};

// This allows for specializations of TmplType
template <typename T> struct GateKeeper< TmplType<T> > { typedef int TYPE; };

void bar ()
{
  TmplType<char> tt;
  foo (tt);   // Compiles
}
</code>```

For each type that you wish to support you add a new specialization.

UPDATE: What is happening:

Note: I've changed the template parameter names from the original version to make things a bit clearer.

When the compiler sees a call to foo(x) the only function that it can correctly specialize is foo<T>(T).  This is because it cannot deduce all the template parameters for foo<S,T>(T).

The body of foo<T>(T) forwards the call to the real function:

```<code>foo< typename GateKeeper<T>::TYPE, T > ( t );
</code>```

(ASIDE: see here for description of when to use typename)

This is doing 2 things at once.

The first is to provide the 2 template parameters (S and T) which are required to call the other function.

The second is to use a member of GateKeeper<T> as this other type.  The type GateKeeper<T> must be complete and have that member.  It is this check that allows us to specify which types we want to allow and which we don't:

```<code>template <typename T> struct GateKeeper;                  // Incomplete
template <> struct GateKeeper<int> { typedef int TYPE; }; // Complete
</code>```

As we have only provided a definition for GateKeeper<int> and not for GateKeeper<double>, the call to foo(0) works correctly, and foo(0.0) fails with a compile error.

To allow double, we just need to add an explicit specialization for it:

```<code>template <> struct GateKeeper<double> { typedef int TYPE; }; // double now works.
</code>```

Body:
Using partial specialization of templates I would like to  create a function/method:

A) processing only one specific primitive type (int, double, float,...) of the formal parameter and for other types throwing exception

template <class T>
T min ( Point <T> p )
{
    /*if (T == int) continue;
    else throw exception*/
}

B)  processing more non-primitive types (user defined types) of the formal parameter and for other types throwing exception...

Some code examples would be helpful (without c++ boost library). Thanks for your help.

Body:
As mentioned in the comment by Alexender C., are you sure a compile error wouldn't be more suitable?

template <typename T> struct GateKeeper;

// Func we want to call
template <typename S, typename T> void foo (T t);

// Warpper that checks the type and forwards the call
template <typename T> inline void foo (T t)
{
  //
  // This call will fail for unless a specialization of
  // GateKeeper for `T` is defined with a member TYPE
  foo< typename GateKeeper<T>::TYPE, T > ( t );
}

//
// This declaration "allows" the type int.
template <> struct GateKeeper<int> { typedef int TYPE; };

void bar ()
{
  foo (0);   // Compiles
  foo (0.0); // Causes error in wrapping foo
}

A partial specialization can be used to allow any specialization of a given template:

// Some template type
template <typename T>
class TmplType
{
};

// This allows for specializations of TmplType
template <typename T> struct GateKeeper< TmplType<T> > { typedef int TYPE; };

void bar ()
{
  TmplType<char> tt;
  foo (tt);   // Compiles
}

For each type that you wish to support you add a new specialization.

UPDATE: What is happening:

Note: I've changed the template parameter names from the original version to make things a bit clearer.

When the compiler sees a call to foo(x) the only function that it can correctly specialize is foo<T>(T).  This is because it cannot deduce all the template parameters for foo<S,T>(T).

The body of foo<T>(T) forwards the call to the real function:

foo< typename GateKeeper<T>::TYPE, T > ( t );

(ASIDE: see here for description of when to use typename)

This is doing 2 things at once.

The first is to provide the 2 template parameters (S and T) which are required to call the other function.

The second is to use a member of GateKeeper<T> as this other type.  The type GateKeeper<T> must be complete and have that member.  It is this check that allows us to specify which types we want to allow and which we don't:

template <typename T> struct GateKeeper;                  // Incomplete
template <> struct GateKeeper<int> { typedef int TYPE; }; // Complete

As we have only provided a definition for GateKeeper<int> and not for GateKeeper<double>, the call to foo(0) works correctly, and foo(0.0) fails with a compile error.

To allow double, we just need to add an explicit specialization for it:

template <> struct GateKeeper<double> { typedef int TYPE; }; // double now works.


问:
Binding to a nullable data type in WPF
Well, this little quirk of WPF is really getting under my skin. So, I have a DataGrid like this:

```<code><DataGrid x:Name="Rates" AlternatingRowBackground="#FCFCFC" AutoGenerateColumns="False" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserAddRows="False" SelectionUnit="FullRow" CanUserSortColumns="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Item" Width="Auto" IsReadOnly="True" Binding="{Binding item}"/>
        <DataGridTextColumn Header="Rate" Width ="*" Binding="{Binding rate, UpdateSourceTrigger=PropertyChanged}"/>
    </DataGrid.Columns>
</code>```

It simply has a list of items in column A and we have to enter the rates in column B. Sounds simple enough.

Here is the property in the ViewModel to which it is bound.

```<code>private BindableCollection<Rate> _rates;

public BindableCollection<Rate> Rates
{
    get
    {
        return _rates;
    }

    set
    {
        if (value == _rates)
        {
            return;
        }

        _rates = value;
        NotifyOfPropertyChange();
    }
}
</code>```

Here is the definition for Rate:

```<code>public partial class Rate
{
    public int ID { get; set; }
    public string client { get; set; }
    public string item { get; set; }
    public Nullable<decimal> rate { get; set; }
}
</code>```

So, the second column of my DataGrid is getting bound to Rate.rate which is a Nullable<decimal>. Herein lies the problem. The Nullable<decimal> does accept NULL but the TextBox wouldn't let me enter a blank value. Moreover, if I type in some value like 5 and then delete it, the ViewModel retains the previous value.

I have seen solutions involving the IValueConverter, but I would prefer a XAML-based solution. Is there any? I have several modules where the DataType is Nullable, and it can quickly become very tedious if I have to use IValueConverter every time.

EDIT

I am using Caliburn.Micro, hence using TargetNullValue='' will not work everywhere, as the binding is automatic. It'll work in the above example, where the binding is explicitly mentioned.

答:
Well, customizing the binding in ConventionManagerof Caliburn was the way to go.

Here is the solution:
https://github.com/Caliburn-Micro/Caliburn.Micro/issues/448

Title: Binding to a nullable data type in WPF

Body:
Well, this little quirk of WPF is really getting under my skin. So, I have a DataGrid like this:

<DataGrid x:Name="Rates" AlternatingRowBackground="#FCFCFC" AutoGenerateColumns="False" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserAddRows="False" SelectionUnit="FullRow" CanUserSortColumns="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Item" Width="Auto" IsReadOnly="True" Binding="{Binding item}"/>
        <DataGridTextColumn Header="Rate" Width ="*" Binding="{Binding rate, UpdateSourceTrigger=PropertyChanged}"/>
    </DataGrid.Columns>

It simply has a list of items in column A and we have to enter the rates in column B. Sounds simple enough.

Here is the property in the ViewModel to which it is bound.

private BindableCollection<Rate> _rates;

public BindableCollection<Rate> Rates
{
    get
    {
        return _rates;
    }

    set
    {
        if (value == _rates)
        {
            return;
        }

        _rates = value;
        NotifyOfPropertyChange();
    }
}

Here is the definition for Rate:

public partial class Rate
{
    public int ID { get; set; }
    public string client { get; set; }
    public string item { get; set; }
    public Nullable<decimal> rate { get; set; }
}

So, the second column of my DataGrid is getting bound to Rate.rate which is a Nullable<decimal>. Herein lies the problem. The Nullable<decimal> does accept NULL but the TextBox wouldn't let me enter a blank value. Moreover, if I type in some value like 5 and then delete it, the ViewModel retains the previous value.

I have seen solutions involving the IValueConverter, but I would prefer a XAML-based solution. Is there any? I have several modules where the DataType is Nullable, and it can quickly become very tedious if I have to use IValueConverter every time.

EDIT

I am using Caliburn.Micro, hence using TargetNullValue='' will not work everywhere, as the binding is automatic. It'll work in the above example, where the binding is explicitly mentioned.


问:
Scan C disk and copy files
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

```<code>Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"
</code>```

How should I fix the last couple of things on my list?
Thanks

答:
First you have to use double backslash for UNC paths.
Second, the copy-item does not output anything to the pipeline, you have to use the -Passthru parameter.</p>

```<code>Get-ChildItem -path z:\ -recurse -include *.pst  -PipelineVariable source |
    Copy-Item -Destination "\\path\temp" -Verbose -PassThru |
    Select-Object @{n="Source";e={$source.versioninfo.filename}},fullname,lastwritetime | export-csv "\\path\temp\copy_result.csv" -Append -Verbose
</code>```

Title: Scan C disk and copy files

Body:
I would appreciate some help here.

The Powershell script should close Outlook process which works.

Aswell as scan C disk for .pst files which works.

Copy these files to "\fileserver01\temp\test\"

Export to csv/excel list where these files where located and last write time.

Possible hide error messages for the user when running the script since it complains about not full access on a few folders when running the scan.

Code:

Get-Process outlook | Foreach-Object { $_.CloseMainWindow() }

Get-ChildItem -path c:\ -recurse -include *.pst | `
Copy-Item -destination "\\fileserver01\temp\test\" | `
Select-object fullname,lastwritetime|export-csv "\\fileserver01\temp\test\"

How should I fix the last couple of things on my list?
Thanks

Body:
First you have to use double backslash for UNC paths.
Second, the copy-item does not output anything to the pipeline, you have to use the -Passthru parameter.

Get-ChildItem -path z:\ -recurse -include *.pst  -PipelineVariable source |
    Copy-Item -Destination "\\path\temp" -Verbose -PassThru |
    Select-Object @{n="Source";e={$source.versioninfo.filename}},fullname,lastwritetime | export-csv "\\path\temp\copy_result.csv" -Append -Verbose


问:
TFS(Git): More active pull request on same branch
I have a process question. Now Im planning the move from git/gerrit to TFS(Git) environment. Its very hard to me left the perfect functioning gerrit behind of us. :-(.
I start to checking the abilities of the TFS(Git) and I have a question.
We would use feature-branches and during the tests I see I can not create more active pull requests on the same branch or I can not add extra file versions to the same pull request. Besides I always have to merge when the pull request finished.

How can I use the the following process:?

```<code>1. DEveloper A send a commit to a feature F branch
2. DEveloper B and DEveloper C review the commit
3. Developer A send fixes to the feature F branch
4. Developer B and C review it again
5. After everyone is extremely happy and the feature is finished feature F
   will be merged
</code>```

I could not find a soulution in TFS(Git) to expand the pull request in extra commits.

DO you have an idea?

答:
You can add extra changesto the pull request. So it’s not necessary to have multiple active pull request on the same branch. This is because the new committed changes after the pull request will automatically add to the active pull request.

As the process you showed, after a pull request created for merge commit a from featureX into featureF branch, and then you make additional change on featureX branch during the above pull request still active. Now developer B and C review this pull request, they will find the additional change you made fir the second time also contain in the pull request.

Body:
I have a process question. Now Im planning the move from git/gerrit to TFS(Git) environment. Its very hard to me left the perfect functioning gerrit behind of us. :-(.
I start to checking the abilities of the TFS(Git) and I have a question.
We would use feature-branches and during the tests I see I can not create more active pull requests on the same branch or I can not add extra file versions to the same pull request. Besides I always have to merge when the pull request finished.

How can I use the the following process:?

1. DEveloper A send a commit to a feature F branch
2. DEveloper B and DEveloper C review the commit
3. Developer A send fixes to the feature F branch
4. Developer B and C review it again
5. After everyone is extremely happy and the feature is finished feature F
   will be merged

I could not find a soulution in TFS(Git) to expand the pull request in extra commits.

DO you have an idea?


问:
How to display set access permission & display /hide div based on database values
I want to set access permissions page where setting the permissions to the user to only view selected divs only for example:

There are 5 checkboxes  in admin page and 5 divs in user page if check 3 div user has to get 3 div only I am mapping userlocation & client location & username for setting access permissions and how to display / hide the div in user page based on the checkbox selection or database values?

There is a user login separately and admin login separately. The admin will disable certain features for certain users. Using wcf rest and sql server as backend.

答:
Before we get into the answer I have to mention security. You probably know, but for future readers benefit...you must not rely on simply hiding or not generating HTML elements as a means of restricting user access. Why - because when your form submits data to the server this can be observed with simple tools like Fiddlr. If you simply hide important inputs on the web page but still submit them, then a mischievous user could use something like Postman to edit and submit dodgy values to your server INCLUDING for the fields that were not visible on the form. Even if you have some server-side code to restrict the generation of the HTML for the restricted inputs, if a user is able to see a full form submit, or more likely if your API is self-describing or well documented, then they can fire up Postman and start sending your server all manner of hooky data.

For this reason it is vital that you re-validate the user, their role and their right to modify at the server at each interaction. Sermon over.

Assuming the above protection is in place then the way forward is relatively simple. In your HTML you assign classes to the elements that need to show/hide and you send a variable from the server to dictate their hidden or visible state.

For example, say you have two groups of users called usrNormal and usrAdmin. You might have an input defined as:

```<code><input type="text" class="usrNormal usrAdmin" name="somedata" style="display:hidden;"></input>
<input type="text" class="usrAdmin" name="admindata" style="display:hidden;"></input>
<div class="usrNormal usrAdmin" style="display:hidden;">Some important info here....</div>
<div class="usrAdmin" style="display:hidden;">Some admin-only info here....    </div>
</code>```

The key to this technique is the css class setting class="usrNormal usrAdmin"

And the accompanying JS function is:

var usrType = "usrNormal";
function protect() {
$("." + usrType).show();
}
protect();

I have used JQuery here in the line inside the function, you could use plain JS to achieve the same. We start the page with the important inputs, divs and other html elements hidden. The usrType setting comes from the server,  and when the protect() function is called it finds all elements with the given user type class and makes them visible.

EDIT: See working snippet below. Though contrived the idea is clear I hope. One point to consider is the use of a generic marker class to indicate that the appropriate elements should take part in the show/hide operation. Let me know if you have any queries.

$( document ).ready(function() { // Important: wait for the document dom to be ready

  // get the value of the server access variable - simulated by the radio buttons in this case
  // var access = <you would put your server value here !>
  var access = ".usrNormal";
  setAccess(access);

  // next part is just to let you play.
  $('.serverVal').on('change', function(e){
    setAccess($(this).val());
    })

  // key function - this will show pr hide based on classes.
  function setAccess(accessVal) {

    // next line finds all elements with class including 'usrAccess' and shows if they have the request class or otherwise hides.
    $(".usrAccess").each( function() {
      var ele = $(this); // readability

      showHide(ele, accessVal);

    })

  }

  // show or hide the element based on class
  function showHide(ele, cls){

    if ( ele.is(cls) ){ // pay attention - this uses the jquery 'is' feature.
      ele.show();
    }
    else {
     ele.hide();
    }

  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1">
  <p>
    <span>This selection simulates the value passed from the server. When changed the elements with the matching classes are shown or hidden.</span><br />
  </p>
  <p>
    <span>
      <input type="radio" class="serverVal" id="usrType1"  name="usrType" value=".usrNormal"  checked="1" />
      <label for="usrType1"> Normal User only</label>
    </span>
    <span>
      <input type="radio" class="serverVal" id="usrType2"  name="usrType" value=".usrAdmin"/>
      <label for="usrType2"> Admin User only </label>
    </span>
    <span>
      <input type="radio" class="serverVal" id="usrType3"  name="usrType" value=".usrAdmin, .usrNormal" name="usrType3"/>
      <label for="usrType3"> Both </label><br />
    </span>
  </p>
  <hr>
  <p class="usrNormal usrAccess" style="display:none;">
    <label for="somedata">Normal only</label>
    <input type="text" name="somedata" />
  </p>
  <p class="usrAdmin usrAccess" style="display:none;">
    <label for="admindata1">Admin only</label>
    <input type="text" class="usrAdmin" name="admindata1"  />
  </p>
  <p class="usrNormal usrAccess" style="display:none;">
    <label for="someinfo">Info 1</label>
    <textarea id="someinfo">This textare is visible to normal users...</textarea>
  </p>
  <p class="usrAdmin usrAccess" style="display:none;">
    <label for="admininfo">Info 2</label>
    <textarea id="admininfo">This textare is visible to only Admin users...</textarea>
  </p>

</form></code>```

Body:
Before we get into the answer I have to mention security. You probably know, but for future readers benefit...you must not rely on simply hiding or not generating HTML elements as a means of restricting user access. Why - because when your form submits data to the server this can be observed with simple tools like Fiddlr. If you simply hide important inputs on the web page but still submit them, then a mischievous user could use something like Postman to edit and submit dodgy values to your server INCLUDING for the fields that were not visible on the form. Even if you have some server-side code to restrict the generation of the HTML for the restricted inputs, if a user is able to see a full form submit, or more likely if your API is self-describing or well documented, then they can fire up Postman and start sending your server all manner of hooky data.

For this reason it is vital that you re-validate the user, their role and their right to modify at the server at each interaction. Sermon over.

Assuming the above protection is in place then the way forward is relatively simple. In your HTML you assign classes to the elements that need to show/hide and you send a variable from the server to dictate their hidden or visible state.

For example, say you have two groups of users called usrNormal and usrAdmin. You might have an input defined as:

<input type="text" class="usrNormal usrAdmin" name="somedata" style="display:hidden;"></input>
<input type="text" class="usrAdmin" name="admindata" style="display:hidden;"></input>
<div class="usrNormal usrAdmin" style="display:hidden;">Some important info here....</div>
<div class="usrAdmin" style="display:hidden;">Some admin-only info here....    </div>

The key to this technique is the css class setting class="usrNormal usrAdmin"

And the accompanying JS function is:

var usrType = "usrNormal";
function protect() {
$("." + usrType).show();
}
protect();

I have used JQuery here in the line inside the function, you could use plain JS to achieve the same. We start the page with the important inputs, divs and other html elements hidden. The usrType setting comes from the server,  and when the protect() function is called it finds all elements with the given user type class and makes them visible.

EDIT: See working snippet below. Though contrived the idea is clear I hope. One point to consider is the use of a generic marker class to indicate that the appropriate elements should take part in the show/hide operation. Let me know if you have any queries.

$( document ).ready(function() { // Important: wait for the document dom to be ready

  // get the value of the server access variable - simulated by the radio buttons in this case
  // var access = <you would put your server value here !>
  var access = ".usrNormal";
  setAccess(access);

  // next part is just to let you play.
  $('.serverVal').on('change', function(e){
    setAccess($(this).val());
    })

  // key function - this will show pr hide based on classes.
  function setAccess(accessVal) {

    // next line finds all elements with class including 'usrAccess' and shows if they have the request class or otherwise hides.
    $(".usrAccess").each( function() {
      var ele = $(this); // readability

      showHide(ele, accessVal);

    })

  }

  // show or hide the element based on class
  function showHide(ele, cls){

    if ( ele.is(cls) ){ // pay attention - this uses the jquery 'is' feature.
      ele.show();
    }
    else {
     ele.hide();
    }

  }

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1">
  <p>
    <span>This selection simulates the value passed from the server. When changed the elements with the matching classes are shown or hidden.</span><br />
  </p>
  <p>
    <span>
      <input type="radio" class="serverVal" id="usrType1"  name="usrType" value=".usrNormal"  checked="1" />
      <label for="usrType1"> Normal User only</label>
    </span>
    <span>
      <input type="radio" class="serverVal" id="usrType2"  name="usrType" value=".usrAdmin"/>
      <label for="usrType2"> Admin User only </label>
    </span>
    <span>
      <input type="radio" class="serverVal" id="usrType3"  name="usrType" value=".usrAdmin, .usrNormal" name="usrType3"/>
      <label for="usrType3"> Both </label><br />
    </span>
  </p>
  <hr>
  <p class="usrNormal usrAccess" style="display:none;">
    <label for="somedata">Normal only</label>
    <input type="text" name="somedata" />
  </p>
  <p class="usrAdmin usrAccess" style="display:none;">
    <label for="admindata1">Admin only</label>
    <input type="text" class="usrAdmin" name="admindata1"  />
  </p>
  <p class="usrNormal usrAccess" style="display:none;">
    <label for="someinfo">Info 1</label>
    <textarea id="someinfo">This textare is visible to normal users...</textarea>
  </p>
  <p class="usrAdmin usrAccess" style="display:none;">
    <label for="admininfo">Info 2</label>
    <textarea id="admininfo">This textare is visible to only Admin users...</textarea>
  </p>

</form>


答:
If you are using Caliburn.Micro, you can configure the way CM applies automatic bindings between your View and your ViewModel.

So in the Configure method of your Bootstrapper classe you can write something like:

```<code>protected override void Configure()
{
    ConventionManager.SetBinding = delegate(Type viewModelType, string path, PropertyInfo property, FrameworkElement element, ElementConvention convention, DependencyProperty bindableProperty)
    {
        Binding binding = new Binding(path);
        ConventionManager.ApplyBindingMode(binding, property);
        ConventionManager.ApplyValueConverter(binding, bindableProperty, property);
        ConventionManager.ApplyStringFormat(binding, convention, property);
        ConventionManager.ApplyValidation(binding, viewModelType, property);
        ConventionManager.ApplyUpdateSourceTrigger(bindableProperty, element, binding, property);

        if (Nullable.GetUnderlyingType(property.PropertyType) != null)
        {
            binding.TargetNullValue = String.Empty;
        }

        BindingOperations.SetBinding(element, bindableProperty, binding);
    };

    // Your own configurations...
}
</code>```

As you can see this code sets the TargetNullValue property of the Binding if the source property is Nullable. It is applied to all automatic binding that CM creates for you in your application.

I hope it helps.

EDIT

About your last comment, consider that Caliburn Micro do not handle FrameworkElements which are already binded (in the XAML) to a property when it applies the "automatic binding".

So if you want to automatically set the TargetNullValue of your "manual" bindings, well the simpliest idea is to create your own binding:

```<code>public class NullableBinding : Binding
{
    public NullableBinding(string path)
        : base(path)
    {
        TargetNullValue = String.Empty;
    }

    public NullableBinding()
        : base()
    {
        TargetNullValue = String.Empty;
    }
}
</code>```

and then use it in your XAML:

```<code><DataGridTextColumn Header="Rate" Width ="*" Binding="{local:NullableBinding rate}"/>
</code>```

Title: Binding to a nullable data type in WPF

Body:
If you are using Caliburn.Micro, you can configure the way CM applies automatic bindings between your View and your ViewModel.

So in the Configure method of your Bootstrapper classe you can write something like:

protected override void Configure()
{
    ConventionManager.SetBinding = delegate(Type viewModelType, string path, PropertyInfo property, FrameworkElement element, ElementConvention convention, DependencyProperty bindableProperty)
    {
        Binding binding = new Binding(path);
        ConventionManager.ApplyBindingMode(binding, property);
        ConventionManager.ApplyValueConverter(binding, bindableProperty, property);
        ConventionManager.ApplyStringFormat(binding, convention, property);
        ConventionManager.ApplyValidation(binding, viewModelType, property);
        ConventionManager.ApplyUpdateSourceTrigger(bindableProperty, element, binding, property);

        if (Nullable.GetUnderlyingType(property.PropertyType) != null)
        {
            binding.TargetNullValue = String.Empty;
        }

        BindingOperations.SetBinding(element, bindableProperty, binding);
    };

    // Your own configurations...
}

As you can see this code sets the TargetNullValue property of the Binding if the source property is Nullable. It is applied to all automatic binding that CM creates for you in your application.

I hope it helps.

EDIT

About your last comment, consider that Caliburn Micro do not handle FrameworkElements which are already binded (in the XAML) to a property when it applies the "automatic binding".

So if you want to automatically set the TargetNullValue of your "manual" bindings, well the simpliest idea is to create your own binding:

public class NullableBinding : Binding
{
    public NullableBinding(string path)
        : base(path)
    {
        TargetNullValue = String.Empty;
    }

    public NullableBinding()
        : base()
    {
        TargetNullValue = String.Empty;
    }
}

and then use it in your XAML:

<DataGridTextColumn Header="Rate" Width ="*" Binding="{local:NullableBinding rate}"/>


问:
iOS App with this Features? Possible?
I'm trying to develop an application with prohibited features for iOS. Swift.

I just want to know how possible they are (to make and to submit).

1 - Silencing the phone: I've seen this question in a lot of posts and the all says NO, No posible and will be rejected but... how about this app? This app silence the phone (putting ringer volume to 0) -> https://itunes.apple.com/us/app/autosilent-automatically-silence-your-phone/id474777148?mt=8
This app was summited a few years ago, i think when Celestial Framework and submitting apps with Private Frameworks was something possible, not now, so, is this possible?

2 - Blocking calls: I know since iOS 10 you can block calls with CallKit but, you need to give XCProvider a list of numbers to block. I want to block all the calls, can i give all the numbers? in the world?.

3 - Respond blocked calls with an SMS back: I can not have information about the incoming call (phone number) to send some request to a web API so it can send a message to the caller. Or do i?.

Thank you very much for all your responses...

答:
I think your second and third point are impossible at the current situation.
You could give XCProvider a list with all number but that list would have a length of about 10^13 entries.
Apple doesn't provide a public API to recognize blocked calls and thats why you third point seems to be impossible too.</p>

Title: iOS App with this Features? Possible?


问:
How to build and sign an iOS app on separate machines?
We have an iOS app which is built using a series of Bash scripts run by Jenkins. As things are today, we build an xcarchive using this command:

```<code>xcodebuild archive -workspace "..." -scheme "..." -configuration "Release" -archivePath "..."
</code>```

This builds the app and signs it using the certs specified in the provisioning profile which is set using an xcconfig. Once it is complete, we then turn it into an IPA using:

```<code>xcodebuild -archivePath "..." -exportArchive -exportOptionsPlist "${export_options_plist}" -exportPath "..."
</code>```

This IPA can then be uploaded to Hockey or to the App store depending on the xcconfig we use (we swap them out to create different builds).

We now want to make sure our certificates are kept safe as much as possible. This means we want to perform the build on one machine, but the signing on another. In order to do that, we need to do this:

Create an unsigned xcarchive

Transfer the xcarchive to the signing machine

Turn the xcarchive into a signed IPA

Step 2 can be ignored for now though, so lets just focus on steps #1 and #3.

Creating the unsigned xcarchive can be done by adding the arguments CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO to the archive command.

Signing the IPA is much trickier though. We assumed we could just create the IPA again and use the codesign command to sign the binary in the IPA. This had a couple of problems though. The first is that the .entitlements file we had for the app wasn't respected. We had to pass this as a flag to the signing command. Then we realised that we had to correct all the variables in the .entitlements file since Xcode was no longer replacing them with the correct values. Then we realised that we had to do this for each extension we had.

We finally got this all working, with the correct entitlements, replacing the variables and everything was signed, but when I tried uploading the new signed IPA to Hockey it rejected it. The error message wasn't helpful either.

We diff'ed a build with the previous system with the new system and each binary was different. We're not sure if this is a codesigning issue, or just a timestamp change, but there are changes. Furthermore, we discovered that my extensions are all missing archived-expanded-entitlements.xcent files, plus possibly more issues.

It definitely seems like we are going about this the wrong way. We clearly shouldn't have to re-do everything just to sign on a different machine, so where are we going wrong? How are we supposed to build on one machine and sign on another?

P.S. Our current tools use xcodebuild directly, but we have support for fastlane for other parts of our build process, so we are happy to use it if needed.

Update: We have a "solution" to this which is to sign the Release builds with a dev cert, then resign them using the distribution one. This solves all the problems with entitlements being populated etc. but still requires each binary to be resigned and entitlements combined, etc. so I'm curious if there is a better solution.

答:
This might work for you I think

Create an unsigned IPA on your build machine.

Have a script in the build machine that transfers the IPA to your
signing machine.

Use the FloatSign script on the signing machine to resign the
IPA.

Body:
We have an iOS app which is built using a series of Bash scripts run by Jenkins. As things are today, we build an xcarchive using this command:

xcodebuild archive -workspace "..." -scheme "..." -configuration "Release" -archivePath "..."

This builds the app and signs it using the certs specified in the provisioning profile which is set using an xcconfig. Once it is complete, we then turn it into an IPA using:

xcodebuild -archivePath "..." -exportArchive -exportOptionsPlist "${export_options_plist}" -exportPath "..."

This IPA can then be uploaded to Hockey or to the App store depending on the xcconfig we use (we swap them out to create different builds).

We now want to make sure our certificates are kept safe as much as possible. This means we want to perform the build on one machine, but the signing on another. In order to do that, we need to do this:

Create an unsigned xcarchive

Transfer the xcarchive to the signing machine

Turn the xcarchive into a signed IPA

Step 2 can be ignored for now though, so lets just focus on steps #1 and #3.

Creating the unsigned xcarchive can be done by adding the arguments CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO to the archive command.

Signing the IPA is much trickier though. We assumed we could just create the IPA again and use the codesign command to sign the binary in the IPA. This had a couple of problems though. The first is that the .entitlements file we had for the app wasn't respected. We had to pass this as a flag to the signing command. Then we realised that we had to correct all the variables in the .entitlements file since Xcode was no longer replacing them with the correct values. Then we realised that we had to do this for each extension we had.

We finally got this all working, with the correct entitlements, replacing the variables and everything was signed, but when I tried uploading the new signed IPA to Hockey it rejected it. The error message wasn't helpful either.

We diff'ed a build with the previous system with the new system and each binary was different. We're not sure if this is a codesigning issue, or just a timestamp change, but there are changes. Furthermore, we discovered that my extensions are all missing archived-expanded-entitlements.xcent files, plus possibly more issues.

It definitely seems like we are going about this the wrong way. We clearly shouldn't have to re-do everything just to sign on a different machine, so where are we going wrong? How are we supposed to build on one machine and sign on another?

P.S. Our current tools use xcodebuild directly, but we have support for fastlane for other parts of our build process, so we are happy to use it if needed.

Update: We have a "solution" to this which is to sign the Release builds with a dev cert, then resign them using the distribution one. This solves all the problems with entitlements being populated etc. but still requires each binary to be resigned and entitlements combined, etc. so I'm curious if there is a better solution.


问:
sql - multiple primary keys on inner join
I need to count all rows with distinctive ItemID:s with the highest RevisionID on the item with that ItemID. Here's my code (relevant parts):

```<code>(
SELECT count(parent.ItemID) FROM item AS parent
INNER JOIN item AS child ON parent.ItemID = child.ItemID AND parent.RevisionID = Max(child.RevisionID)
WHERE parent.orderID = orders.orderID AND parent.StatusInfo != '2'
) as notordered,
</code>```

The code works if you take out "AND parent.RevisionID = Max(child.RevisionID)", but then it takes all the revision of the items. I am aware that I can't use "Max" with INNER JOIN ON, but I couldn't find a way to get it in a way that it was consistent with the rule parent.ItemID = child.ItemID with a subquery.
Please help.

Example:

Input

A- ID:1 RevID:2

B- ID:1 RevID:3

C- ID:2 RevID:4

Return:

B & C, because they have unique ID:s and the highest RevID with that ID

答:
The correct answer hinted by http://stackoverflow.com/questions/17882073/mysql-select-max-date-inside-a-join-statement/17882188#17882188 was:</p>

```
SELECT count(parent.ItemID) FROM item AS parent
JOIN (SELECT itemID, MAX(RevisionID) as MaxRevision FROM Item GROUP BY ItemID) as child ON parent.ItemID = child.ItemID AND parent.RevisionID = child.MaxRevision
WHERE parent.orderID = orders.orderID
) as notordered,
```

Body:
I need to count all rows with distinctive ItemID:s with the highest RevisionID on the item with that ItemID. Here's my code (relevant parts):

(
SELECT count(parent.ItemID) FROM item AS parent
INNER JOIN item AS child ON parent.ItemID = child.ItemID AND parent.RevisionID = Max(child.RevisionID)
WHERE parent.orderID = orders.orderID AND parent.StatusInfo != '2'
) as notordered,

The code works if you take out "AND parent.RevisionID = Max(child.RevisionID)", but then it takes all the revision of the items. I am aware that I can't use "Max" with INNER JOIN ON, but I couldn't find a way to get it in a way that it was consistent with the rule parent.ItemID = child.ItemID with a subquery.
Please help.

Example:

Input

A- ID:1 RevID:2

B- ID:1 RevID:3

C- ID:2 RevID:4

Return:

B & C, because they have unique ID:s and the highest RevID with that ID

Body:
The correct answer hinted by http://stackoverflow.com/questions/17882073/mysql-select-max-date-inside-a-join-statement/17882188#17882188 was:

SELECT count(parent.ItemID) FROM item AS parent
JOIN (SELECT itemID, MAX(RevisionID) as MaxRevision FROM Item GROUP BY ItemID) as child ON parent.ItemID = child.ItemID AND parent.RevisionID = child.MaxRevision
WHERE parent.orderID = orders.orderID
) as notordered,


问:
I want to form a set of new matrices from a matrix which varies with time
I have a data matrix called xnt of size 16*96. I break this data into overlapping windows as follows:

```<code>WL = 4;
for t = 4:96
    X_time_Total(:,:,t) = xnt(:,[(t-WL+1):t]);
end
</code>```

Now I have X_time_Total which is a 16*4*96 matrix.

Next I form a new 16*16*93 matrix Four_Xt, which combines every four consecutive windows formed previously:

```<code>for tt = WL:93
    Four_Xt(:,:,tt)=[X_time_Total(:,:,tt),X_time_Total(:,:,tt+1),X_time_Total(:,:,tt+2),X_time_Total(:,:,tt+3)];
end
</code>```

The first row of this Four_Xt(:,:,tt) is vector form of the first 4*4 matrix ujTt, the second row forms the second one of wanted 4*4 matrix ujTt. There are 16 rows in Four_Xt(:,:,tt), so I have 16 ujTts each of size 4*4 (For one istant of time tt).

The problem is: I want a new 4*4*16 matrix called U, for each time tt:WL,....

For j = 1:16 the 4*4 matrix layers are formed from Four_Xt as follows:

```<code>    ujTt(:,:,j)=[Four_Xt(j,tt-WL+1:tt);
                 Four_Xt(j,tt-WL+2:tt+1);
                 Four_Xt(j,tt-WL+3:tt+2);
                 Four_Xt(j,tt-WL+4:tt+3)];
</code>```

ujTt must change with time because Four_Xt changes with time. How can I have ujTt for all times tt and all j=1:16?

I wrote the following for this but it's not correct.

```<code>ujTt_temp=[];
for tt=WL:93
    for j=1:N
        ujTt(:,:,j)=[Four_Xt(j,tt-WL+1:tt);Four_Xt(j,tt-WL+2:tt+1);Four_Xt(j,tt-WL+3:tt+2);Four_Xt(j,tt-WL+4:tt+3)];

        ujTt_temp(:,:,tt) = ujTt(:,:,j);
    end
    ujTt_all=[ujTt_temp;ujTt_temp];
end
</code>```

It's a little bit confusing at least for me. I appreciate any help.

答:
If I understand correctly, you arrive at a point where you have a 16*16*93 matrix of all your data, and you want to split each of the 16 rows into a 4*4 matrix? You can turn it into a 4*4*16*93 matrix using reshape:

```<code>U = reshape(Four_Xt, 4, 4, 16, 93);
</code>```

Then you have 93 matrices of size 4*4*16 which are indexed using

```<code>t = 27;            % 27th sub-matrix;
ujTt = U(:,:,:,t); % 4*4*16 matrix
</code>```

Body:
I have a data matrix called xnt of size 16*96. I break this data into overlapping windows as follows:

WL = 4;
for t = 4:96
    X_time_Total(:,:,t) = xnt(:,[(t-WL+1):t]);
end

Now I have X_time_Total which is a 16*4*96 matrix.

Next I form a new 16*16*93 matrix Four_Xt, which combines every four consecutive windows formed previously:

for tt = WL:93
    Four_Xt(:,:,tt)=[X_time_Total(:,:,tt),X_time_Total(:,:,tt+1),X_time_Total(:,:,tt+2),X_time_Total(:,:,tt+3)];
end

The first row of this Four_Xt(:,:,tt) is vector form of the first 4*4 matrix ujTt, the second row forms the second one of wanted 4*4 matrix ujTt. There are 16 rows in Four_Xt(:,:,tt), so I have 16 ujTts each of size 4*4 (For one istant of time tt).

The problem is: I want a new 4*4*16 matrix called U, for each time tt:WL,....

For j = 1:16 the 4*4 matrix layers are formed from Four_Xt as follows:

    ujTt(:,:,j)=[Four_Xt(j,tt-WL+1:tt);
                 Four_Xt(j,tt-WL+2:tt+1);
                 Four_Xt(j,tt-WL+3:tt+2);
                 Four_Xt(j,tt-WL+4:tt+3)];

ujTt must change with time because Four_Xt changes with time. How can I have ujTt for all times tt and all j=1:16?

I wrote the following for this but it's not correct.

ujTt_temp=[];
for tt=WL:93
    for j=1:N
        ujTt(:,:,j)=[Four_Xt(j,tt-WL+1:tt);Four_Xt(j,tt-WL+2:tt+1);Four_Xt(j,tt-WL+3:tt+2);Four_Xt(j,tt-WL+4:tt+3)];

        ujTt_temp(:,:,tt) = ujTt(:,:,j);
    end
    ujTt_all=[ujTt_temp;ujTt_temp];
end

It's a little bit confusing at least for me. I appreciate any help.

Body:
If I understand correctly, you arrive at a point where you have a 16*16*93 matrix of all your data, and you want to split each of the 16 rows into a 4*4 matrix? You can turn it into a 4*4*16*93 matrix using reshape:

U = reshape(Four_Xt, 4, 4, 16, 93);

Then you have 93 matrices of size 4*4*16 which are indexed using

t = 27;            % 27th sub-matrix;
ujTt = U(:,:,:,t); % 4*4*16 matrix


答:
a little verbose but does the work (EDIT need lubridate package)</p>

```<code>library(lubridate)
        tmp <- seq(as.POSIXct('2011-08-01 13:00'), as.POSIXct('2011-08-05 03:00'),
                       len=42)
            df <- data.frame(tm=tmp, x=seq(42))

            df$h<-substring(df$tm,12)
            df$h<-parse_date_time(df$h,"HMS")

            a<-df$h>=parse_date_time("00:00:00","HMS") & df$h<parse_date_time("06:00:00","HMS")
            b<-df$h>=parse_date_time("06:00:00","HMS") & df$h<parse_date_time("12:00:00","HMS")
            c<-df$h>=parse_date_time("12:00:00","HMS") & df$h<parse_date_time("18:00:00","HMS")
            d<-df$h>=parse_date_time("18:00:00","HMS") & df$h<parse_date_time("24:00:00","HMS")

            df<-cbind(df,a,b,c,d)

            df$group<-as.factor(1*a+2*b+3*c+4*d)
    levels(df$group)<-c("12am-6am", "6am-12pm", "12pm-6pm", "6pm-12am")
            df$h<-NULL
            df$a<-NULL
            df$b<-NULL
            df$c<-NULL
            df$d<-NULL
            df
</code>```

Title: how to cut the time in R

Body:
I have following date time column in R dataframe

date
2016-03-21 16:18:00 IST
2016-04-01 03:12:00 IST
2016-04-01 14:58:00 IST
2016-04-02 03:24:00 IST
2016-04-02 19:00:00 IST
2016-04-02 20:40:00 IST

Date column is in POSIXct format

I want to bucket time in 12am-6am,6am-12pm,12pm-6pm and 6pm-12am

My desired data frame would be

date                        time_bucket
2016-03-21 16:18:00 IST     12pm-6pm
2016-04-01 03:12:00 IST     12am-6am
2016-04-01 14:58:00 IST     12pm-6pm
2016-04-02 03:24:00 IST     12pm-6pm
2016-04-02 19:00:00 IST     6pm-12am
2016-04-02 20:40:00 IST     6pm-12am

How can I do it in r ?

Body:
a little verbose but does the work (EDIT need lubridate package)

library(lubridate)
        tmp <- seq(as.POSIXct('2011-08-01 13:00'), as.POSIXct('2011-08-05 03:00'),
                       len=42)
            df <- data.frame(tm=tmp, x=seq(42))

            df$h<-substring(df$tm,12)
            df$h<-parse_date_time(df$h,"HMS")

            a<-df$h>=parse_date_time("00:00:00","HMS") & df$h<parse_date_time("06:00:00","HMS")
            b<-df$h>=parse_date_time("06:00:00","HMS") & df$h<parse_date_time("12:00:00","HMS")
            c<-df$h>=parse_date_time("12:00:00","HMS") & df$h<parse_date_time("18:00:00","HMS")
            d<-df$h>=parse_date_time("18:00:00","HMS") & df$h<parse_date_time("24:00:00","HMS")

            df<-cbind(df,a,b,c,d)

            df$group<-as.factor(1*a+2*b+3*c+4*d)
    levels(df$group)<-c("12am-6am", "6am-12pm", "12pm-6pm", "6pm-12am")
            df$h<-NULL
            df$a<-NULL
            df$b<-NULL
            df$c<-NULL
            df$d<-NULL
            df


问:
Call Child class method from Parent class method
Consider the following case

```<code>class A
{
    X()
    {
        //some code
        Y();
    }
}

class B extends A
{
    Y(){ //some code }
}
</code>```

If I create an object of the class B, and i try to use function X as it is extended from A, is it possible that the function X can access the function Y of the calling object of class B.

答:
you could but this must be met

A class is abstract

Y method is abstract too

Example:

```<code>abstract class A {
    void X() {
        Y();
    }

    abstract void Y();
}

class B extends A {
    @Override
    void Y() {
        System.out.println("Hello from B class");
    }
}
</code>```

in that form every time class A calls Y, it will actually invoke an implememted method of the abstract method Y

Body:
Consider the following case

class A
{
    X()
    {
        //some code
        Y();
    }
}

class B extends A
{
    Y(){ //some code }
}

If I create an object of the class B, and i try to use function X as it is extended from A, is it possible that the function X can access the function Y of the calling object of class B.

Body:
you could but this must be met

A class is abstract

Y method is abstract too

Example:

abstract class A {
    void X() {
        Y();
    }

    abstract void Y();
}

class B extends A {
    @Override
    void Y() {
        System.out.println("Hello from B class");
    }
}

in that form every time class A calls Y, it will actually invoke an implememted method of the abstract method Y


问:
SQL SERVER: SELECT TOP 1 entire row into "ROW" variable
I am trying to store the entire row as a result of the SELECT TOP * into a kind of "datarow" variable because later, depending on some condition, I need to insert this entire row to a temporary table.

For example, I have done below. The problem is that first I have to assign the values resulting from select top 1 * to variables and then using all these variables to insert into the temporary table, so I want to avoid this, I would like to insert the entire row of select top 1 * into the temporary table at once, see below.

Current scenario:

```<code>DECLARE @Field1 varchar(50)
DECLARE @Field2 int
DECLARE @Field3 DateTime

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

SELECT TOP 1 @Field1 = field1, @Field2 = field2, @Field3 = field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES (@Field1, @Field2, @Field3)
</code>```

And I would like to do something like this, if possible:

Desired scenario:

```<code>DECLARE @Row SOME_KIND_OF_DATA_ROW_VARIABLE

SET @Row = SELECT TOP 1 field1, field2, field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES @Row <-- Obviously, this is incorrect, but I would like to insert the entire row at once
</code>```

答:
You do not need any @Row variable. Just use insert into ... select....

```<code>CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

INSERT INTO #tmpTbl (Field1, Field2, Field3)
SELECT TOP 1
       field1, field2, field3
from OneTable
</code>```

Body:
I am trying to store the entire row as a result of the SELECT TOP * into a kind of "datarow" variable because later, depending on some condition, I need to insert this entire row to a temporary table.

For example, I have done below. The problem is that first I have to assign the values resulting from select top 1 * to variables and then using all these variables to insert into the temporary table, so I want to avoid this, I would like to insert the entire row of select top 1 * into the temporary table at once, see below.

Current scenario:

DECLARE @Field1 varchar(50)
DECLARE @Field2 int
DECLARE @Field3 DateTime

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

SELECT TOP 1 @Field1 = field1, @Field2 = field2, @Field3 = field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES (@Field1, @Field2, @Field3)

And I would like to do something like this, if possible:

Desired scenario:

DECLARE @Row SOME_KIND_OF_DATA_ROW_VARIABLE

SET @Row = SELECT TOP 1 field1, field2, field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES @Row <-- Obviously, this is incorrect, but I would like to insert the entire row at once

Body:
You do not need any @Row variable. Just use insert into ... select....

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

INSERT INTO #tmpTbl (Field1, Field2, Field3)
SELECT TOP 1
       field1, field2, field3
from OneTable