问:
How to get only the unique values out of a list of strings in C#?
Is there an easy way to get only the unique values out of a list of strings in C#?  My google-fu is failing me today.

(I know I can put them in another structure and pull them out again.  I'm looking for stupidly-easy, like Ruby's .uniq method.  C# has bloody well everything else, so I'm probably just using the wrong synonym.)

Specifically, this is coming from Linq, so if Linq had a built-in way to select only unique strings, that would be even cooler.

答:
In .net 3.5:-

```<code>var strings = new List<string> { "one", "two", "two", "three" };
var distinctStrings = strings.Distinct(); // IEnumerable<string>
var listDistinctStrings = distinctStrings.ToList(); // List<string>
</code>```

Boom shaka-laka!

OwnerDisplayName: Ken

Body:
In .net 3.5:-

var strings = new List<string> { "one", "two", "two", "three" };
var distinctStrings = strings.Distinct(); // IEnumerable<string>
var listDistinctStrings = distinctStrings.ToList(); // List<string>

Boom shaka-laka!

OwnerDisplayName: kronoz


来源: stackexchange

问:
How to group items by category and count?
I am doing stats with gem "groupdate", "~> 3.1.1" and gem "chartkick", and I need to know how many items were sold in each category.
Here are my models and there associations.

category.rb

```<code>has_many :products
</code>```

product.rb

```<code>belongs_to :category, optional: true
has_many :variants, dependent: :destroy
</code>```

variant.rb

```<code>belongs_to :product
has_many :order_items, dependent: :destroy
</code>```

order_item.rb

```<code>belongs_to :variant
</code>```

I can find the category's title of an order item like so:

```<code>OrderItem.last.variant.product.category.title
</code>```

But how from all the order_items, I can group the categories by title and count?

below is not working of course but that's my  try...

```<code>def order_item_category
 OrderItem.joins(:variant).product.category.group(:title).count
end

</code>```

答:
You need to join them properly as you need all records

```<code>OrderItem.joins(variant: [product: :category]).group('categories.title').count
</code>```

This should give you the category wise count of the Order Items.

Note: You may also want to add the scope depending on if you only want order items in the completed state.

ContentLicense: CC BY-SA 4.0

Body:
I am doing stats with gem "groupdate", "~> 3.1.1" and gem "chartkick", and I need to know how many items were sold in each category.
Here are my models and there associations.

category.rb

has_many :products

product.rb

belongs_to :category, optional: true
has_many :variants, dependent: :destroy

variant.rb

belongs_to :product
has_many :order_items, dependent: :destroy

order_item.rb

belongs_to :variant

I can find the category's title of an order item like so:

OrderItem.last.variant.product.category.title

But how from all the order_items, I can group the categories by title and count?

below is not working of course but that's my  try...

def order_item_category
 OrderItem.joins(:variant).product.category.group(:title).count
end

Body:
You need to join them properly as you need all records

OrderItem.joins(variant: [product: :category]).group('categories.title').count

This should give you the category wise count of the Order Items.

Note: You may also want to add the scope depending on if you only want order items in the completed state.


问:
sqlite query to get all list of table names with number of records in it
Please help on below query :
sqlite query to get all list of table names with number of records in it :

I want to get the count of rows in every table in a Sqlite3 database. I want to avoid writing out a longhand query. I can get the list of tables like this:

SELECT name FROM sqlite_master WHERE type='table'
and I would like to use it in a subquery like this:

select count (*) from (SELECT name FROM sqlite_master WHERE type='table');
but would just return the total rows in the subquery, which isn't what I want.

答:
Perhaps you use the results of ANALYZE to create a workaround. It creates the internal schema object sqlite_stat1

2.6.3. The sqlite_stat1 table

The sqlite_stat1 is an internal table created by the ANALYZE command
  and used to hold supplemental information about tables and indexes
  that the query planner can use to help it find better ways of
  performing queries. Applications can update, delete from, insert into
  or drop the sqlite_stat1 table, but may not create or alter the
  sqlite_stat1 table. The schema of the sqlite_stat1 table is as
  follows:

```<code>CREATE TABLE sqlite_stat1(tbl,idx,stat);
</code>```

There is normally one row per index, with the index identified by the
  name in the sqlite_stat1.idx column. The sqlite_stat1.tbl column is
  the name of the table to which the index belongs. In each such row,
  the sqlite_stat.stat column will be a string consisting of a list of
  integers followed by zero or more arguments. The first integer in this
  list is the approximate number of rows in the index. (The number of
  rows in the index is the same as the number of rows in the table,
  except for partial indexes.) .....

If there are no partial indexes, the SELECT tbl,cast(stat as INT) will return the number of rows in each table, unless the table has 0 rows.

This sql gives the expected results on a small (25MB, 34 tables, 26 indexes, 33K+ rows) production database. Your mileage may (will?) vary.

```<code>ANALYZE;
select  DISTINCT tbl_name, CASE WHEN stat is null then 0 else cast(stat as INT) END numrows
from sqlite_master m
LEFT JOIN sqlite_stat1 stat on   m.tbl_name = stat.tbl
where m.type='table'
and m.tbl_name not like 'sqlite_%'
order by 1;
--drop table sqlite_stat1;
</code>```

Body:
Perhaps you use the results of ANALYZE to create a workaround. It creates the internal schema object sqlite_stat1

2.6.3. The sqlite_stat1 table

The sqlite_stat1 is an internal table created by the ANALYZE command
  and used to hold supplemental information about tables and indexes
  that the query planner can use to help it find better ways of
  performing queries. Applications can update, delete from, insert into
  or drop the sqlite_stat1 table, but may not create or alter the
  sqlite_stat1 table. The schema of the sqlite_stat1 table is as
  follows:

CREATE TABLE sqlite_stat1(tbl,idx,stat);

There is normally one row per index, with the index identified by the
  name in the sqlite_stat1.idx column. The sqlite_stat1.tbl column is
  the name of the table to which the index belongs. In each such row,
  the sqlite_stat.stat column will be a string consisting of a list of
  integers followed by zero or more arguments. The first integer in this
  list is the approximate number of rows in the index. (The number of
  rows in the index is the same as the number of rows in the table,
  except for partial indexes.) .....

If there are no partial indexes, the SELECT tbl,cast(stat as INT) will return the number of rows in each table, unless the table has 0 rows.

This sql gives the expected results on a small (25MB, 34 tables, 26 indexes, 33K+ rows) production database. Your mileage may (will?) vary.

ANALYZE;
select  DISTINCT tbl_name, CASE WHEN stat is null then 0 else cast(stat as INT) END numrows
from sqlite_master m
LEFT JOIN sqlite_stat1 stat on   m.tbl_name = stat.tbl
where m.type='table'
and m.tbl_name not like 'sqlite_%'
order by 1;
--drop table sqlite_stat1;


问:
How to find the top three column totals using SQL
Trying to sum all columns in my table and to find the top 3 of them.

columns have only a value of 1 or 0. That's why I am trying to sum the all inputs to compare them with each other.

I've stucked with order by code integrated into sum()

```<code>SELECT (ID)
FROM Student
ORDER BY SUM(C1), SUMC(C2)...SUM(C10)
lIMIT 3
</code>```

答:
If I understand correctly, you can use union all to calculate the sum for each column and then order by and limit:

```<code>select c.*
from ((select 'col1', sum(col1) as s from t) union all
      (select 'col2', sum(col2) as s from t) union all
      . . .
      (select 'col10', sum(col10) as s from t)
     ) c
order by s desc
limit 3;
</code>```

Body:
Trying to sum all columns in my table and to find the top 3 of them.

columns have only a value of 1 or 0. That's why I am trying to sum the all inputs to compare them with each other.

I've stucked with order by code integrated into sum()

SELECT (ID)
FROM Student
ORDER BY SUM(C1), SUMC(C2)...SUM(C10)
lIMIT 3

Body:
If I understand correctly, you can use union all to calculate the sum for each column and then order by and limit:

select c.*
from ((select 'col1', sum(col1) as s from t) union all
      (select 'col2', sum(col2) as s from t) union all
      . . .
      (select 'col10', sum(col10) as s from t)
     ) c
order by s desc
limit 3;


问:
Can i change the text "view project" on button with javascript or jquery?
I would like to change the text "view project" of button at this page:
https://new.emanuelemarazzi.com/pacchetti-creativi/

If you see the code there is a span under a class.

I tried to use jQuery with this code:

```<code>$('.button-style5 span').text('Text changed');
</code>```

答:
No need for JQ.

document
    .querySelectorAll('.button-style5 span')
    .forEach(span=> span.innerText = 'All your span are belong to us')
```

References:

Document.querySelectorAll()
HTMLElement.innerText

Body:
I would like to change the text "view project" of button at this page:
https://new.emanuelemarazzi.com/pacchetti-creativi/

If you see the code there is a span under a class.

I tried to use jQuery with this code:

$('.button-style5 span').text('Text changed');

Body:
No need for JQ.

document
    .querySelectorAll('.button-style5 span')
    .forEach(span=> span.innerText = 'All your span are belong to us')

References:

Document.querySelectorAll()
HTMLElement.innerText


问:
Firestore: Updating field in an object removes previous field
I am using Flutter cloud firestore. Here is how my database looks like.

I want to add more fields (like "2222") in a_numbers object. I use updateData()like this,

```<code>DocumentReference ref = Firestore.instance.document("products/-LMhR5cAyW4T0sa03UtU");
ref.updateData({"a_numbers": {"2222" : false}});
</code>```

The above snippet basically deletes the previous value (1111) and then updates the database with 2222 field.

Any solution?

答:
To update 'a_numbers' with Pair without removing the previous values, you should assign the reference path (example: 'a_number.2222') to K and assign value to V. I edited your code. please review it for more information.</p>

```<code>DocumentReference ref = Firestore.instance.document("products/-LMhR5cAyW4T0sa03UtU");
ref.updateData({'a_numbers.2222': value});
</code>```

Body:
I am using Flutter cloud firestore. Here is how my database looks like.

I want to add more fields (like "2222") in a_numbers object. I use updateData()like this,

DocumentReference ref = Firestore.instance.document("products/-LMhR5cAyW4T0sa03UtU");
ref.updateData({"a_numbers": {"2222" : false}});

The above snippet basically deletes the previous value (1111) and then updates the database with 2222 field.

Any solution?

Body:
To update 'a_numbers' with Pair without removing the previous values, you should assign the reference path (example: 'a_number.2222') to K and assign value to V. I edited your code. please review it for more information.

DocumentReference ref = Firestore.instance.document("products/-LMhR5cAyW4T0sa03UtU");
ref.updateData({'a_numbers.2222': value});


问:
RESTful collections & controlling member details
I have come across this issue a few times now, and each time I make a fruitless search to come up with a satisfying answer.

We have a collection resource which returns a representation of the member URIs, as well as a Link header field with the same URIs (and a custom relation type). Often we find that we need specific data from each member in the collection.

At one extreme, we can have the collection return nothing but the member URIs; the client must then query each URI in turn to determine the required data from each member.

At the other extreme, we return all of the details we might want on the collection. Neither of these is perfect; the first can result in a large number of API calls, and the second may return a lot of potentially unneeded information.

Of the two extremes I favour the second in our case, since we rarely use this for more than one sutiation. However, for a more general approach, I wondered if anyone had a nice way of dynamically specifying which details should be included for each member of the collection? I guess a query string parameter would be most appropriate, but I don't want to break the self-descriptiveness of the resource.

答:
I prefer your first option..

At one extreme, we can have the
  collection return nothing but the
  member URIs; the client must then
  query each URI in turn to determine
  the required data from each member.

If you are wanting to reduce the number of HTTP calls over the wire, for example calling a service from a handset app (iOS/Android). You can include an additional header to include the child resources:

X-Aggregate-Resources-Depth: 2

Your server side code will have to aggregate the resources to the desired depth.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Awk with an IF condition
I have a file called: input:

```<code>160957 docliente_up hdfs://nameservice1/user/hive/warehouse/docliente_up.db
160958 docliente_bu hdfs://nameservice1/user/hive/warehouse/docliente_bu.db
</code>```

I am using awk to compare $2 with words ending in up

```<code>awk '{ if ($2 = "*_up" )
print "UPDATE DBS SET DB_LOCATION_URI=\"hdfs://nameservice1/databases_users/" $2"\"" " WHERE DB_ID=\""$1"\";";
else
print "UPDATE DBS SET DB_LOCATION_URI=\"hdfs://nameservice1/databases/" $2"\"" " WHERE DB_ID=\""$1"\";";}' input
</code>```

but isn't work. I have been looking for a expresion to solve my problems but I can't find it.

答:
You must do the if in a block, and add curly brackets:

```<code>awk ' { if ($2 ~ /_up/) { print "YES ", $0 } else { print "NO ", $0 } }' /tmp/SO
</code>```

Related question on Stackoverflow.

Title: Awk with an IF condition

Body:
I have a file called: input:

160957 docliente_up hdfs://nameservice1/user/hive/warehouse/docliente_up.db
160958 docliente_bu hdfs://nameservice1/user/hive/warehouse/docliente_bu.db

I am using awk to compare $2 with words ending in up

awk '{ if ($2 = "*_up" )
print "UPDATE DBS SET DB_LOCATION_URI=\"hdfs://nameservice1/databases_users/" $2"\"" " WHERE DB_ID=\""$1"\";";
else
print "UPDATE DBS SET DB_LOCATION_URI=\"hdfs://nameservice1/databases/" $2"\"" " WHERE DB_ID=\""$1"\";";}' input

but isn't work. I have been looking for a expresion to solve my problems but I can't find it.

Body:
You must do the if in a block, and add curly brackets:

awk ' { if ($2 ~ /_up/) { print "YES ", $0 } else { print "NO ", $0 } }' /tmp/SO

Related question on Stackoverflow.


问:
Review of this linked list program
This is a program on the linked list which prints the given input. But is it possible to do it Without using the if(start==NULL) ...else .. statement?

```<code>#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
}* start = NULL;

void main()
{
    struct node* tmp;
    struct node *ptr, *tmp1;

    int n = 0;
    int choice = 2;

    while (1)
    {
        printf("Enter a number less than 3 to continue");
        scanf("%d", &choice);
        if (choice >= 3)
            break;

        printf("Enter the input");
        scanf("%d", &n);
        // n=n+10;
        if (start == NULL)
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            start = tmp;
            start->data = n;
            ptr = start;
        }
        else
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            ptr->next = tmp;
            tmp->data = n;
            ptr = tmp;
        }
    }
    tmp->next = NULL;

    printf("\nThe output of the linked list is\n");
    n = 0;
    ptr = start;
    while (ptr != NULL)
    {
        printf("\n  1 ptr =           %d", ptr->data);
        ptr = ptr->next;
    }
}
</code>```

答:
The start variable holds the head of the linked list.

The condition if (start == NULL) checks for an empty list.

If the list is empty, you need to create the head of the list. The second element onwards, you need to link the next element to the last element of the list. This is taken care by the else condition.

To look at it another way, if you do not have the if condition, you have the line

```<code> ptr->next = tmp;
</code>```

Since ptr is not initialized at this time, you will have undefined behaviour and most likely get a segmentation fault.

Title: Review of this linked list program

Body:
This is a program on the linked list which prints the given input. But is it possible to do it Without using the if(start==NULL) ...else .. statement?

#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
}* start = NULL;

void main()
{
    struct node* tmp;
    struct node *ptr, *tmp1;

    int n = 0;
    int choice = 2;

    while (1)
    {
        printf("Enter a number less than 3 to continue");
        scanf("%d", &choice);
        if (choice >= 3)
            break;

        printf("Enter the input");
        scanf("%d", &n);
        // n=n+10;
        if (start == NULL)
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            start = tmp;
            start->data = n;
            ptr = start;
        }
        else
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            ptr->next = tmp;
            tmp->data = n;
            ptr = tmp;
        }
    }
    tmp->next = NULL;

    printf("\nThe output of the linked list is\n");
    n = 0;
    ptr = start;
    while (ptr != NULL)
    {
        printf("\n  1 ptr =           %d", ptr->data);
        ptr = ptr->next;
    }
}

Body:
The start variable holds the head of the linked list.

The condition if (start == NULL) checks for an empty list.

If the list is empty, you need to create the head of the list. The second element onwards, you need to link the next element to the last element of the list. This is taken care by the else condition.

To look at it another way, if you do not have the if condition, you have the line

 ptr->next = tmp;

Since ptr is not initialized at this time, you will have undefined behaviour and most likely get a segmentation fault.


问:
How to open file in vim while having session autoload?
I have following code in .vimrc to automatically save / load session on vim start:

```<code>" Session saving
" Automatically save / rewrite the session when leaving Vim
augroup leave
        autocmd VimLeave * mksession! ~/.vim/session.vim
augroup END

" Automatically silently load the session when entering vim
autocmd VimEnter * silent source ~/.vim/session.vim
</code>```

Which works properly, the only issue I have is when I want to create new file or open existing with:

```<code>vim test.txt
</code>```

In this case file is not opened and instead I have the last saved session loaded.

The desired behavior is following. When I run vim with no arguments - it restores last session. If I provide file argument, e.x. vim test.py - it loads last session AND in new tab opens / creates provided file.
How to do it? Ideally without any plugins.

答:
Should be something like this:</p>

```<code>" use ++nested to allow automatic file type detection and such
autocmd VimEnter * ++nested call <SID>load_session()

function! s:load_session()
    " save curdir and arglist for later
    let l:cwd = getcwd()
    let l:args = argv()
    " source session
    silent source ~/.vim/session.vim
    "restore curdir (otherwise relative paths may change)
    call chdir(l:cwd)
    " open all args
    for l:file in l:args
        execute 'tabnew' l:file
    endfor
    " add args to our arglist just in case
    execute 'argadd' join(l:args)
endfunction
</code>```

Body:
I have following code in .vimrc to automatically save / load session on vim start:

" Session saving
" Automatically save / rewrite the session when leaving Vim
augroup leave
        autocmd VimLeave * mksession! ~/.vim/session.vim
augroup END

" Automatically silently load the session when entering vim
autocmd VimEnter * silent source ~/.vim/session.vim

Which works properly, the only issue I have is when I want to create new file or open existing with:

vim test.txt

In this case file is not opened and instead I have the last saved session loaded.

The desired behavior is following. When I run vim with no arguments - it restores last session. If I provide file argument, e.x. vim test.py - it loads last session AND in new tab opens / creates provided file.
How to do it? Ideally without any plugins.

Body:
Should be something like this:

" use ++nested to allow automatic file type detection and such
autocmd VimEnter * ++nested call <SID>load_session()

function! s:load_session()
    " save curdir and arglist for later
    let l:cwd = getcwd()
    let l:args = argv()
    " source session
    silent source ~/.vim/session.vim
    "restore curdir (otherwise relative paths may change)
    call chdir(l:cwd)
    " open all args
    for l:file in l:args
        execute 'tabnew' l:file
    endfor
    " add args to our arglist just in case
    execute 'argadd' join(l:args)
endfunction


问:
Database too large - store as a row or serialise data?
I have Quiz App that constitutes many Modules containing Questions. Each question has many Categories (many-to-many). Every time a quiz is completed, the user's score is sent to the Scores Table. (I've attached an entity-relation diagram for clarification purposes).

I have been thinking of breaking down the user scores according to categories (i.e. a user when completing a quiz will get an overall quiz score along with score for each category).

However, if each quiz consists of at least 30 questions, there could around 15-20 categories per quiz. So if one user completes a quiz, then it would create a minimum of 15-20 rows in the scores table. With multiple users, the Scores table would get really big really fast.

I assume this would affect the performance of retrieving data from the Scores table. For example, if I wanted to calculate the average score for a user for a specific category.

Does anyone have a better suggestion for how I can still be able to store scores based on categories?

I thought about serialising the JSON data, but of course, this has its limitations.

答:
I doubt that serialization would give you a significant benefit.
I would even dare to say that you'd kind of limit the power of a database by doing so.

Relational databases are designed to store a lot of rows in their tables, and they also usually use their own compression algorithms, so you should be fine.

Additionally, you will need to deserialize every time you want to read from your table. That would eliminate the possibility to use SQL statements for sorting, filtering, JOINing etc.

So in the end you will probably cause yourself more trouble by serializing than by simply storing the rows.


问:
Find all rows in another sheet matching key
I have two sheets in my Excel workbook, one called Customer and the other called Product:

I wish to make a Lookup table in the Customer sheet, where in for example cell G2, above the lookup table, I put in the customer_id I wish to find all rows for in the sheet called Product. So, for example if I in G2 put in "1", I will get the two matching rows in sheet "Product". I have tried using VLOOKUP, but I always just match the first row, and none of the others.

EDIT:
in the lookup table you will only get the information in the sheet named "Product": if you put in "1" you will get rows 2 and 3 from the Product sheet. Customer_id only has one row per customer_id in the sheet called "customer", whereas in the sheet called "Product" you can have many rows per customer_id

答:
You could try Workbook_Change:

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim wsCus As Worksheet, wsPro As Worksheet
    Dim LastRow As Long, ID As Long, i As Long
    Dim arr As Variant
    Dim FullRecord

    With ThisWorkbook
        Set wsCus = .Worksheets("Customer")
        Set wsPro = .Worksheets("Product")
    End With

    If Not Intersect(Target, wsCus.Range("G2")) Is Nothing And Target.Count = 1 Then

        ID = Target.Value

        With wsPro

            LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

            arr = .Range("A2:A" & LastRow)

            For i = LBound(arr) To UBound(arr)

                If arr(i, 1) = ID Then

                    If FullRecord = "" Then
                        FullRecord = i + 1
                    Else
                        FullRecord = FullRecord & ", " & i + 1
                    End If

                End If

            Next i

            Application.EnableEvents = False
                If FullRecord = "" Then
                    wsCus.Range("I2").Value = "No match found"
                Else
                    wsCus.Range("I2").Value = "Matched lines for ID (" & ID & "): " & FullRecord
                End If
            Application.EnableEvents = True

        End With

    End If

End Sub
</code>```

Instructions:

Once you have your workbook open press ALT & F11 to open VBA Editor.

Double click on the Customer sheet on the left upper part.

Select Worksheet.

Change event.

Paste the code  as you see in the picture.

Then save the workbook as Excel Macro - Enabled Workbook, close VBA Editor and change G2 value.

Steps:

Results:

Find Match

No Match

Body:
You could try Workbook_Change:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim wsCus As Worksheet, wsPro As Worksheet
    Dim LastRow As Long, ID As Long, i As Long
    Dim arr As Variant
    Dim FullRecord

    With ThisWorkbook
        Set wsCus = .Worksheets("Customer")
        Set wsPro = .Worksheets("Product")
    End With

    If Not Intersect(Target, wsCus.Range("G2")) Is Nothing And Target.Count = 1 Then

        ID = Target.Value

        With wsPro

            LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

            arr = .Range("A2:A" & LastRow)

            For i = LBound(arr) To UBound(arr)

                If arr(i, 1) = ID Then

                    If FullRecord = "" Then
                        FullRecord = i + 1
                    Else
                        FullRecord = FullRecord & ", " & i + 1
                    End If

                End If

            Next i

            Application.EnableEvents = False
                If FullRecord = "" Then
                    wsCus.Range("I2").Value = "No match found"
                Else
                    wsCus.Range("I2").Value = "Matched lines for ID (" & ID & "): " & FullRecord
                End If
            Application.EnableEvents = True

        End With

    End If

End Sub

Instructions:

Once you have your workbook open press ALT & F11 to open VBA Editor.

Double click on the Customer sheet on the left upper part.

Select Worksheet.

Change event.

Paste the code  as you see in the picture.

Then save the workbook as Excel Macro - Enabled Workbook, close VBA Editor and change G2 value.

Steps:

Results:

Find Match

No Match


问:
Pass a string to RGB Colour format
I have a dict like this:

```<code>colour_dict={'Red': '0xFF, 0x00, 0x00','Green':'0x00, 0xFF, 0x00','White':'0xFF, 0xFF, 0xFF','Yellow':'0xff, 0xff, 0x00'}
</code>```

I need to pass value of this dict to this code and it works right:

```<code>from pptx.dml.color import RGBColor
RGBColor(0xFF, 0x00, 0x00)
</code>```

When I do below to achieve the same:

```<code>RGBColor(colour_dict["Red"])
</code>```

It throws me an error as this is a string and this just want in straight number format.

I already tried converting this string to int format but nothing is working.

Overall  Problem:

How to pass the value to RGBColor using dict?

答:
I find the map lambda answer a bit overkill, here is a less fancy variant:

```<code>color = RGBColor(*[int(x,16) for x in colour_dict["Red"].split(",")])
</code>```

Title: Pass a string to RGB Colour format

Body:
I have a dict like this:

colour_dict={'Red': '0xFF, 0x00, 0x00','Green':'0x00, 0xFF, 0x00','White':'0xFF, 0xFF, 0xFF','Yellow':'0xff, 0xff, 0x00'}

I need to pass value of this dict to this code and it works right:

from pptx.dml.color import RGBColor
RGBColor(0xFF, 0x00, 0x00)

When I do below to achieve the same:

RGBColor(colour_dict["Red"])

It throws me an error as this is a string and this just want in straight number format.

I already tried converting this string to int format but nothing is working.

Overall  Problem:

How to pass the value to RGBColor using dict?

Body:
I find the map lambda answer a bit overkill, here is a less fancy variant:

color = RGBColor(*[int(x,16) for x in colour_dict["Red"].split(",")])


问:
Laravel Query Error - htmlspecialchars() expects parameter 1 to be string, object given
Am trying to get the total sum for amount from in table for a particular month, but I got this error:

htmlspecialchars() expects parameter 1 to be string, object given

'currentmonthbilling' => object(Builder),

The table name is billings

I have written the query

```<code> $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
            ->select(DB::raw("SUM(amount)"))
                        ->whereRaw('MONTH(created_at) = ?',[$currentMonth]);
</code>```

I want to get the total amount paid by everyone for the current month

答:
Use sum(DB::raw('amount')) in place of select(DB::raw("SUM(amount)"))

```<code>$currentMonth = date('m');
     $currentmonthbilling = DB::table("billings")
                              ->sum(DB::raw('amount'))
                              ->whereRaw('MONTH(created_at) = ?',[$currentMonth])->get();
</code>```

Body:
Am trying to get the total sum for amount from in table for a particular month, but I got this error:

htmlspecialchars() expects parameter 1 to be string, object given

'currentmonthbilling' => object(Builder),

The table name is billings

I have written the query

 $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
            ->select(DB::raw("SUM(amount)"))
                        ->whereRaw('MONTH(created_at) = ?',[$currentMonth]);

I want to get the total amount paid by everyone for the current month

Body:
Use sum(DB::raw('amount')) in place of select(DB::raw("SUM(amount)"))

$currentMonth = date('m');
     $currentmonthbilling = DB::table("billings")
                              ->sum(DB::raw('amount'))
                              ->whereRaw('MONTH(created_at) = ?',[$currentMonth])->get();


问:
Exclude supported language by external dependency (aar)
How to exclude supported languages by an external dependency (.aar)? The external dependency is supporting more languages that my application, and I'm trying to avoid having activities with different languages according if it comes from the external dependency or not.

I've been trying something like this, but without success:

compile ('...-3.17.1@aar') { exclude("res/values-es") }

答:
https://developer.android.com/studio/build/shrink-code#unused-alt-resources</p>

```<code>android {
    defaultConfig {
        ...
        resConfigs "en", "fr"
    }
}
</code>```

Body:
https://developer.android.com/studio/build/shrink-code#unused-alt-resources

android {
    defaultConfig {
        ...
        resConfigs "en", "fr"
    }
}


问:
How should I serialize Datetime into a string in AspNetUserTokens table in ASP.NET Core 2.0?
When I'm using OAuth2 in ASP.NET Core, the middleware converts datetimes into a string the way the result looks like

2019-05-27T13:07:49.0000000+00:00

I'm refreshing access tokens manually then and I would like to replicate this behavior. Is there any defined method to use to serialize a DateTime value into a string for subsequent writing into AspNetUserTokens table?

I know that I can use DateTime.ToString and create the formatting by analyzing 2019-05-27T13:07:49.0000000+00:00 string but I would better prefer to use something more elegant and do not depend on a particular format details. I.e. in case if tomorrow they will change something in the format, I'll use a higher-level call which will stay compatible with the changed implementation.

Actually, I see that expires_at value is already a "2019-05-27T13:07:49.0000000+00:00" string in tokens in googleOptions.Events.OnCreatingTicket

```<code>googleOptions.Events.OnCreatingTicket = ctx =>
    {
        List<AuthenticationToken> tokens = ctx.Properties.GetTokens().ToList();

        return Task.CompletedTask;
    };
</code>```

So this serialization is done even before putting data into database. I need to find out how they do it and use the same call (if possible).

答:
That format is the “Round-trip date/time pattern”:

```<code>var date = DateTime.Now;
Console.WriteLine(date.ToString("o")); // 2019-05-27T14:34:02.8029466+02:00
</code>```

Since this format is very verbose while being compliant with ISO 8601 and stable on all locales, it is very well suited for serializing dates and times at maximum precision.

Body:
When I'm using OAuth2 in ASP.NET Core, the middleware converts datetimes into a string the way the result looks like

2019-05-27T13:07:49.0000000+00:00

I'm refreshing access tokens manually then and I would like to replicate this behavior. Is there any defined method to use to serialize a DateTime value into a string for subsequent writing into AspNetUserTokens table?

I know that I can use DateTime.ToString and create the formatting by analyzing 2019-05-27T13:07:49.0000000+00:00 string but I would better prefer to use something more elegant and do not depend on a particular format details. I.e. in case if tomorrow they will change something in the format, I'll use a higher-level call which will stay compatible with the changed implementation.

Actually, I see that expires_at value is already a "2019-05-27T13:07:49.0000000+00:00" string in tokens in googleOptions.Events.OnCreatingTicket

googleOptions.Events.OnCreatingTicket = ctx =>
    {
        List<AuthenticationToken> tokens = ctx.Properties.GetTokens().ToList();

        return Task.CompletedTask;
    };

So this serialization is done even before putting data into database. I need to find out how they do it and use the same call (if possible).

Body:
That format is the “Round-trip date/time pattern”:

var date = DateTime.Now;
Console.WriteLine(date.ToString("o")); // 2019-05-27T14:34:02.8029466+02:00

Since this format is very verbose while being compliant with ISO 8601 and stable on all locales, it is very well suited for serializing dates and times at maximum precision.


问:
C# foreach iterating rule for collections
How .NET decides for order of items when iterating through collections ?

For example:

```<code>list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}
</code>```

I need this order (accessing collection members):

```<code>for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}
</code>```

Can I safely use foreach with List? What about other types of collections?

答: A generic List will enumerate in the order of addition, as you suggest. Other implementations of Enumerator may vary, If its important you could consider a SortedList.</p>

Body:
How .NET decides for order of items when iterating through collections ?

For example:

list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}

I need this order (accessing collection members):

for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}

Can I safely use foreach with List? What about other types of collections?


问:
Programming In SQLITE
In college I learned PL/SQL, which I used to insert/update data into table programmatically.

So is there any way to do it in SQLITE?

I have one table book which has two columns: readPages and currentPage. readPage contains info about how many pages I've read today and currentPage shows total read pages till today.

Currently I have data for only readPages so I want to calculate currentPage for past days, e.g.

```<code>readPages:   19  10  43  20  35   # I have data for 5 days
currentPage: 19  29  72  92  127  # I want to calculate it
</code>```

So this can be easy with programming, but how to do with sqlite as it is not like plsql.

答:
If you're using sqlite 3.25 or newer, something like:

```<code>SELECT date, readPages
      , sum(readPages) OVER (ORDER BY date) AS total_pages_read
FROM yourTableName
ORDER BY date;
</code>```

will compute the running total of pages.

Title: Programming In SQLITE

Body:
In college I learned PL/SQL, which I used to insert/update data into table programmatically.

So is there any way to do it in SQLITE?

I have one table book which has two columns: readPages and currentPage. readPage contains info about how many pages I've read today and currentPage shows total read pages till today.

Currently I have data for only readPages so I want to calculate currentPage for past days, e.g.

readPages:   19  10  43  20  35   # I have data for 5 days
currentPage: 19  29  72  92  127  # I want to calculate it

So this can be easy with programming, but how to do with sqlite as it is not like plsql.

Body:
If you're using sqlite 3.25 or newer, something like:

SELECT date, readPages
      , sum(readPages) OVER (ORDER BY date) AS total_pages_read
FROM yourTableName
ORDER BY date;

will compute the running total of pages.


问:
Group by two case statement with date
I have to group by date for below query, but REG and OT hours are coming on different row for same date. Can anyone tell me how to achieve this?

I did group by date but its not working.

```<code>SELECT VP.PERSONNUM AS PERSONID,
VP.FIRSTNM AS FIRST_NAME,
VP.LASTNM AS LAST_NAME,
(select personnum from vp_employeev42 where personnum = vp.homelaborlevelnm6) as FOREMAN_CODE,
CA.PERSONCSTMDATATXT as SHIFT,
TO_CHAR(X.APPLYDTM, 'DD-MM-YYYY') AS LABOR_DATE,
VP.HOMELABORLEVELNM3 AS DEPARTMENT,
CASE WHEN TS.LABORLEVELNAME3 != 'NULL' THEN TS.LABORLEVELNAME3 ELSE VP.HOMELABORLEVELNM3 END AS CHGD_DEPARTMENT,
CASE WHEN P.NAME = 'US-Regular' THEN SUM(X.DURATIONSECSQTY/3600.0) ELSE 0 END AS REG,
CASE WHEN P.NAME = 'US-Overtime' THEN SUM(X.DURATIONSECSQTY/3600.0) ELSE 0 END AS OT,
CASE WHEN P.NAME = 'US-Doubletime' THEN SUM(X.DURATIONSECSQTY/3600.0) ELSE 0 END AS DBL ,
CASE WHEN TS.LABORLEVELNAME4 != 'NULL' THEN TS.LABORLEVELNAME4 ELSE VP.HOMELABORLEVELNM4 END AS ACCOUNT_ID
FROM VP_EMPLOYEEV42 VP,
WFCTOTAL X, PAYCODE P,
PERSONCSTMDATA CA,
VP_TIMESHTPUNCHV42 TS
WHERE VP.PERSONID = X.EMPLOYEEID AND
X.PAYCODEID = P.PAYCODEID AND
X.EMPLOYEEID = CA.PERSONID AND
CA.CUSTOMDATADEFID ='13' AND
X.TIMESHEETITEMID = TS.TIMESHEETITEMID AND
P.NAME in ('US-Regular','US-Overtime','US-Doubletime') AND
X.EMPLOYEEID in (select personid from PERSONCSTMDATA where CUSTOMDATADEFID ='14' and PERSONCSTMDATATXT = 'USKEANE')
and VP.PAYRULENAME in ('USKEANE 10 HR Shift','USKEANE 12 HR Shift','USKEANE 1st Shift','USKEANE 2nd Shift','USKEANE 3rd Shift')
and X.APPLYDTM between '01-APR-19' and '30-APR-19'
group by VP.PERSONID, VP.PERSONNUM, VP.FIRSTNM, VP.LASTNM, VP.HOMELABORLEVELNM6,
X.APPLYDTM, VP.HOMELABORLEVELNM3, CA.PERSONCSTMDATATXT ,VP.HOMELABORLEVELNM4,
P.NAME, TS.LABORLEVELNAME3, TS.LABORLEVELNAME4 ORDER BY VP.PERSONID, X.APPLYDTM DESC
</code>```

```<code>{
PERSONID FIRST_NAME LAST_NAME FOREMAN_CODE SHIFT LABOR_DATE DEPARTMENT CHGD_DEPARTMENT REG OT DBL ACCOUNT_ID
E0002887 Maria Putnam E0061775 1 10-04-2019 25855 25855 0 4 0 60467
E0002887 Maria Putnam E0061775 1 10-04-2019 25855 25855 4 0 0 60467
E0002887 Maria Putnam E0061775 1 15-04-2019 25855 25855 8 0 0 60467
}
</code>```

答:
You are doing this:

```<code>select case p.name when 'US-Regular'    then sum(x.durationsecsqty/3600) else 0 end as reg,
       case p.name when 'US-Overtime'   then sum(x.durationsecsqty/3600) else 0 end as ot,
       case p.name when 'US-Doubletime' then sum(x.durationsecsqty/3600) else 0 end as dbl
  from p, x
  where x.paycodeid = p.paycodeid
  group by p.name
</code>```

But you do not want to differentiate p.name in your output. So remove it from group by and change case part like here:

```<code>select sum(case p.name when 'US-Regular'    then x.durationsecsqty/3600 else 0 end) as reg,
       sum(case p.name when 'US-Overtime'   then x.durationsecsqty/3600 else 0 end) as ot,
       sum(case p.name when 'US-Doubletime' then x.durationsecsqty/3600 else 0 end) as dbl
  from p, x
  where x.paycodeid = p.paycodeid
</code>```

If I were you I would also change old-join syntax to more readable:

```<code>  ...
  from paycode        p
  join wfctotal       x  on x.paycodeid = p.paycodeid
  join personcstmdata ca on x.employeeid = ca.personid
  ...
  where p.name in ('US-Regular','US-Overtime','US-Doubletime')
  ...
</code>```

though there are people who prefer old way :)

Title: Group by two case statement with date

Body:
I have to group by date for below query, but REG and OT hours are coming on different row for same date. Can anyone tell me how to achieve this?

I did group by date but its not working.

SELECT VP.PERSONNUM AS PERSONID,
VP.FIRSTNM AS FIRST_NAME,
VP.LASTNM AS LAST_NAME,
(select personnum from vp_employeev42 where personnum = vp.homelaborlevelnm6) as FOREMAN_CODE,
CA.PERSONCSTMDATATXT as SHIFT,
TO_CHAR(X.APPLYDTM, 'DD-MM-YYYY') AS LABOR_DATE,
VP.HOMELABORLEVELNM3 AS DEPARTMENT,
CASE WHEN TS.LABORLEVELNAME3 != 'NULL' THEN TS.LABORLEVELNAME3 ELSE VP.HOMELABORLEVELNM3 END AS CHGD_DEPARTMENT,
CASE WHEN P.NAME = 'US-Regular' THEN SUM(X.DURATIONSECSQTY/3600.0) ELSE 0 END AS REG,
CASE WHEN P.NAME = 'US-Overtime' THEN SUM(X.DURATIONSECSQTY/3600.0) ELSE 0 END AS OT,
CASE WHEN P.NAME = 'US-Doubletime' THEN SUM(X.DURATIONSECSQTY/3600.0) ELSE 0 END AS DBL ,
CASE WHEN TS.LABORLEVELNAME4 != 'NULL' THEN TS.LABORLEVELNAME4 ELSE VP.HOMELABORLEVELNM4 END AS ACCOUNT_ID
FROM VP_EMPLOYEEV42 VP,
WFCTOTAL X, PAYCODE P,
PERSONCSTMDATA CA,
VP_TIMESHTPUNCHV42 TS
WHERE VP.PERSONID = X.EMPLOYEEID AND
X.PAYCODEID = P.PAYCODEID AND
X.EMPLOYEEID = CA.PERSONID AND
CA.CUSTOMDATADEFID ='13' AND
X.TIMESHEETITEMID = TS.TIMESHEETITEMID AND
P.NAME in ('US-Regular','US-Overtime','US-Doubletime') AND
X.EMPLOYEEID in (select personid from PERSONCSTMDATA where CUSTOMDATADEFID ='14' and PERSONCSTMDATATXT = 'USKEANE')
and VP.PAYRULENAME in ('USKEANE 10 HR Shift','USKEANE 12 HR Shift','USKEANE 1st Shift','USKEANE 2nd Shift','USKEANE 3rd Shift')
and X.APPLYDTM between '01-APR-19' and '30-APR-19'
group by VP.PERSONID, VP.PERSONNUM, VP.FIRSTNM, VP.LASTNM, VP.HOMELABORLEVELNM6,
X.APPLYDTM, VP.HOMELABORLEVELNM3, CA.PERSONCSTMDATATXT ,VP.HOMELABORLEVELNM4,
P.NAME, TS.LABORLEVELNAME3, TS.LABORLEVELNAME4 ORDER BY VP.PERSONID, X.APPLYDTM DESC

{
PERSONID FIRST_NAME LAST_NAME FOREMAN_CODE SHIFT LABOR_DATE DEPARTMENT CHGD_DEPARTMENT REG OT DBL ACCOUNT_ID
E0002887 Maria Putnam E0061775 1 10-04-2019 25855 25855 0 4 0 60467
E0002887 Maria Putnam E0061775 1 10-04-2019 25855 25855 4 0 0 60467
E0002887 Maria Putnam E0061775 1 15-04-2019 25855 25855 8 0 0 60467
}

Body:
You are doing this:

select case p.name when 'US-Regular'    then sum(x.durationsecsqty/3600) else 0 end as reg,
       case p.name when 'US-Overtime'   then sum(x.durationsecsqty/3600) else 0 end as ot,
       case p.name when 'US-Doubletime' then sum(x.durationsecsqty/3600) else 0 end as dbl
  from p, x
  where x.paycodeid = p.paycodeid
  group by p.name

But you do not want to differentiate p.name in your output. So remove it from group by and change case part like here:

select sum(case p.name when 'US-Regular'    then x.durationsecsqty/3600 else 0 end) as reg,
       sum(case p.name when 'US-Overtime'   then x.durationsecsqty/3600 else 0 end) as ot,
       sum(case p.name when 'US-Doubletime' then x.durationsecsqty/3600 else 0 end) as dbl
  from p, x
  where x.paycodeid = p.paycodeid

If I were you I would also change old-join syntax to more readable:

  ...
  from paycode        p
  join wfctotal       x  on x.paycodeid = p.paycodeid
  join personcstmdata ca on x.employeeid = ca.personid
  ...
  where p.name in ('US-Regular','US-Overtime','US-Doubletime')
  ...

though there are people who prefer old way :)


问:
Cplex get coefficients of objective function
I have an IloCplex object and I want to get the coefficients of the IloObjective with the Cplex Java api.

With this code I get the IloObjective and IloNumExpr but I can't access the coefficients.

```<code>IloCplex cplex = new IloCplex();
cplex.importModel("model.lp");
IloObjective obj = cplex.getObjective();
IloNumExpr expr = obj.getExpr();
</code>```

How can I get the coefficients of IloObjective or IloNumExpr?

答:
Since your model.lp file contains a linear model, expr should be an instance of IloLinearNumExpr, and you should be able to iterate over it using the linearIterator method:

```<code>if (expr instanceof IloLinearNumExpr) {
    IloLinearNumExpr lexpr = (IloLinearNumExpr) expr;

    IloLinearNumExprIterator it = lexpr.linearIterator();

    while (it.hasNext()) {
        IloNumVar var = it.nextNumVar();
        double coeff = it.getValue();
        System.out.println(var + " " + coeff);
    }
}

</code>```

Body:
I have an IloCplex object and I want to get the coefficients of the IloObjective with the Cplex Java api.

With this code I get the IloObjective and IloNumExpr but I can't access the coefficients.

IloCplex cplex = new IloCplex();
cplex.importModel("model.lp");
IloObjective obj = cplex.getObjective();
IloNumExpr expr = obj.getExpr();

How can I get the coefficients of IloObjective or IloNumExpr?

Body:
Since your model.lp file contains a linear model, expr should be an instance of IloLinearNumExpr, and you should be able to iterate over it using the linearIterator method:

if (expr instanceof IloLinearNumExpr) {
    IloLinearNumExpr lexpr = (IloLinearNumExpr) expr;

    IloLinearNumExprIterator it = lexpr.linearIterator();

    while (it.hasNext()) {
        IloNumVar var = it.nextNumVar();
        double coeff = it.getValue();
        System.out.println(var + " " + coeff);
    }
}


问:
How to get button left and right corner position on screen?
I am trying to get the view position (Right upper corner position and left bottom corner position) and display custom dialog right or left side of view but i am not getting exact position of view. This is my code

```<code>    int x=view.getLeft()+  (view.getHeight()*4);
    int y= view.getBottom()+(view.getWidth()*2);
    showDialog(x,y,Gravity.TOP,Gravity.LEFT);`

    public void showDialog(int x, int y,int gravity_y,int gravity_x){
    final Dialog dialog  = new Dialog(this, R.style.ActivityDialog);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
    dialog.setContentView(R.layout.cofirm_sell);
    dialog.setCanceledOnTouchOutside(false);
    WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
    dialog.getWindow().getAttributes().windowAnimations=R.style.DialogTheme;
    wmlp.gravity = gravity_y | gravity_x;
    wmlp.x = x;
    wmlp.y = y;
    ImageButton close=(ImageButton)dialog.findViewById(R.id.close);
    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();
</code>```

}

I want this

答:
Thanks to @Sree, in Kotlin:</p>

```<code>val location = IntArray(2)
view.getLocationInWindow(location)

val left = location[0]
val right = left + view.width
val top = location[1]
val bottom = top + view.height
</code>```

Body:
I am trying to get the view position (Right upper corner position and left bottom corner position) and display custom dialog right or left side of view but i am not getting exact position of view. This is my code

    int x=view.getLeft()+  (view.getHeight()*4);
    int y= view.getBottom()+(view.getWidth()*2);
    showDialog(x,y,Gravity.TOP,Gravity.LEFT);`

    public void showDialog(int x, int y,int gravity_y,int gravity_x){
    final Dialog dialog  = new Dialog(this, R.style.ActivityDialog);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
    dialog.setContentView(R.layout.cofirm_sell);
    dialog.setCanceledOnTouchOutside(false);
    WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
    dialog.getWindow().getAttributes().windowAnimations=R.style.DialogTheme;
    wmlp.gravity = gravity_y | gravity_x;
    wmlp.x = x;
    wmlp.y = y;
    ImageButton close=(ImageButton)dialog.findViewById(R.id.close);
    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();

}

I want this

Body:
Thanks to @Sree, in Kotlin:

val location = IntArray(2)
view.getLocationInWindow(location)

val left = location[0]
val right = left + view.width
val top = location[1]
val bottom = top + view.height


问:
Getting all selected toggle buttons from same group
I have 3 toggle buttons (FXML):

```<code><ToggleButton fx:id="toggle1" text="Option 1" />
<ToggleButton fx:id="toggle2" text="Option 2" />
<ToggleButton fx:id="toggle3" text="Option 3" />
</code>```

Those are several options the user can select or deselect. Multiple selection should also be possible.

In order to get all selected toggles, I put them into one toggle group:

```<code>final ToggleGroup toggleGroup = new ToggleGroup();

toggle1.setToggleGroup(toggleGroup);
toggle2.setToggleGroup(toggleGroup);
toggle3.setToggleGroup(toggleGroup);
</code>```

But, in that case, only 1 button at a time can be selected, not 2 or 3.

How to get all selected toggle buttons from the same group?
So, basically, same principle as with check boxes.

答:
You can use a CheckBox and make it look like a radio button using CSS.
To get all selected checkboxes, you can create an observable collection like ObservableSet and assign listeners to the checkboxes, when a checkbox is selected add it to the collection and remove it when it gets unselected</p>

```<code>ObservableSet<CheckBox> selectedCheckBoxes = FXCollections.observableSet();
CheckBox checkBox1 = new CheckBox();
checkBox1.selectedProperty().addListener((observable, oldValue, selectedNow) -> {
    if (selectedNow) {
        selectedCheckBoxes.add(checkBox1);
    } else {
        selectedCheckBoxes.remove(checkBox1);
    }
});
</code>```

Body:
I have 3 toggle buttons (FXML):

<ToggleButton fx:id="toggle1" text="Option 1" />
<ToggleButton fx:id="toggle2" text="Option 2" />
<ToggleButton fx:id="toggle3" text="Option 3" />

Those are several options the user can select or deselect. Multiple selection should also be possible.

In order to get all selected toggles, I put them into one toggle group:

final ToggleGroup toggleGroup = new ToggleGroup();

toggle1.setToggleGroup(toggleGroup);
toggle2.setToggleGroup(toggleGroup);
toggle3.setToggleGroup(toggleGroup);

But, in that case, only 1 button at a time can be selected, not 2 or 3.

How to get all selected toggle buttons from the same group?
So, basically, same principle as with check boxes.

Body:
You can use a CheckBox and make it look like a radio button using CSS.
To get all selected checkboxes, you can create an observable collection like ObservableSet and assign listeners to the checkboxes, when a checkbox is selected add it to the collection and remove it when it gets unselected

ObservableSet<CheckBox> selectedCheckBoxes = FXCollections.observableSet();
CheckBox checkBox1 = new CheckBox();
checkBox1.selectedProperty().addListener((observable, oldValue, selectedNow) -> {
    if (selectedNow) {
        selectedCheckBoxes.add(checkBox1);
    } else {
        selectedCheckBoxes.remove(checkBox1);
    }
});


问:
How to lookup values from code and make some new columns based on it
I want to lookup value from a database and make some new columns in a file
actually I have a file like this

```<code>promo code item stok
sale1  100   a   200
sale2  101   b   300
sale3  102   c   100
sale4  103   d    50
</code>```

and a database looks like this

```<code>code item1 code_item1 amount_item1 item2 code_item2 amount_item2
100   a1     1001          2        a2     1002          1
102   a2     1002          1        a3     1003          1
</code>```

and then I want to add my first file several columns which are taken from the database

```<code>promo code item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
sale1  100   a   200   a1     1001          400        a2     1002          200
sale2  101   b   300
sale3  102   c   100   a2     1002          100        a3     1003          100
sale4  103   d    50
</code>```

How do I do this?

答:
Yes, dplyr is good option, however I such cases always use merge().

```<code>my_df <- data.frame(promo = c("sale1", "sale2", "sale3", "sale4"), code = c(100, 101, 102, 103), item = c("a", "b", "c", "d"), stok = c(200, 300, 100, 50))
db_df <- data.frame(code = c(100, 102), item1 = c("a1", "a2"), code_item1 = c(1001, 1002), amount_item1 = c(2,1), item2 = c("a2", "a3"), code_item2 = c(1002, 1003), amount_item2 = c(1,1))

result <- merge(x=my_df, y=db_df, by='code', all.x = TRUE)

> result
  code promo item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
1  100 sale1    a  200    a1       1001            2    a2       1002            1
2  101 sale2    b  300  <NA>         NA           NA  <NA>         NA           NA
3  102 sale3    c  100    a2       1002            1    a3       1003            1
4  103 sale4    d   50  <NA>         NA           NA  <NA>         NA           NA
</code>```

Body:
I want to lookup value from a database and make some new columns in a file
actually I have a file like this

promo code item stok
sale1  100   a   200
sale2  101   b   300
sale3  102   c   100
sale4  103   d    50

and a database looks like this

code item1 code_item1 amount_item1 item2 code_item2 amount_item2
100   a1     1001          2        a2     1002          1
102   a2     1002          1        a3     1003          1

and then I want to add my first file several columns which are taken from the database

promo code item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
sale1  100   a   200   a1     1001          400        a2     1002          200
sale2  101   b   300
sale3  102   c   100   a2     1002          100        a3     1003          100
sale4  103   d    50

How do I do this?

Body:
Yes, dplyr is good option, however I such cases always use merge().

my_df <- data.frame(promo = c("sale1", "sale2", "sale3", "sale4"), code = c(100, 101, 102, 103), item = c("a", "b", "c", "d"), stok = c(200, 300, 100, 50))
db_df <- data.frame(code = c(100, 102), item1 = c("a1", "a2"), code_item1 = c(1001, 1002), amount_item1 = c(2,1), item2 = c("a2", "a3"), code_item2 = c(1002, 1003), amount_item2 = c(1,1))

result <- merge(x=my_df, y=db_df, by='code', all.x = TRUE)

> result
  code promo item stok item1 code_item1 amount_item1 item2 code_item2 amount_item2
1  100 sale1    a  200    a1       1001            2    a2       1002            1
2  101 sale2    b  300  <NA>         NA           NA  <NA>         NA           NA
3  102 sale3    c  100    a2       1002            1    a3       1003            1
4  103 sale4    d   50  <NA>         NA           NA  <NA>         NA           NA


问:
The policy failed legacy parsing
I am trying to create IAM Role in AWS, but while I am creating I am facing error

"We encountered the following errors while processing your request:
 Problem in attaching permission to role. Role will be created without permission.
 The policy failed legacy parsing  "

```<code>{"Version": "2012-10-17",  "Statement": [
{
  "Effect": "Allow",
  "Action": [
    "logs:CreateLogGroup",
    "logs:CreateLogStream",
    "logs:PutLogEvents"
  ],
  "Resource": "arn:aws:logs:*:*:*"
},
{
  "Action": [
    "sqs:SendMessage",
    "sqs:GetQueueUrl"
  ],
  "Effect": "Allow",
  "Resource": "arn:aws:sqs:ap-northeast-1:SOME_ID_HERE:test-messages"
}]}
</code>```

答:
If it fails for s3, ensure that you are using the correct arn format:

Correct one is 3 ::: arn:aws:s3:::AccountABucketName

"Resource": "arn:aws:s3:::AccountABucketName"

Wrong one 2 :: arn:aws:s3::AccountABucketName

"Resource": "arn:aws:s3::AccountABucketName"

Count the number of colons between s3 and AccountABucketName

Title: The policy failed legacy parsing

Body:
I am trying to create IAM Role in AWS, but while I am creating I am facing error

"We encountered the following errors while processing your request:
 Problem in attaching permission to role. Role will be created without permission.
 The policy failed legacy parsing  "

{"Version": "2012-10-17",  "Statement": [
{
  "Effect": "Allow",
  "Action": [
    "logs:CreateLogGroup",
    "logs:CreateLogStream",
    "logs:PutLogEvents"
  ],
  "Resource": "arn:aws:logs:*:*:*"
},
{
  "Action": [
    "sqs:SendMessage",
    "sqs:GetQueueUrl"
  ],
  "Effect": "Allow",
  "Resource": "arn:aws:sqs:ap-northeast-1:SOME_ID_HERE:test-messages"
}]}


问:
How do I fix a problem with a function that is supposed to only move 0's to the end of the list, but moves False values as well?
I'm writing a function to move 0's to the end of a list, but when a False value is in the list, it converts it to 0 and moves it to the end as well.

I've tried many variations of if statements including:

if i == 0

if type(i) != bool and i == 0

if str(i) == '0'

```<code>def move_zeros(array):
    for i in array:
        if str(i) == '0' and str(i) != 'False':
            array.remove(i)
            array.append(0)
    return array
</code>```

In case of [0,1,None,2,False,1,0], I expected the function to return [1,None,2,False,1,0,0], but it returned [1,None,2,1,0,0,0] instead.

答:
You have two issues here. First, in Python, bool is a subclass of int and False == 0, so to tell apart 0 from False you have to test on your object's type. Also, modifying a list in place while iterating over it is a sure recipe for "off" errors.

Here's a plain stupid simple implementation that works:

```<code>def move_zeros(seq):
    head, tail = [], []
    for v in seq:
        if isinstance(v, int) and not isinstance(v, bool) and v == 0:
            tail.append(v)
        else:
            head.append(v)
    return head + tail
</code>```

Body:
I'm writing a function to move 0's to the end of a list, but when a False value is in the list, it converts it to 0 and moves it to the end as well.

I've tried many variations of if statements including:

if i == 0

if type(i) != bool and i == 0

if str(i) == '0'

def move_zeros(array):
    for i in array:
        if str(i) == '0' and str(i) != 'False':
            array.remove(i)
            array.append(0)
    return array

In case of [0,1,None,2,False,1,0], I expected the function to return [1,None,2,False,1,0,0], but it returned [1,None,2,1,0,0,0] instead.

Body:
You have two issues here. First, in Python, bool is a subclass of int and False == 0, so to tell apart 0 from False you have to test on your object's type. Also, modifying a list in place while iterating over it is a sure recipe for "off" errors.

Here's a plain stupid simple implementation that works:

def move_zeros(seq):
    head, tail = [], []
    for v in seq:
        if isinstance(v, int) and not isinstance(v, bool) and v == 0:
            tail.append(v)
        else:
            head.append(v)
    return head + tail


问:
Splitting a string and inserting the parts in the correct columns inside a table
I am trying to build a fact table with sql server. It currently looks like this:

```<code>[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NULL         NULL       NULL
02         BLACK/S4       COLOUR/STYLE    NULL         NULL       NULL
</code>```

I need to split the String in [Variant Descr.] and insert the parts into the correct Dim_ Column so the table will eventually look like this:

```<code>[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NAVY         44       NULL
02         BLACK/S4       COLOUR/STYLE    BLACK        NULL     S4
</code>```

The problem is that the parts of [Variant Order] and the number of parts of [Variant Descr.] may vary for each row. So I basically need to do something like:

Get the String before the '/' in [Variant Descr.]

Get the String before the '/' in [Variant Order]

Insert the first value into the column specified by the second value

Do this for all parts of [Variant Descr.]

Do this for every row in the table

I have already tried to solve this with a user-defined function, only to find out that I cannot use dynamic SQL within a UDF.

Any help would be greatly appreciated

Cheers!

答:
One possible approach is to split the texts in [Variant Descr.] and [Variant Order] columns and update the table with dynamic statement.
Although using STRING_SPLIT() is the first choice starting with SQL Server 2016, this function is not an option in this case, because the order of the substrings is not guaranteed.
A working solution is to use OPENJSON() - columns values are transformed into a valid JSON object ('NAVY/44' is translated into '["NAVY", "44"]' for example) and substrings are retrieved using OPENJSON().

Input:

```<code>CREATE TABLE #Data (
   [Item] varchar(10),
   [Variant Descr.] varchar(50),
   [Variant Order] varchar(50),
   [Dim_Colour] varchar(50),
   [Dim_Size] varchar(50),
   [Dim_Style] varchar(50)
)
INSERT INTO #Data
   ([Item], [Variant Descr.], [Variant Order], [Dim_Colour], [Dim_Size], [Dim_Style])
VALUES
   ('01', 'NAVY/44',    'COLOUR/SIZE',       NULL, NULL, NULL),
   ('02', 'BLACK/S4',   'COLOUR/STYLE',      NULL, NULL, NULL),
   ('03', 'NAVY/44/S4', 'COLOUR/SIZE/STYLE', NULL, NULL, NULL),
   ('04', 'GREEN',      'COLOUR',            NULL, NULL, NULL)
</code>```

T-SQL:

```<code>-- Dynamic statement
DECLARE @stm nvarchar(max) = N''
SELECT @stm = @stm +
   N'UPDATE #Data ' +
   N'SET ' +
   QUOTENAME('Dim_' + j1.[value]) +
   N' = ''' +
   j2.[value] +
   N''' WHERE Item = ''' +
   d.Item +
   N'''; '
FROM #Data d
CROSS APPLY OPENJSON(CONCAT('["', REPLACE([Variant Order], '/', '","'), '"]')) j1
CROSS APPLY OPENJSON(CONCAT('["', REPLACE([Variant Descr.], '/', '","'), '"]')) j2
WHERE j1.[key] = j2.[key]

-- Execution and output
EXEC (@stm)
SELECT *
FROM #Data
</code>```

Output:

```<code>-----------------------------------------------------------------------------
Item    Variant Descr.  Variant Order     Dim_Colour    Dim_Size    Dim_Style
-----------------------------------------------------------------------------
01      NAVY/44         COLOUR/SIZE       NAVY          44
02      BLACK/S4        COLOUR/STYLE      BLACK                     S4
03      NAVY/44/S4      COLOUR/SIZE/STYLE NAVY          44          S4
04      GREEN           COLOUR            GREEN
</code>```

Body:
I am trying to build a fact table with sql server. It currently looks like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NULL         NULL       NULL
02         BLACK/S4       COLOUR/STYLE    NULL         NULL       NULL

I need to split the String in [Variant Descr.] and insert the parts into the correct Dim_ Column so the table will eventually look like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NAVY         44       NULL
02         BLACK/S4       COLOUR/STYLE    BLACK        NULL     S4

The problem is that the parts of [Variant Order] and the number of parts of [Variant Descr.] may vary for each row. So I basically need to do something like:

Get the String before the '/' in [Variant Descr.]

Get the String before the '/' in [Variant Order]

Insert the first value into the column specified by the second value

Do this for all parts of [Variant Descr.]

Do this for every row in the table

I have already tried to solve this with a user-defined function, only to find out that I cannot use dynamic SQL within a UDF.

Any help would be greatly appreciated

Cheers!

Body:
One possible approach is to split the texts in [Variant Descr.] and [Variant Order] columns and update the table with dynamic statement.
Although using STRING_SPLIT() is the first choice starting with SQL Server 2016, this function is not an option in this case, because the order of the substrings is not guaranteed.
A working solution is to use OPENJSON() - columns values are transformed into a valid JSON object ('NAVY/44' is translated into '["NAVY", "44"]' for example) and substrings are retrieved using OPENJSON().

Input:

CREATE TABLE #Data (
   [Item] varchar(10),
   [Variant Descr.] varchar(50),
   [Variant Order] varchar(50),
   [Dim_Colour] varchar(50),
   [Dim_Size] varchar(50),
   [Dim_Style] varchar(50)
)
INSERT INTO #Data
   ([Item], [Variant Descr.], [Variant Order], [Dim_Colour], [Dim_Size], [Dim_Style])
VALUES
   ('01', 'NAVY/44',    'COLOUR/SIZE',       NULL, NULL, NULL),
   ('02', 'BLACK/S4',   'COLOUR/STYLE',      NULL, NULL, NULL),
   ('03', 'NAVY/44/S4', 'COLOUR/SIZE/STYLE', NULL, NULL, NULL),
   ('04', 'GREEN',      'COLOUR',            NULL, NULL, NULL)

T-SQL:

-- Dynamic statement
DECLARE @stm nvarchar(max) = N''
SELECT @stm = @stm +
   N'UPDATE #Data ' +
   N'SET ' +
   QUOTENAME('Dim_' + j1.[value]) +
   N' = ''' +
   j2.[value] +
   N''' WHERE Item = ''' +
   d.Item +
   N'''; '
FROM #Data d
CROSS APPLY OPENJSON(CONCAT('["', REPLACE([Variant Order], '/', '","'), '"]')) j1
CROSS APPLY OPENJSON(CONCAT('["', REPLACE([Variant Descr.], '/', '","'), '"]')) j2
WHERE j1.[key] = j2.[key]

-- Execution and output
EXEC (@stm)
SELECT *
FROM #Data

Output:

-----------------------------------------------------------------------------
Item    Variant Descr.  Variant Order     Dim_Colour    Dim_Size    Dim_Style
-----------------------------------------------------------------------------
01      NAVY/44         COLOUR/SIZE       NAVY          44
02      BLACK/S4        COLOUR/STYLE      BLACK                     S4
03      NAVY/44/S4      COLOUR/SIZE/STYLE NAVY          44          S4
04      GREEN           COLOUR            GREEN


问:
MySQL server requested caching_sha2_password for a user with standard password
I have MySQL database up and running with the caching_sha2_password authentication.

It allows for creating users with the standard password authentication (mysql_native_password) but when trying to connect from a remote host with standard auth the user I'm getting 'The server requested authentication method unknown to the client [caching_sha2_password]...' error anyway.

Is it possible to use the legacy authentication for selected users even if the server supports caching_sha2_password.

The reason would be e. g. using strong authentication for the root and standard for the other accounts with limited access to single schemas.

(Version 8.0.16 GPL)

答:
Turned out that problem was on the client side – PHP 7 compatibility issues with MySQL 8.

Helpful link: https://github.com/laradock/laradock/issues/1130

After upgrading PHP to 7.3 my problem vanished.


问:
Singleton class in swift gives EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) error
I am writing a swift Network Manager library specifically to cater to my own API needs. This class is declared as final and there is a static let variable to define the singleton design pattern for this class. All the other functions in this class are class functions.

Unfortunately whenever this singleton class is called and the singleton design pattern method , i.e. static let sharedInstance : NetworkManager = NetworkManager.init() is called, it gives me

stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  error.

I thought that there could be an issue with the threads, but no. I just invoked the NetworkManager.shared simply in a UIViewController's viewDidLoad and it gave me the same error.

I am providing the whole code for NetworkManager class herewith

```<code>final class NetworkManager {

    static let sharedInstance : NetworkManager = NetworkManager.init()

    private var urlConfig = URLSessionConfiguration.default
    private var urlSession = URLSession(configuration: sharedInstance.urlConfig)

    var basePath : String = "https://api.myjson.com/";

    private init() {

        print("This is getting called at all");
    }
    //MARK:- POST METHODS
    class func performPOST(urlString : String?, bodyParams : [String : AnyObject]? = nil, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(urlString: urlString, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(url: url, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
       self.performJSON(request: request, completionHandler: completionHandler)
    }

    //MARK:- JSON FUNCTIONS
    class func performJSON(urlString : String?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET , completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){

        guard let urlString = urlString, let compURL = URL.init(string: NetworkManager.sharedInstance.basePath + urlString) else {
            completionHandler(.failure(.badURL))
            return
        }

        var urlReq = URLRequest.init(url: compURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30)

        do {
            try self.prepareTheURLRequest( request : &urlReq,
                                  bodyParams : bodyParams,
                                  headerParams : headerParams,
                                  method :method)
        }catch let error as NetworkError {
             completionHandler(.failure(error))
        }catch let error {
            completionHandler(.failure(NetworkError.unknownError(error)))
        }

        self.performJSON(request: urlReq, completionHandler: completionHandler)
    }

    class func performJSON( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET,  completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
    }

    //MARK:- FIRE_THE_REQUEST
    class func performJSON( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        if let req = request {
            let _ = NetworkManager.sharedInstance.urlSession.dataTask(with: req) { (data, response, error) in
                if let er = error{
                    completionHandler(.failure(NetworkError.unknownError(er)))
                }else if let resp = response{
                    do {
                        try self.validateTheResponse(response: resp)
                        completionHandler(.success(data))
                    } catch let error {
                        completionHandler(.failure(NetworkError.unknownError(error)))
                    }
                }else{
                    completionHandler(.failure(NetworkError.noResponseReceived))
                }
            }
        }
    }

    //MARK:- VALIDATE_RESPONSE
    class func validateTheResponse(response : URLResponse) throws {

        if let httpResponse = response as? HTTPURLResponse {
            let statusCode = httpResponse.statusCode

            switch statusCode {

            case 200 ... 300 :
                break
            default:
                let newError = NSError(domain: "Improper Status Code Received", code: 42, userInfo: ["statusCode":statusCode] )
                throw newError
            }
        }
    }
}
</code>```

The error received is as follows

       (lldb) bt
  * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
      frame #0: 0x000000010deab9d3 libdispatch.dylib_dispatch_once_wait + 101
      frame #1: 0x000000010bd00579 libswiftCore.dylibswift_once + 25   * frame #2: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #3: 0x000000010a7c010a MVVMNetworkManager.(self=0x0000600002756e20).init() at
  NetworkManager.swift:28:30
      frame #4: 0x000000010a7bfca0 MVVMNetworkManager.__allocating_init() at NetworkManager.swift:0
      frame #5: 0x000000010a7bfc4c MVVMglobalinit_33_100BB9A6FE18335AA78CDFBEA4A3C62B_func0 at
  NetworkManager.swift:25:65
      frame #6: 0x000000010deaadb5 libdispatch.dylib_dispatch_client_callout + 8
      frame #7: 0x000000010deac83d libdispatch.dylib_dispatch_once_callout + 66
      frame #8: 0x000000010bd00579 libswiftCore.dylibswift_once + 25
      frame #9: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #10: 0x000000010a7c06c3 MVVMstatic NetworkManager.performJSON(urlString="bins/9asku", bodyParams=nil,
  headerParams=nil, method=POST, completionHandler=0x000000010a7cc650
  MVVMpartial apply forwarder for closure #1
  (Swift.Result, MVVM.NetworkError>) ->
  () in MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:52:88
      frame #11: 0x000000010a7c03fa MVVMstatic NetworkManager.performPOST(urlString="bins/9asku", bodyParams=nil,
  completionHandler=0x000000010a7cc650 MVVMpartial apply forwarder for
  closure #1 (Swift.Result,
  MVVM.NetworkError>) -> () in
  MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:38:14
      frame #12: 0x000000010a7cc547 MVVMListRequest.fetchAllLists(completionHandler=0x000000010a7cf740
  MVVMclosure #1 (Swift.Result>,
  MVVM.NetworkError>) -> () in MVVM.ListPresenter.fetchAndShowList() ->
  () at ListPresenter.swift:29, self=0x0000600002b1c3a0) at
  ListRequest.swift:15:24
      frame #13: 0x000000010a7cf726 MVVMListPresenter.fetchAndShowList(self=0x0000600002779140) at
  ListPresenter.swift:29:17
      frame #14: 0x000000010a7c5551 MVVMListVC.viewDidAppear(animated=false, self=0x00007ff125e04540) at
  ListVC.swift:33:25
      frame #15: 0x000000010a7c55d3 MVVM@objc ListVC.viewDidAppear(_:) at <compiler-generated>:0
      frame #16: 0x000000010edb2536 UIKitCore-[UIViewController _setViewAppearState:isAnimating:] + 942
      frame #17: 0x000000010edb521c UIKitCore__64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke + 42
      frame #18: 0x000000010edb35ab UIKitCore-[UIViewController _executeAfterAppearanceBlock] + 75
      frame #19: 0x000000010f3b9e05 UIKitCore_runAfterCACommitDeferredBlocks + 634
      frame #20: 0x000000010f3a9199 UIKitCore_cleanUpAfterCAFlushAndRunDeferredBlocks + 358
      frame #21: 0x000000010f3c7cd9 UIKitCore__34-[UIApplication _firstCommitBlock]_block_invoke_2 + 142
      frame #22: 0x000000010ca7eaec CoreFoundationCFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK + 12
      frame #23: 0x000000010ca7e2b0 CoreFoundation__CFRunLoopDoBlocks + 336
      frame #24: 0x000000010ca78b34 CoreFoundation__CFRunLoopRun + 1252
      frame #25: 0x000000010ca78302 CoreFoundationCFRunLoopRunSpecific + 626
      frame #26: 0x0000000114b302fe GraphicsServicesGSEventRunModal + 65
      frame #27: 0x000000010f3aeba2 UIKitCoreUIApplicationMain + 140
      frame #28: 0x000000010a7caceb MVVMmain at AppDelegate.swift:12:7
      frame #29: 0x000000010df1f541 libdyld.dylib`start + 1 (lldb)

答:
Move the initialisation of your properties inside the init method. You can't access the static property sharedInstance when the object is being instantiated so that was what caused the crash

```<code>final class NetworkManager {

    static let sharedInstance = NetworkManager.init()

    private var urlConfig: URLSessionConfiguration
    private var urlSession: URLSession

    var basePath : String = "https://api.myjson.com/";

    private init() {
        urlConfig = URLSessionConfiguration.default
        urlSession = URLSession(configuration: urlConfig)
    }

    //... rest of class
</code>```

Body:
I am writing a swift Network Manager library specifically to cater to my own API needs. This class is declared as final and there is a static let variable to define the singleton design pattern for this class. All the other functions in this class are class functions.

Unfortunately whenever this singleton class is called and the singleton design pattern method , i.e. static let sharedInstance : NetworkManager = NetworkManager.init() is called, it gives me

stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  error.

I thought that there could be an issue with the threads, but no. I just invoked the NetworkManager.shared simply in a UIViewController's viewDidLoad and it gave me the same error.

I am providing the whole code for NetworkManager class herewith

final class NetworkManager {

    static let sharedInstance : NetworkManager = NetworkManager.init()

    private var urlConfig = URLSessionConfiguration.default
    private var urlSession = URLSession(configuration: sharedInstance.urlConfig)

    var basePath : String = "https://api.myjson.com/";

    private init() {

        print("This is getting called at all");
    }
    //MARK:- POST METHODS
    class func performPOST(urlString : String?, bodyParams : [String : AnyObject]? = nil, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(urlString: urlString, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(url: url, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
       self.performJSON(request: request, completionHandler: completionHandler)
    }

    //MARK:- JSON FUNCTIONS
    class func performJSON(urlString : String?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET , completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){

        guard let urlString = urlString, let compURL = URL.init(string: NetworkManager.sharedInstance.basePath + urlString) else {
            completionHandler(.failure(.badURL))
            return
        }

        var urlReq = URLRequest.init(url: compURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30)

        do {
            try self.prepareTheURLRequest( request : &urlReq,
                                  bodyParams : bodyParams,
                                  headerParams : headerParams,
                                  method :method)
        }catch let error as NetworkError {
             completionHandler(.failure(error))
        }catch let error {
            completionHandler(.failure(NetworkError.unknownError(error)))
        }

        self.performJSON(request: urlReq, completionHandler: completionHandler)
    }

    class func performJSON( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET,  completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
    }

    //MARK:- FIRE_THE_REQUEST
    class func performJSON( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        if let req = request {
            let _ = NetworkManager.sharedInstance.urlSession.dataTask(with: req) { (data, response, error) in
                if let er = error{
                    completionHandler(.failure(NetworkError.unknownError(er)))
                }else if let resp = response{
                    do {
                        try self.validateTheResponse(response: resp)
                        completionHandler(.success(data))
                    } catch let error {
                        completionHandler(.failure(NetworkError.unknownError(error)))
                    }
                }else{
                    completionHandler(.failure(NetworkError.noResponseReceived))
                }
            }
        }
    }

    //MARK:- VALIDATE_RESPONSE
    class func validateTheResponse(response : URLResponse) throws {

        if let httpResponse = response as? HTTPURLResponse {
            let statusCode = httpResponse.statusCode

            switch statusCode {

            case 200 ... 300 :
                break
            default:
                let newError = NSError(domain: "Improper Status Code Received", code: 42, userInfo: ["statusCode":statusCode] )
                throw newError
            }
        }
    }
}

The error received is as follows

       (lldb) bt
  * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
      frame #0: 0x000000010deab9d3 libdispatch.dylib_dispatch_once_wait + 101
      frame #1: 0x000000010bd00579 libswiftCore.dylibswift_once + 25   * frame #2: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #3: 0x000000010a7c010a MVVMNetworkManager.(self=0x0000600002756e20).init() at
  NetworkManager.swift:28:30
      frame #4: 0x000000010a7bfca0 MVVMNetworkManager.__allocating_init() at NetworkManager.swift:0
      frame #5: 0x000000010a7bfc4c MVVMglobalinit_33_100BB9A6FE18335AA78CDFBEA4A3C62B_func0 at
  NetworkManager.swift:25:65
      frame #6: 0x000000010deaadb5 libdispatch.dylib_dispatch_client_callout + 8
      frame #7: 0x000000010deac83d libdispatch.dylib_dispatch_once_callout + 66
      frame #8: 0x000000010bd00579 libswiftCore.dylibswift_once + 25
      frame #9: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #10: 0x000000010a7c06c3 MVVMstatic NetworkManager.performJSON(urlString="bins/9asku", bodyParams=nil,
  headerParams=nil, method=POST, completionHandler=0x000000010a7cc650
  MVVMpartial apply forwarder for closure #1
  (Swift.Result, MVVM.NetworkError>) ->
  () in MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:52:88
      frame #11: 0x000000010a7c03fa MVVMstatic NetworkManager.performPOST(urlString="bins/9asku", bodyParams=nil,
  completionHandler=0x000000010a7cc650 MVVMpartial apply forwarder for
  closure #1 (Swift.Result,
  MVVM.NetworkError>) -> () in
  MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:38:14
      frame #12: 0x000000010a7cc547 MVVMListRequest.fetchAllLists(completionHandler=0x000000010a7cf740
  MVVMclosure #1 (Swift.Result>,
  MVVM.NetworkError>) -> () in MVVM.ListPresenter.fetchAndShowList() ->
  () at ListPresenter.swift:29, self=0x0000600002b1c3a0) at
  ListRequest.swift:15:24
      frame #13: 0x000000010a7cf726 MVVMListPresenter.fetchAndShowList(self=0x0000600002779140) at
  ListPresenter.swift:29:17
      frame #14: 0x000000010a7c5551 MVVMListVC.viewDidAppear(animated=false, self=0x00007ff125e04540) at
  ListVC.swift:33:25
      frame #15: 0x000000010a7c55d3 MVVM@objc ListVC.viewDidAppear(_:) at <compiler-generated>:0
      frame #16: 0x000000010edb2536 UIKitCore-[UIViewController _setViewAppearState:isAnimating:] + 942
      frame #17: 0x000000010edb521c UIKitCore__64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke + 42
      frame #18: 0x000000010edb35ab UIKitCore-[UIViewController _executeAfterAppearanceBlock] + 75
      frame #19: 0x000000010f3b9e05 UIKitCore_runAfterCACommitDeferredBlocks + 634
      frame #20: 0x000000010f3a9199 UIKitCore_cleanUpAfterCAFlushAndRunDeferredBlocks + 358
      frame #21: 0x000000010f3c7cd9 UIKitCore__34-[UIApplication _firstCommitBlock]_block_invoke_2 + 142
      frame #22: 0x000000010ca7eaec CoreFoundationCFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK + 12
      frame #23: 0x000000010ca7e2b0 CoreFoundation__CFRunLoopDoBlocks + 336
      frame #24: 0x000000010ca78b34 CoreFoundation__CFRunLoopRun + 1252
      frame #25: 0x000000010ca78302 CoreFoundationCFRunLoopRunSpecific + 626
      frame #26: 0x0000000114b302fe GraphicsServicesGSEventRunModal + 65
      frame #27: 0x000000010f3aeba2 UIKitCoreUIApplicationMain + 140
      frame #28: 0x000000010a7caceb MVVMmain at AppDelegate.swift:12:7
      frame #29: 0x000000010df1f541 libdyld.dylib`start + 1 (lldb)

Body:
Move the initialisation of your properties inside the init method. You can't access the static property sharedInstance when the object is being instantiated so that was what caused the crash

final class NetworkManager {

    static let sharedInstance = NetworkManager.init()

    private var urlConfig: URLSessionConfiguration
    private var urlSession: URLSession

    var basePath : String = "https://api.myjson.com/";

    private init() {
        urlConfig = URLSessionConfiguration.default
        urlSession = URLSession(configuration: urlConfig)
    }

    //... rest of class


问:
Create non-duplicate appointments from list in worksheet
I am trying to make appointments from a given date.

To avoid duplicates I tried coloring the cells but that does not seem viable.

Now I am trying to check if an appointment with the same "subject" as the cell exists and if so go to the next line.

I get the error

Object required

Private Sub Workbook_Open()
    Set myOutlook = CreateObject("Outlook.Application")
    r = 2

    Do Until Trim(Cells(r, 8).Value) = ""
        If Cells(r, 9).Value = myapt.Subject = Cells(r, 9).Value Then
            r = r + 1
        Else
            Set myapt = myOutlook.createitem(1)

            myapt.Subject = Cells(r, 9).Value
            myapt.Start = Cells(r, 8).Value
            myapt.AllDayEvent = True
            myapt.BusyStatus = 5
            myapt.ReminderSet = True
            'myapt.Body = ""
            myapt.Save

            Cells(r, 8).Interior.ColorIndex = 4
            r = r + 1
        End If
    Loop
End Sub
```

答:
To check if an item exists you need to filter the existing items:

```<code>Option Explicit

Public Sub CreateItemsIfNotExist()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1") 'define your sheet!

    Dim olApp As Object  'create outlook application
    Set olApp = CreateObject("Outlook.Application")

    Dim olNS As Object 'get namespace
    Set olNS = olApp.GetNamespace("MAPI")

    'define constants if using late binding
    Const olFolderCalendar As Long = 9
    Const olAppointmentItem As Long = 1

    Dim olRecItems As Object 'get all appointments
    Set olRecItems = olNS.GetDefaultFolder(olFolderCalendar)

    Dim strFilter As String  'filter for appointments
    Dim olFilterRecItems As Object 'filtered appointments

    Dim iRow As Long
    iRow = 2

    Do Until Trim$(ws.Cells(iRow, 8).Value) = vbNullString
        'filter appointments for subject
        strFilter = "[Subject] = '" & Trim$(ws.Cells(iRow, 9).Value) & "'"
        Set olFilterRecItems = olRecItems.Items.Restrict(strFilter)

        If olFilterRecItems.Count = 0 Then 'if subject does not exist
            With olApp.CreateItem(olAppointmentItem)
                .Subject = ws.Cells(iRow, 9).Value
                .Start = ws.Cells(iRow, 8).Value
                .AllDayEvent = True
                .BusyStatus = 5
                .ReminderSet = True
                .Save
            End With
            ws.Cells(iRow, 8).Interior.ColorIndex = 4
        End If

        iRow = iRow + 1
    Loop
End Sub
</code>```

Note that maybe you want to quit outlook in the end olApp.Quit.

Body:
To check if an item exists you need to filter the existing items:

Option Explicit

Public Sub CreateItemsIfNotExist()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1") 'define your sheet!

    Dim olApp As Object  'create outlook application
    Set olApp = CreateObject("Outlook.Application")

    Dim olNS As Object 'get namespace
    Set olNS = olApp.GetNamespace("MAPI")

    'define constants if using late binding
    Const olFolderCalendar As Long = 9
    Const olAppointmentItem As Long = 1

    Dim olRecItems As Object 'get all appointments
    Set olRecItems = olNS.GetDefaultFolder(olFolderCalendar)

    Dim strFilter As String  'filter for appointments
    Dim olFilterRecItems As Object 'filtered appointments

    Dim iRow As Long
    iRow = 2

    Do Until Trim$(ws.Cells(iRow, 8).Value) = vbNullString
        'filter appointments for subject
        strFilter = "[Subject] = '" & Trim$(ws.Cells(iRow, 9).Value) & "'"
        Set olFilterRecItems = olRecItems.Items.Restrict(strFilter)

        If olFilterRecItems.Count = 0 Then 'if subject does not exist
            With olApp.CreateItem(olAppointmentItem)
                .Subject = ws.Cells(iRow, 9).Value
                .Start = ws.Cells(iRow, 8).Value
                .AllDayEvent = True
                .BusyStatus = 5
                .ReminderSet = True
                .Save
            End With
            ws.Cells(iRow, 8).Interior.ColorIndex = 4
        End If

        iRow = iRow + 1
    Loop
End Sub

Note that maybe you want to quit outlook in the end olApp.Quit.


问:
Python: How to pip install opencv2 with specific version 2.4.9?
I know that I could pip install opencv-python which installs opencv3, but is there a separate command or name for opencv specific version such as 2.4.9?

If not, how can I specify which version to install?

Thanks.

答:
Below Python packages are to be downloaded and installed to their default locations.

1.1. Python-2.7.x.

1.2. Numpy.

1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials).

Install all packages into their default locations. Python will be installed to C:/Python27/.

After installation, open Python IDLE. Enter import numpy and make sure Numpy is working fine.

Download latest OpenCV release from sourceforge site and double-click to extract it.

Goto opencv/build/python/2.7 folder.

Copy cv2.pyd to C:/Python27/lib/site-packeges.

Open Python IDLE and type following codes in Python terminal.

import cv2
      print cv2.version
      If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html


问:
How is "this" passed in C#
I'm trying to understand how "this" gets passed around as a property in C#-6.0 (VS 2015).

```<code>using System;

public class Person
{
    private Person instance;

    public Person()
    {
        instance = this;
    }

    public Person myself
    {
        get { return instance; }
        set { instance = value; }
    }

    public string name = "Eddie";

}

public class Example
{
    public static void Main()
    {
        Person firstPerson = new Person();
        Person secondPerson = firstPerson.myself;

        secondPerson.name = "Bill";
        Console.WriteLine(firstPerson.name);
        Console.WriteLine(secondPerson.name);

        firstPerson.myself = new Person();
        Console.WriteLine(firstPerson.name);
        Console.WriteLine(secondPerson.name);

        Console.ReadLine();
    }
}
</code>```

My assumption is that when the line:

Person secondPerson = firstPerson.myself;

is run, that secondPerson becomes a reference to firstPerson, so when I change the name to "Bill", firstPerson.name and secondPerson.name are both Bill. But when I run

firstPerson.myself = new Person();

I expected firstPerson.name and secondPerson.name to go back to "Eddie", but it remains "Bill". Why? Thanks in advance!

答:
1.Actually class variables are reference types.

2.So when you assign same instance to two variables then they will points to same instance.

3.Whenever you what to point fresh one you need to use 'new' keyword for assignment.

Title: How is "this" passed in C#

Body:
I'm trying to understand how "this" gets passed around as a property in C#-6.0 (VS 2015).

using System;

public class Person
{
    private Person instance;

    public Person()
    {
        instance = this;
    }

    public Person myself
    {
        get { return instance; }
        set { instance = value; }
    }

    public string name = "Eddie";

}

public class Example
{
    public static void Main()
    {
        Person firstPerson = new Person();
        Person secondPerson = firstPerson.myself;

        secondPerson.name = "Bill";
        Console.WriteLine(firstPerson.name);
        Console.WriteLine(secondPerson.name);

        firstPerson.myself = new Person();
        Console.WriteLine(firstPerson.name);
        Console.WriteLine(secondPerson.name);

        Console.ReadLine();
    }
}

My assumption is that when the line:

Person secondPerson = firstPerson.myself;

is run, that secondPerson becomes a reference to firstPerson, so when I change the name to "Bill", firstPerson.name and secondPerson.name are both Bill. But when I run

firstPerson.myself = new Person();

I expected firstPerson.name and secondPerson.name to go back to "Eddie", but it remains "Bill". Why? Thanks in advance!