问:
How to unflatten properties, ignored in other map?
Sources for my destination are spitted in root dto and its child property:

```<code>public class Source {
    public AccountSource {get;set;}
    public string AccountKey {get;set;}
    public string AccountPassword {get;set;}
}

public class AccountSource {
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class Dest
{
    public Account Account { get; set; }

    public class Account
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string Key { get; set; }
    }
}
</code>```

At now I have such mapping:

```<code>CreateMap<Source, Dest>()
    .ForPath(x => x.Account.Id, o => o.MapFrom(x => x.Account.Id))
    .ForPath(x => x.Account.Name, o => o.MapFrom(x => x.Account.Name))
    .ForPath(x => x.Account.Key, o => o.MapFrom(x => x.AccountKey))
    .ForPath(x => x.Account.Password, o => o.MapFrom(x => x.AccountPassword));
CreateMap<AccountSource, Dest.Account>()
    .ForAllMembers(x => x.Ignore());
</code>```

but it have one issue: new members added to Dest.Account will be not validated.

If remove ForPath and just leave

```<code>CreateMap<Source, Dest>();
CreateMap<AccountSource, Dest.Account>();
</code>```

than Password and Key are Unmapped, so I have to Ignore() them in such way CreateMap<AccountSource, Dest.Account>().ForMember(x => x.Password, x=> x.Ignore()).ForMember(x => x.Key, x=> x.Ignore()).

But then unflattening not working (props ignored absolutely, not only when account→account mapping occurred).

答:
By default, ForPath will ignore Dest.Account, but you can always map it explicitly:</p>

```<code>    CreateMap<Source, Dest>()
        .ForPath(d => d.Account.Key, o => o.MapFrom(s => s.AccountKey))
        .ForPath(d => d.Account.Password, o => o.MapFrom(s => s.AccountPassword))
        .ForMember(d => d.Account, o => o.MapFrom(s => s.Account));
    CreateMap<AccountSource, Account>()
        .ForMember(d => d.Password, o => o.Ignore())
        .ForMember(d => d.Key, o => o.Ignore());
</code>```

Body:
Sources for my destination are spitted in root dto and its child property:

public class Source {
    public AccountSource {get;set;}
    public string AccountKey {get;set;}
    public string AccountPassword {get;set;}
}

public class AccountSource {
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class Dest
{
    public Account Account { get; set; }

    public class Account
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string Key { get; set; }
    }
}

At now I have such mapping:

CreateMap<Source, Dest>()
    .ForPath(x => x.Account.Id, o => o.MapFrom(x => x.Account.Id))
    .ForPath(x => x.Account.Name, o => o.MapFrom(x => x.Account.Name))
    .ForPath(x => x.Account.Key, o => o.MapFrom(x => x.AccountKey))
    .ForPath(x => x.Account.Password, o => o.MapFrom(x => x.AccountPassword));
CreateMap<AccountSource, Dest.Account>()
    .ForAllMembers(x => x.Ignore());

but it have one issue: new members added to Dest.Account will be not validated.

If remove ForPath and just leave

CreateMap<Source, Dest>();
CreateMap<AccountSource, Dest.Account>();

than Password and Key are Unmapped, so I have to Ignore() them in such way CreateMap<AccountSource, Dest.Account>().ForMember(x => x.Password, x=> x.Ignore()).ForMember(x => x.Key, x=> x.Ignore()).

But then unflattening not working (props ignored absolutely, not only when account→account mapping occurred).

Body:
By default, ForPath will ignore Dest.Account, but you can always map it explicitly:

    CreateMap<Source, Dest>()
        .ForPath(d => d.Account.Key, o => o.MapFrom(s => s.AccountKey))
        .ForPath(d => d.Account.Password, o => o.MapFrom(s => s.AccountPassword))
        .ForMember(d => d.Account, o => o.MapFrom(s => s.Account));
    CreateMap<AccountSource, Account>()
        .ForMember(d => d.Password, o => o.Ignore())
        .ForMember(d => d.Key, o => o.Ignore());


来源: stackexchange

问:
Is it really better to have an actual static file index.html that merely uses client JavaScript for Cloud Firestore?
So I was watching multiple tutorials about how to present data on an actual webpage using Cloud Firestore. The thing is, everyone was using an actual index.html file sitting in Public folder(instead of serving html content within node.js code) and  tags which would mean that their program would use client-side JavaScript instead of node.js. But why? for what reason? According to Firebase tutorials and documentation, having an ACTUAL index.html sitting in Public folder is only for making static webpages, thus, if I'm making a complicated and dynamic webpage(which will also present Firestore data within the webpage), I should be using node.js right?</p>

答:
The Firebase SDKs for Cloud Firestore perform local persistence (caching) of doucments fetched from the database.  The persistence is enabled by default for Android and iOS, and you can programmatically enable it for web (currently experimental).  This local caching allows the client to avoid requesting documents from the server, which is obviously faster and cheaper than going through some API endpoint to request the data each time it's needed.

There is also the fact that the SDKs will push you realtime updates of data as it changes on the server, as long as you have a listener attached to some document or query of interest.  You won't be able to duplicate this if you write it all in Cloud Functions.  You will spend a tremendous amount of time trying to duplicate and scale this behavior using socket.io or something similar on a backend you control.

You could write the entire app to be driven through API endpoints that you create.  There's nothing wrong with that, if it meets your needs.  But you'll write more code, you'll sacrifice realtime updates, and it will likely be slower and more expensive than allowing the client SDKs to optimize for you.

ContentLicense: CC BY-SA 4.0


问:
Mysql datatype if expected number of characters in a column is around 150K
I read that in MySql varchar allows a (variable) max size of 65KB. Text data type  fixed max size is 65K. Meaning if a column is declared of type Text and field has only one character, it will still take up disk space of 65KB and similarly when loaded into memory takes up 65KB. Is this correct?

Also is this the same for medium text (occupying 16MB even if that column has just one character)?

Lets say i need to declare a column which will be occupied by strings with number of characters in the range of 150K, i cannot use text and can use medium text but wondering if i will be wasting lot of disk space/memory. What is a better way to do this. One way i can think of is to create 3 rows (split 150k characters into 3 rows of 50K), but is there is a better way of doing this

答:
No, variable length data types like VARCHAR and TEXT and their cousins do not occupy as much space as their maximum size. They only occupy the length of the string they store, and this can vary row by row, as you store strings of different lengths.

They also have between 1 and 4 bytes per row to encode the length. For example, a VARCHAR(255) is stored with 1 preceding byte, because 1 byte can encode any length up to 255. Whereas LONGTEXT requires 4 bytes to encode the length, because that's what is required for the 4GB maximum length of a LONGTEXT. Following the bytes encoding the length, the actual data content only needs to be as long as the respective string.

It's a bit more complicated than that, since InnoDB stores all data in pages of uniform size (16KB by default), so long strings must be split over multiple pages.

For a column where you expect typical data will be 150K characters, you should use MEDIUMTEXT. The VARCHAR and TEXT types can't store 150K characters.

The variable-length quality does not apply to the CHAR type, which always stores the full length according to the definition of the column. I use CHAR only for strings that are of fixed size on every row, so there's no wasted space.


问:
Why would an Acumatica API action work correctly in Postman, but not work in .NET (although it reports success)?
I'm calling the Shipment/ConfirmShipment endpoint, and it's returning success in both .NET and Postman, but using Postman the shipment actually gets confirmed, while in .NET it doesn't.

In Postman, I'm doing a POST with the body containing JSON for the shipment number:

```<code>{"entity":{"ShipmentNbr":{"value":"022025"}}}
</code>```

In .NET, I'm doing a HttpClient.PostAsync() to the same URL and with the same JSON as above. They both return success with a 202 Accepted response. However, as I mentioned, the Postman call confirms the shipment (Confirm = 1, Status = F), but in .NET, the POST doesn't actually confirm the shipment. Any ideas of what might be preventing it?

API v17.200.001

答:
The status 202 Accepted might be a bit confusing but it does not mean that the action has completed succefully.

It only means that the execution request is valid and has been accepted by the system.

If you want to monitor the status of the Action itself you will need to use the address given in the header of the 202 Accepted response (the Location header)

So in my example that follows, you can see that my action has been accepted and that when I request the status of the operation I then get the 204 No Content which is the Success response.

Here I have requested the execution of the Confirm Shipment action and it has been accepted and I can see the url where I can fetch the status of the action

Here I have requested the status of the the action and can see the successful result

You can find more information here about the execution of an action through the REST API.

I recommend taking a look at the response section.

https://help-2017r2.acumatica.com/(W(1))/Main?ScreenId=ShowWiki&pageid=91bf9106-062a-47a8-be1f-b48517a54324

Here is more information about the 202 and the 204 http response:

https://httpstatuses.com/202

https://httpstatuses.com/204

Body:
I'm calling the Shipment/ConfirmShipment endpoint, and it's returning success in both .NET and Postman, but using Postman the shipment actually gets confirmed, while in .NET it doesn't.

In Postman, I'm doing a POST with the body containing JSON for the shipment number:

{"entity":{"ShipmentNbr":{"value":"022025"}}}

In .NET, I'm doing a HttpClient.PostAsync() to the same URL and with the same JSON as above. They both return success with a 202 Accepted response. However, as I mentioned, the Postman call confirms the shipment (Confirm = 1, Status = F), but in .NET, the POST doesn't actually confirm the shipment. Any ideas of what might be preventing it?

API v17.200.001


问:
If Measure Value = Something Then X Else Y End
I have 2 lines as measure values and I would like each line having their own % information but I cannot do that as a Text. Any workaround to get it to work?

Tableau file sample:
https://www.dropbox.com/s/1upehg61rg5psas/Percentage_on_success.twbx?dl=0

答: You should try a dual-axis with your two line measures and put the bars as reference lines.  See this as an example.  You can't independently control the Text on "Measure Values" because it is treated as a single measure.</p>


问:
How to let Facebook Login button redirect to a particular URL
This is the info on Facebook Login button

http://developers.facebook.com/docs/guides/web/

So it will render a Login button, and a user can click on it to log in on Facebook (a log in window will pop up)
But after the user logs in, even though the Like or Share buttons work now, but the Log in button still shows.

1) Is there a way to redirect to a URL after the user successfully logs in?

2) Another way is to dynamically change the Log in button to invisible or better yet,
show it as "Logged in as [Peter (username)]"

How can (1) and/or (2) be done?   (I don't see a callback URL in the Facebook app setting and also the redirection may need to go to different URL from page A or page B on the website)

Update: I found some info about <fb:login-button on-login="top.location = '...'; "> but I see some website doing the redirect but there is no on-login='...'

答:
1) You can also redirect on login using some code like this (note the auth.login event):

  <fb:login-button>
     Login with Facebook
  </fb:login-button>
```

2) To determine whether to show or hide the login button, you can use FB.getLoginStatus to discover whether the user is logged in. The following page might be of use: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

ContentLicense: CC BY-SA 2.5

Body:
1) You can also redirect on login using some code like this (note the auth.login event):

 <script src="http://connect.facebook.net/en_US/all.js">
  </script>
  <script>
      FB.init({
          appId: '??????????????', cookie: true,
          status: true, xfbml: true
      });
      FB.Event.subscribe('auth.login', function () {
          window.location = "http://example.com";
      });
  </script>
  <fb:login-button>
     Login with Facebook
  </fb:login-button>

2) To determine whether to show or hide the login button, you can use FB.getLoginStatus to discover whether the user is logged in. The following page might be of use: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

ContentLicense: CC BY-SA 3.0


问:
FloatingActionButton setVisibility() not working
I can't hide my FloatingActionButton. Here is my code:

XML:

```<code><CoordinatorLayout>

    <AppBarLayout android:id="@+id/appbar">

        <CollapsingToolbarLayout>

            <ImageView/>

            <android.support.v7.widget.Toolbar />

        </CollapsingToolbarLayout>

    </AppBarLayout>

    <NestedScrollView />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"/>

</CoordinatorLayout>
</code>```

And I'm calling:

```<code>fab.clearAnimation();
fab.setVisibility(View.GONE);
</code>```

I'm trying to hide the FAB, but it seems that setVisibility + clearAnimation does not work if the FAB is in a CoordinatorLayout.

Even if I call fab.clearAnimation, the animation is still triggered. Can anyone help me?

答:
For FloatingActionButton the setVisibility() method will give you an error while building with the latest Gradle 6.x and build-tool 28.x.x and is not encouraged any more. Instead, use:

```<code>fab.hide()    // fab.setVisibility(View.GONE)
fab.show()    // fab.setVisibility(View.VISIBLE)
</code>```

Note: Succesfully tested on Android Studio 3.4.1, Gradle 6.0 and
  build-tool 28.0.1

Body:
I can't hide my FloatingActionButton. Here is my code:

XML:

<CoordinatorLayout>

    <AppBarLayout android:id="@+id/appbar">

        <CollapsingToolbarLayout>

            <ImageView/>

            <android.support.v7.widget.Toolbar />

        </CollapsingToolbarLayout>

    </AppBarLayout>

    <NestedScrollView />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"/>

</CoordinatorLayout>

And I'm calling:

fab.clearAnimation();
fab.setVisibility(View.GONE);

I'm trying to hide the FAB, but it seems that setVisibility + clearAnimation does not work if the FAB is in a CoordinatorLayout.

Even if I call fab.clearAnimation, the animation is still triggered. Can anyone help me?

Body:
For FloatingActionButton the setVisibility() method will give you an error while building with the latest Gradle 6.x and build-tool 28.x.x and is not encouraged any more. Instead, use:

fab.hide()    // fab.setVisibility(View.GONE)
fab.show()    // fab.setVisibility(View.VISIBLE)

Note: Succesfully tested on Android Studio 3.4.1, Gradle 6.0 and
  build-tool 28.0.1


问:
Passing Observable to another component in Angular
I have two components details and details-view.

In the details I have to pass obserwable by @Input() into second component.

Details Component

```<code> res$: (id: number, type: string) => Observable<DetailsResponse[]>;
 constructor(private service: Service) {
  this.res$ = service.getData;
 }
</code>```

Service

```<code> getData(id: number, type: string): Observable<DetailsResponse[]>{
   const params = new HttpParams().append('typename', type);
   return this.http.get<any>('api/id', {params: params});
 }
</code>```

Detalis-View HTML

<dwtalis-view [resources$]="res$"></dwtalis-view>

Detalis-Viev TS Component

```<code>@Input()
resouces$: Observable<DetailsResponse[]>
</code>```

My question is how to subscribe and get the data from resources$ observable in the detalis view component. Subscribing this object retunrs error "resources$ is not a finction can not subscribe"

答:
Apart from the typo at service.getData(), it is also important to know when input properties are available to be bound. Input's are not set in the constructor, they are available in the ngOnChanges life cycle hook every time an input changes. or in ngOnInit if you want to bind just the first time it is received.

https://angular.io/guide/lifecycle-hooks

Body:
I have two components details and details-view.

In the details I have to pass obserwable by @Input() into second component.

Details Component

 res$: (id: number, type: string) => Observable<DetailsResponse[]>;
 constructor(private service: Service) {
  this.res$ = service.getData;
 }

Service

 getData(id: number, type: string): Observable<DetailsResponse[]>{
   const params = new HttpParams().append('typename', type);
   return this.http.get<any>('api/id', {params: params});
 }

Detalis-View HTML

<dwtalis-view [resources$]="res$"></dwtalis-view>

Detalis-Viev TS Component

@Input()
resouces$: Observable<DetailsResponse[]>

My question is how to subscribe and get the data from resources$ observable in the detalis view component. Subscribing this object retunrs error "resources$ is not a finction can not subscribe"


问:
kafka consumer rebalancing in case of manual/assigned partitioning
I have some doubt regarding rebalancing. Right now, I am manually assigning partition to consumer. So as per docs, there will no rebalancing in case consumer leave/crashed in a consumer groups.

Let's say there are 3 partition and 3 consumers in same group and each partition is manually assigned to each consumer. And after some time, the 3rd consumer went down. Since there is no rebalancing, what all measures I can take to ensure minimum downtime?
Do I need to change config of any of the 1st two partition to start consuming from 3rd partition or something else?

答:
Although there might be context that would make the approach valid, as written, I question your approach a little bit.

The best way to ensure minimum downtime is to let the kafka brokers and zookeeper do what they're good at, managing your workload (partitions) among your consumers, which includes reassigning partitions when a consumer goes down.

Your best path is likely to use the OnPartitionsRevoked and OnpartitionsAssigned events to handle whatever logic you need to be able to assume a new partition (see JRs link for more-details information on these events).

I'll describe a recent use-case I've had, in the hope it is relevant to your use-case.
I recently had 5 consumers that required an in-memory cache of 50 million objects.  Without partitioning, each consumer had its own cache, resulting in 250 mil objects.
To reduce that number to the original 50 million, we could use the onpartitionsrevoked event to clear the cache and the onassigned to repopulate the cache with the relevant cache for the assigned partitions.

Short of using those two handlers, if you really want to manually assign your partitions, you're going to have to do all of the orchestration yourself:

Something to monitor if one of the other consumers is down

Something to pick up the dead consumer's partition and process it

Orchestrate communication between the consumers to communicate when the dead consumer is alive again, so it can start working again.

As you can probably tell from the list, you're in for a real world of hurt if you force yourself down that path, and you probably won't do a better job than the kafka brokers - there's an entire business whose entire focus focus is developing and maintaining kafka so you don't have to handle all of that complexity.


问:
How to send Push Notification to multiple devices?
This is the first time I am using push notification in my App. I have gone through sample applications along with books and I got how to send push notification to a single device. But I am not getting exactly what changes should I do in my program to send push notification to multiple devices. I am using 'PushMeBaby' application for server side coding.
Please, help me out.</p>

答:
Try this example code and modify for your environment.

```<code>    $apnsHost = '<APNS host>';
    $apnsPort = <port num>;
    $apnsCert = '<cert>';

    $streamContext = stream_context_create();
    stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

    $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

    $payload['aps'] = array('alert' => 'some notification', 'badge' => 0, 'sound' => 'none');
    $payload = json_encode($payload);

// Note: $device_tokens_array has list of 5 devices' tokens

    for($i=0; $i<5; $i++)
    {
            $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_tokens_array[i])) . chr(0) . chr(strlen($payload)) . $payload;

            fwrite($apns, $apnsMessage);
    }?>
</code>```

This article helps verifying drop connection and connection status: Apple Push Notification: Sending high volumes of messages

Other reference links:

How can I send push notification to multiple devices in one go in iPhone?
and
how to handle multiple devices when using Push Notification?

Body:
Try this example code and modify for your environment.

    $apnsHost = '<APNS host>';
    $apnsPort = <port num>;
    $apnsCert = '<cert>';

    $streamContext = stream_context_create();
    stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

    $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

    $payload['aps'] = array('alert' => 'some notification', 'badge' => 0, 'sound' => 'none');
    $payload = json_encode($payload);

// Note: $device_tokens_array has list of 5 devices' tokens

    for($i=0; $i<5; $i++)
    {
            $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_tokens_array[i])) . chr(0) . chr(strlen($payload)) . $payload;

            fwrite($apns, $apnsMessage);
    }?>

This article helps verifying drop connection and connection status: Apple Push Notification: Sending high volumes of messages

Other reference links:

How can I send push notification to multiple devices in one go in iPhone?
and
how to handle multiple devices when using Push Notification?


问:
How do I repaint after a mouse click in java?
The graphics should repaint with a new color after a mouse click, but they don´t.

I´ve already implemented the MouseListener in the component and in the frame, but in both versions it did´nt work.

The Frame and MouseListener:

```<code>public class frame extends Frame
 {
     public static void main(String[] args)
        {

           JFrame frame = new JFrame();

           String string = new String("1  2  3  4  5  6  7");

           final int FRAME_WIDTH = 527;
           final int FRAME_HEIGHT = 77;

           frame.setAlwaysOnTop(true);
           frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
           frame.setTitle("Praxis");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setUndecorated(true);
           // JFrame zentriert positionieren; selbst berechnet:
           Toolkit tk = Toolkit.getDefaultToolkit();
           Dimension d = tk.getScreenSize();
           frame.setLocation((int) ((d.width)-700), (int) (0));

           Font font = new Font("Jokerman", Font.BOLD, 35);
           JLabel textLabel = new JLabel(string);
           textLabel.setFont(font);

           test component = new test();
           frame.add(component);

           MouseListener listen = new MouseListener()
           {
            public void mouseClicked(MouseEvent e) {
                GlobalVar obj = new GlobalVar();
                obj.fillColor1 = obj.farben[1];
                component.repaint();
            }
            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }
            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }
            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }
            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }
           };
           component.addMouseListener(listen);

           frame.setVisible(true);

        }

 }
</code>```

The File where they get the Color from:

```<code>public class GlobalVar{
    public static final Color[] farben = new Color[4];{
        farben[0] = Color.LIGHT_GRAY;
        farben[1] = Color.RED;
        farben[2] = Color.GREEN;
        farben[3] = Color.PINK;
    }
    Color fillColor1 = farben[0];
    Color fillColor2 = farben[0];
    Color fillColor3 = farben[0];
    Color fillColor4 = farben[0];
    Color fillColor5 = farben[0];
    Color fillColor6 = farben[0];
    Color fillColor7 = farben[0];
}
</code>```

The Component which draws the graphics:

```<code>public class test extends JComponent
 {
        GlobalVar obj = new GlobalVar();

     @Override
        public void paintComponent(Graphics g)
        {

          if(g instanceof Graphics2D) {
           // Recover Graphics2D
           Graphics2D g2 = (Graphics2D) g;

           // Construct a rectangle and draw it
           Rectangle box1 = new Rectangle(2, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box1);
           g2.setColor(obj.fillColor1);
           g2.fill(box1);

           Rectangle box2 = new Rectangle(77, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box2);
           g2.setColor(obj.fillColor2);
           g2.fill(box2);

           Rectangle box3 = new Rectangle(152, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box3);
           g2.setColor(obj.fillColor3);
           g2.fill(box3);

           Rectangle box4 = new Rectangle(227, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box4);
           g2.setColor(obj.fillColor4);
           g2.fill(box4);

           Rectangle box5 = new Rectangle(302, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box5);
           g2.setColor(obj.fillColor5);
           g2.fill(box5);

           Rectangle box6 = new Rectangle(377, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box6);
           g2.setColor(obj.fillColor6);
           g2.fill(box6);

           Rectangle box7 = new Rectangle(452, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box7);
           g2.setColor(obj.fillColor7);
           g2.fill(box7);

           g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

           Font f = new Font("Dialog", Font.PLAIN, 30);
           g2.setFont(f);
           g2.setColor(Color.BLACK);
           g2.drawString("1", 30, 48);
           g2.drawString("2", 105, 48);
           g2.drawString("3", 180, 48);
           g2.drawString("4", 255, 48);
           g2.drawString("5", 330, 48);
           g2.drawString("6", 405, 48);
           g2.drawString("7", 480, 48);
          }

        }

        private Color fillColor1;
        private Color fillColor2;
        private Color fillColor3;
        private Color fillColor4;
        private Color fillColor5;
        private Color fillColor6;
        private Color fillColor7;
 }
</code>```

As I said, I expected the graphics to repaint with the first square to be filled with the color red, but the actual result is, that nothing happens when I click on the frame.

答:
Instead of having the test class extending JComponent, I would make it into a JPanel and then put the JPanel on top of the JFrame.

Then I would remove the mouselistener from the JFrame and add it onto the JPanel, by doing this the only command needed to repaint is repaint();.
I believe that this way is more simple and more organized than what you are currently doing.

This should do the trick (note: I made this in netbeans, that is why there is some autogenerated code.):

```<code>import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;

public class Test extends javax.swing.JPanel {

    /**
     * Creates new form Test
     */
    public Test() {
        initComponents();
    }
        GlobalVar obj = new GlobalVar();

     @Override
        public void paintComponent(Graphics g)
        {

          if(g instanceof Graphics2D) {
           // Recover Graphics2D
           Graphics2D g2 = (Graphics2D) g;

           // Construct a rectangle and draw it
           Rectangle box1 = new Rectangle(2, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box1);
           g2.setColor(obj.fillColor1);
           g2.fill(box1);

           Rectangle box2 = new Rectangle(77, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box2);
           g2.setColor(obj.fillColor2);
           g2.fill(box2);

           Rectangle box3 = new Rectangle(152, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box3);
           g2.setColor(obj.fillColor3);
           g2.fill(box3);

           Rectangle box4 = new Rectangle(227, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box4);
           g2.setColor(obj.fillColor4);
           g2.fill(box4);

           Rectangle box5 = new Rectangle(302, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box5);
           g2.setColor(obj.fillColor5);
           g2.fill(box5);

           Rectangle box6 = new Rectangle(377, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box6);
           g2.setColor(obj.fillColor6);
           g2.fill(box6);

           Rectangle box7 = new Rectangle(452, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box7);
           g2.setColor(obj.fillColor7);
           g2.fill(box7);

           g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

           Font f = new Font("Dialog", Font.PLAIN, 30);
           g2.setFont(f);
           g2.setColor(Color.BLACK);
           g2.drawString("1", 30, 48);
           g2.drawString("2", 105, 48);
           g2.drawString("3", 180, 48);
           g2.drawString("4", 255, 48);
           g2.drawString("5", 330, 48);
           g2.drawString("6", 405, 48);
           g2.drawString("7", 480, 48);
          }

        }

        private Color fillColor1;
        private Color fillColor2;
        private Color fillColor3;
        private Color fillColor4;
        private Color fillColor5;
        private Color fillColor6;
        private Color fillColor7;

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>

    private void formMouseClicked(java.awt.event.MouseEvent evt) {
                GlobalVar obj = new GlobalVar();
                obj.fillColor1 = obj.farben[1];
                repaint();
        // TODO add your handling code here:
    }

    // Variables declaration - do not modify
    // End of variables declaration
}
</code>```

Body:
The graphics should repaint with a new color after a mouse click, but they don´t.

I´ve already implemented the MouseListener in the component and in the frame, but in both versions it did´nt work.

The Frame and MouseListener:

public class frame extends Frame
 {
     public static void main(String[] args)
        {

           JFrame frame = new JFrame();

           String string = new String("1  2  3  4  5  6  7");

           final int FRAME_WIDTH = 527;
           final int FRAME_HEIGHT = 77;

           frame.setAlwaysOnTop(true);
           frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
           frame.setTitle("Praxis");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setUndecorated(true);
           // JFrame zentriert positionieren; selbst berechnet:
           Toolkit tk = Toolkit.getDefaultToolkit();
           Dimension d = tk.getScreenSize();
           frame.setLocation((int) ((d.width)-700), (int) (0));

           Font font = new Font("Jokerman", Font.BOLD, 35);
           JLabel textLabel = new JLabel(string);
           textLabel.setFont(font);

           test component = new test();
           frame.add(component);

           MouseListener listen = new MouseListener()
           {
            public void mouseClicked(MouseEvent e) {
                GlobalVar obj = new GlobalVar();
                obj.fillColor1 = obj.farben[1];
                component.repaint();
            }
            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }
            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }
            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }
            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }
           };
           component.addMouseListener(listen);

           frame.setVisible(true);

        }

 }

The File where they get the Color from:

public class GlobalVar{
    public static final Color[] farben = new Color[4];{
        farben[0] = Color.LIGHT_GRAY;
        farben[1] = Color.RED;
        farben[2] = Color.GREEN;
        farben[3] = Color.PINK;
    }
    Color fillColor1 = farben[0];
    Color fillColor2 = farben[0];
    Color fillColor3 = farben[0];
    Color fillColor4 = farben[0];
    Color fillColor5 = farben[0];
    Color fillColor6 = farben[0];
    Color fillColor7 = farben[0];
}

The Component which draws the graphics:

public class test extends JComponent
 {
        GlobalVar obj = new GlobalVar();

     @Override
        public void paintComponent(Graphics g)
        {

          if(g instanceof Graphics2D) {
           // Recover Graphics2D
           Graphics2D g2 = (Graphics2D) g;

           // Construct a rectangle and draw it
           Rectangle box1 = new Rectangle(2, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box1);
           g2.setColor(obj.fillColor1);
           g2.fill(box1);

           Rectangle box2 = new Rectangle(77, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box2);
           g2.setColor(obj.fillColor2);
           g2.fill(box2);

           Rectangle box3 = new Rectangle(152, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box3);
           g2.setColor(obj.fillColor3);
           g2.fill(box3);

           Rectangle box4 = new Rectangle(227, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box4);
           g2.setColor(obj.fillColor4);
           g2.fill(box4);

           Rectangle box5 = new Rectangle(302, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box5);
           g2.setColor(obj.fillColor5);
           g2.fill(box5);

           Rectangle box6 = new Rectangle(377, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box6);
           g2.setColor(obj.fillColor6);
           g2.fill(box6);

           Rectangle box7 = new Rectangle(452, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box7);
           g2.setColor(obj.fillColor7);
           g2.fill(box7);

           g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

           Font f = new Font("Dialog", Font.PLAIN, 30);
           g2.setFont(f);
           g2.setColor(Color.BLACK);
           g2.drawString("1", 30, 48);
           g2.drawString("2", 105, 48);
           g2.drawString("3", 180, 48);
           g2.drawString("4", 255, 48);
           g2.drawString("5", 330, 48);
           g2.drawString("6", 405, 48);
           g2.drawString("7", 480, 48);
          }

        }

        private Color fillColor1;
        private Color fillColor2;
        private Color fillColor3;
        private Color fillColor4;
        private Color fillColor5;
        private Color fillColor6;
        private Color fillColor7;
 }

As I said, I expected the graphics to repaint with the first square to be filled with the color red, but the actual result is, that nothing happens when I click on the frame.

Body:
Instead of having the test class extending JComponent, I would make it into a JPanel and then put the JPanel on top of the JFrame.

Then I would remove the mouselistener from the JFrame and add it onto the JPanel, by doing this the only command needed to repaint is repaint();.
I believe that this way is more simple and more organized than what you are currently doing.

This should do the trick (note: I made this in netbeans, that is why there is some autogenerated code.):

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;

public class Test extends javax.swing.JPanel {

    /**
     * Creates new form Test
     */
    public Test() {
        initComponents();
    }
        GlobalVar obj = new GlobalVar();

     @Override
        public void paintComponent(Graphics g)
        {

          if(g instanceof Graphics2D) {
           // Recover Graphics2D
           Graphics2D g2 = (Graphics2D) g;

           // Construct a rectangle and draw it
           Rectangle box1 = new Rectangle(2, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box1);
           g2.setColor(obj.fillColor1);
           g2.fill(box1);

           Rectangle box2 = new Rectangle(77, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box2);
           g2.setColor(obj.fillColor2);
           g2.fill(box2);

           Rectangle box3 = new Rectangle(152, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box3);
           g2.setColor(obj.fillColor3);
           g2.fill(box3);

           Rectangle box4 = new Rectangle(227, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box4);
           g2.setColor(obj.fillColor4);
           g2.fill(box4);

           Rectangle box5 = new Rectangle(302, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box5);
           g2.setColor(obj.fillColor5);
           g2.fill(box5);

           Rectangle box6 = new Rectangle(377, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box6);
           g2.setColor(obj.fillColor6);
           g2.fill(box6);

           Rectangle box7 = new Rectangle(452, 2, 71, 71);
           g2.setColor(Color.BLACK);
           g2.draw(box7);
           g2.setColor(obj.fillColor7);
           g2.fill(box7);

           g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

           Font f = new Font("Dialog", Font.PLAIN, 30);
           g2.setFont(f);
           g2.setColor(Color.BLACK);
           g2.drawString("1", 30, 48);
           g2.drawString("2", 105, 48);
           g2.drawString("3", 180, 48);
           g2.drawString("4", 255, 48);
           g2.drawString("5", 330, 48);
           g2.drawString("6", 405, 48);
           g2.drawString("7", 480, 48);
          }

        }

        private Color fillColor1;
        private Color fillColor2;
        private Color fillColor3;
        private Color fillColor4;
        private Color fillColor5;
        private Color fillColor6;
        private Color fillColor7;

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>

    private void formMouseClicked(java.awt.event.MouseEvent evt) {
                GlobalVar obj = new GlobalVar();
                obj.fillColor1 = obj.farben[1];
                repaint();
        // TODO add your handling code here:
    }

    // Variables declaration - do not modify
    // End of variables declaration
}


问:
Have a each() with if statement not working

Problem

I only want the commands in the if logic to happen if the 3rd default button is visible, but it throws an error saying its parent has the css class of visibility: hidden. When you need to remove that state the 3rd default button becomes visible so I'm not sure why it isn't passing.

Desired Behaviour

I want it so for each state that is underlined to click on them to unselect them. Then the if statement is to take care of those who need to be actually removed, because they have info filled out for them, and so if the 3rd default button is visible, which is the remove button, then to execute the code inside the if statement which is to make sure the other default buttons are hidden and click the remove button.

Code

```<code>it('deletes all selected states', () => {
  cy.get('span[class*="css-ddft8r-StateText"]').each($el => {
    cy.wrap($el)
      .filter(':has(span[class*="css-1qkbmzm-Underline css-1x6iasc4"])')
      .click({ multiple: true });
    if (cy.get('[data-cy=default-buttons]').eq(3).should('be.visible')) {
      cy.get('[data-cy=default-buttons]')
        .eq(0)
        .should('be.hidden');
      cy.get('[data-cy=default-buttons]')
        .eq(2)
        .should('be.visible');
      cy.get('[data-cy=default-buttons]')
        .eq(3)
        .click();
    }
  });
});
</code>```

答:
So the solution I ended up using was actually just using .each() instead of the if statement within it. We figured out we could utilize a ternary inside of a data-cy due to those css classes being unstable/unreliable and this took care of not having to write an if statement.

We did roughly this:

```<code>cy.get('[data-cy=example_data_cy]').each($el => {
//click on the state if it was selected to unselect it
</code>```

Body:
Problem

I only want the commands in the if logic to happen if the 3rd default button is visible, but it throws an error saying its parent has the css class of visibility: hidden. When you need to remove that state the 3rd default button becomes visible so I'm not sure why it isn't passing.

Desired Behaviour

I want it so for each state that is underlined to click on them to unselect them. Then the if statement is to take care of those who need to be actually removed, because they have info filled out for them, and so if the 3rd default button is visible, which is the remove button, then to execute the code inside the if statement which is to make sure the other default buttons are hidden and click the remove button.

Code

it('deletes all selected states', () => {
  cy.get('span[class*="css-ddft8r-StateText"]').each($el => {
    cy.wrap($el)
      .filter(':has(span[class*="css-1qkbmzm-Underline css-1x6iasc4"])')
      .click({ multiple: true });
    if (cy.get('[data-cy=default-buttons]').eq(3).should('be.visible')) {
      cy.get('[data-cy=default-buttons]')
        .eq(0)
        .should('be.hidden');
      cy.get('[data-cy=default-buttons]')
        .eq(2)
        .should('be.visible');
      cy.get('[data-cy=default-buttons]')
        .eq(3)
        .click();
    }
  });
});

Body:
So the solution I ended up using was actually just using .each() instead of the if statement within it. We figured out we could utilize a ternary inside of a data-cy due to those css classes being unstable/unreliable and this took care of not having to write an if statement.

We did roughly this:

cy.get('[data-cy=example_data_cy]').each($el => {
//click on the state if it was selected to unselect it


问:
Android App crashes on launch after downloading from Google Play
The app is made with React Native, and it's running fine in both simulators/emulators.

Also on iPhone (through usb... on debug mode).

I couldn't try it on Android (there was no "Build number" !?).

I haven't upload it yet to "App Store"...

But when I download it from "Google Play" the app crashes on launch.

Note: I "use the signing/keytool UI that's part of Android Studio" to generate the APK.

I've found this: Support third-party 64-bit libraries on Android.

And I tried this solution: Mixing 32- and 64-bit Dependencies in Android.

And some other similar to the above...

I tried deleting the ios and android files and then run ios and android again...

Also, tried to upload an "Android App Bundle" instead of APK (with this the app wouldn't even download... not just pending. There was only the spinner to see...

So, nothing worked!

Then I realised I get an error message on the Android device which was:

java.lang.RuntimeException: Unable to load script. Make sure you're either running a Metro server or that your bundle index.android.bundle is packaged correctly for release.

I've found this: Release APK fails immediately on launch.

I want to try the following comment, but I don't understand it.

@alexmbp

Well. It's working with

1 react-native run-android --variant=release

2 and with ./gradlew assembleRelease and configuring signing.

3 Also I've updated gradle and should set android.enableAapt2=false.

Probably issue connected with gradle update.

Could someone please explain...

I think 1 is just a command in terminal.

But what is 2 and 3?

Thanks :)

答:
The native bundle is not created by default if you are using a debug build. Instead it is expecting that you're running the bundler on your computer and the phone is connected to your computer.

You should build for release anyway (gradle assembleRelease) when submitting to the Play Store, but you can also have it generate the bundle in debug by adding the following to your android/app/build.gradle file:

```<code>project.ext.react = [
        entryFile: "index.js", //this part is there by default
        bundleInDebug: true, //this causes it to bundle when building debug, defaults to false
        bundleInRelease: true, //this causes it to bundle when building release, defaults to true
]
</code>```

Body:
The native bundle is not created by default if you are using a debug build. Instead it is expecting that you're running the bundler on your computer and the phone is connected to your computer.

You should build for release anyway (gradle assembleRelease) when submitting to the Play Store, but you can also have it generate the bundle in debug by adding the following to your android/app/build.gradle file:

project.ext.react = [
        entryFile: "index.js", //this part is there by default
        bundleInDebug: true, //this causes it to bundle when building debug, defaults to false
        bundleInRelease: true, //this causes it to bundle when building release, defaults to true
]


问:
How to implement Slowly Changing Dimensions (SCD2) Type 2 in Spark using SQL Join
We want to implement SCD2 in Spark using SQL Join. i got reference  from Github

https://gist.github.com/rampage644/cc4659edd11d9a288c1b

but it's not very clear.

Can anybody provide any example or reference to implement SCD2 in spark

Regards,
Manish

答:
Here's the detailed implementation of slowly changing dimension type 2 in Spark (Data frame and SQL) using exclusive join approach.

Assuming that the source is sending a complete data file i.e. old, updated and new records.

Steps:

Load the recent file data to STG table
Select all the expired records from HIST table

```<code>1. select * from HIST_TAB where exp_dt != '2099-12-31'
</code>```

Select all the records which are not changed from STG and HIST using inner join and filter on HIST.column = STG.column as below

```<code>2. select hist.* from HIST_TAB hist inner join STG_TAB stg on hist.key = stg.key where hist.column = stg.column
</code>```

Select all the new and updated records which are changed from STG_TAB using exclusive left join with HIST_TAB and set expiry and effective date as below

```<code>3. select stg.*, eff_dt (yyyy-MM-dd), exp_dt (2099-12-31) from STG_TAB stg left join (select * from HIST_TAB where exp_dt = '2099-12-31') hist
on hist.key = stg.key where hist.key is null or hist.column != stg.column
</code>```

Select all updated old records from the HIST table using exclusive left join with STG table and set their expiry date as shown below:

```<code>4. select hist.*, exp_dt(yyyy-MM-dd) from (select * from HIST_TAB where exp_dt = '2099-12-31') hist left join STG_TAB stg
on hist.key= stg.key where hist.key is null or hist.column!= stg.column
</code>```

unionall queries from 1-4 and insert overwrite result to HIST table

More detailed implementation of SCD type 2 in Scala and Pyspark can be found here-

https://github.com/sahilbhange/spark-slowly-changing-dimension

Hope this helps!

Body:
Here's the detailed implementation of slowly changing dimension type 2 in Spark (Data frame and SQL) using exclusive join approach.

Assuming that the source is sending a complete data file i.e. old, updated and new records.

Steps:

Load the recent file data to STG table
Select all the expired records from HIST table

1. select * from HIST_TAB where exp_dt != '2099-12-31'

Select all the records which are not changed from STG and HIST using inner join and filter on HIST.column = STG.column as below

2. select hist.* from HIST_TAB hist inner join STG_TAB stg on hist.key = stg.key where hist.column = stg.column

Select all the new and updated records which are changed from STG_TAB using exclusive left join with HIST_TAB and set expiry and effective date as below

3. select stg.*, eff_dt (yyyy-MM-dd), exp_dt (2099-12-31) from STG_TAB stg left join (select * from HIST_TAB where exp_dt = '2099-12-31') hist
on hist.key = stg.key where hist.key is null or hist.column != stg.column

Select all updated old records from the HIST table using exclusive left join with STG table and set their expiry date as shown below:

4. select hist.*, exp_dt(yyyy-MM-dd) from (select * from HIST_TAB where exp_dt = '2099-12-31') hist left join STG_TAB stg
on hist.key= stg.key where hist.key is null or hist.column!= stg.column

unionall queries from 1-4 and insert overwrite result to HIST table

More detailed implementation of SCD type 2 in Scala and Pyspark can be found here-

https://github.com/sahilbhange/spark-slowly-changing-dimension

Hope this helps!


问:
Visual Studio 2008 and Visual studio 2005
I am developing a Windows Application using the .net Framework 2.0 and Visual C#(Microsoft Visual Studio 2008) in my PC.

On the completion of my project I have to execute it in a system which has Visual Studio 2005 and .net framework 2.0.

So my doubt is if I develop an application in Microsoft Visual Studio 2008 will I be able to execute it in Visual Studio 2005 properly? Is it possible?

Please help me!

Thanks in advance!

答:
Replace Version 10.0 in *.sln files with Version 9.00

Replace 2008 with 2005 in *.sln

Replace Version="9.00" with Version="8.00" in each *.vcproj file


问:
How to bind class attribute to Data Template generated item
I am trying to do a little To-Do app for my school project. I have one problem: i don't know how to delete items both generated by data template in app and those in database.

I've tried accesing items by getting selected item and then deleting it but at some point the id's of those items in db are diffrent from those in the app. I am using SQL server and in my db i have one table with 4 columns: ID(int, auto incremented, primary key), Task(varchar), Descr(varchar), Active(bit). Now i am trying to bind checkbox attribute isChecked to Active of Task class in my app.

this is my xaml code

```<code><Window x:Class="ToDoApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ToDoApp2"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="400" ResizeMode="NoResize">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="244*"/>
        <ColumnDefinition Width="149*"/>
    </Grid.ColumnDefinitions>
    <TreeView x:Name="TrvMenu" HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:ToDoTask}" ItemsSource="{Binding Tasks}">
                <StackPanel Orientation="Horizontal">
                    <CheckBox Content="{Binding Title}" IsChecked="{Binding active}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
    <TextBox x:Name="TaskTb" HorizontalAlignment="Left" Height="30" Margin="0,400,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2"/>
    <TextBox x:Name="DescriptionTb" HorizontalAlignment="Left" Height="80" Margin="0,430,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2"/>
    <Button  x:Name="CreateBtn" Content="Create New Task" HorizontalAlignment="Left" Margin="0,510,0,0" VerticalAlignment="Top" Width="197" Height="59" Click="Button_Click"/>
    <Button  x:Name="DeleteBtn" Content="Delete Selected Task" HorizontalAlignment="Left" Margin="197,510,-1,0" VerticalAlignment="Top" Width="196" Height="59" Click="DeleteBtn_Click" Grid.ColumnSpan="2"/>

</Grid>
</Window>
</code>```

this is the class that represents one task in app

```<code>public class ToDoTask
{

    public ToDoTask()
    {
        this.Tasks = new ObservableCollection<ToDoTask>();
    }
    public string Title { get; set; }
    public bool active=true;

    public ObservableCollection<ToDoTask> Tasks { get; set; }
    }
</code>```

And this is how i add new tasks to db and app

```<code>public MainWindow()
    {

        InitializeComponent();
        SQLCnn init = new SQLCnn();
        ObservableCollection<ToDoTask> initList = init.readQuery();
        for(int i=0; i < initList.Count; i++)
        {
            TrvMenu.Items.Add(initList[i]);
        }
        SQLCnn.connection.Close();

    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (!String.IsNullOrEmpty(TaskTb.Text))
        {
            string value = TaskTb.Text;
            string desc = DescriptionTb.Text;

            ToDoTask task = new ToDoTask() { Title = value };
            task.Tasks.Add(new ToDoTask() { Title = desc });
            SQLCnn SQLtask = new SQLCnn();
            SQLtask.insertQuery(value, desc);
            TrvMenu.Items.Add(task);
        }
    }
  }
</code>```

答:
As you mentioned in your question you have a problem with Id's generation in your code. You should create a method where you pass all necessary data to create your task and after that, your database should return you back Id of newly created task. So in your case method SQLTask.insertQuery(...) should return id (int value) which is auto-generated by your database. Now you can assign it to newly created object ToDoTask task = new ToDoTask(); task.Id = ... and after that, you can add it to list of tasks. If you do that you will have a valid id value to delete the task from the database. And one more thing, fields are not supported as a binding source so in the ToDoTask class you should change active field to the property if you want to bind it.

In this case, it's all but...

In your project, you can use framework and patterns that will learn you a lot more cool stuff and increase the quality of your code. So to improve working with the database you can use ORM e.g. Entity Framework (https://learn.microsoft.com/en-us/ef/). To separate GUI code from a business logic code, you can use the MVVM pattern. Here you have a lot of options e.g. you can use one of the following projects:

Prism

MVVM Light

Caliburn Micro

To learn more about MVVM please look at this question: MVVM: Tutorial from start to finish?

Body:
I am trying to do a little To-Do app for my school project. I have one problem: i don't know how to delete items both generated by data template in app and those in database.

I've tried accesing items by getting selected item and then deleting it but at some point the id's of those items in db are diffrent from those in the app. I am using SQL server and in my db i have one table with 4 columns: ID(int, auto incremented, primary key), Task(varchar), Descr(varchar), Active(bit). Now i am trying to bind checkbox attribute isChecked to Active of Task class in my app.

this is my xaml code

<Window x:Class="ToDoApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ToDoApp2"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="400" ResizeMode="NoResize">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="244*"/>
        <ColumnDefinition Width="149*"/>
    </Grid.ColumnDefinitions>
    <TreeView x:Name="TrvMenu" HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:ToDoTask}" ItemsSource="{Binding Tasks}">
                <StackPanel Orientation="Horizontal">
                    <CheckBox Content="{Binding Title}" IsChecked="{Binding active}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
    <TextBox x:Name="TaskTb" HorizontalAlignment="Left" Height="30" Margin="0,400,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2"/>
    <TextBox x:Name="DescriptionTb" HorizontalAlignment="Left" Height="80" Margin="0,430,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="392" Grid.ColumnSpan="2"/>
    <Button  x:Name="CreateBtn" Content="Create New Task" HorizontalAlignment="Left" Margin="0,510,0,0" VerticalAlignment="Top" Width="197" Height="59" Click="Button_Click"/>
    <Button  x:Name="DeleteBtn" Content="Delete Selected Task" HorizontalAlignment="Left" Margin="197,510,-1,0" VerticalAlignment="Top" Width="196" Height="59" Click="DeleteBtn_Click" Grid.ColumnSpan="2"/>

</Grid>
</Window>

this is the class that represents one task in app

public class ToDoTask
{

    public ToDoTask()
    {
        this.Tasks = new ObservableCollection<ToDoTask>();
    }
    public string Title { get; set; }
    public bool active=true;

    public ObservableCollection<ToDoTask> Tasks { get; set; }
    }

And this is how i add new tasks to db and app

public MainWindow()
    {

        InitializeComponent();
        SQLCnn init = new SQLCnn();
        ObservableCollection<ToDoTask> initList = init.readQuery();
        for(int i=0; i < initList.Count; i++)
        {
            TrvMenu.Items.Add(initList[i]);
        }
        SQLCnn.connection.Close();

    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (!String.IsNullOrEmpty(TaskTb.Text))
        {
            string value = TaskTb.Text;
            string desc = DescriptionTb.Text;

            ToDoTask task = new ToDoTask() { Title = value };
            task.Tasks.Add(new ToDoTask() { Title = desc });
            SQLCnn SQLtask = new SQLCnn();
            SQLtask.insertQuery(value, desc);
            TrvMenu.Items.Add(task);
        }
    }
  }


问:
Can't install PyAudio in python
I get the following ERROR while installing pyaudio</p>

```<code>C:\Users\Admin\Downloads>pip install pyaudio
Collecting pyaudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
    ERROR: Complete output from command 'c:\users\admin\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-snth_fqh\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-3n7dvpm8\install-record.txt' --single-version-externally-managed --compile:
    ERROR: running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    copying src\pyaudio.py -> build\lib.win-amd64-3.7
    running build_ext
    building '_portaudio' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
ERROR: Command "'c:\users\admin\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-snth_fqh\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-3n7dvpm8\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Admin\AppData\Local\Temp\pip-install-snth_fqh\pyaudio\
</code>```

答:
You are missing Visual C++ from your computer. Download and install from here: https://www.microsoft.com/en-us/download/details.aspx?id=48145

and then re run the install for PyAudio.

Title: Can't install PyAudio in python

Body:
I get the following ERROR while installing pyaudio

C:\Users\Admin\Downloads>pip install pyaudio
Collecting pyaudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
    ERROR: Complete output from command 'c:\users\admin\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-snth_fqh\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-3n7dvpm8\install-record.txt' --single-version-externally-managed --compile:
    ERROR: running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    copying src\pyaudio.py -> build\lib.win-amd64-3.7
    running build_ext
    building '_portaudio' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
ERROR: Command "'c:\users\admin\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-snth_fqh\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-3n7dvpm8\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Admin\AppData\Local\Temp\pip-install-snth_fqh\pyaudio\


问:
Display entry values in combobox for grid and edit window. Extjs6
I have an example fiddle in which I use Ext.window.Window to edit the grid entries.
The id of the value is displayed in the grid itself, and empty in the edit window.

For combobox in the grid, I did this and it works

```<code>{
            text      : 'type',
            dataIndex : 'type',
            flex: 1,
            renderer: function (v, p, record) {
                    return record.get('type');
                },
        },
</code>```

For combobox in the form edit I added to the combobox listeners:{ render: function(combo)}

```<code>{
                xtype: 'combobox',
                store: {
                    type: 'type-store'
                },
                fieldLabel: 'Type',
                displayField: 'name',
                valueField: 'id',
                queryMode: 'remote',
                publishes: 'name',
                name: 'name',
                listeners:{
                'render': function(combo){
                    console.log(combo);
                    combo.setValue();//How  set current value
                }
            }
</code>```

But I do not understand how to correctly set the current value?

thank

答:
First things first, in order to link the value of the combo,  your data data.json you must include the id for the "type", not just the description:

```<code>{
    "id": 1, "id_type":3 , "type": "Третий", "mytextfield": "Текстовое значение"
},
</code>```

You can actualy use the "name" if you want to, but you have to change your combo valueField to "name" also.

In the controller, first load the combo store (or autoload) and then, instead using the view_model of the windows, use the form to load your record:

```<code>console.log(wind.lookup("mycombo").getStore().load());
wind.down('form').loadRecord(record);
</code>```

I modified your fiddle with those changes

Body:
I have an example fiddle in which I use Ext.window.Window to edit the grid entries.
The id of the value is displayed in the grid itself, and empty in the edit window.

For combobox in the grid, I did this and it works

{
            text      : 'type',
            dataIndex : 'type',
            flex: 1,
            renderer: function (v, p, record) {
                    return record.get('type');
                },
        },

For combobox in the form edit I added to the combobox listeners:{ render: function(combo)}

{
                xtype: 'combobox',
                store: {
                    type: 'type-store'
                },
                fieldLabel: 'Type',
                displayField: 'name',
                valueField: 'id',
                queryMode: 'remote',
                publishes: 'name',
                name: 'name',
                listeners:{
                'render': function(combo){
                    console.log(combo);
                    combo.setValue();//How  set current value
                }
            }

But I do not understand how to correctly set the current value?

thank

Body:
First things first, in order to link the value of the combo,  your data data.json you must include the id for the "type", not just the description:

{
    "id": 1, "id_type":3 , "type": "Третий", "mytextfield": "Текстовое значение"
},

You can actualy use the "name" if you want to, but you have to change your combo valueField to "name" also.

In the controller, first load the combo store (or autoload) and then, instead using the view_model of the windows, use the form to load your record:

console.log(wind.lookup("mycombo").getStore().load());
wind.down('form').loadRecord(record);

I modified your fiddle with those changes


问:
2x one-to-many relationships in OO
Imagine these relationships:

1 A has many B's

1 B has many C's...

In reverse:

C has 1 B

B has 1A

By transitivity, C has 1 A

To model this relationship in DB, we have:

```<code>TableA
a_id

TableB
b_id
a_id (fk to TableA)

TableC
c_id
b_id (fk to TableB)
</code>```

To model this relationship in OO, we have:

```<code>objA
objB
objC
</code>```

And...
- objB has reference to objA
- objC has reference to objB

If objC has a method that needs to call a method of objA, what will you do?

Option 1.

```<code>b.getA().runMethodX()
</code>```

Many ppl I know would do this, but I've also learned that this is not good because getA() is not a behavior of B in a pure OO sense.  Doing so is just like doing procedural programming.  Agree/Disagree?

Option 2.

Let objC has direct reference to objA and objB through constructor injection / setter

Is this a good idea?  but then objB that objC has reference to also has reference to objA.  Is this okay?  Or as long as it is not a case of cyclic object references, it is acceptable?

Option 3.

Move the method in question to objA, and pass objC in by parameter.

I'm not sure if this considers as an option.  I think it'll not work in every case.  Have the method in objC reduce to bare minimum that only works on its states, and let objA do whatever objA needs to do before or after.

Option 4.  (Delegation)

add runMethodXinA() to B, it calls

```<code>a.runMethodX()
</code>```

C calls

```<code>b.runMethodXinA()
</code>```

I tried this method before, but B will very likely end up having as many methods as A, and doesn't having 1 method in both B and A violates DRY?

What are your though?  Any other options?  Comments?  Suggestions?

答:
Do you actually need the back pointers from C to B to A, or do you only have them so that you can access A from C?  Maybe A should take responsibility for creating B and C and for managing their relationship.  In that scenario, A can insert itself into C when it creates C (ex. C might have a constructor that takes A).

You might also isolate the function on A that C needs and create an interface for it.  The interface (instead of A) will be passed into C on construction.  That will decouple C from A.

OwnerDisplayName: Henry

Title: 2x one-to-many relationships in OO

Body:
Imagine these relationships:

1 A has many B's

1 B has many C's...

In reverse:

C has 1 B

B has 1A

By transitivity, C has 1 A

To model this relationship in DB, we have:

TableA
a_id

TableB
b_id
a_id (fk to TableA)

TableC
c_id
b_id (fk to TableB)

To model this relationship in OO, we have:

objA
objB
objC

And...
- objB has reference to objA
- objC has reference to objB

If objC has a method that needs to call a method of objA, what will you do?

Option 1.

b.getA().runMethodX()

Many ppl I know would do this, but I've also learned that this is not good because getA() is not a behavior of B in a pure OO sense.  Doing so is just like doing procedural programming.  Agree/Disagree?

Option 2.

Let objC has direct reference to objA and objB through constructor injection / setter

Is this a good idea?  but then objB that objC has reference to also has reference to objA.  Is this okay?  Or as long as it is not a case of cyclic object references, it is acceptable?

Option 3.

Move the method in question to objA, and pass objC in by parameter.

I'm not sure if this considers as an option.  I think it'll not work in every case.  Have the method in objC reduce to bare minimum that only works on its states, and let objA do whatever objA needs to do before or after.

Option 4.  (Delegation)

add runMethodXinA() to B, it calls

a.runMethodX()

C calls

b.runMethodXinA()

I tried this method before, but B will very likely end up having as many methods as A, and doesn't having 1 method in both B and A violates DRY?

What are your though?  Any other options?  Comments?  Suggestions?

LastEditorDisplayName: cletus


问:
how to get the neighboring elements in a numpy array with taking boundaries into account?
I want to get the neighbors of the certain element in the numpy array. Lets consider following example

```<code>    a = numpy.array([0,1,2,3,4,5,6,7,8,9])
</code>```

So I want to specify position 5 and want to get three neighbors from both sides. It can be done

```<code>   index = 5
   num_neighbor=3
   left = a[index-num_neighbor:index]
   right= a[num_neighbor+1:num_neighbor+index+1]
</code>```

The above code does not take care of the boundaries... I want that i get the neighbours within the boundaries of the array. For this consider the following example if index is 1 then the left neighbor is only one element which is 0.

Thanks a lot

答:
The method I came up with involves slicing the array and then padding as necessary to fill out-of-bounds values.

Taken from here:

```<code>def surrounding(x, idx, radius=1, fill=0):
"""
Gets surrounding elements from a numpy array

Parameters:
x (ndarray of rank N): Input array
idx (N-Dimensional Index): The index at which to get surrounding elements. If None is specified for a particular axis,
    the entire axis is returned.
radius (array-like of rank N or scalar): The radius across each axis. If None is specified for a particular axis,
    the entire axis is returned.
fill (scalar or None): The value to fill the array for indices that are out-of-bounds.
    If value is None, only the surrounding indices that are within the original array are returned.

Returns:
ndarray: The surrounding elements at the specified index
"""

assert len(idx) == len(x.shape)

if np.isscalar(radius): radius = tuple([radius for i in range(len(x.shape))])

slices = []
paddings = []
for axis in range(len(x.shape)):
    if idx[axis] is None or radius[axis] is None:
        slices.append(slice(0, x.shape[axis]))
        paddings.append((0, 0))
        continue

    r = radius[axis]
    l = idx[axis] - r
    r = idx[axis] + r

    pl = 0 if l > 0 else abs(l)
    pr = 0 if r < x.shape[axis] else r - x.shape[axis] + 1

    slices.append(slice(max(0, l), min(x.shape[axis], r+1)))
    paddings.append((pl, pr))

if fill is None: return x[slices]
return np.pad(x[slices], paddings, 'constant', constant_values=fill)
</code>```

Body:
I want to get the neighbors of the certain element in the numpy array. Lets consider following example

    a = numpy.array([0,1,2,3,4,5,6,7,8,9])

So I want to specify position 5 and want to get three neighbors from both sides. It can be done

   index = 5
   num_neighbor=3
   left = a[index-num_neighbor:index]
   right= a[num_neighbor+1:num_neighbor+index+1]

The above code does not take care of the boundaries... I want that i get the neighbours within the boundaries of the array. For this consider the following example if index is 1 then the left neighbor is only one element which is 0.

Thanks a lot

Body:
The method I came up with involves slicing the array and then padding as necessary to fill out-of-bounds values.

Taken from here:

def surrounding(x, idx, radius=1, fill=0):
"""
Gets surrounding elements from a numpy array

Parameters:
x (ndarray of rank N): Input array
idx (N-Dimensional Index): The index at which to get surrounding elements. If None is specified for a particular axis,
    the entire axis is returned.
radius (array-like of rank N or scalar): The radius across each axis. If None is specified for a particular axis,
    the entire axis is returned.
fill (scalar or None): The value to fill the array for indices that are out-of-bounds.
    If value is None, only the surrounding indices that are within the original array are returned.

Returns:
ndarray: The surrounding elements at the specified index
"""

assert len(idx) == len(x.shape)

if np.isscalar(radius): radius = tuple([radius for i in range(len(x.shape))])

slices = []
paddings = []
for axis in range(len(x.shape)):
    if idx[axis] is None or radius[axis] is None:
        slices.append(slice(0, x.shape[axis]))
        paddings.append((0, 0))
        continue

    r = radius[axis]
    l = idx[axis] - r
    r = idx[axis] + r

    pl = 0 if l > 0 else abs(l)
    pr = 0 if r < x.shape[axis] else r - x.shape[axis] + 1

    slices.append(slice(max(0, l), min(x.shape[axis], r+1)))
    paddings.append((pl, pr))

if fill is None: return x[slices]
return np.pad(x[slices], paddings, 'constant', constant_values=fill)