问:
Finding Duplicates: GROUP BY and DISTINCT giving different answers
I have looked through all the questions about group by and distinct and they seem to be different in terms of allowing aggregate functions, but none of them answered my question... so here goes..

I have a database table with 126266 rows of data, each complete row should be unique, but I'm not using row numbers.
I'm trying to find all the duplicate values in this table (as I know they exist) and then delete them. None of the columns are aggregates.

Table:

```<code>CREATE TABLE [dbo].[DBAScanResults](
    [ScanNumber] [float] NOT NULL,
    [DB_ID] [bigint] NOT NULL,
    [PluginID] [bigint] NOT NULL,
    [PluginID_Version] [bigint] NOT NULL,
    [Result] [nvarchar](50) NULL,
    [ActualValue] [nvarchar](max) NULL
</code>```

I've got foreign keys on: ScanNumber, DB_ID, PluginID_Version. Each related primary key is on a different table. (So my database is four tables currently)

If I do a group by, it gives me 12745 rows, which are my duplicate rows:

```<code>Select top 1000000 [ScanNumber]
      ,[DB_ID]
      ,[PluginID]
      ,[PluginID_Version]
      ,[Result]
      ,[ActualValue]
  FROM [ITSecMaster].[dbo].[DBAScanResultsNew]
  group by [ScanNumber]
      ,[DB_ID]
      ,[PluginID]
      ,[PluginID_Version]
      ,[Result]
      ,[ActualValue]
      HAVING COUNT(*) >1
</code>```

If I do a distinct (  Select distinct * from [dbo].[DBAScanResults]) it gives me 78,871 rows, which I am guessing is my unique count of rows without duplicates. My issue here is that 12745+78871 does not equal 126226 ...

So which one is actually right? Do I have 12745 duplicates, or 47,355 duplicates?
And Once I've worked out which is right, I then need to delete the duplicate values from the table ... Normally I'd do this to delete values with a fk, but I can't get the syntax right for multiple fks across 2+ tables.

```<code>DELETE a
FROM DBAScanResults a
INNER JOIN DBAScanDate b
ON a.ScanNumber = b.ScanNumber
WHERE (expression)
</code>```

Any help with this would be greatly appreciated.

Thanks in advance!

答:
Your counting logic is off, and mine was too, until I came up with a simple example to better understand your question.  Imagine a simple table with only one column, text:

```<code>text
----
A
B
B
C
C
C
</code>```

Running SELECT COUNT(*) just yields 6 records, as expected.  SELECT DISTINCT text returns 3 records, for A,B,C.  Finally, SELECT text with HAVING COUNT(*) > 1 returns only two records, for the B and C groups.

None of these numbers add up at all.  The issue here is that a distinct select also returns records which are not duplicate, in addition to records which are duplicate.  Also, a given duplicate record could occur more than two times.  Your current comparison is somewhat apples to oranges.

Edit:

If you want to remove all duplicates in your six-column table, leaving only one distinct record from all columns, then try using a deletable CTE:

```<code>WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ScanNumber, DB_ID, PluginID,
                                        PluginID_Version, Result, ActualValue
                               ORDER BY (SELECT NULL)) rn
    FROM DBAScanResults
)

DELETE
FROM cte
WHERE rn > 1;
</code>```

Body:
I have looked through all the questions about group by and distinct and they seem to be different in terms of allowing aggregate functions, but none of them answered my question... so here goes..

I have a database table with 126266 rows of data, each complete row should be unique, but I'm not using row numbers.
I'm trying to find all the duplicate values in this table (as I know they exist) and then delete them. None of the columns are aggregates.

Table:

CREATE TABLE [dbo].[DBAScanResults](
    [ScanNumber] [float] NOT NULL,
    [DB_ID] [bigint] NOT NULL,
    [PluginID] [bigint] NOT NULL,
    [PluginID_Version] [bigint] NOT NULL,
    [Result] [nvarchar](50) NULL,
    [ActualValue] [nvarchar](max) NULL

I've got foreign keys on: ScanNumber, DB_ID, PluginID_Version. Each related primary key is on a different table. (So my database is four tables currently)

If I do a group by, it gives me 12745 rows, which are my duplicate rows:

Select top 1000000 [ScanNumber]
      ,[DB_ID]
      ,[PluginID]
      ,[PluginID_Version]
      ,[Result]
      ,[ActualValue]
  FROM [ITSecMaster].[dbo].[DBAScanResultsNew]
  group by [ScanNumber]
      ,[DB_ID]
      ,[PluginID]
      ,[PluginID_Version]
      ,[Result]
      ,[ActualValue]
      HAVING COUNT(*) >1

If I do a distinct (  Select distinct * from [dbo].[DBAScanResults]) it gives me 78,871 rows, which I am guessing is my unique count of rows without duplicates. My issue here is that 12745+78871 does not equal 126226 ...

So which one is actually right? Do I have 12745 duplicates, or 47,355 duplicates?
And Once I've worked out which is right, I then need to delete the duplicate values from the table ... Normally I'd do this to delete values with a fk, but I can't get the syntax right for multiple fks across 2+ tables.

DELETE a
FROM DBAScanResults a
INNER JOIN DBAScanDate b
ON a.ScanNumber = b.ScanNumber
WHERE (expression)

Any help with this would be greatly appreciated.

Thanks in advance!

Body:
Your counting logic is off, and mine was too, until I came up with a simple example to better understand your question.  Imagine a simple table with only one column, text:

text
----
A
B
B
C
C
C

Running SELECT COUNT(*) just yields 6 records, as expected.  SELECT DISTINCT text returns 3 records, for A,B,C.  Finally, SELECT text with HAVING COUNT(*) > 1 returns only two records, for the B and C groups.

None of these numbers add up at all.  The issue here is that a distinct select also returns records which are not duplicate, in addition to records which are duplicate.  Also, a given duplicate record could occur more than two times.  Your current comparison is somewhat apples to oranges.

Edit:

If you want to remove all duplicates in your six-column table, leaving only one distinct record from all columns, then try using a deletable CTE:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ScanNumber, DB_ID, PluginID,
                                        PluginID_Version, Result, ActualValue
                               ORDER BY (SELECT NULL)) rn
    FROM DBAScanResults
)

DELETE
FROM cte
WHERE rn > 1;


来源: stackexchange

问:
Should I learn Swing before learning JavaFx?
Does it make sense to start learning JavaFx if I do not have any background in UI programming? Is it more advisable to learn Swing first and then move on to JavaFx ?

I tried the getting started tutorial on JavaFx website in Netbeans and the code looked extremely complicated to me. I am wondering if JavaFx is too advanced for a beginnner GUI developer.

答:
Looking at the JavaFX tutorial I would say that:

you don't need to know Swing to use JavaFX

if you find the JavaFX tutorial hard learning Swing won't be easier

If you have no programming background at all then starting in any language is going to be a challenge.  If you know a little programming in a language then it is still going to be a challenge.

My advice is to dive in and work at it.  A quick google search (JavaFX Hello World) has a number of hits... I took a quick look at this one and I'd say start with it.

OwnerDisplayName: Rahul

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: TofuBeer

LastEditorDisplayName: TofuBeer


问:
WCF and custom text encoding - messy business
I have a really weird WCF problem here...

We're connecting to a crappy third-party web service; it was a nightmare to even get it going, we had to create a custom WCF binding since those guys decided to use "ISO-8859-1" as their text encoding (instead of UTF-8 like everyone else on the web), and the other settings were messy, too - and not documented anywhere, of course...

It's been working ok for a while now, but suddenly, some of our data coming back in mangled up. We expect to get back names of places, and being in Switzerland, some of those have German umlauts in them. But for the past two or three months, we suddenly get back

```<code>HÃ¼nibach
</code>```

instead of the proper

```<code>Hünibach
</code>```

So the ü (u umlaut) is mangled.

No problem, I figured they finally switched to UTF-8, and I changed my custom binding to use UTF-8 as its text encoder instead of ISO-8859-1 - but no luck - no I'm getting:

EXCEPTION: System.ServiceModel.Security.MessageSecurityException

  The HTTP request was forbidden with client authentication scheme 'Basic'.

What the f????? The service is protected by a username/password which we pass in using the ClientCredentials of WCF. Seems that changing the text encoding somehow messes up the credentials !?!?! Weird.....

OK - back to ISO-8859-1, and I just tried to interpret the response payload as UTF-8 - again no luck :-(  Tried with UTF-16, UTF-32, UTF-7 even, Unicode, BigEndianUnicode - all to no avail.

So how on earth do I get back my proper umlauts, and still be able to call that bloody service... works just fine in SoapUI, btw.....

Any ideas?? I'm desperately grasping at any straws you might throw me!!

答:
Actually, I finally figured out what the trouble was.

For some reason, changing the sample CustomTextEncoder (provided by Microsoft in the WCF & WF samples) to use UTF-8 instead of ISO-8859-1 doesn't work.

On the other hand, ripping out the custom text encoder from my custom binding and just using the standard TextMessageEncoder that WCF provides from the get go (which uses UTF-8 by default) did work.

Don't ask me why.... that's just the facts I found.....

Body:
I have a really weird WCF problem here...

We're connecting to a crappy third-party web service; it was a nightmare to even get it going, we had to create a custom WCF binding since those guys decided to use "ISO-8859-1" as their text encoding (instead of UTF-8 like everyone else on the web), and the other settings were messy, too - and not documented anywhere, of course...

It's been working ok for a while now, but suddenly, some of our data coming back in mangled up. We expect to get back names of places, and being in Switzerland, some of those have German umlauts in them. But for the past two or three months, we suddenly get back

HÃ¼nibach

instead of the proper

Hünibach

So the ü (u umlaut) is mangled.

No problem, I figured they finally switched to UTF-8, and I changed my custom binding to use UTF-8 as its text encoder instead of ISO-8859-1 - but no luck - no I'm getting:

EXCEPTION: System.ServiceModel.Security.MessageSecurityException

  The HTTP request was forbidden with client authentication scheme 'Basic'.

What the f????? The service is protected by a username/password which we pass in using the ClientCredentials of WCF. Seems that changing the text encoding somehow messes up the credentials !?!?! Weird.....

OK - back to ISO-8859-1, and I just tried to interpret the response payload as UTF-8 - again no luck :-(  Tried with UTF-16, UTF-32, UTF-7 even, Unicode, BigEndianUnicode - all to no avail.

So how on earth do I get back my proper umlauts, and still be able to call that bloody service... works just fine in SoapUI, btw.....

Any ideas?? I'm desperately grasping at any straws you might throw me!!

ContentLicense: CC BY-SA 3.0


问:
Getting error in convert a string of a hex to a byte array in Java
I am looking for a way to convert string that represents hex values into a byte array. This code is perfect working for even number string length but not for odd number string length. If string length is odd then I get java.lang.StringIndexOutOfBoundsException. Please help. </p>

```<code>public byte[] hexStringToByteArray(String s) {
     byte[] data = null;
         if(! s.equals("")){
            int len = s.length();
            data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                     + Character.digit(s.charAt(i+1), 16));
            }
         }
     return data;
}
</code>```

答:
Your for loop says to keep looping while i < len which allows i to be the string's last index within your loop, causing s.charAt(i+1) to access a non-existent byte.

Either change the loop condition to i < len-1 or i+1 < len.

ContentLicense: CC BY-SA 4.0

Body:
I am looking for a way to convert string that represents hex values into a byte array. This code is perfect working for even number string length but not for odd number string length. If string length is odd then I get java.lang.StringIndexOutOfBoundsException. Please help.

public byte[] hexStringToByteArray(String s) {
     byte[] data = null;
         if(! s.equals("")){
            int len = s.length();
            data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                     + Character.digit(s.charAt(i+1), 16));
            }
         }
     return data;
}


问:
Data structure to store key - value pair where the value can be modified in objective-C
I want to have a data structure where corresponding to each key I have a value(Int) associated where the value can be modified like some value can be added to it.

Can NSMutableDictionary work ?

If yes then how ?

答: Yes, you can use NSMutableDictionary to modified values. But for the value, it should be NSNumber. I think like this it will be okay for you.</p>


问:
Git - Custom command "cd"
Is it possible in the git custom command to change the console bash directory?

My example code:

```<code>#!/bin/bash
# This is a test
cd /c/testfolder
ls
</code>```

the code is working, but the cd only works on this block doesn't do any alteration on the bash.

So what I need it is the console / change to /c/testfolder

答:
It is not possible for a command or shell script to cause the shell / console's current directory to change.

(Unless you are executing the script in the shell itself using source / ..  You can't do that with a git custom command because they are executed by a child process of git not by the console's shell.)

See Bash script to change parent shell directory for a more detailed explanation of the base problem.

Title: Git - Custom command "cd"

Body:
Is it possible in the git custom command to change the console bash directory?

My example code:

#!/bin/bash
# This is a test
cd /c/testfolder
ls

the code is working, but the cd only works on this block doesn't do any alteration on the bash.

So what I need it is the console / change to /c/testfolder


答:
You cannot store primitive types with Cocoa types like NSMutableDictionary, you need to bridge them to their NS types i.e, NSNumber etc</p>

```<code>NSNumber *val1= [NSNumber numberWithInt:0];
NSNumber *val2= [NSNumber numberWithInt:1];
NSNumber *val3= [NSNumber numberWithInt:2];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict["yourKey"] = val1;
dict["yourKey1"] = val2;
dict["yourKey2"] = val3;
</code>```

Title: Data structure to store key - value pair where the value can be modified in objective-C

Body:
I want to have a data structure where corresponding to each key I have a value(Int) associated where the value can be modified like some value can be added to it.

Can NSMutableDictionary work ?

If yes then how ?

Body:
You cannot store primitive types with Cocoa types like NSMutableDictionary, you need to bridge them to their NS types i.e, NSNumber etc

NSNumber *val1= [NSNumber numberWithInt:0];
NSNumber *val2= [NSNumber numberWithInt:1];
NSNumber *val3= [NSNumber numberWithInt:2];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict["yourKey"] = val1;
dict["yourKey1"] = val2;
dict["yourKey2"] = val3;


问:
Conversion of string to integer, then again to string
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

```<code>      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });
</code>```

spinner1:

```<code>public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}
</code>```

spinner 2:

```<code>public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}
</code>```

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

答:
```<code>     String price=Place_View.prices[spinner1.getSelectedItemPosition()];
    String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
    String result="";
    int calc1 = 0;
    int calc2 = 0;
    try {
         calc1 = Integer.parseInt(price);
         calc2 = Integer.parseInt(fare);
    }catch(NumberFormatException e) {
    Log.e("Error","price or fare are not a Number in string format");
    }
    int calc3=calc1+calc2;
    result=String.valueOf(calc3);
    Price.setText(result);
</code>```

<p>Might be the String value you are extracting from spinners are not a number but a generic non numeric string which might be crashing while you parse using Integer.parseInt, just add a catch for NumberFormatException to avoid runtime crash.
and handle the exception according to your usecase by showing some message or whatever feels right for your app.  </p>

Body:
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });

spinner1:

public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}

spinner 2:

public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

Body:
     String price=Place_View.prices[spinner1.getSelectedItemPosition()];
    String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
    String result="";
    int calc1 = 0;
    int calc2 = 0;
    try {
         calc1 = Integer.parseInt(price);
         calc2 = Integer.parseInt(fare);
    }catch(NumberFormatException e) {
    Log.e("Error","price or fare are not a Number in string format");
    }
    int calc3=calc1+calc2;
    result=String.valueOf(calc3);
    Price.setText(result);

Might be the String value you are extracting from spinners are not a number but a generic non numeric string which might be crashing while you parse using Integer.parseInt, just add a catch for NumberFormatException to avoid runtime crash.
and handle the exception according to your usecase by showing some message or whatever feels right for your app.


问:
How can I apply CSS style changes just for one page?
I have two css files:

A main file (main.css)

A specific page file (page5.css). My page.css contains main.css (@import url(main.css));)

My main.css has this as one part of it that sets the height of the page

```<code>#content {
    background:url(../images/image.png) no-repeat;
    width:154px;
    height:356px;
    clear:both;
}
</code>```

This works fine for all the other pages, but at page 5, I need a little bit more height.

How would I go about doing it?

答:
In page5.css, simply re-define the height.

page5.css

```<code>#content {
    height:400px;
}
</code>```

Body:
I have two css files:

A main file (main.css)

A specific page file (page5.css). My page.css contains main.css (@import url(main.css));)

My main.css has this as one part of it that sets the height of the page

#content {
    background:url(../images/image.png) no-repeat;
    width:154px;
    height:356px;
    clear:both;
}

This works fine for all the other pages, but at page 5, I need a little bit more height.

How would I go about doing it?

Body:
In page5.css, simply re-define the height.

page5.css

#content {
    height:400px;
}


问:
How to handle static content in Spring MVC?
I am developing a webapp using Spring MVC 3 and have the DispatcherServlet catching all requests to '/' like so (web.xml):

```<code>  <servlet>
    <servlet-name>app</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>app</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</code>```

Now this works as advertised, however how can I handle static content? Previously, before using RESTful URLs, I would have caught all *.html for example and sent that to the DispatcherServlet, but now it's a different ball game.

I have a /static/ folder which includes /styles/, /js/, /images/ etc and I would like to exclude /static/* from the DispatcherServlet.

Now I could get static resources working when I did this:

```<code>  <servlet-mapping>
    <servlet-name>app</servlet-name>
    <url-pattern>/app/</url-pattern>
  </servlet-mapping>
</code>```

But I want it to have nice URLs (the point of me using Spring MVC 3) not the landing page being www.domain.com/app/

I also don't want a solution coupled to tomcat or any other servlet container, and because this is (relatively) low traffic I don't need a webserver (like apache httpd) infront.

Is there a clean solution to this?

答:
Place static contents like css ,js in following path</p>

```<code>resources
        ->static
               ->css
               ->js
(or)
resources
        ->public
               ->css
               ->js
</code>```

Body:
I am developing a webapp using Spring MVC 3 and have the DispatcherServlet catching all requests to '/' like so (web.xml):

  <servlet>
    <servlet-name>app</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>app</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

Now this works as advertised, however how can I handle static content? Previously, before using RESTful URLs, I would have caught all *.html for example and sent that to the DispatcherServlet, but now it's a different ball game.

I have a /static/ folder which includes /styles/, /js/, /images/ etc and I would like to exclude /static/* from the DispatcherServlet.

Now I could get static resources working when I did this:

  <servlet-mapping>
    <servlet-name>app</servlet-name>
    <url-pattern>/app/</url-pattern>
  </servlet-mapping>

But I want it to have nice URLs (the point of me using Spring MVC 3) not the landing page being www.domain.com/app/

I also don't want a solution coupled to tomcat or any other servlet container, and because this is (relatively) low traffic I don't need a webserver (like apache httpd) infront.

Is there a clean solution to this?

Body:
Place static contents like css ,js in following path

resources
        ->static
               ->css
               ->js
(or)
resources
        ->public
               ->css
               ->js


问:
echo %JAVA_HOME% returns %JAVA_HOME%
When I do

```<code>echo %JAVA_HOME%
</code>```

it returns %JAVA_HOME% on windows 10 what did I do wrong?

答:
If you just added the System Variable you need to reboot for System to read it

if you are using an classic cmd command "echo %JAVA_HOME%" in windowsJAVA is fine

Title: echo %JAVA_HOME% returns %JAVA_HOME%

Body:
When I do

echo %JAVA_HOME%

it returns %JAVA_HOME% on windows 10 what did I do wrong?


问:
JavaScript: Add space between Char and Number with Regex
Hello I have a plate number BZ8345LK and want convert to BZ 8345 LK (adding space between char and number).

I tried with this Regex but not working, only space first char with number. Ex BZ 8345LK, the 'LK' keep not space with number.

```<code>var str = 'BZ8345LK';
str.replace(/[^0-9](?=[0-9])/g, '$& ');
# return BZ 8345LK, I want BZ 8345 LK
</code>```

答:
An anoher option is to use:

```<code>^[^\d]+|[\d]{4}
</code>```

Search for any not numeric character [^\d] followed by 4 numeric [\d]{4} characters

const str = 'BZ8345LK'
let answer = str.replace(/^[^\d]+|[\d]{4}/gi, '$& ')
console.log(answer)```

Body:
Hello I have a plate number BZ8345LK and want convert to BZ 8345 LK (adding space between char and number).

I tried with this Regex but not working, only space first char with number. Ex BZ 8345LK, the 'LK' keep not space with number.

var str = 'BZ8345LK';
str.replace(/[^0-9](?=[0-9])/g, '$& ');
# return BZ 8345LK, I want BZ 8345 LK

Body:
An anoher option is to use:

^[^\d]+|[\d]{4}

Search for any not numeric character [^\d] followed by 4 numeric [\d]{4} characters

const str = 'BZ8345LK'
let answer = str.replace(/^[^\d]+|[\d]{4}/gi, '$& ')
console.log(answer)


答:
You don't even need a separate CSS file necessarily.  You can add classes to your body for various purposes, identifying page or page type being one of them.  So if you had:

```<code><body class="page5">
</code>```

Then in your CSS you could apply:

```<code>.page5 #content {
  height: XXXpx;
}
</code>```

And it would only apply to that page as long as it occurs after your main #content definition.

Title: How can I apply CSS style changes just for one page?

Body:
You don't even need a separate CSS file necessarily.  You can add classes to your body for various purposes, identifying page or page type being one of them.  So if you had:

<body class="page5">

Then in your CSS you could apply:

.page5 #content {
  height: XXXpx;
}

And it would only apply to that page as long as it occurs after your main #content definition.


问:
How can I size table nodes in graphviz that contain bold text?
I'm rendering a pipeline diagram with graphviz. Each node is a step in the pipeline and uses a table for layout. The top row is in bold and shows the name of the step. The other rows show the outputs of the step. Arrows between steps show dependencies.

```<code>digraph {
  node[shape=plaintext]

  A [
    label=<
      <table border="1" cellborder="0" cellspacing="1" >
      <tr><td align="left"><b>FirstVeryLongVeryBoldStepName</b></td></tr>
      <tr><td align="left">→ out.txt</td></tr>
      </table>
    >];

  B [
    label=<
      <table border="1" cellborder="0" cellspacing="1" >
      <tr><td align="left"><b>SecondVeryLongVeryBoldStepName</b></td></tr>
      <tr><td align="left">→ out2.txt</td></tr>
      <tr><td align="left">→ out3.json</td></tr>
      </table>
    >];

  A -> B
}
</code>```

Here's how it renders:

The width of each box seems to be set based on the non-bold width of the text. If I remove the  tag, the layout looks just right:

How can I get the tight layout with the bold text? If it's helpful, here's a link to the example in Graphviz Online

答:
It's interesting, that on on my machine your code renders fine (on both Mac with graphviz 2.41 and Ubundtu with graphviz 2.40: rendered.png). Maybe it depends on the font engine used during graphviz build.

In your situation you may just add three spaces at the end of each bold text node: link to fixed example

If the spaces are being eaten up by HTML parser (may occur especially if you are rendering svg), you can replace them with   symbol (non-breakable space).

Body:
I'm rendering a pipeline diagram with graphviz. Each node is a step in the pipeline and uses a table for layout. The top row is in bold and shows the name of the step. The other rows show the outputs of the step. Arrows between steps show dependencies.

digraph {
  node[shape=plaintext]

  A [
    label=<

FirstVeryLongVeryBoldStepName

→ out.txt

    >];

  B [
    label=<

SecondVeryLongVeryBoldStepName

→ out2.txt

→ out3.json

    >];

  A -> B
}

Here's how it renders:

The width of each box seems to be set based on the non-bold width of the text. If I remove the  tag, the layout looks just right:

How can I get the tight layout with the bold text? If it's helpful, here's a <a href="https://dreampuf.github.io/GraphvizOnline/#digraph%20%7B%0A%20%20%20%20node%5Bshape%3Dplaintext%5D%0A%20%20%20%20%0A%20%20%20%20A%20%5B%0A%20%20%20%20%20%20label%3D%3C%0A%20%20%20%20%20%20%20%20%3Ctable%20border%3D%221%22%20cellborder%3D%220%22%20cellspacing%3D%221%22%20%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%3Cb%3EFirstVeryLongVeryBoldStepName%3C%2Fb%3E%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%E2%86%92%20out.txt%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3C%2Ftable%3E%0A%20%20%20%20%20%20%3E%5D%3B%0A%20%20%20%20%0A%20%20%20%20B%20%5B%0A%20%20%20%20%20%20label%3D%3C%0A%20%20%20%20%20%20%20%20%3Ctable%20border%3D%221%22%20cellborder%3D%220%22%20cellspacing%3D%221%22%20%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%3Cb%3ESecondVeryLongVeryBoldStepName%3C%2Fb%3E%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%E2%86%92%20out2.txt%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%E2%86%92%20out3.json%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3C%2Ftable%3E%0A%20%20%20%20%20%20%3E%5D%3B%0A%0A%20%20%20%20A%20-%3E%20B%0A%0A%20%20%7D" rel="nofollow noreferrer">link to the example in Graphviz Online

Body:
It's interesting, that on on my machine your code renders fine (on both Mac with graphviz 2.41 and Ubundtu with graphviz 2.40: rendered.png). Maybe it depends on the font engine used during graphviz build.

In your situation you may just add three spaces at the end of each bold text node: <a href="https://dreampuf.github.io/GraphvizOnline/#digraph%20%7B%0A%20%20%20%20node%5Bshape%3Dplaintext%5D%0A%20%20%20%20%0A%20%20%20%20A%20%5B%0A%20%20%20%20%20%20label%3D%3C%0A%20%20%20%20%20%20%20%20%3Ctable%20border%3D%221%22%20cellborder%3D%220%22%20cellspacing%3D%221%22%20%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%3Cb%3EFirstVeryLongVeryBoldStepName%20%20%20%3C%2Fb%3E%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%E2%86%92%20out.txt%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3C%2Ftable%3E%0A%20%20%20%20%20%20%3E%5D%3B%0A%20%20%20%20%0A%20%20%20%20B%20%5B%0A%20%20%20%20%20%20label%3D%3C%0A%20%20%20%20%20%20%20%20%3Ctable%20border%3D%221%22%20cellborder%3D%220%22%20cellspacing%3D%221%22%20%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%3Cb%3ESecondVeryLongVeryBoldStepName%20%20%20%3C%2Fb%3E%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%E2%86%92%20out2.txt%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%20align%3D%22left%22%3E%E2%86%92%20out3.json%3C%2Ftd%3E%3C%2Ftr%3E%0A%20%20%20%20%20%20%20%20%3C%2Ftable%3E%0A%20%20%20%20%20%20%3E%5D%3B%0A%0A%20%20%20%20A%20-%3E%20B%0A%0A%20%20%7D" rel="nofollow noreferrer">link to fixed example

If the spaces are being eaten up by HTML parser (may occur especially if you are rendering svg), you can replace them with &nbsp; symbol (non-breakable space).


问:
GitHub Remote: forbidden fatal: unable to access the requested url returned error: 403
Error encountered while pushing branch to the remote repository: Git failed with a fatal error.

I tried using github desktop, command line, git bash and via azure devops too, nothing seems to be working. I have an individual account and I am the owner, so I don't think I shouldn't have access. I can't push or fetch.
Attaching screenshots below -

答:
I just tried to clone your repo and it works fine.

Did you try to check this help from GitHub https://help.github.com/en/articles/https-cloning-errors ?

You might have to enter your github credentials or store them correctly - or provide a token if you have 2FA enabled.


问:
Is there a way to use await keyword inside render in React code
I am trying to use the Substrate UI to display the functionalities that are available in my run-time module. The code is written in React. I am trying to create a component that will help me track all the previous states of a structure.

The runtime.template.assets(i) call takes a hex value i as input and returns a structure kitty which has a key parent_hash(having a hex value). I want the while loop to execute till I have reached a special hex value which in this case is "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9" which I have converted to String to achieve the termination condition.

Please ignore the <KittyShrieks> tag because it is something that I am using to display some values in the UI. Basically I am unable to do this inside the while loop

```<code>var kitty = await runtime.template.kitties(i);
.
.
i = kitty.parent_hash;
</code>```

The required code

```<code>export class TrackCards extends ReactiveComponent {
    constructor(props) {
        super(['hash'])

    }

    unreadyRender() {
        return <span>Nothing to track</span>
    }
    async readyRender() {
      let kitties = [];
        var i = this.state.hash;
        var root_hash = "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9";
        var root = "17,218,109,31,118,29,223,155,219,76,157,110,83,3,235,212,31,97,133,141,10,86,71,161,167,191,224,137,191,146,27,233";
        var iter = 0;
        var a;

        while ((root != i.toString())  {

          var kitty = await runtime.template.kitties(i);
          kitties.push(
              <div className="column" key={i}>

                  <KittyShrieks
                  owner_count = {runtime.template.kittyHistoryCount(i)}
                  hash_original = {this.state.hash}
                  />
              </div>
          );
          i = kitty.parent_hash;
        }
        return <div className="ui stackable six column grid">{kitties}</div>;
    }
}

</code>```

I don't think using async render is a valid thing, but I am doing that because I seem to have no choice but to use the await keyword. So, the problem is that the UI doesnot load and I get the following error:

Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

The UI loads fine if I remove async keyword, var kitty = await runtime.template.kitties(i); statement and insert a break statement at the end of the loop. Therefore, disallowing me to iterate through the loop.

I am kind of new to React and even Javascript in general. Any kind of help would be appreciated.

答:
A component always needs to be able to render something (or null). Here, effectively you are asking React to render a promise, hence your error.

You should extract this logic into the componentDidMount() life cycle. Taking your code as an example, it could look something like this:

```<code>export class TrackCards extends ReactiveComponent {
  constructor(props) {
      super(['hash'])

      this.state = {
        kitties: []
      }
  }

  async componentDidMount() {
    const kitties = [];
    var i = this.state.hash;
    var root_hash = "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9";
    var root = "17,218,109,31,118,29,223,155,219,76,157,110,83,3,235,212,31,97,133,141,10,86,71,161,167,191,224,137,191,146,27,233";
    var iter = 0;
    var a;

    while (root != i.toString())  {
      var kitty = await runtime.template.kitties(i);
      kitties.push(
          <div className="column" key={i}>
              <KittyShrieks
              owner_count = {runtime.template.kittyHistoryCount(i)}
              hash_original = {this.state.hash}
              />
          </div>
      );
      i = kitty.parent_hash;
    }
    this.setState(
      kitties
    );
  }

  render () {
    const { kitties } = this.state;
    return (
      kitties.length
        ? <div className="ui stackable six column grid">{kitties}</div>
        : <span>Nothing to track</span>
    )
  }
}
</code>```

We are initially returning Nothing to track, while you are waiting for kitties to complete.

Body:
I am trying to use the Substrate UI to display the functionalities that are available in my run-time module. The code is written in React. I am trying to create a component that will help me track all the previous states of a structure.

The runtime.template.assets(i) call takes a hex value i as input and returns a structure kitty which has a key parent_hash(having a hex value). I want the while loop to execute till I have reached a special hex value which in this case is "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9" which I have converted to String to achieve the termination condition.

Please ignore the <KittyShrieks> tag because it is something that I am using to display some values in the UI. Basically I am unable to do this inside the while loop

var kitty = await runtime.template.kitties(i);
.
.
i = kitty.parent_hash;

The required code

export class TrackCards extends ReactiveComponent {
    constructor(props) {
        super(['hash'])

    }

    unreadyRender() {
        return Nothing to track
    }
    async readyRender() {
      let kitties = [];
        var i = this.state.hash;
        var root_hash = "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9";
        var root = "17,218,109,31,118,29,223,155,219,76,157,110,83,3,235,212,31,97,133,141,10,86,71,161,167,191,224,137,191,146,27,233";
        var iter = 0;
        var a;

        while ((root != i.toString())  {

          var kitty = await runtime.template.kitties(i);
          kitties.push(

                  <KittyShrieks
                  owner_count = {runtime.template.kittyHistoryCount(i)}
                  hash_original = {this.state.hash}
                  />

          );
          i = kitty.parent_hash;
        }
        return
{kitties}
;
    }
}

I don't think using async render is a valid thing, but I am doing that because I seem to have no choice but to use the await keyword. So, the problem is that the UI doesnot load and I get the following error:

Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

The UI loads fine if I remove async keyword, var kitty = await runtime.template.kitties(i); statement and insert a break statement at the end of the loop. Therefore, disallowing me to iterate through the loop.

I am kind of new to React and even Javascript in general. Any kind of help would be appreciated.

Body:
A component always needs to be able to render something (or null). Here, effectively you are asking React to render a promise, hence your error.

You should extract this logic into the componentDidMount() life cycle. Taking your code as an example, it could look something like this:

export class TrackCards extends ReactiveComponent {
  constructor(props) {
      super(['hash'])

      this.state = {
        kitties: []
      }
  }

  async componentDidMount() {
    const kitties = [];
    var i = this.state.hash;
    var root_hash = "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9";
    var root = "17,218,109,31,118,29,223,155,219,76,157,110,83,3,235,212,31,97,133,141,10,86,71,161,167,191,224,137,191,146,27,233";
    var iter = 0;
    var a;

    while (root != i.toString())  {
      var kitty = await runtime.template.kitties(i);
      kitties.push(
          <div className="column" key={i}>
              <KittyShrieks
              owner_count = {runtime.template.kittyHistoryCount(i)}
              hash_original = {this.state.hash}
              />
          </div>
      );
      i = kitty.parent_hash;
    }
    this.setState(
      kitties
    );
  }

  render () {
    const { kitties } = this.state;
    return (
      kitties.length
        ? <div className="ui stackable six column grid">{kitties}</div>
        : <span>Nothing to track</span>
    )
  }
}

We are initially returning <span>Nothing to track</span>, while you are waiting for kitties to complete.


问:
Where I must contain business logic of my application?
After read a lot of articles about right architecture application, I still have a question: where app business logic must contains?
Becouse someone told, that logic must contains in models (skinny controllers), another said that models must contain only Database operations logic.

For example:

In my project (online shop) I have a products filter, that used in CategoryController and filtered by Products and Parameters table. So it's not a controller and not a model. I solved it by creation of new directory named Filters (yes, there are few different filters), and contain all logic there.
But i dont know is it right solution? I think not, but I dont know how to build it correctly.

So here is my questions:

Did i do the right thing?

Where I must contain business logic?

Thanks and have a nice day!

P.s
Sorry for my english.

答:
It's down to preferences. As long as you are using the correct standards, you should be fine!

So in Laravel, I use Models strictly for database operations. I also create a folder called Services and another folder called Hydrators

My services in the service folder handles the business logic e.g grabbing data from the models and any logical operations. My hydrators take the data and sort it in the way I want the data to be presented to the view.

Both my services and hydrators take on the Single Responsibility Principle as this allows me to reuse the same code elsewhere to avoid code duplication!

My controllers are just an entry point to the back end and only do two things; call the services and stitch the ones needed together and return a result (a result could be anything from JSON to a view with data).

This is just my personal way of doing things. Others may have a different way.


问:
Django rest api DRF - ViewSet hide a field from get but include for put
I have a field that I need to hide from a get put it needs to be there for a put in a Viewset, how would I achieve this?

my serialiser is as the below, the field stores data as JSON so I need to load it as JSON to perform a get. but having the original field (routing_data) there on a get will cause a 500 error, so I need to hide it from get. but when I'm using a put, it will be this field I put into.

Thanks

serializers.py

```<code>class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt','routing_data')
</code>```

views.py

```<code>class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    serializer_class = MonitoringSerializerRoutingTable
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')
</code>```

EDIT
the update serialiser doesn't seem to be updating the data

```<code>class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')
    def get_serializer_class(self):
        serializers = {
            create: MonitoringCreateSerializer,
            update: MonitoringCreateSerializer,
            list: MonitoringSerializerRoutingTable,
            retrieve: MonitoringSerializerRoutingTable,
        }
        return serializers.get(self.action)
</code>```

serialiezr.py

```<code>class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt')

class MonitoringCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','routing_data')
</code>```

PUT request

```<code>URL: http://10.66.193.200:8100/api/rt_upload/9/
data: {"routing_data": "[{'subnet': '10.10.0.0/16', 'age': '6w3d', 'next_hop': '10.20.0.0/16'}, {'subnet': '10.30.0.0/16', 'age': '6w3d', 'next_hop': '10.40.0.0/16'}, {'subnet': '10.50.0.0/16', 'age': '6w3d'...}]"}
</code>```

response from postman:

```<code>{
    "id": 9,
    "site_id": 118,
    "device_id": 460,
    "hostname": "EDGE",
    "use": "Remote Site Connectivity",
    "timestamp": "2019-05-31T10:12:58.300252",
    "rt": ""
}
</code>```

答:
Add write_only=True to your serializer field

or

Create two serializers one for get request and one for put request.
change the serializer based on request method inside view's get_serializer_class  method.

Body:
I have a field that I need to hide from a get put it needs to be there for a put in a Viewset, how would I achieve this?

my serialiser is as the below, the field stores data as JSON so I need to load it as JSON to perform a get. but having the original field (routing_data) there on a get will cause a 500 error, so I need to hide it from get. but when I'm using a put, it will be this field I put into.

Thanks

serializers.py

class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt','routing_data')

views.py

class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    serializer_class = MonitoringSerializerRoutingTable
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')

EDIT
the update serialiser doesn't seem to be updating the data

class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')
    def get_serializer_class(self):
        serializers = {
            create: MonitoringCreateSerializer,
            update: MonitoringCreateSerializer,
            list: MonitoringSerializerRoutingTable,
            retrieve: MonitoringSerializerRoutingTable,
        }
        return serializers.get(self.action)

serialiezr.py

class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt')

class MonitoringCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','routing_data')

PUT request

URL: http://10.66.193.200:8100/api/rt_upload/9/
data: {"routing_data": "[{'subnet': '10.10.0.0/16', 'age': '6w3d', 'next_hop': '10.20.0.0/16'}, {'subnet': '10.30.0.0/16', 'age': '6w3d', 'next_hop': '10.40.0.0/16'}, {'subnet': '10.50.0.0/16', 'age': '6w3d'...}]"}

response from postman:

{
    "id": 9,
    "site_id": 118,
    "device_id": 460,
    "hostname": "EDGE",
    "use": "Remote Site Connectivity",
    "timestamp": "2019-05-31T10:12:58.300252",
    "rt": ""
}


问:
Heroku PostgreSQL Migration Issue
I am working on the model of my rails based website, and created a model class called ItemAttributes, which defines a set of valid attributes for a specific item. For example, 'bed size' is an attribute of the item 'bed.' I have also created a AttributeValue class which defines valid values for Attributes, like 'king' 'queen' 'full' etc.

I am attempting to populate the PostgreSQL database on heroku with a migration, but it throws this rather unhelpful error (the migration works locally on SQLite):

```<code>PGError: ERROR:  current transaction is aborted, commands ignored until end of transaction block
:             SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
              FROM pg_attribute a LEFT JOIN pg_attrdef d
                ON a.attrelid = d.adrelid AND a.attnum = d.adnum
             WHERE a.attrelid = '"attribute_values"'::regclass
               AND a.attnum > 0 AND NOT a.attisdropped
             ORDER BY a.attnum
</code>```

Here is the migration I am using:

```<code>class AddBedSizeValues < ActiveRecord::Migration
  def self.up
    id = ItemAttribute.find_by_name('bed size').id

    AttributeValue.create(
      :name => 'king',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'queen',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'full',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'x-long twin',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'twin',
      :item_attribute_id => id
    )
  end
</code>```

答:
This error is given when in the same transaction there has been an earlier error. Find and resolve that error. You can use savepoints if you expect certain error and don't want to rollback the complete transaction.

Edit, some clarifications

To clarify, the cases where I have seen the error the flow was about as follows:

```<code>BEGIN; -- start of transaction
SOME QUERY; -- Causes error but error is ignored
SECOND QUERY; -- Causes the error you get because it is still in the same transaction
</code>```

After an error the transaction must be rolledback and a new one started before you can continue, or you must rollback to a savepoint.

It could be you have hit some other condition that gives this error but maybe you should check the logs in PGDATA/pg_log to check if your engine is logging some error rails is ignoring.

If that doesn't help can you try to create a log of all the actual queries (instead of the rails code) executed during the migration.

Title: Heroku PostgreSQL Migration Issue

Body:
I am working on the model of my rails based website, and created a model class called ItemAttributes, which defines a set of valid attributes for a specific item. For example, 'bed size' is an attribute of the item 'bed.' I have also created a AttributeValue class which defines valid values for Attributes, like 'king' 'queen' 'full' etc.

I am attempting to populate the PostgreSQL database on heroku with a migration, but it throws this rather unhelpful error (the migration works locally on SQLite):

PGError: ERROR:  current transaction is aborted, commands ignored until end of transaction block
:             SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
              FROM pg_attribute a LEFT JOIN pg_attrdef d
                ON a.attrelid = d.adrelid AND a.attnum = d.adnum
             WHERE a.attrelid = '"attribute_values"'::regclass
               AND a.attnum > 0 AND NOT a.attisdropped
             ORDER BY a.attnum

Here is the migration I am using:

class AddBedSizeValues < ActiveRecord::Migration
  def self.up
    id = ItemAttribute.find_by_name('bed size').id

    AttributeValue.create(
      :name => 'king',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'queen',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'full',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'x-long twin',
      :item_attribute_id => id
    )
    AttributeValue.create(
      :name => 'twin',
      :item_attribute_id => id
    )
  end

Body:
This error is given when in the same transaction there has been an earlier error. Find and resolve that error. You can use savepoints if you expect certain error and don't want to rollback the complete transaction.

Edit, some clarifications

To clarify, the cases where I have seen the error the flow was about as follows:

BEGIN; -- start of transaction
SOME QUERY; -- Causes error but error is ignored
SECOND QUERY; -- Causes the error you get because it is still in the same transaction

After an error the transaction must be rolledback and a new one started before you can continue, or you must rollback to a savepoint.

It could be you have hit some other condition that gives this error but maybe you should check the logs in PGDATA/pg_log to check if your engine is logging some error rails is ignoring.

If that doesn't help can you try to create a log of all the actual queries (instead of the rails code) executed during the migration.


问:
SignalR and switching servers and connection lost
SignalR is running on a certain Server with an open connnection.  If we need to bring up another server, then take the original down does SignalR automatically reconnect with the NEW server and start functioning like it was on the first?</p>

答:
We had a similar problem and what we discovered was that SignalR does not automatically reconnect with the new server. Our solution to was to not use the generated proxy. We used an intermediary endpoint whose job it is to provide the current url to use. To connect to SignalR our flow calls the endpoint gets the result using that result we connect to that server for SignalR then when the SignalR connection closes or is lost we repeat the process again as if for the first time.</p>

```<code>async function reconnect(connection){
   const signalRUrl = await request('<<our intermediary url>>');
   connection.hub.url = signalRUrl;
   connection.start();
}

var connection = $.hubConnection();
var hubProxy = connection.createHubProxy('yourHub');
hubProxy.on('message',function(){});

await reconnect(connection);
connection.onClose(function () {
   reconnect(connection);
});

</code>```

Body:
We had a similar problem and what we discovered was that SignalR does not automatically reconnect with the new server. Our solution to was to not use the generated proxy. We used an intermediary endpoint whose job it is to provide the current url to use. To connect to SignalR our flow calls the endpoint gets the result using that result we connect to that server for SignalR then when the SignalR connection closes or is lost we repeat the process again as if for the first time.

async function reconnect(connection){
   const signalRUrl = await request('<<our intermediary url>>');
   connection.hub.url = signalRUrl;
   connection.start();
}

var connection = $.hubConnection();
var hubProxy = connection.createHubProxy('yourHub');
hubProxy.on('message',function(){});

await reconnect(connection);
connection.onClose(function () {
   reconnect(connection);
});


问:
How i can run selenium C# test cases in order one by one?
I have written several test cases using selenium web drivers in C#.
I have used ORDER attribute to run the test cases in order. It is run by order. But tests does not wait for prior tests to finish.

I have used WebDriverWait also. But it does not wait.

Reference Link: https://github.com/nunit/docs/wiki/Order-Attribute

Please find the below code snippet:

```<code>[Test, Order(1)]
    public void OpenUserPage()
    {
        try
        {
            var wait = new WebDriverWait(_webDriver, new TimeSpan(2000));
            wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("NavigationMenu")));

            var userPageEle = _webDriver.FindElement(By.ClassName("icon-Users"));
            userPageEle.Click();
        }
        catch (Exception e)
        {
            SendMail.SendErrorEmail(e.StackTrace, "OpenUserPage()");
        }
    }

    [Test, Order(2)]
    public void AddUser()
    {
        try
        {
            var waitForAddUser= new WebDriverWait(_webDriver, new TimeSpan(5000));
            waitForAddUser.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("[ng-click*=AddUserBtnClick]")));

            var addUser = _webDriver.FindElement(By.CssSelector("[ng-click*=AddUserBtnClick]"));
            addUser.Click();

            var element = _webDriver.FindElement(By.XPath("//input[@id='Role_hidden']"));
            var permissionSet = _webDriver.FindElement(By.XPath("//input[@id='RolePermissionSet_hidden']"));

            var FirstName = _webDriver.FindElement(By.Name("FirstName"));
            FirstName.SendKeys("Sangeetha");

            var LastName = _webDriver.FindElement(By.Name("Last Name"));
            LastName.SendKeys("Periyaiah");

            var UserName = _webDriver.FindElement(By.Name("UserName"));
            UserName.SendKeys("SangeetheP");

            var Password = _webDriver.FindElement(By.Name("Password"));
            Password.SendKeys("Sync@123");

            var Email = _webDriver.FindElement(By.Name("Email"));
            Email.SendKeys("sangee900@gmail.com");

            var RoleList = _webDriver.FindElement(By.Name("RoleList"));
            element.SendKeys("SuperAdmin");

            var RolePermissionList = _webDriver.FindElement(By.Name("RolePermissionList"));
            permissionSet.SendKeys("SuperAdmin");

            var MobileNumber = _webDriver.FindElement(By.Name("MobileNumber"));
            MobileNumber.SendKeys("8220867882");

            var AreaCode = _webDriver.FindElement(By.Name("AreaCode"));
            AreaCode.SendKeys("600002");

            var Address = _webDriver.FindElement(By.Name("Address"));
            Address.SendKeys("3/761, Ab Block");

            var submit = _webDriver.FindElement(By.CssSelector("[ng-click*=AddUpdateUser]"));
            submit.Click();
        }
        catch (Exception e)
        {
            SendMail.SendErrorEmail(e.StackTrace, "AddUser()");
        }
    }

    [Test, Order(3)]
    public void ApplyFilter()
    {
        try
        {
            var waitForSearch = new WebDriverWait(_webDriver, new TimeSpan(55000));
            waitForSearch.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(".form-control.ng-pristine.ng-valid")));

            var searchUser = _webDriver.FindElement(By.CssSelector(".form-control.ng-pristine.ng-valid"));
            searchUser.SendKeys("as");

            var waitFilter = new WebDriverWait(_webDriver, new TimeSpan(55000));
            waitFilter.Until(ExpectedConditions.ElementToBeClickable((By.CssSelector("[ng-click*=filterUserBtnClick]"))));

            var applyUserFilter = _webDriver.FindElement(By.CssSelector("[ng-click*=filterUserBtnClick]"));
            applyUserFilter.Click();

            var waitResetFilter = new WebDriverWait(_webDriver, new TimeSpan(55000));
            waitResetFilter.Until(ExpectedConditions.ElementToBeClickable((By.CssSelector("[ng-click*=resetFilter]"))));

            var resetFilter = _webDriver.FindElement(By.CssSelector("[ng-click*=resetFilter]"));
            resetFilter.Click();
        }
        catch (Exception e)
        {
            SendMail.SendErrorEmail(e.StackTrace, "ApplyFilter()");
        }
    }
</code>```

Please share any other solution.

Thanks in advance

答:
Since you haven't mentioned the exact outcome of the test cases but after going though codes i would suggest two ways to solve it.

If webdriverwait code line throw some exception and it doesn't work then you can refer following code

```<code>   var waitForAddUser= new WebDriverWait(_webDriver, new TimeSpan(5000));
     waitForAddUser.IgnoreExceptionTypes(typeof(NoSuchElementException),
             typeof(ElementNotVisibleException));
    waitForAddUser.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("[ng-
           click*=AddUserBtnClick]")));
</code>```

Use  [Setup()]CommonWait() { Thread.sleep(5000)); }

Body:
I have written several test cases using selenium web drivers in C#.
I have used ORDER attribute to run the test cases in order. It is run by order. But tests does not wait for prior tests to finish.

I have used WebDriverWait also. But it does not wait.

Reference Link: https://github.com/nunit/docs/wiki/Order-Attribute

Please find the below code snippet:

[Test, Order(1)]
    public void OpenUserPage()
    {
        try
        {
            var wait = new WebDriverWait(_webDriver, new TimeSpan(2000));
            wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("NavigationMenu")));

            var userPageEle = _webDriver.FindElement(By.ClassName("icon-Users"));
            userPageEle.Click();
        }
        catch (Exception e)
        {
            SendMail.SendErrorEmail(e.StackTrace, "OpenUserPage()");
        }
    }

    [Test, Order(2)]
    public void AddUser()
    {
        try
        {
            var waitForAddUser= new WebDriverWait(_webDriver, new TimeSpan(5000));
            waitForAddUser.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("[ng-click*=AddUserBtnClick]")));

            var addUser = _webDriver.FindElement(By.CssSelector("[ng-click*=AddUserBtnClick]"));
            addUser.Click();

            var element = _webDriver.FindElement(By.XPath("//input[@id='Role_hidden']"));
            var permissionSet = _webDriver.FindElement(By.XPath("//input[@id='RolePermissionSet_hidden']"));

            var FirstName = _webDriver.FindElement(By.Name("FirstName"));
            FirstName.SendKeys("Sangeetha");

            var LastName = _webDriver.FindElement(By.Name("Last Name"));
            LastName.SendKeys("Periyaiah");

            var UserName = _webDriver.FindElement(By.Name("UserName"));
            UserName.SendKeys("SangeetheP");

            var Password = _webDriver.FindElement(By.Name("Password"));
            Password.SendKeys("Sync@123");

            var Email = _webDriver.FindElement(By.Name("Email"));
            Email.SendKeys("sangee900@gmail.com");

            var RoleList = _webDriver.FindElement(By.Name("RoleList"));
            element.SendKeys("SuperAdmin");

            var RolePermissionList = _webDriver.FindElement(By.Name("RolePermissionList"));
            permissionSet.SendKeys("SuperAdmin");

            var MobileNumber = _webDriver.FindElement(By.Name("MobileNumber"));
            MobileNumber.SendKeys("8220867882");

            var AreaCode = _webDriver.FindElement(By.Name("AreaCode"));
            AreaCode.SendKeys("600002");

            var Address = _webDriver.FindElement(By.Name("Address"));
            Address.SendKeys("3/761, Ab Block");

            var submit = _webDriver.FindElement(By.CssSelector("[ng-click*=AddUpdateUser]"));
            submit.Click();
        }
        catch (Exception e)
        {
            SendMail.SendErrorEmail(e.StackTrace, "AddUser()");
        }
    }

    [Test, Order(3)]
    public void ApplyFilter()
    {
        try
        {
            var waitForSearch = new WebDriverWait(_webDriver, new TimeSpan(55000));
            waitForSearch.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(".form-control.ng-pristine.ng-valid")));

            var searchUser = _webDriver.FindElement(By.CssSelector(".form-control.ng-pristine.ng-valid"));
            searchUser.SendKeys("as");

            var waitFilter = new WebDriverWait(_webDriver, new TimeSpan(55000));
            waitFilter.Until(ExpectedConditions.ElementToBeClickable((By.CssSelector("[ng-click*=filterUserBtnClick]"))));

            var applyUserFilter = _webDriver.FindElement(By.CssSelector("[ng-click*=filterUserBtnClick]"));
            applyUserFilter.Click();

            var waitResetFilter = new WebDriverWait(_webDriver, new TimeSpan(55000));
            waitResetFilter.Until(ExpectedConditions.ElementToBeClickable((By.CssSelector("[ng-click*=resetFilter]"))));

            var resetFilter = _webDriver.FindElement(By.CssSelector("[ng-click*=resetFilter]"));
            resetFilter.Click();
        }
        catch (Exception e)
        {
            SendMail.SendErrorEmail(e.StackTrace, "ApplyFilter()");
        }
    }

Please share any other solution.

Thanks in advance

Body:
Since you haven't mentioned the exact outcome of the test cases but after going though codes i would suggest two ways to solve it.

If webdriverwait code line throw some exception and it doesn't work then you can refer following code

   var waitForAddUser= new WebDriverWait(_webDriver, new TimeSpan(5000));
     waitForAddUser.IgnoreExceptionTypes(typeof(NoSuchElementException),
             typeof(ElementNotVisibleException));
    waitForAddUser.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("[ng-
           click*=AddUserBtnClick]")));

Use  [Setup()]CommonWait() { Thread.sleep(5000)); }


问:
Get Geometry from revit element
I have Created the following code and Iam stuck at extracting geometry from the element(in my case it going to be a CAD import)

I am expecting solutions to these:

How to classify or filter geometry types in the iron python.

what is a indexer#

I really didnt understand this but tried this too..

options = Autodesk.Revit.DB.Options()

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves[options])

Actual code:

```<code>#Import Autodesk stuffs
import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI.Selection import *

clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager

# Import iron python packages
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

app = __revit__.Application
Ui = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
view = doc.ActiveView

from Autodesk.Revit.UI import Selection

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves)
</code>```

答: You are in luck. The method GetCurvesInPlane in my latest blog post on Retrieving Section View Intersection Cut Geometry shows how to dig deeper into a GeometryElement and extract the Curve objects contained within it.

Title: Get Geometry from revit element

Body:
I have Created the following code and Iam stuck at extracting geometry from the element(in my case it going to be a CAD import)

I am expecting solutions to these:

How to classify or filter geometry types in the iron python.

what is a indexer#

I really didnt understand this but tried this too..

options = Autodesk.Revit.DB.Options()

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves[options])

Actual code:

#Import Autodesk stuffs
import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI.Selection import *

clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager

# Import iron python packages
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

app = __revit__.Application
Ui = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
view = doc.ActiveView

from Autodesk.Revit.UI import Selection

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves)


问:
I am trying get date as a String type from a DateChooserPanel and show the date on a textfield
I can't seem to get the date from the DateChooserPanel...

I want to choose a date from DateChooserPanel and I want to show the selected date to the textfield.

How can I get the date from DateChooserPanel in a String type?

I tried to change the date format into string but didn't work.

Am I using datechooser correctly??

The error says the it cannot format given object as a Date...

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.Caret;

import java.awt.BorderLayout;
import datechooser.beans.DateChooserPanel;
import datechooser.beans.DateChooserDialog;
import datechooser.beans.DateChooserCombo;
import java.awt.TextField;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class SetTime {

    private JFrame frame;
    private DateChooserPanel dateChooserPanel_1;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SetTime window = new SetTime();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
     }

    /**
     * Create the application.
     */
    public SetTime() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        this.frame = new JFrame();
        this.frame.setBounds(100, 100, 450, 300);
        this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.frame.getContentPane().setLayout(null);

        this.dateChooserPanel_1 = new DateChooserPanel();
        this.dateChooserPanel_1.setBounds(12, 44, 250, 180);
        this.frame.getContentPane().add(this.dateChooserPanel_1);

        this.textField = new JTextField();
        this.textField.setBounds(306, 113, 116, 21);
        this.frame.getContentPane().add(this.textField);
        this.textField.setColumns(10);

        Calendar date = dateChooserPanel_1.getSelectedDate();

        String strdate = DateFormat.getDateInstance().format(date);

        textField.setText(strdate);

        }
    }
</code>```

答:
Your issue is that you're trying to pass a Calendar object into a method that requires a Date object.

To get a Date from your Calendar call

```<code>Date selectedDate = date.getTime();
</code>```

Then you can use

```<code>String strdate = DateFormat.getDateInstance().format(selectedDate);
</code>```

Body:
I can't seem to get the date from the DateChooserPanel...

I want to choose a date from DateChooserPanel and I want to show the selected date to the textfield.

How can I get the date from DateChooserPanel in a String type?

I tried to change the date format into string but didn't work.

Am I using datechooser correctly??

The error says the it cannot format given object as a Date...

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.Caret;

import java.awt.BorderLayout;
import datechooser.beans.DateChooserPanel;
import datechooser.beans.DateChooserDialog;
import datechooser.beans.DateChooserCombo;
import java.awt.TextField;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class SetTime {

    private JFrame frame;
    private DateChooserPanel dateChooserPanel_1;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SetTime window = new SetTime();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
     }

    /**
     * Create the application.
     */
    public SetTime() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        this.frame = new JFrame();
        this.frame.setBounds(100, 100, 450, 300);
        this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.frame.getContentPane().setLayout(null);

        this.dateChooserPanel_1 = new DateChooserPanel();
        this.dateChooserPanel_1.setBounds(12, 44, 250, 180);
        this.frame.getContentPane().add(this.dateChooserPanel_1);

        this.textField = new JTextField();
        this.textField.setBounds(306, 113, 116, 21);
        this.frame.getContentPane().add(this.textField);
        this.textField.setColumns(10);

        Calendar date = dateChooserPanel_1.getSelectedDate();

        String strdate = DateFormat.getDateInstance().format(date);

        textField.setText(strdate);

        }
    }

Body:
Your issue is that you're trying to pass a Calendar object into a method that requires a Date object.

To get a Date from your Calendar call

Date selectedDate = date.getTime();

Then you can use

String strdate = DateFormat.getDateInstance().format(selectedDate);