问:
How do I run two separate threads printing numbers (or words) in ascending and descending order?
I need to write a program for my online class. Here is the prompt:

Write a program to run two separate threads printing numbers (or words) in ascending and descending orders. The numbers (or words) should be given by the user.

I think I have the threads down, but I'm confused on how I would have the code take the user input and then print it in either ascending/descending order. So basically I'm confused on the syntax/methods that would need to be used.

Here is the code I have so far:

```<code>Module Module1

    Sub Main()
        Dim A As System.Threading.Thread = New Threading.Thread(AddressOf ThreadA)
        Dim B As System.Threading.Thread = New Threading.Thread(AddressOf ThreadB)
        A.Start()
    End Sub

    Sub ThreadA()
        Dim nl As String = Environment.NewLine
        Console.WriteLine("Enter a word:")
        Dim x = Console.ReadLine()
    End Sub

    Sub ThreadB()
        Dim nl As String = Environment.NewLine
        Console.WriteLine("Enter a word:")
        Dim x = Console.ReadLine()
    End Sub
End Module
</code>```

答:
I think that you've misunderstood the question slightly. The program below takes input for 5 numbers each for two word lists, sorts each wordlist and then starts 2 threads to write each word to the console. The multi-threading is demonstrated by the way the lines from each wordlist are output to the console.

Each list is in fact in alphabetical order but multi-threading means that as both of the pieces of code run "at the same time", they don't run at exactly the same time, so the output statements don't get printed in exact alternate order. You might get a few of one word list clumped together because of the way multi-threading happens. I've added a line to sleep each thread for different amounts of time to highlight the threads running independant of each other.

```<code>Module Module1
    Dim wordlist1 As New List(Of String)
    Dim wordlist2 As New List(Of String)

    Sub Main()
        Dim A As System.Threading.Thread = New Threading.Thread(AddressOf ThreadA)
        Dim B As System.Threading.Thread = New Threading.Thread(AddressOf ThreadB)
        Dim word As String
        For i As Integer = 1 To 5
            Console.WriteLine("Enter List 1 word " & i.ToString & ":")
            word = Console.ReadLine()
            wordlist1.Add(word)
        Next

        For i As Integer = 1 To 5
            Console.WriteLine("Enter List 2 word " & i.ToString & ":")
            word = Console.ReadLine()
            wordlist2.Add(word)
        Next

        Dim sortOrder As String = ""
        Do
            Console.WriteLine("Do you want to sort in ascending order or descending. Enter 'a' or 'd'")
            sortOrder = Console.ReadLine().ToLower
        Loop Until sortOrder = "a" Or sortOrder = "d"

        wordlist1.Sort()
        wordlist2.Sort()

        If sortOrder = "d" Then
            wordlist1.Reverse()
            wordlist2.Reverse()
        End If

        A.Start()
        B.Start()
        Console.ReadLine()

    End Sub

    Sub ThreadA()
        For Each word As String In wordlist1
            Console.WriteLine("List 1 :" & word)
            Thread.Sleep(40)
        Next
    End Sub

    Sub ThreadB()
        For Each word As String In wordlist2
            Console.WriteLine("List 2 :" & word)
            Thread.Sleep(80)
        Next
    End Sub
End Module
</code>```

Body:
I need to write a program for my online class. Here is the prompt:

Write a program to run two separate threads printing numbers (or words) in ascending and descending orders. The numbers (or words) should be given by the user.

I think I have the threads down, but I'm confused on how I would have the code take the user input and then print it in either ascending/descending order. So basically I'm confused on the syntax/methods that would need to be used.

Here is the code I have so far:

Module Module1

    Sub Main()
        Dim A As System.Threading.Thread = New Threading.Thread(AddressOf ThreadA)
        Dim B As System.Threading.Thread = New Threading.Thread(AddressOf ThreadB)
        A.Start()
    End Sub

    Sub ThreadA()
        Dim nl As String = Environment.NewLine
        Console.WriteLine("Enter a word:")
        Dim x = Console.ReadLine()
    End Sub

    Sub ThreadB()
        Dim nl As String = Environment.NewLine
        Console.WriteLine("Enter a word:")
        Dim x = Console.ReadLine()
    End Sub
End Module

Body:
I think that you've misunderstood the question slightly. The program below takes input for 5 numbers each for two word lists, sorts each wordlist and then starts 2 threads to write each word to the console. The multi-threading is demonstrated by the way the lines from each wordlist are output to the console.

Each list is in fact in alphabetical order but multi-threading means that as both of the pieces of code run "at the same time", they don't run at exactly the same time, so the output statements don't get printed in exact alternate order. You might get a few of one word list clumped together because of the way multi-threading happens. I've added a line to sleep each thread for different amounts of time to highlight the threads running independant of each other.

Module Module1
    Dim wordlist1 As New List(Of String)
    Dim wordlist2 As New List(Of String)

    Sub Main()
        Dim A As System.Threading.Thread = New Threading.Thread(AddressOf ThreadA)
        Dim B As System.Threading.Thread = New Threading.Thread(AddressOf ThreadB)
        Dim word As String
        For i As Integer = 1 To 5
            Console.WriteLine("Enter List 1 word " & i.ToString & ":")
            word = Console.ReadLine()
            wordlist1.Add(word)
        Next

        For i As Integer = 1 To 5
            Console.WriteLine("Enter List 2 word " & i.ToString & ":")
            word = Console.ReadLine()
            wordlist2.Add(word)
        Next

        Dim sortOrder As String = ""
        Do
            Console.WriteLine("Do you want to sort in ascending order or descending. Enter 'a' or 'd'")
            sortOrder = Console.ReadLine().ToLower
        Loop Until sortOrder = "a" Or sortOrder = "d"

        wordlist1.Sort()
        wordlist2.Sort()

        If sortOrder = "d" Then
            wordlist1.Reverse()
            wordlist2.Reverse()
        End If

        A.Start()
        B.Start()
        Console.ReadLine()

    End Sub

    Sub ThreadA()
        For Each word As String In wordlist1
            Console.WriteLine("List 1 :" & word)
            Thread.Sleep(40)
        Next
    End Sub

    Sub ThreadB()
        For Each word As String In wordlist2
            Console.WriteLine("List 2 :" & word)
            Thread.Sleep(80)
        Next
    End Sub
End Module


来源: stackexchange

问:
How to limit MQTT user to only one topic
I'm looking for a way to limit user access only to dedicated topics e.g.:

user1 should have access only to user1/# topics,
so he can subscribe/publish user1/sensor/1 or user1/conf/mode but not user2/sensor/2 etc.

Analogically user2 should have access only to user2/# with all sub-topics.

I can do it in eMQTT broker by using ACL settings but I can't find similar in RabbitMQ. I already use AMQP in my project so I'd like to avoid installing additional eMQTT broker, especially when RabbitMQ can support MQTT.

答:
From what I can tell topic based authentication is a work in progress for RabbitMQ. Take a look at these two discussions for more context:

https://github.com/rabbitmq/rabbitmq-server/issues/505

https://github.com/rabbitmq/rabbitmq-mqtt/issues/95

Looks like it will be included in a future release but, from a quick skim of the changelog, it appears to not have been implemented yet.

I haven't used it but Antione Galataud's topic authorization plugin looks like it might provide you with an interim solution until an official one exists: https://antoine-galataud.github.io/messaging/rabbitmq/mqtt/stomp/authorization/2015/10/15/rabbit-topic-auth.html

ContentLicense: CC BY-SA 3.0


问:
Azure notification hub best practice in social network scenario
I am wondering which is the best practice in Azure notification hub to send push notifications to a couple of certain users (e.g. about followed activities).

Imagine, users can follow other users and these followers should be notified about new activities (facebook, twitter principle).

How to send these notifications in detail, there are two options I am thinking about, but which one is the best?

1) looping through all desired users by code and calling SendTemplateNotificationAsync for each individual user?

```<code>foreach(user in allSubscribedUsers) {
    tags.Add("userid:" + userId);
    await hub.SendTemplateNotificationAsync(notification, tags);
}
</code>```

2) Having special tags a user can register to

```<code>registration.Tags = new HashSet<string>(deviceUpdate.Tags);

// the current user follows other users with the ids 1,2 and 3
registration.Tags.Add("followerUserid:1");
registration.Tags.Add("followerUserid:2");
registration.Tags.Add("followerUserid:3");
...
// an acivity by user with id 2 is happen
// send a push notification to all users who follow the user with id 2
tags.Add("followerUserid:2");
await hub.SendTemplateNotificationAsync(notification, tags);
</code>```

It's possible that a user follows up to 1.000 other users, so he needs to register 1.000 of the followerUserId-Tag.

Is the second approach a reliable solution?

Are there any tag limitations a user can register to?

答:
This answer describes tag limits on NH. There is a limit of 60 tags per registration, so you won't be able to use your second approach if you want to allow 1k followers.

You can use the SendNotificationAsync(Notification, IEnumerable<String>) overload of the method to "batch" calls in your first scenario in groups of 20 max to save on the number of calls you make to the service.

Body:
I am wondering which is the best practice in Azure notification hub to send push notifications to a couple of certain users (e.g. about followed activities).

Imagine, users can follow other users and these followers should be notified about new activities (facebook, twitter principle).

How to send these notifications in detail, there are two options I am thinking about, but which one is the best?

1) looping through all desired users by code and calling SendTemplateNotificationAsync for each individual user?

foreach(user in allSubscribedUsers) {
    tags.Add("userid:" + userId);
    await hub.SendTemplateNotificationAsync(notification, tags);
}

2) Having special tags a user can register to

registration.Tags = new HashSet<string>(deviceUpdate.Tags);

// the current user follows other users with the ids 1,2 and 3
registration.Tags.Add("followerUserid:1");
registration.Tags.Add("followerUserid:2");
registration.Tags.Add("followerUserid:3");
...
// an acivity by user with id 2 is happen
// send a push notification to all users who follow the user with id 2
tags.Add("followerUserid:2");
await hub.SendTemplateNotificationAsync(notification, tags);

It's possible that a user follows up to 1.000 other users, so he needs to register 1.000 of the followerUserId-Tag.

Is the second approach a reliable solution?

Are there any tag limitations a user can register to?


问:
Make Django build contenteditable div for TextField instead of textarea
In my Django 1.10 project, I have a model:

```<code>class Contact(models.Model):
    notes = models.TextField()
</code>```

...and ModelForm:

```<code>class ContactForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control input-sm plain'
            if field.required == True:
                field.widget.attrs['required'] = ''

    class Meta:
        model = Contact
        fields = ('notes',)
</code>```

I have two questions regarding this:

Can I make Django render the notes field as div with contenteditable=true rather than textarea?

If yes, how do I automate the form.save() method?

The second question is a bit vague, so I would be grateful for a hint regarding the first question. I have read through the doc, but couldn't find relevant section :(

答:
Question 1: Render a field with a specific HTML tag

In this case,
...

You can customize the widget used to render a form field. Basically, when you declare the field, you have to pass the argument widget=TheWidgetClass. Django has a lot of builtin widgets you can use. But you can also define your own. To know how, you will find many resources on the Internet. Simply search for "django create custom widget" on a search engine, or on SO. Possible answer: Django: How to build a custom form widget?

Since Django doesn't provide any official documentation on how to create custom widget, the smartest way would be to create a class inheriting Django's TextArea and using a custom html template based on original one.

Question 2: Automate form.save() method with such a custom widget

Basically, you have to make sure the value of the div tag is sent with other inputs values to the target view of your form, in POST data. In other words, you have to make sure the content of the div acts like the content of any form field.
Maybe this SO question can help you: one solution could be using JavaScript to copy the content of your div to a hidden textarea tag in the form when the user click on submit button.

Good luck ;)

Body:
In my Django 1.10 project, I have a model:

class Contact(models.Model):
    notes = models.TextField()

...and ModelForm:

class ContactForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control input-sm plain'
            if field.required == True:
                field.widget.attrs['required'] = ''

    class Meta:
        model = Contact
        fields = ('notes',)

I have two questions regarding this:

Can I make Django render the notes field as div with contenteditable=true rather than textarea?

If yes, how do I automate the form.save() method?

The second question is a bit vague, so I would be grateful for a hint regarding the first question. I have read through the doc, but couldn't find relevant section :(

Body:
Question 1: Render a field with a specific HTML tag

In this case, <div contenteditable="true">...</div>

You can customize the widget used to render a form field. Basically, when you declare the field, you have to pass the argument widget=TheWidgetClass. Django has a lot of builtin widgets you can use. But you can also define your own. To know how, you will find many resources on the Internet. Simply search for "django create custom widget" on a search engine, or on SO. Possible answer: Django: How to build a custom form widget?

Since Django doesn't provide any official documentation on how to create custom widget, the smartest way would be to create a class inheriting Django's TextArea and using a custom html template based on original one.

Question 2: Automate form.save() method with such a custom widget

Basically, you have to make sure the value of the div tag is sent with other inputs values to the target view of your form, in POST data. In other words, you have to make sure the content of the div acts like the content of any form field.
Maybe this SO question can help you: one solution could be using JavaScript to copy the content of your div to a hidden textarea tag in the form when the user click on submit button.

Good luck ;)


问:
Jquery jtable sorting child table
General query at this stage - I can post code if needs be but I shall probably have to simplify it a bit first.
I have used jtable quite a bit but I am having trouble getting sorting to work on a child table - are there fundamental differences between sorting a child table and a parent table?

When I put in the custom listAction function on the child table definition with parameters (postData, jtParams), and sorting: true on the definition, jtParams just comes through as an empty object.

Am I missing something?

Thanks

答:
Solved it!

It was necessary to use different parameter names for the parameters passed into the listAction custom function for the child table otherwise I guess they are conflicting with the parent table variable names.  I changed my custom function definition in the child table to listAction: function(pData, jParams) { ... } and all was well.

Title: Jquery jtable sorting child table


问:
PHP - highlight text from a string containing HTML
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

```<code><p>bla bla foo bar bla</p>
</code>```

so it should be something like:

```<code><p>bla <span class="highlight">foo bar</span> bla bla</p>
</code>```

答:
```<code><?php

$result = "<p>Bla bla foo bar bla bla test x x x</p>";

$query = "foo bar";

// The important point here is, USE single quote ( ' ) in replacement part!!
echo preg_replace( "/($query)/", '<span class="highlight">${1}</span>', $result );
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

bla bla foo bar bla

so it should be something like:

bla foo bar bla bla


问:
Change the Connecting string of the C# windows form application to it in another computer
I have a C# windows form application and I connect it to the SQL server in my computer. Now I going to deliver the software to a user. So, what can I do to change the connection string to the user SQL server? Is there any way to do the connection string computer independent? Kindly help me

Regards.

答:
Or you could use connection string like this (if database (SQL server) is on same machine as app using it and database name is the same) :

```<code>Server=localhost\instanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
</code>```

instanceName could be "nothing" (default instance) or named instance (SQLEXPRESS).

Or do it as @Xavier J suggested - store connection string in app config or INI file.

Body:
Or you could use connection string like this (if database (SQL server) is on same machine as app using it and database name is the same) :

Server=localhost\instanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;

instanceName could be "nothing" (default instance) or named instance (SQLEXPRESS).

Or do it as @Xavier J suggested - store connection string in app config or INI file.


问:
SQL: Using x and y coordinates to display line information, more details below
I have a database which contains data like this:

```<code>Connector_id | C_x | C_y | Line_id | L_x | L_y
'C100'         2     3     'L100'   2     3
'C200'         8     9     'L100'   8     9
</code>```

The program is supposed to find out which connections are at the endpoints of a line by using the x and y coordinates and output the database like so:

```<code>line_id | endpoint_1 | endpoint_2
'L100'   'C100'       'C200'
</code>```

Thank you very much in advance!

答:
I am offering the following query as a possible solution.  This assumes that the "lower" connector ID corresponds to the first endpoint and the "higher" connector ID to the second endpoint.</p>

```<code>SELECT
    line_id,
    MIN(Connector_id) AS endpoint_1,
    MAX(Connector_id) AS endpoint_2
FROM
(
    -- your intermediate query/CTE
) t
GROUP BY line_id
</code>```

Body:
I have a database which contains data like this:

Connector_id | C_x | C_y | Line_id | L_x | L_y
'C100'         2     3     'L100'   2     3
'C200'         8     9     'L100'   8     9

The program is supposed to find out which connections are at the endpoints of a line by using the x and y coordinates and output the database like so:

line_id | endpoint_1 | endpoint_2
'L100'   'C100'       'C200'

Thank you very much in advance!

Body:
I am offering the following query as a possible solution.  This assumes that the "lower" connector ID corresponds to the first endpoint and the "higher" connector ID to the second endpoint.

SELECT
    line_id,
    MIN(Connector_id) AS endpoint_1,
    MAX(Connector_id) AS endpoint_2
FROM
(
    -- your intermediate query/CTE
) t
GROUP BY line_id


问:
Method chaining to communicate between GUI parts in a MVC in Java
I am creating a Java Desktop GUI application using the MVC pattern. For the sake of simplicity, I have divided in GUI application into different panels (Scheme of the GUI application) so that each class takes care of something specific. Now, when I am in the Controller part and want to display something in the DRAW PANEL, I have a method chaining. I mean I am calling several methods in a row:

```<code>view.getRightPanel().getDrawPanel().appendText(model.getResults());
</code>```

I am wondering whether or not I am making a mistake somewhere. Is it normal to do so, or should I change my code to make it more efficient and elegant?
Any information is welcome! Thank you!

答:
You are not making a mistake if you are doing this in the controller.

In the MVC pattern, the controller listens for model changes and updates the view. That is what the controller is supposed to do. Here,

```<code>view.getRightPanel().getDrawPanel().appendText(model.getResults());
</code>```

I guess you are changing the text in a draw panel in the view that controller is controlling, which is exactly what the controller is supposed to do.

Do be careful not to change update the model directly from the view, or update the view from the model though. That violates MVC.

I also suggest you to create multiple controllers to control different panels on the screen. I think that way it will be more manageable.

Body:
I am creating a Java Desktop GUI application using the MVC pattern. For the sake of simplicity, I have divided in GUI application into different panels (Scheme of the GUI application) so that each class takes care of something specific. Now, when I am in the Controller part and want to display something in the DRAW PANEL, I have a method chaining. I mean I am calling several methods in a row:

view.getRightPanel().getDrawPanel().appendText(model.getResults());

I am wondering whether or not I am making a mistake somewhere. Is it normal to do so, or should I change my code to make it more efficient and elegant?
Any information is welcome! Thank you!

Body:
You are not making a mistake if you are doing this in the controller.

In the MVC pattern, the controller listens for model changes and updates the view. That is what the controller is supposed to do. Here,

view.getRightPanel().getDrawPanel().appendText(model.getResults());

I guess you are changing the text in a draw panel in the view that controller is controlling, which is exactly what the controller is supposed to do.

Do be careful not to change update the model directly from the view, or update the view from the model though. That violates MVC.

I also suggest you to create multiple controllers to control different panels on the screen. I think that way it will be more manageable.


问:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
I have created a new column in my database through a migration as below :

```<code>public function up(){
  Schema::table('complains', function (Blueprint $table) {
  $table->integer('user_id')->after('id');
   });
}
</code>```

When I fill in my form to post data into the database, I get the error below :

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into complains (title, body, name, regnumber, updated_at, created_at) values (Testing user id, Testing user id, John, cs-282-2145/2010, 2017-06-08 18:47:53, 2017-06-08 18:47:53))

How do I fix this?

答:
Probably you aren't sending a value for user_id

Other possibility, yout can "transform" the column user_id nullable

Body:
I have created a new column in my database through a migration as below :

public function up(){
  Schema::table('complains', function (Blueprint $table) {
  $table->integer('user_id')->after('id');
   });
}

When I fill in my form to post data into the database, I get the error below :

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into complains (title, body, name, regnumber, updated_at, created_at) values (Testing user id, Testing user id, John, cs-282-2145/2010, 2017-06-08 18:47:53, 2017-06-08 18:47:53))

How do I fix this?


问:
PHP 'addslashes' not behaving as expected
This has been driving be crazy, but I can't seem to find an answer. We run a technical knowledge base that will sometimes include Windows samba paths for mapping to network drives.

For example: \\servername\sharename

When we include paths that have two backslashes followed by each other, they are not escaped properly when running 'addslashes'. My expected results would be "\\\\servername\\sharename", however it returns "\\servername\\sharename". Obviously, when running 'stripslashes' later on, the double backslash prefix is only a single slash. I've also tried using a str_replace("\\", "\", $variable); however it returns "\servername\sharename" when I would expect "\\servername\sharename".

So with addslashes, it ignores the first set of double-backslashes and with str_replace it changes the double-backslashes into a single, encoded backslash.

We need to run addslashes and stripslashes for database insertion; using pg_escape_string won't work in our specific case.

This is running on PHP 5.3.1 on Apache.

EDIT: Example Code

$variable = 'In the box labeled Folder type: \\servername\sharename';

echo addslashes($variable);

This returns: In the box labeled Folder type: \\servername\\sharename

EDIT: Example Code #2

$variable = 'In the box labeled Folder type: \\servername\sharename';

echo str_replace('\\', '\', $variable);

This returns: In the box labeled Folder type: \servername\sharename

I'd also like to state that using a single quotes or double-quotes does not give me different results (as you would expect). Using either or both give me the same exact results.

Does anyone have any suggestions on what I can possibly do?

答:
I think I know where is a problem. Just try to run this one:

```<code>echo addslashes('\\servername\sharename');
</code>```

And this one

```<code>echo addslashes('\\\\servername\sharename');
</code>```

PHP escapes double slashes even with single quotes, because it is used to escape single quote.

Body:
I think I know where is a problem. Just try to run this one:

echo addslashes('\\servername\sharename');

And this one

echo addslashes('\\\\servername\sharename');

PHP escapes double slashes even with single quotes, because it is used to escape single quote.


问:
Repeat VBA code and change values based on other sheet
I'm trying to automate an excel sheet using the code below. It works for the first part of what i need it for but i can't figure out the next part.

I need to repeat this code for every value in a sheet called Materials. Each cell contains a different material number. The material number used for the first set of data Result (A2) would then be overwritten by the next available value from Column A in the Materials sheet and so forth until the last cell.

So basically this creates the first set and i want to copy and paste it with updated values in column A from the Materials sheet. Hope that makes sense.

```<code>Sub Test2()

Dim sh4 As Worksheet, sh5 As Worksheet, lr As Long, rng As Range
    Set sh4 = Sheets("Template")
    Set sh5 = Sheets("Result")
    lr = sh4.Cells(Rows.Count, 1).End(xlUp).Row
    Set rng = sh4.Range("A2:E2" & lr)
        rng.EntireRow.Copy sh5.Cells(Rows.Count, 1).End(xlUp)(2)

        Sheets("Materials").Select
        Range("A2").Select
        Selection.Copy
        Sheets("Result").Select
        Range("A2").Select
        ActiveSheet.Paste
        Sheets("Result").Select

Dim lastrow As Long
    lastrow = Worksheets("Result").Range("E65536").End(xlUp).Row
With Worksheets("Result").Range("A2")
    .AutoFill Destination:=Range("A2:A" & lastrow&)
End With
</code>```

End Sub

答:
This is a bit of a guess because I'm not clear from your picture what exactly you are after, and seems to differ from your actual file</p>

```<code>Sub Test2()

Dim sh4 As Worksheet, sh5 As Worksheet, rng As Range, r As Range

Application.ScreenUpdating = False

Set sh4 = Sheets("Template")
Set sh5 = Sheets("Result")
Set rng = sh4.Range("B2:E2" & lr)

With Sheets("Materials")
    For Each r In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
        sh5.Range("A" & Rows.Count).End(xlUp)(2).Offset(, 1).Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
        sh5.Range("A" & Rows.Count).End(xlUp)(2).Resize(rng.Rows.Count).Value = r.Value
    Next r
End With

Application.ScreenUpdating = True

End Sub
</code>```

Body:
I'm trying to automate an excel sheet using the code below. It works for the first part of what i need it for but i can't figure out the next part.

I need to repeat this code for every value in a sheet called Materials. Each cell contains a different material number. The material number used for the first set of data Result (A2) would then be overwritten by the next available value from Column A in the Materials sheet and so forth until the last cell.

So basically this creates the first set and i want to copy and paste it with updated values in column A from the Materials sheet. Hope that makes sense.

Sub Test2()

Dim sh4 As Worksheet, sh5 As Worksheet, lr As Long, rng As Range
    Set sh4 = Sheets("Template")
    Set sh5 = Sheets("Result")
    lr = sh4.Cells(Rows.Count, 1).End(xlUp).Row
    Set rng = sh4.Range("A2:E2" & lr)
        rng.EntireRow.Copy sh5.Cells(Rows.Count, 1).End(xlUp)(2)

        Sheets("Materials").Select
        Range("A2").Select
        Selection.Copy
        Sheets("Result").Select
        Range("A2").Select
        ActiveSheet.Paste
        Sheets("Result").Select

Dim lastrow As Long
    lastrow = Worksheets("Result").Range("E65536").End(xlUp).Row
With Worksheets("Result").Range("A2")
    .AutoFill Destination:=Range("A2:A" & lastrow&)
End With

End Sub

Body:
This is a bit of a guess because I'm not clear from your picture what exactly you are after, and seems to differ from your actual file

Sub Test2()

Dim sh4 As Worksheet, sh5 As Worksheet, rng As Range, r As Range

Application.ScreenUpdating = False

Set sh4 = Sheets("Template")
Set sh5 = Sheets("Result")
Set rng = sh4.Range("B2:E2" & lr)

With Sheets("Materials")
    For Each r In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
        sh5.Range("A" & Rows.Count).End(xlUp)(2).Offset(, 1).Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
        sh5.Range("A" & Rows.Count).End(xlUp)(2).Resize(rng.Rows.Count).Value = r.Value
    Next r
End With

Application.ScreenUpdating = True

End Sub


问:
How to enable alternative StyleCop rules (prefixed with SX) when using StyleCopAnalyzers (Roslyn)?
For an existing C# web project I am trying to setup StyleCop code analysis based on Roslyn analyzers. (DotNetAnalyzers/StyleCopAnalyzers)

I have managed to get it to work quite fine for our desired code-style except that we would like to not use these default rules:

SA1101: Prefix local calls with this

SA1309: Field names must not begin with underscore

Instead we want to somehow enable these alternative rules mentioned at stylecop.pdelvo.com as DisabledAlternative

SX1101: Do not prefix local calls with 'this.'

SX1309: Field names must begin with underscore

SX1309S: Static field names must begin with underscore

The mentioned site shows that these alternative rules even have code fixes implemented so I expect them to be available for usage.

I have searched the net repeatedly and only found proposal posts to introduce these rules and other documentation on how the rules work, how to suppress them etc., but not how to enable them.

Using GlobalSuppressions.cs file I can only suppress some rules but I am unable to enable any.

Documentation on using stylecop.json to fine-tune some rules does not mention that either.

How do I enable these alternative rules?

Adjusting the existing code to pass the default rules is not an option and simply disabling the SA1101 and SA1309 rules works but is not optimal either.

答:
Pretty same way as other rules.

Right Click on Project > Properties > Code Analysis

You should see Rule set which is currently used in your project. Click open

You should see list of rules grouped by rule family like 'StyleCop analyzer rules', 'Microsoft.CodeAnalysis.CSharp.Features' etc. Your desired rules are under 'StyleCop analyzer rules'

You can speed up search by typing SX into filter field

Check your rules, try to build project and you should see warnings/errors where this. is used


答:
application config files are one idea, but because they are managed through the IDE means have to change manually for deployment.
Better to use the registry (cleaner too - no need to post-edit the file), and the installer can get conditional on where it's deployed, alternatively ask the user during installation, skip if the registry entry already exists.), confirm the connection string at install time. database path/host/name exists...</p>

Title: Change the Connecting string of the C# windows form application to it in another computer

Body:
I have a C# windows form application and I connect it to the SQL server in my computer. Now I going to deliver the software to a user. So, what can I do to change the connection string to the user SQL server? Is there any way to do the connection string computer independent? Kindly help me

Regards.


问:
Which permission required in order to get ACTION_HEADSET_PLUG inside broadcast receiver
I am using the manifest file for creating broadcast receiver, for ACTION_HEADSET_PLUG.
But I can't get the broadcast when headset is connect/disconnect,
Which permission should I use inside the manifest file in order to be able to receive ACTION_HEADSET_PLUG broadcast intent?

答:
It's not a permission thing, it's actually a problem with how you registered the receiver. The headset plug action broadcast can only be received by actively registered receivers like this:

```<code>registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
</code>```

This means that you need to have a service kept alive that holds a reference to the receiver and also unregisters it when the service is killed. Lastly, the service that registers the receiver needs to also be started on boot; which you do with yet another receiver that intercepts the android.intent.action.BOOT_COMPLETED intent. For this part, you will need to use the android.permission.RECEIVE_BOOT_COMPLETED permission.

For a full example of a service that does this stuff, you can check out an app I wrote that does just that.

Body:
It's not a permission thing, it's actually a problem with how you registered the receiver. The headset plug action broadcast can only be received by actively registered receivers like this:

registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));

This means that you need to have a service kept alive that holds a reference to the receiver and also unregisters it when the service is killed. Lastly, the service that registers the receiver needs to also be started on boot; which you do with yet another receiver that intercepts the android.intent.action.BOOT_COMPLETED intent. For this part, you will need to use the android.permission.RECEIVE_BOOT_COMPLETED permission.

For a full example of a service that does this stuff, you can check out an app I wrote that does just that.


问:
Javascript hide menu on outside click
I got the following html:

```<code><div id="otherdiv"></div>
 <div class="overlay">
  <div class="menu">
    <ul>
      <li><a href="#">Val1</a></li>
     <li><a href="#">Val2</a></li>
    </ul>
   </div>
</div>
</code>```

and JS code:

```<code>$(document).ready(function(){
$('#otherdiv').on('mouseup', function(e){
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
 $(document).on('click', function(e) {
    $('.overlay').hide(200);
  });
});
</code>```

I need to hide my .overlay when the user clicks somewhere outside it and show it when the user clicks #otherdiv. When I attach an event to document and click on otherdiv, my overlay shows and then immediately hides. How to fix that behaviour? Thank you.

答:
click and mouseup events fire at the same time read more about it here - https://www.quirksmode.org/dom/events/click.html

An interesting thing about how jQuery handles animations is it puts things in the queue - so, your hide() animation is queued to run 200ms after show(), even though the both functions are firing at the same time.

Instead, I would just suggest using one click event for this -

```<code>$(document).on('click', function(e) {
    if(event.target.id == 'otherdiv' && !$('.overlay').is(":visible")) {
       //do stuff to show
    }
    else if($('.overlay').is(":visible")) {
        $('.overlay').hide(200);
    }
});
</code>```

The first if checks to make sure that the element with the id otherdiv has been clicked and that the overlay is not currently visible. The next if checks to see if there has been a click and the overlay is visible.

Title: Javascript hide menu on outside click

Body:
I got the following html:

Val1

Val2

and JS code:

$(document).ready(function(){
$('#otherdiv').on('mouseup', function(e){
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
 $(document).on('click', function(e) {
    $('.overlay').hide(200);
  });
});

I need to hide my .overlay when the user clicks somewhere outside it and show it when the user clicks #otherdiv. When I attach an event to document and click on otherdiv, my overlay shows and then immediately hides. How to fix that behaviour? Thank you.

Body:
click and mouseup events fire at the same time read more about it here - https://www.quirksmode.org/dom/events/click.html

An interesting thing about how jQuery handles animations is it puts things in the queue - so, your hide() animation is queued to run 200ms after show(), even though the both functions are firing at the same time.

Instead, I would just suggest using one click event for this -

$(document).on('click', function(e) {
    if(event.target.id == 'otherdiv' && !$('.overlay').is(":visible")) {
       //do stuff to show
    }
    else if($('.overlay').is(":visible")) {
        $('.overlay').hide(200);
    }
});

The first if checks to make sure that the element with the id otherdiv has been clicked and that the overlay is not currently visible. The next if checks to see if there has been a click and the overlay is visible.


问:
Update Results from MS-SQL Query into MySql Database
Running into a bit of an issue here that I can't seem to figure it out. I have a result set from a query on a MS-SQL database which I need to import into a MySQL database. Don't ask why, I just have to. Below is my code, but when I run it, it just doesn't do anything with the results. Can anyone help me?

```<code>      <?php

    putenv("TDSVER=80");
    putenv("FREETDSCONF=/etc/freetds/freetds.conf");
    putenv("ODBCSYSINI=/etc/odbcinst.ini");
    putenv("ODBCINI=/etc/odbc.ini");

    $myServer = "*****";
    $username = "*****";
    $password = "*****";
    $database = "*****";

    //connection to the database
    $dbhandle = mssql_connect($myServer, $username, $password)
    or die("Couldn't connect to SQL Server on $myServer");

    //select a database to work with
    $selected = mssql_select_db($database, $dbhandle)
    or die("Couldn't open database $myDB");

    $sql_connection = mysqli_connect("*****", "*****", "*****", "*****");
if (mysqli_connect_errno()) {
        echo "Failed to connect to the SQL Database: " . mysqli_connect_error();
    }

    $query = "DECLARE @Agent NVARCHAR(250) = '%*****%';
    WITH Agent AS
    (SELECT
        COUNT (r.id) as 'count',
        p.category_id AS 'category'
    FROM
        service_req r LEFT JOIN
        problem_type p on r.problem_type = p.problem_type
    WHERE
        r.problem_sub_type = p.problem_sub_type
        AND r.problem_type = p.problem_type
        AND r.responsibility LIKE @Agent
        AND r.insert_time BETWEEN '2017-06-01 01:00:00' AND '2018-06-01 01:00:00'
        AND p.category_id BETWEEN '491' AND '1050'
        AND r.status IN ('3', '32')
        AND r.escalation IN ('0', '1', '2')
        GROUP BY
            p.category_id,
            p.problem_sub_type), CatList AS
    (SELECT
        COUNT (r.id) as 'count',
        p.category_id AS 'category'
    FROM
        service_req r RIGHT JOIN
        problem_type p ON r.problem_type = p.problem_type
        GROUP BY p.category_id)

    SELECT
        COALESCE(a.COUNT, 0) as 'count'
        --cl.category
    FROM
        Agent AS A RIGHT JOIN
        CatList AS cl ON a.category = cl.category
    ";

    $result = mssql_query($query);
    $numRows = mssql_num_rows($result);
    //display the results
    while ($row = mssql_fetch_array($result)) {

        $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = ".($row['count']);
        $result1 = mysqli_query($sql_connection,$query2);

    }

    ?>
</code>```

When i run the MSSQL portion of it with out put to the browser i do get results but when trying to update the Mysql db i am missing something.

UPDATE:

I have added the following line of code echo $row['count'] . "
"; in here:

```<code>   while ($row = mssql_fetch_array($result)) {

        echo $row['count'] . "<br />";
        $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = ".($row['count']);
        $result1 = mysqli_query($sql_connection,$query2) or die(mysqli_error($sql_connection));
 }
</code>```

and when running the script i can see my result set in the browser but none of the data is being pushed to the MySQL database.

UPDATE 2:

I have fixed my syntax issue here from this

```<code> $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = ".($row['count']);
</code>```

TO THIS:

```<code> $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = '".($row['count'])."'";
</code>```

But now it updates my MySQL database with only the first value in the result set. The returned data from the MSSQL query is 521 rows of data (different values) and this dataset needs to be updated as is to the new db.

UPDATE 3:

Here is the table structure for the MySQL table

```<code>id  points_cat_count    points_cat_id   points_cat_points   points_cat_total
1   0   491 0   0
2   0   492 3   0
3   0   493 0   0
4   0   494 1   0
5   0   495 1   0
6   0   496 1   0
7   0   497 3   0
</code>```

答:
Simply add a WHERE clause to UPDATE query as right now all rows are updated with each loop. Specifically, use the related fields, namely the category ids between both database tables.

Also, use prepared statements to parameterize queries. Notice prepared statement lies outside loop and only values are binded iteratively in loop:

```<code>$query2 = "UPDATE performance_engine_sysaidstat_dino
           SET points_cat_count = ? WHERE points_cat_id = ?";

while ($row = mssql_fetch_array($result)) {
   echo $row['count'] . "<br />";

   $stmt = $mysqli->prepare(query2);
   // ASSUMES COUNT IS STR AND CATEGORY IS INT
   $stmt->bind_param('si', $row['count'], $row['category'])
   $stmt->execute();

}

$stmt->close();
$mysqli->close();
</code>```

Body:
Running into a bit of an issue here that I can't seem to figure it out. I have a result set from a query on a MS-SQL database which I need to import into a MySQL database. Don't ask why, I just have to. Below is my code, but when I run it, it just doesn't do anything with the results. Can anyone help me?

      <?php

    putenv("TDSVER=80");
    putenv("FREETDSCONF=/etc/freetds/freetds.conf");
    putenv("ODBCSYSINI=/etc/odbcinst.ini");
    putenv("ODBCINI=/etc/odbc.ini");

    $myServer = "*****";
    $username = "*****";
    $password = "*****";
    $database = "*****";

    //connection to the database
    $dbhandle = mssql_connect($myServer, $username, $password)
    or die("Couldn't connect to SQL Server on $myServer");

    //select a database to work with
    $selected = mssql_select_db($database, $dbhandle)
    or die("Couldn't open database $myDB");

    $sql_connection = mysqli_connect("*****", "*****", "*****", "*****");
if (mysqli_connect_errno()) {
        echo "Failed to connect to the SQL Database: " . mysqli_connect_error();
    }

    $query = "DECLARE @Agent NVARCHAR(250) = '%*****%';
    WITH Agent AS
    (SELECT
        COUNT (r.id) as 'count',
        p.category_id AS 'category'
    FROM
        service_req r LEFT JOIN
        problem_type p on r.problem_type = p.problem_type
    WHERE
        r.problem_sub_type = p.problem_sub_type
        AND r.problem_type = p.problem_type
        AND r.responsibility LIKE @Agent
        AND r.insert_time BETWEEN '2017-06-01 01:00:00' AND '2018-06-01 01:00:00'
        AND p.category_id BETWEEN '491' AND '1050'
        AND r.status IN ('3', '32')
        AND r.escalation IN ('0', '1', '2')
        GROUP BY
            p.category_id,
            p.problem_sub_type), CatList AS
    (SELECT
        COUNT (r.id) as 'count',
        p.category_id AS 'category'
    FROM
        service_req r RIGHT JOIN
        problem_type p ON r.problem_type = p.problem_type
        GROUP BY p.category_id)

    SELECT
        COALESCE(a.COUNT, 0) as 'count'
        --cl.category
    FROM
        Agent AS A RIGHT JOIN
        CatList AS cl ON a.category = cl.category
    ";

    $result = mssql_query($query);
    $numRows = mssql_num_rows($result);
    //display the results
    while ($row = mssql_fetch_array($result)) {

        $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = ".($row['count']);
        $result1 = mysqli_query($sql_connection,$query2);

    }

    ?>

When i run the MSSQL portion of it with out put to the browser i do get results but when trying to update the Mysql db i am missing something.

UPDATE:

I have added the following line of code echo $row['count'] . "
"; in here:

   while ($row = mssql_fetch_array($result)) {

        echo $row['count'] . "
";
        $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = ".($row['count']);
        $result1 = mysqli_query($sql_connection,$query2) or die(mysqli_error($sql_connection));
 }

and when running the script i can see my result set in the browser but none of the data is being pushed to the MySQL database.

UPDATE 2:

I have fixed my syntax issue here from this

 $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = ".($row['count']);

TO THIS:

 $query2 = "UPDATE performance_engine_sysaidstat_dino SET points_cat_count = '".($row['count'])."'";

But now it updates my MySQL database with only the first value in the result set. The returned data from the MSSQL query is 521 rows of data (different values) and this dataset needs to be updated as is to the new db.

UPDATE 3:

Here is the table structure for the MySQL table

id  points_cat_count    points_cat_id   points_cat_points   points_cat_total
1   0   491 0   0
2   0   492 3   0
3   0   493 0   0
4   0   494 1   0
5   0   495 1   0
6   0   496 1   0
7   0   497 3   0

Body:
Simply add a WHERE clause to UPDATE query as right now all rows are updated with each loop. Specifically, use the related fields, namely the category ids between both database tables.

Also, use prepared statements to parameterize queries. Notice prepared statement lies outside loop and only values are binded iteratively in loop:

$query2 = "UPDATE performance_engine_sysaidstat_dino
           SET points_cat_count = ? WHERE points_cat_id = ?";

while ($row = mssql_fetch_array($result)) {
   echo $row['count'] . "<br />";

   $stmt = $mysqli->prepare(query2);
   // ASSUMES COUNT IS STR AND CATEGORY IS INT
   $stmt->bind_param('si', $row['count'], $row['category'])
   $stmt->execute();

}

$stmt->close();
$mysqli->close();


问:
how to call jquery's datepicker in angular?
I have installed jquery and jquery types and also tested the inclusion of jquery, by simply implementing a jquerys click function. The problem is that i am unable to call datepicker function.
 Here is the plunker link: http://plnkr.co/edit/3meCZf3Myg4VGzKv5x3u?p=preview
 This is how i have called datepicker in my component,

```<code>ngOnInit() {
        $(function() {
            (<any>$( ".datepicker" )).datepicker();
        });
        $(".datepicker" ).change(()=>{
            let startDate =  $( "#startdate" ).val();
            let endDate =  $( "#enddate" ).val();
            this.singleFilmEventFormService.formGroup.patchValue({
                startDate: startDate,
                endDate: endDate
            });
        });
    }
</code>```

The angular is complaining that  TypeError: $(...).datepicker is not a function

答:
In the top of your component file, with your import statements, try adding the following line.

declare var $: any;

Should set the $ as a variable/function/class.

Body:
I have installed jquery and jquery types and also tested the inclusion of jquery, by simply implementing a jquerys click function. The problem is that i am unable to call datepicker function.
 Here is the plunker link: http://plnkr.co/edit/3meCZf3Myg4VGzKv5x3u?p=preview
 This is how i have called datepicker in my component,

ngOnInit() {
        $(function() {
            (<any>$( ".datepicker" )).datepicker();
        });
        $(".datepicker" ).change(()=>{
            let startDate =  $( "#startdate" ).val();
            let endDate =  $( "#enddate" ).val();
            this.singleFilmEventFormService.formGroup.patchValue({
                startDate: startDate,
                endDate: endDate
            });
        });
    }

The angular is complaining that  TypeError: $(...).datepicker is not a function


答:
You can store it in the app.config of your project. Then if you wanted the user to give credentials you could make a form and save the string to the value of that configuration.

```<code><appSettings>
    <add key="connectionString" value="Connection string goes here"/>
</appSettings>
</code>```

Then call it and set it using the ConfigurationManager

```<code>ConfigurationManager.AppSettings["connectionString"] = "Your Value";
</code>```

Or you could just replace the connection string yourself in the file once its on the users computer

Body:
You can store it in the app.config of your project. Then if you wanted the user to give credentials you could make a form and save the string to the value of that configuration.

<appSettings>
    <add key="connectionString" value="Connection string goes here"/>
</appSettings>

Then call it and set it using the ConfigurationManager

ConfigurationManager.AppSettings["connectionString"] = "Your Value";

Or you could just replace the connection string yourself in the file once its on the users computer


问:
React-Native map data and save all items
I have this code:

```<code>  this.state.viaturas.map((item, index) =>
    this.setState({preco: item.Preco, codigo: item.CodViatura})
  )
</code>```

"preco" is only saving 1 item, when viaturas.map has more than 1 object, and more than 1 item.Preco.
And I want to save all item.Preco of all objects in an array or something.

Sorry for the bad explanation, but I've been dealing with bugs all day and I'm really tired.

答:
So all this is doing is looping over viaturas and overwriting preco with the next item in the loop. If I'm understanding correctly you want preco to be an array of all the preco's from viaturas and same with codigo so you can do something like this:</p>

```<code>const preco = this.state.viaturas.map(item => item.Preco);
const codigo = this.state.viaturas.map(item => item.Codviatura);
this.setState({ preco, codigo });
</code>```

Body:
I have this code:

  this.state.viaturas.map((item, index) =>
    this.setState({preco: item.Preco, codigo: item.CodViatura})
  )

"preco" is only saving 1 item, when viaturas.map has more than 1 object, and more than 1 item.Preco.
And I want to save all item.Preco of all objects in an array or something.

Sorry for the bad explanation, but I've been dealing with bugs all day and I'm really tired.

Body:
So all this is doing is looping over viaturas and overwriting preco with the next item in the loop. If I'm understanding correctly you want preco to be an array of all the preco's from viaturas and same with codigo so you can do something like this:

const preco = this.state.viaturas.map(item => item.Preco);
const codigo = this.state.viaturas.map(item => item.Codviatura);
this.setState({ preco, codigo });


问:
DOM specified Property return true
Someone told me if the attribute not defined, the specified value will return false. xms attribute did not have definition, but specified return true. What situation does specified return false?</p>

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button find out if the button has an onclick attribute specified.</p>

<button onclick="myFunction()" class="" xms >Try it</button>

<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
function myFunction() {
    var btn = document.getElementsByTagName("BUTTON")[0];
    var x = btn.getAttributeNode("onclick").specified;
    document.getElementById("demo").innerHTML = x;

        var y = btn.getAttributeNode("class").specified;
    document.getElementById("demo2").innerHTML = y;

        var z = btn.getAttributeNode("xms").specified;
    document.getElementById("demo3").innerHTML = z;

}
</script>

</body>
</html>
</code>```

答:
Just get the attribute values and check if they are equal to undefined.

```<code>var x = btn.getAttributeNode("onclick");
if (x !== undefined)
    document.getElementById("demo").innerHTML = x;
</code>```

EDIT:
To check if node exists and it have a real value

```<code>var a = btn.getAttributeNode("xms").specified;
var b = btn.getAttributeNode("xms").nodeValue;
if (!a || a===undefined || b=='') //It's like false, because the node doesn't exists or its value is empty
</code>```

Title: DOM specified Property return true

Body:
Someone told me if the attribute not defined, the specified value will return false. xms attribute did not have definition, but specified return true. What situation does specified return false?

<!DOCTYPE html>

Click the button find out if the button has an onclick attribute specified.

<button onclick="myFunction()" class="" xms >Try it</button>

Body:
Just get the attribute values and check if they are equal to undefined.

var x = btn.getAttributeNode("onclick");
if (x !== undefined)
    document.getElementById("demo").innerHTML = x;

EDIT:
To check if node exists and it have a real value

var a = btn.getAttributeNode("xms").specified;
var b = btn.getAttributeNode("xms").nodeValue;
if (!a || a===undefined || b=='') //It's like false, because the node doesn't exists or its value is empty


问:
PowerPoint 2013 VSTO Undo-Redo CustomerData or CustomXMLPart manipulation
I'm building a PowerPoint VSTO addin where I store a lot of metadata on the presentation.

I'm currently storing it as XML as either manipulating AddIn.Application.ActivePresentation.CustomXMLParts for global data and Slide.CustomerData for slide specific information.

The problem is that neither of them is represented on the Undo/Redo stack. I can make a quintrillion changes to the presentation and modify my Custom XML at the middle somewhere, undo everything and still read back the XML I have last set.

Since I want my modifications to be Undo/Redoable, the best I could think of is storing the XML on a Shape and delete+recreate it on every modification. The problem with this is that the user can obliviously delete the shape or the slide the shape is stored on.

I need something less visible (to prevent accidental removal) and - preferably global - object on the presentation that I can store my XML on that is deletable/recreatable and modifies that Undo/Redo stack.

Is there something like this?

Or is there a better way to do this?

答:
To answer my own question:

There is Tags!

When you add something to it with Tags.Add("Name", "Value") it is properly undoable, unlike CustomerData or CustomXMLParts.

Tags is present on the presentation and on the slides so both of my scenarios are covered.


问:
Is there a streaming API for JSON?
Is DOM the only way to parse JSON?</p>

答: In reply to your 2nd question, no, many languages have JSON parsers. PHP, Java, C, Ruby and many others. Just Google for the language of your choice plus "JSON parser".</p>

Title: Is there a streaming API for JSON?

Body: Is DOM the only way to parse JSON?

OwnerDisplayName: Ryan Doherty


问:
How to Configure Unity in n-tier ASP .net MVC application
I am having a little problem figuring out how to configure Unity IoC container in my n-tier ASP .net MVC application.

I have 3 projects in my solution:
1. MVC (Used as View) : Has referene to Business Logic Layer only
2. Business Logic Layer: Has reference to Repository project only
3. Respository: Do not have reference to any of the above projects

Please notice the way my reference work, I have done it like this so I will be able to replace the communication between my tiers using WCF with less difficulties.

I have configured a Unity container in my MVC application doing something like this (Global.asax):

container.RegisterType(); //MyService is in my Business Logic Layer

The MyService class uses my repository in its constructor meaning that when one of those MyService classes is created a MyRepository is also required:

public MyService(IRepository repository) : base(repository)
 {       }

As you can see I still have not configured IRepository in my container.

I don't want to do it in my Global.asax because i dont want to add any reference of Repository to MVC (View) tier.

Where is the best place to configure this ? I am kind of confused here....

Thanks in advance.

答:
Let me tell you what I did so far:

I created a static class in my Service and Repository Later, I create the Unity container in my View Layer (MVC) and pass it to those static classes, they populate the container with what they need plus the next layer, for example service layer also call the static class in my repository.

This way I configure the container with everything i need.

The question is : is this a good thing to do ?


问:
Angular 2 Asp.net core Loading page without a shared layout
I would like to know how to have a login page while using angular 2 with asp.net core, that does not uses the shared layout and does not load other components in it.

For example my app.component.html looks like this:

```<code><nav-menu></nav-menu>

<top-nav></top-nav>

<router-outlet></router-outlet>
</code>```

And I would like to be able to have a login page that does not include the nav-menu and top-nav.

In theory the login page would be the default page.

I am not understanding how this is possible with Angular 2.

Many thanks

答:
I manage to solve this issue by using 2 main components, one for login and other for navigation.

Inside the navigation component I added all the other components as children.

If anyone wants help on this I can explain it better, just a leave a comment.

Body:
I would like to know how to have a login page while using angular 2 with asp.net core, that does not uses the shared layout and does not load other components in it.

For example my app.component.html looks like this:

<top-nav></top-nav>

<router-outlet></router-outlet>

And I would like to be able to have a login page that does not include the nav-menu and top-nav.

In theory the login page would be the default page.

I am not understanding how this is possible with Angular 2.

Many thanks


问:
jq - nested dictionary parser and extract key
I am trying to parse with jq the following structure:

```<code>{
    "a": {
        "sensitive": false,
        "type": "string",
        "value": "mykeypair"
    },
    "b": {
        "sensitive": false,
        "type": "string",
        "value": "123"
    }
}
</code>```

and get this as an output:

```<code>{
        "a": "mykeypair",
        "b": "123"
}
</code>```

I would like the key and as a value, the value of the field 'value'.
Any idea?
Cheers,

答:
I think this is what you are looking for:

```<code>[ to_entries[] | .value = .value.value ] | from_entries
</code>```

A simpler way:

```<code>with_entries(.value |= .value)
</code>```

Check the result here:

https://jqplay.org/s/uHqfdPoF3e

Body:
I am trying to parse with jq the following structure:

{
    "a": {
        "sensitive": false,
        "type": "string",
        "value": "mykeypair"
    },
    "b": {
        "sensitive": false,
        "type": "string",
        "value": "123"
    }
}

and get this as an output:

{
        "a": "mykeypair",
        "b": "123"
}

I would like the key and as a value, the value of the field 'value'.
Any idea?
Cheers,

Body:
I think this is what you are looking for:

[ to_entries[] | .value = .value.value ] | from_entries

A simpler way:

with_entries(.value |= .value)

Check the result here:

https://jqplay.org/s/uHqfdPoF3e


问:
How to get a self-closing xml tag in Oracle PLSQL?
The Requested output is should be as follows:

```<code><Consignment id="123" date="2017-06-08">
    <Box id="321" />
</Consignment>
</code>```

where the <box> tag should be self-closing as above.

I am using the following code:

```<code>SELECT XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
            XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
                 ).getstringval() as xxx FROM DUAL;
</code>```

but it always return the following results (where the tag <box> has a separated closing tag </box>):

```<code><Consignment id="123" date="2017-06-08">
    <Box id="321"></Box>
</Consignment>
</code>```

how to get the above <box> tag self-closed?

答:
If you pass your generated XML fragment/document through the XMLSerialize() function, and specify either INDENT or NO INDENT, then empty tags will be transformed to be self-closed. (Not specifying either leaves them untouched).

```<code>SELECT XMLSerialize(CONTENT
    XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
      XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
  ) as VARCHAR2(4000) INDENT) as xxx FROM DUAL;

XXX
--------------------------------------------------------------------------------
<Consignment id="123" date="2017-06-08">
  <Box id="321"/>
</Consignment>
</code>```

or without formatting:

```<code>SELECT XMLSerialize(CONTENT
    XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
      XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
  ) as VARCHAR2(4000) NO INDENT) as xxx FROM DUAL;

XXX
--------------------------------------------------------------------------------
<Consignment id="123" date="2017-06-08"><Box id="321"/></Consignment>
</code>```

Your question shows the output as indented, but the code you provided does not indent it, so not really sure which of those you actually want.

I've used VARCHAR2 for the data type based on your use of getStringVal, and you can make that smaller if you know the size - or switch to CLOB if you don't, or know it might be too big for VARCHAR2.

Body:
The Requested output is should be as follows:

<Consignment id="123" date="2017-06-08">
    <Box id="321" />
</Consignment>

where the <box> tag should be self-closing as above.

I am using the following code:

SELECT XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
            XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
                 ).getstringval() as xxx FROM DUAL;

but it always return the following results (where the tag <box> has a separated closing tag </box>):

<Consignment id="123" date="2017-06-08">
    <Box id="321"></Box>
</Consignment>

how to get the above <box> tag self-closed?

Body:
If you pass your generated XML fragment/document through the XMLSerialize() function, and specify either INDENT or NO INDENT, then empty tags will be transformed to be self-closed. (Not specifying either leaves them untouched).

SELECT XMLSerialize(CONTENT
    XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
      XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
  ) as VARCHAR2(4000) INDENT) as xxx FROM DUAL;

XXX
--------------------------------------------------------------------------------
<Consignment id="123" date="2017-06-08">
  <Box id="321"/>
</Consignment>

or without formatting:

SELECT XMLSerialize(CONTENT
    XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
      XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
  ) as VARCHAR2(4000) NO INDENT) as xxx FROM DUAL;

XXX
--------------------------------------------------------------------------------
<Consignment id="123" date="2017-06-08"><Box id="321"/></Consignment>

Your question shows the output as indented, but the code you provided does not indent it, so not really sure which of those you actually want.

I've used VARCHAR2 for the data type based on your use of getStringVal, and you can make that smaller if you know the size - or switch to CLOB if you don't, or know it might be too big for VARCHAR2.


问:
Binding SortedList comparator to TableView comparator removes sort
I have a SortedList that backs the data in a TableView. I want to sort the data by a particular column following queries to the database, but I want to maintain the TableView's interactive sorting functionality. My code:

```<code>sortedData = new SortedList<>(data, new TableSort(sortIndex));
sortedData.comparatorProperty().bind(Table.comparatorProperty());
Table.setItems(sortedData);
</code>```

However, when I bind the SortedList comparator to the TableView, my original comparator TableSort is ignored, and the data appears unsorted. If I choose not to bind comparators, my data is sorted correctly, but I can't perform interactive column sorting. How can I get the best of both worlds here? Thank you for your help.

答:
So if you want to sort them initially before you put them in the table its quite simple.
I have a class TestRow that holds the information in the table, and implements the Comparable interface:

```<code>package stackoverflow;

import javafx.beans.property.SimpleStringProperty;

public class TestRow implements Comparable<TestRow> {

    private SimpleStringProperty name;
    private SimpleStringProperty age;

    public TestRow(String name, String age) {
        this.name = new SimpleStringProperty(name);
        this.age = new SimpleStringProperty(age);
    }

    public String getName() {
        return name.get();
    }

    public SimpleStringProperty nameProperty() {
        return name;
    }

    public String getAge() {
        return age.get();
    }

    public SimpleStringProperty ageProperty() {
        return age;
    }

    @Override
    public int compareTo(TestRow that) {
        return this.getName().compareTo(that.getName());
    }

}
</code>```

Then in my controller i simply added two rows :

```<code>TestRow first = new TestRow("Steve", "20");
TestRow second = new TestRow("Mike", "22");
ObservableList<TestRow> data = FXCollections.observableArrayList(Arrays.asList(first, second));
</code>```

They you can simply call the Collections.sort(data);, then you can do the rest part, that you already have.

Body:
I have a SortedList that backs the data in a TableView. I want to sort the data by a particular column following queries to the database, but I want to maintain the TableView's interactive sorting functionality. My code:

sortedData = new SortedList<>(data, new TableSort(sortIndex));
sortedData.comparatorProperty().bind(Table.comparatorProperty());
Table.setItems(sortedData);

However, when I bind the SortedList comparator to the TableView, my original comparator TableSort is ignored, and the data appears unsorted. If I choose not to bind comparators, my data is sorted correctly, but I can't perform interactive column sorting. How can I get the best of both worlds here? Thank you for your help.

Body:
So if you want to sort them initially before you put them in the table its quite simple.
I have a class TestRow that holds the information in the table, and implements the Comparable interface:

package stackoverflow;

import javafx.beans.property.SimpleStringProperty;

public class TestRow implements Comparable<TestRow> {

    private SimpleStringProperty name;
    private SimpleStringProperty age;

    public TestRow(String name, String age) {
        this.name = new SimpleStringProperty(name);
        this.age = new SimpleStringProperty(age);
    }

    public String getName() {
        return name.get();
    }

    public SimpleStringProperty nameProperty() {
        return name;
    }

    public String getAge() {
        return age.get();
    }

    public SimpleStringProperty ageProperty() {
        return age;
    }

    @Override
    public int compareTo(TestRow that) {
        return this.getName().compareTo(that.getName());
    }

}

Then in my controller i simply added two rows :

TestRow first = new TestRow("Steve", "20");
TestRow second = new TestRow("Mike", "22");
ObservableList<TestRow> data = FXCollections.observableArrayList(Arrays.asList(first, second));

They you can simply call the Collections.sort(data);, then you can do the rest part, that you already have.


问:
how to make html5 canvas background pattern responsive
I have a chart made with chart.js...I want to make a background image for my canvas responsive...I made something about that...you can see with this link...

Bu I cannot make this background image responsive (or fit to canvas width and height)...anyone can help me?

```<code>var img = new Image();
img.src = 'http://www.360kreatif.com/ersen/efektler/images/light.png';
var canvas = document.getElementById("myChart");
var context = canvas.getContext('2d');
var fillPattern = context.createPattern(img, 'repeat');
context.fillStyle = fillPattern;
context.fillRect(0, 0, 100, 100);

var myChart = new Chart(canvas, {
    type: 'pie',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [1, 1, 1, 1, 1, 1],
            displacements: [2, 2, 2, 2, 2, 2],
            backgroundColor: fillPattern,
            borderColor: [
                'rgba(255,99,132,0)',
                'rgba(54, 162, 235, 0)',
                'rgba(255, 206, 86, 0)',
                'rgba(75, 192, 192, 0)',
                'rgba(153, 102, 255, 0)',
                'rgba(255, 159, 64, 0)'
            ],
            borderWidth: 1,
            cutoutPercentage:5
            }]
        },
        options: {
            responsive: true,
                legend: {
                    display: false,
                },
                tooltips: {
                    enabled: false,
                },
                title: {
                    display: false,
                },
                animation: {
                    animateScale: true,
                    animateRotate: true
                }
        }
    });
</code>```

答: The Canvas tag is pixel based, so by definition it isnt responsive - if you need a responsive image you should try using the SVG tag, which uses vector graphics (which are responsive).</p>

Body:
I have a chart made with chart.js...I want to make a background image for my canvas responsive...I made something about that...you can see with this link...

Bu I cannot make this background image responsive (or fit to canvas width and height)...anyone can help me?

var img = new Image();
img.src = 'http://www.360kreatif.com/ersen/efektler/images/light.png';
var canvas = document.getElementById("myChart");
var context = canvas.getContext('2d');
var fillPattern = context.createPattern(img, 'repeat');
context.fillStyle = fillPattern;
context.fillRect(0, 0, 100, 100);

var myChart = new Chart(canvas, {
    type: 'pie',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [1, 1, 1, 1, 1, 1],
            displacements: [2, 2, 2, 2, 2, 2],
            backgroundColor: fillPattern,
            borderColor: [
                'rgba(255,99,132,0)',
                'rgba(54, 162, 235, 0)',
                'rgba(255, 206, 86, 0)',
                'rgba(75, 192, 192, 0)',
                'rgba(153, 102, 255, 0)',
                'rgba(255, 159, 64, 0)'
            ],
            borderWidth: 1,
            cutoutPercentage:5
            }]
        },
        options: {
            responsive: true,
                legend: {
                    display: false,
                },
                tooltips: {
                    enabled: false,
                },
                title: {
                    display: false,
                },
                animation: {
                    animateScale: true,
                    animateRotate: true
                }
        }
    });


问:
REGEX Match [WildCard] but not [WildCard].[WildCard]
Using C# Regex

Example

Simple Input: [testA].[max] [testB]

Match: [testB]

Input: 5/[test1]  [test2].[max]  [test3]*2 [min]

Match:[test1] [test3] [min]

Definition

I want to match anything with like [Whatever] but not match [Whatever].[(min|max|mean|sum|median)]

Attempt

This works sort of it does not match [min] on its own.

```<code>(?!\[((\w|[.])+)\]\.\[(min|max|mean|sum|median)\])\[((?!min|max|mean|sum|median).+?)\]
</code>```

答:
How about

```<code>(?<!\.)\[[A-Za-z0-9]*\](?!\.\[.*\])
</code>```

(?<!\.) - Negative lookbehind to prevent .[max] matching matching as well.

\[[A-Za-z0-9]*\] - Match [...], add other characters if necessary.

(?!\.\[.*\]) - Negative lookahead to ignore [...].[...].

Body:
Using C# Regex

Example

Simple Input: [testA].[max] [testB]

Match: [testB]

Input: 5/[test1]  [test2].[max]  [test3]*2 [min]

Match:[test1] [test3] [min]

Definition

I want to match anything with like [Whatever] but not match [Whatever].[(min|max|mean|sum|median)]

Attempt

This works sort of it does not match [min] on its own.

(?!\[((\w|[.])+)\]\.\[(min|max|mean|sum|median)\])\[((?!min|max|mean|sum|median).+?)\]

Body:
How about

(?<!\.)\[[A-Za-z0-9]*\](?!\.\[.*\])

(?<!\.) - Negative lookbehind to prevent .[max] matching matching as well.

\[[A-Za-z0-9]*\] - Match [...], add other characters if necessary.

(?!\.\[.*\]) - Negative lookahead to ignore [...].[...].


问:
How do you reverse an iterator's flow?
Is it possible to access the previous value of an iterator, for example:

```<code>function* gen () {
   yield* [0,1,2,3]
}

var it = gen();

it.next().value // 0
it.next().value // 1
it.last().value // would be awesome if this was 0
</code>```

This is strictly a curiosity question. I've been playing with generators lately and was wondering if anyone uses generators/iterators in this manner?

If so, I would love to see your solution. (Doesn't need to follow the above syntax) -Thanks

答:
No, this is not generally possible. Iterators can only be advanced, not reversed or anything else.

Of course you can write your own iterator wrapper that caches the last value and makes it accessible in whatever way you like.

Title: How do you reverse an iterator's flow?

Body:
Is it possible to access the previous value of an iterator, for example:

function* gen () {
   yield* [0,1,2,3]
}

var it = gen();

it.next().value // 0
it.next().value // 1
it.last().value // would be awesome if this was 0

This is strictly a curiosity question. I've been playing with generators lately and was wondering if anyone uses generators/iterators in this manner?

If so, I would love to see your solution. (Doesn't need to follow the above syntax) -Thanks


问:
Nested dictionary comprehension to avoid empty values
I have an api call that returns a dictionary with all the ids for all users
and others to get the userDetails like:

```<code>>>> allIds=api.getAllIds()
{1,2,3,4,5}
>>> userDetails=api.getUserDetails(1)
{'name':'Bob','age':'19'}
</code>```

I'm trying to pack the whole structure in a dict with the userId-like key and the info-like value.

I could make it work with:

```<code>>>> users={id:api.getUserDetails(id) for id in allIds}
{1:{'name':'bob','age':'19'},2:None,3:{'name':'alice','age':'21'},...}
</code>```

The problem is that not all Ids returns a response as you can see for the id 2 call. I'm trying not to use traditional loops and I'm solving the situation cleaning the resulting dict after the calls with:

```<code>>>> users=[id:users[id] for id in users.keys() if users[id]!=None]
</code>```

It's working, but I'm trying not to put inside the empty values instead of cleaning. In a normal situation you could create the dict like:

```<code>>>> a=[id:b[id] for id in b.keys() if b[id]!=None ]
</code>```

But in my case if I check if b[i] is None... then I'm calling the api two times because my b[i] expression is api.getUserDetails(id), one to take the value and the other to check if is not None.

So I'm trying something like nested dictionary comprehension:

```<code>users = {(x,y) for x in usersIds for y in api.getUserDetails(x) if y!=None }
</code>```

But I can not make it work.

Anyone know how to do it?

答:
You can put the result of the api call in a singleton tuple:

```<code>users = {x: y for x in usersIds for y in (api.getUserDetails(x),) if y is not None}
</code>```

Demo:

```<code>lst = [(5,6), (2,None)]
d = {k: v for k, x in lst for v in (x,) if v is not None}
print(d)
# {5: 6}
</code>```

However, it is pretty wasteful to set up a nested loop for such and may be more readable to use a vanilla for loop to build the dictionary:

```<code>users = {}
for x in usersIds:
    y = api.getUserDetails(x)
    if y is not None:
        users[x] = y
</code>```

Body:
I have an api call that returns a dictionary with all the ids for all users
and others to get the userDetails like:

>>> allIds=api.getAllIds()
{1,2,3,4,5}
>>> userDetails=api.getUserDetails(1)
{'name':'Bob','age':'19'}

I'm trying to pack the whole structure in a dict with the userId-like key and the info-like value.

I could make it work with:

>>> users={id:api.getUserDetails(id) for id in allIds}
{1:{'name':'bob','age':'19'},2:None,3:{'name':'alice','age':'21'},...}

The problem is that not all Ids returns a response as you can see for the id 2 call. I'm trying not to use traditional loops and I'm solving the situation cleaning the resulting dict after the calls with:

>>> users=[id:users[id] for id in users.keys() if users[id]!=None]

It's working, but I'm trying not to put inside the empty values instead of cleaning. In a normal situation you could create the dict like:

>>> a=[id:b[id] for id in b.keys() if b[id]!=None ]

But in my case if I check if b[i] is None... then I'm calling the api two times because my b[i] expression is api.getUserDetails(id), one to take the value and the other to check if is not None.

So I'm trying something like nested dictionary comprehension:

users = {(x,y) for x in usersIds for y in api.getUserDetails(x) if y!=None }

But I can not make it work.

Anyone know how to do it?

Body:
You can put the result of the api call in a singleton tuple:

users = {x: y for x in usersIds for y in (api.getUserDetails(x),) if y is not None}

Demo:

lst = [(5,6), (2,None)]
d = {k: v for k, x in lst for v in (x,) if v is not None}
print(d)
# {5: 6}

However, it is pretty wasteful to set up a nested loop for such and may be more readable to use a vanilla for loop to build the dictionary:

users = {}
for x in usersIds:
    y = api.getUserDetails(x)
    if y is not None:
        users[x] = y


问:
Assigning a value to a specific column in a multidimensional array (C)
I'm trying to find a way to assign a specific column to a specific value in a multidimensional array

Per below, I'm aware of how to assign it manually and through a for loop.

Is there an easier way to go about doing it? thanks

```<code>#include < stdio.h >
double Test1[4][5];
double a0, a1, a2, a3;

int main() {
  //Assigning one column in a specific row manually
  Test1[1][1] = 1;
  a0 = Test1[0][1];
  a1 = Test1[1][1];
  a2 = Test1[2][1];
  a3 = Test1[3][1];

  printf("a0  %f \r\n", a0);
  printf("a1  %f \r\n", a1);
  printf("a2  %f \r\n", a2);
  printf("a3  %f \r\n", a3);

  int row = sizeof(Test1) / sizeof(Test1[0]);
  printf("rows  %d \r\n", row);
  int column = sizeof(Test1[0]) / sizeof(Test1[0][0]);
  printf("cols  %d \r\n", column);

  int L;
  double a;
  //Assigning one column in all rows to one
  for (L = 0; L < row; L = L + 1) {
    Test1[L][1] = 1;
  }

  a0 = Test1[0][1];
  a1 = Test1[1][1];
  a2 = Test1[2][1];
  a3 = Test1[3][1];

  printf("a0  %f \r\n", a0);
  printf("a1  %f \r\n", a1);
  printf("a2  %f \r\n", a2);
  printf("a3  %f \r\n", a3);

  return 0;
}
</code>```

答:
There is no standard function that sets a column of a 2D array. In C, multidimensional arrays are a bit of an illusion; they compile into 1D arrays. Here is some code to demonstrate that the values unwind into a 1D array:</p>

```<code>#include <stdio.h>

int main(){
    int test[10][2] = {0};
    //point to the 1st element
    int * p1 = &test[0][0];

    //20th position is the 9th row, 2nd column
    p1[19] = 5;

    //9th element is the 5th row, 1st column
    int * p2 = p1 + 8;
    *p2 = 4;

    printf("Value set to 5: %d\n",test[9][1]);
    printf("Value set to 4: %d\n",test[4][0]);
}
</code>```

Body:
I'm trying to find a way to assign a specific column to a specific value in a multidimensional array

Per below, I'm aware of how to assign it manually and through a for loop.

Is there an easier way to go about doing it? thanks

#include < stdio.h >
double Test1[4][5];
double a0, a1, a2, a3;

int main() {
  //Assigning one column in a specific row manually
  Test1[1][1] = 1;
  a0 = Test1[0][1];
  a1 = Test1[1][1];
  a2 = Test1[2][1];
  a3 = Test1[3][1];

  printf("a0  %f \r\n", a0);
  printf("a1  %f \r\n", a1);
  printf("a2  %f \r\n", a2);
  printf("a3  %f \r\n", a3);

  int row = sizeof(Test1) / sizeof(Test1[0]);
  printf("rows  %d \r\n", row);
  int column = sizeof(Test1[0]) / sizeof(Test1[0][0]);
  printf("cols  %d \r\n", column);

  int L;
  double a;
  //Assigning one column in all rows to one
  for (L = 0; L < row; L = L + 1) {
    Test1[L][1] = 1;
  }

  a0 = Test1[0][1];
  a1 = Test1[1][1];
  a2 = Test1[2][1];
  a3 = Test1[3][1];

  printf("a0  %f \r\n", a0);
  printf("a1  %f \r\n", a1);
  printf("a2  %f \r\n", a2);
  printf("a3  %f \r\n", a3);

  return 0;
}

Body:
There is no standard function that sets a column of a 2D array. In C, multidimensional arrays are a bit of an illusion; they compile into 1D arrays. Here is some code to demonstrate that the values unwind into a 1D array:

#include <stdio.h>

int main(){
    int test[10][2] = {0};
    //point to the 1st element
    int * p1 = &test[0][0];

    //20th position is the 9th row, 2nd column
    p1[19] = 5;

    //9th element is the 5th row, 1st column
    int * p2 = p1 + 8;
    *p2 = 4;

    printf("Value set to 5: %d\n",test[9][1]);
    printf("Value set to 4: %d\n",test[4][0]);
}


问:
storing xml in azure table storage
I have a very simple jobs table (currently in sql server) with the following fields:
jobid - int type
details - xml type

I want to move all of this data from sql server to azure table storage. But I don't know how to store the xml data in table storage as I don't believe it supports XML. The app that I will create will only read the xml data - never update/delete it. Any suggestions?

答:
You're correct that Azure Tables does not have an XML data type. It does have String data type. What you could do is convert the XML data into string and then save the data. Please see sample code below:

```<code>    static void SaveDataInTable(int jobId, XDocument details)
    {
        var cred = new StorageCredentials(accountName, accountKey);
        var account = new CloudStorageAccount(cred, true);
        var client = account.CreateCloudTableClient();
        var table = client.GetTableReference("MyTable");
        table.CreateIfNotExists();
        var entity = new DynamicTableEntity(partitionKey: "PK", rowKey: "RK");
        entity.Properties.Add("jobId", new EntityProperty(jobId));
        entity.Properties.Add("details", new EntityProperty(details.ToString()));//Convert XML to string
        var insertOperation = TableOperation.Insert(entity);
        table.Execute(insertOperation);
    }
</code>```

Title: storing xml in azure table storage

Body:
You're correct that Azure Tables does not have an XML data type. It does have String data type. What you could do is convert the XML data into string and then save the data. Please see sample code below:

    static void SaveDataInTable(int jobId, XDocument details)
    {
        var cred = new StorageCredentials(accountName, accountKey);
        var account = new CloudStorageAccount(cred, true);
        var client = account.CreateCloudTableClient();
        var table = client.GetTableReference("MyTable");
        table.CreateIfNotExists();
        var entity = new DynamicTableEntity(partitionKey: "PK", rowKey: "RK");
        entity.Properties.Add("jobId", new EntityProperty(jobId));
        entity.Properties.Add("details", new EntityProperty(details.ToString()));//Convert XML to string
        var insertOperation = TableOperation.Insert(entity);
        table.Execute(insertOperation);
    }


问:
Is it possible to iterate through an array list with elements of different data types and put them out?
Without generics it is possible to create an ArrayList with elements of different types. I want to iterate through it and put out the elements. I can not use a for-each-loop, because it wants a specific type. I tried Iterator but wasn't successful.

So I have two questions:

Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which type they are?

Is it possible to iterate through an array list and put out only the elements which are of a specific type (e. g. only the Strings)?

答:
Is it possible to iterate through an array list and put out (e. g.
  with System.out.println) all elements no matter of which file type
  they are?

Yes, You can use the Object class

```<code>List<Object> myList = new ArrayList<>();
myList.add("Hello World"); // string
myList.add(Math.PI); // a double
myList.add(188); // an int
myList.add(9099099999999L); // a Long
// for java8
myList.forEach(System.out::println);
//before java8
for (Object object : myList) {
    System.out.println(object);
}
</code>```

Is it possible to iterate through an array list and put out only the
  elements which are of a specific file type (e. g. only the strings)?

Yes, you can use the iterator and get the Object checking it against the class you need....

```<code>    Iterator<Object> it = myList.iterator();
    while (it.hasNext()) {
        Object x = it.next();
        if (x instanceof String) {
            System.out.println("this is a String: " + x);
        }
    }
</code>```

Body:
Is it possible to iterate through an array list and put out (e. g.
  with System.out.println) all elements no matter of which file type
  they are?

Yes, You can use the Object class

List<Object> myList = new ArrayList<>();
myList.add("Hello World"); // string
myList.add(Math.PI); // a double
myList.add(188); // an int
myList.add(9099099999999L); // a Long
// for java8
myList.forEach(System.out::println);
//before java8
for (Object object : myList) {
    System.out.println(object);
}

Is it possible to iterate through an array list and put out only the
  elements which are of a specific file type (e. g. only the strings)?

Yes, you can use the iterator and get the Object checking it against the class you need....

    Iterator<Object> it = myList.iterator();
    while (it.hasNext()) {
        Object x = it.next();
        if (x instanceof String) {
            System.out.println("this is a String: " + x);
        }
    }


问:
Dynamically Generated Grid of Images
I'm writing a Winform application that processes a grid of products printed on a sheet. To more effectively communicate with my end user I've been tasked with creating a visual representation of the grid (as opposed to just giving them "Row x Col y in text" ) to depict which items on the sheet could not be processed.

My first thought was to use a grid of images (green check mark/red X) aligned in a grid to match the sheet that the app will actually process. The problem with that approach is that eventually we'll have different jobs that use different sheet alignments. One might be a 3x10 grid, another might be a 1x8 etc.

Is there something I can use to define an area of my form as reserved for images, and also a way to insert copies of my image file that have been resized to fit in that area?

Something like:

```<code>container.add(
    new Image("myFileLocation", imgHeight, imgWidth),
    (container.height / numRows),
    (container.width/numCols)
    );
</code>```

?

Sorry if this is a stupid question. I'm comfortable in c# but have approximately zero experience designing GUIs for these things.

答:
@ASh that's exactly what I wanted, thanks.

In case it helps anyone else out there here are some references that I found useful to learn how to use TableLayoutPanels:

Generate rows/columns at runtime.
TableLayoutPanel rows & columns at runtime

Add image file to picturebox
Set image source to picturebox which is added dynamically to Table Layout Panel

Resize image inside picturebox (stretch to fill)
Fit Image into PictureBox

Center images inside cells
https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control

My code:

```<code>int rows = 7; //Will come from database
int cols = 3; //Will come from database
int colWidth;
int rowHeight;
PictureBox pbox;
Random rnd = new Random();

colWidth = 100 / cols;
if (100 % cols != 0)
    colWidth--;

rowHeight = 100 / rows;
if (100 % rows != 0)
    rowHeight--;

tabLP.Controls.Clear();
tabLP.ColumnStyles.Clear();
tabLP.RowStyles.Clear();

tabLP.ColumnCount = cols;

for (int i = 0; i < rows; i++)
{
    tabLP.RowStyles.Add(new RowStyle(SizeType.Percent, rowHeight));
    for (int j = 0; j < cols; j++)
    {
        tabLP.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, colWidth));

        if (rnd.NextDouble() > 0.5 )
        {
            pbox = new PictureBox() { Image = Properties.Resources.red_X};
        }
        else
        {
            pbox = new PictureBox() { Image = Properties.Resources.checkbox_green };
        }

        pbox.Dock = DockStyle.Fill;
        pbox.SizeMode = PictureBoxSizeMode.StretchImage;
        tabLP.Controls.Add(pbox, j, i);
    }

}
</code>```

Title: Dynamically Generated Grid of Images

Body:
I'm writing a Winform application that processes a grid of products printed on a sheet. To more effectively communicate with my end user I've been tasked with creating a visual representation of the grid (as opposed to just giving them "Row x Col y in text" ) to depict which items on the sheet could not be processed.

My first thought was to use a grid of images (green check mark/red X) aligned in a grid to match the sheet that the app will actually process. The problem with that approach is that eventually we'll have different jobs that use different sheet alignments. One might be a 3x10 grid, another might be a 1x8 etc.

Is there something I can use to define an area of my form as reserved for images, and also a way to insert copies of my image file that have been resized to fit in that area?

Something like:

container.add(
    new Image("myFileLocation", imgHeight, imgWidth),
    (container.height / numRows),
    (container.width/numCols)
    );

?

Sorry if this is a stupid question. I'm comfortable in c# but have approximately zero experience designing GUIs for these things.

Body:
@ASh that's exactly what I wanted, thanks.

In case it helps anyone else out there here are some references that I found useful to learn how to use TableLayoutPanels:

Generate rows/columns at runtime.
TableLayoutPanel rows & columns at runtime

Add image file to picturebox
Set image source to picturebox which is added dynamically to Table Layout Panel

Resize image inside picturebox (stretch to fill)
Fit Image into PictureBox

Center images inside cells
https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control

My code:

int rows = 7; //Will come from database
int cols = 3; //Will come from database
int colWidth;
int rowHeight;
PictureBox pbox;
Random rnd = new Random();

colWidth = 100 / cols;
if (100 % cols != 0)
    colWidth--;

rowHeight = 100 / rows;
if (100 % rows != 0)
    rowHeight--;

tabLP.Controls.Clear();
tabLP.ColumnStyles.Clear();
tabLP.RowStyles.Clear();

tabLP.ColumnCount = cols;

for (int i = 0; i < rows; i++)
{
    tabLP.RowStyles.Add(new RowStyle(SizeType.Percent, rowHeight));
    for (int j = 0; j < cols; j++)
    {
        tabLP.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, colWidth));

        if (rnd.NextDouble() > 0.5 )
        {
            pbox = new PictureBox() { Image = Properties.Resources.red_X};
        }
        else
        {
            pbox = new PictureBox() { Image = Properties.Resources.checkbox_green };
        }

        pbox.Dock = DockStyle.Fill;
        pbox.SizeMode = PictureBoxSizeMode.StretchImage;
        tabLP.Controls.Add(pbox, j, i);
    }

}


问:
Destructured parameter properties in constructor
Typescript allows parameter properties

```<code>class ParameterProperty {
  constructor(private member: number) {}
}
</code>```

The above creates a class with private member member, the constructor sets this.member to the  first argument of the constructor.

But there is no equivalent for 'named parameters' via destructuring.

```<code>interface DestructedOptions {
  prefix: string;
  suffix: string;
}

class Destructed {
  constructor({private prefix, private suffix}: DestructedOptions) {}
}
</code>```

The above doesn't work, you have to do something  like this:

```<code>class Destructed {
  private prefix: string
  private suffix: string
  constructor({prefix, suffix}: DestructedOptions) {
    this.prefix = prefix;
    this.suffix = suffix;
  }
}
</code>```

which is really verbose and requires updates to three places when adding a new property to DestructuredOptions. I tried something similar, using mapped properties

```<code>class Destructed {
  private [P in keyof DestructedOptions]: T[DestructedOptions];
  constructor(opts: DestructedOptions) {
    Object.assign(this, opts)
  }
}
</code>```

Only to find out that mapped properties can only be used in Types, not interfaces or classes. I don't like this option anyway since it copies everything from opts, I would really want something like this:

```<code>class Destructed {
  constructor(opts: DestructedOptions) {
    for (let key in keyof DestructedOptions) {
      this[key] = opts[key];
    }
  }
}
</code>```

But of course typescript doesn't let you get runtime values from Types.

答:
In ECMAScript, destructuring assignment results in variables in variables (not properties than properties) receiving the component values.

There has been a TypeScript feature request/suggestion for combining destructuring with parameter properties open since October of 2015.   That would probably be the most effective place to track the status of whatyou want.

Body:
Typescript allows parameter properties

class ParameterProperty {
  constructor(private member: number) {}
}

The above creates a class with private member member, the constructor sets this.member to the  first argument of the constructor.

But there is no equivalent for 'named parameters' via destructuring.

interface DestructedOptions {
  prefix: string;
  suffix: string;
}

class Destructed {
  constructor({private prefix, private suffix}: DestructedOptions) {}
}

The above doesn't work, you have to do something  like this:

class Destructed {
  private prefix: string
  private suffix: string
  constructor({prefix, suffix}: DestructedOptions) {
    this.prefix = prefix;
    this.suffix = suffix;
  }
}

which is really verbose and requires updates to three places when adding a new property to DestructuredOptions. I tried something similar, using mapped properties

class Destructed {
  private [P in keyof DestructedOptions]: T[DestructedOptions];
  constructor(opts: DestructedOptions) {
    Object.assign(this, opts)
  }
}

Only to find out that mapped properties can only be used in Types, not interfaces or classes. I don't like this option anyway since it copies everything from opts, I would really want something like this:

class Destructed {
  constructor(opts: DestructedOptions) {
    for (let key in keyof DestructedOptions) {
      this[key] = opts[key];
    }
  }
}

But of course typescript doesn't let you get runtime values from Types.