问:
Any existing methods to find a drop in a noisy time series?
I have a time series (array of values) and I would like to find the starting points where a long drop in values begins (at least X consecutive values going down). For example:

Having a list of values

```<code>[1,2,3,4,3,4,5,4,3,4,5,4,3,2,1,2,3,2,3,4,3,4,5,6,7,8]
</code>```

I would like to find a drop of at least 5 consecutive values. So in this case I would find the segment 5,4,3,2,1.

However, in a real scenario, there is noise in the data, so the actual drop includes a lot of little ups and downs.

I could write an algorithm for this. But I was wondering whether there is an existing library or standard signal processing method for this type of analysis.

答:
You can do this pretty easily with pandas (which I know you have). Convert your list to a series, and then perform a groupby + count to find consecutively declining values:

```<code>v = pd.Series([...])
v[v.groupby(v.diff().gt(0).cumsum()).transform('size').ge(5)]

10    5
11    4
12    3
13    2
14    1
dtype: int64
</code>```

Body:
I have a time series (array of values) and I would like to find the starting points where a long drop in values begins (at least X consecutive values going down). For example:

Having a list of values

[1,2,3,4,3,4,5,4,3,4,5,4,3,2,1,2,3,2,3,4,3,4,5,6,7,8]

I would like to find a drop of at least 5 consecutive values. So in this case I would find the segment 5,4,3,2,1.

However, in a real scenario, there is noise in the data, so the actual drop includes a lot of little ups and downs.

I could write an algorithm for this. But I was wondering whether there is an existing library or standard signal processing method for this type of analysis.

Body:
You can do this pretty easily with pandas (which I know you have). Convert your list to a series, and then perform a groupby + count to find consecutively declining values:

v = pd.Series([...])
v[v.groupby(v.diff().gt(0).cumsum()).transform('size').ge(5)]

10    5
11    4
12    3
13    2
14    1
dtype: int64


来源: stackexchange

问:
Jupyter notebook parallel tasks with concurrent.futures
I am trying to do parallel tasks in a Jupyter notebook. Hoping someone can tell me what should I do or what should I learn.

In my Jupyter notebook, I would loop through an argument from 1 to 10 which passed to another py script. What I want is to let my computer do each argument with one single task. I believe, with that, I would expedite the efficiency.

Here is what I have in my Jupyter notebook:

```<code>import os
from time import time
start_1 = time()
# parameters
file = 'Tool_1.py' # the single py script which I would run in a single loop
file_1 = 'my_data.csv'
skiprows = 4
stop_loss_point_init = -50
stop_gain_point = 800
move_step = 100
move_far = 50
# loop body
for window in range(1, 11): # I would loop window from 1 to 10
    start_2 = time()
    cmd = 'python %s %s %d %d %d %d %d %d' % (file,file_1,skiprows,window,stop_loss_point_init,stop_gain_point,move_step,move_far)
    print('Running '+str(cmd))
    os.system(cmd)
    output_file = 'output_file.csv'
    end_2 = time()
    print(output_file)
    print("Exported in {:.2f} minutes.".format((end_2 - start_2)/60))

end_1 = time()
print("Completed in {:.2f} minutes.".format((end_1 - start_1)/60))
</code>```

答:
I think the easiest solution is ipyparallel.
You can create engines inside Jupyter-Notebook to do the parallel computing.

os.system() always waits untill the child process finishes, so you shouldn't use it for parallel computing. A better solution would be to define a method and use ipyparalles map() method as shown in this example.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to do parallel tasks in a Jupyter notebook. Hoping someone can tell me what should I do or what should I learn.

In my Jupyter notebook, I would loop through an argument from 1 to 10 which passed to another py script. What I want is to let my computer do each argument with one single task. I believe, with that, I would expedite the efficiency.

Here is what I have in my Jupyter notebook:

import os
from time import time
start_1 = time()
# parameters
file = 'Tool_1.py' # the single py script which I would run in a single loop
file_1 = 'my_data.csv'
skiprows = 4
stop_loss_point_init = -50
stop_gain_point = 800
move_step = 100
move_far = 50
# loop body
for window in range(1, 11): # I would loop window from 1 to 10
    start_2 = time()
    cmd = 'python %s %s %d %d %d %d %d %d' % (file,file_1,skiprows,window,stop_loss_point_init,stop_gain_point,move_step,move_far)
    print('Running '+str(cmd))
    os.system(cmd)
    output_file = 'output_file.csv'
    end_2 = time()
    print(output_file)
    print("Exported in {:.2f} minutes.".format((end_2 - start_2)/60))

end_1 = time()
print("Completed in {:.2f} minutes.".format((end_1 - start_1)/60))


问:
Row to string with space between items
I have this:

```<code>| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |
</code>```

and I want to MsgBox each row like that

```<code>Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend
</code>```

I want 3 MsgBox to appear  5 FA OFF 107 FA ON 96 FO ON.

Therefore, how to get a row properly and add space between items ?

(After i want to call WshShellExec with parameters)

答:
Please give this a try...</p>

```<code>Sub ConcatenateRowValues()
Dim x
Dim i As Long
Dim Str As String
x = Range("A1").CurrentRegion.Value
For i = 2 To UBound(x, 1)
    Str = Join(Application.Index(x, i, 0), " ")
    MsgBox Str
Next i
End Sub
</code>```

Title: Row to string with space between items

Body:
I have this:

| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |

and I want to MsgBox each row like that

Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend

I want 3 MsgBox to appear  5 FA OFF 107 FA ON 96 FO ON.

Therefore, how to get a row properly and add space between items ?

(After i want to call WshShellExec with parameters)

Body:
Please give this a try...

Sub ConcatenateRowValues()
Dim x
Dim i As Long
Dim Str As String
x = Range("A1").CurrentRegion.Value
For i = 2 To UBound(x, 1)
    Str = Join(Application.Index(x, i, 0), " ")
    MsgBox Str
Next i
End Sub


问:
How can I commit some changes to a file, but not others, in VSCode?
VSCode has excellent git integration but I can't find a way to do partial commits. Basically, I want to be able to select specific changes in my files and stage them without staging the entire file. This functionality is supported by the git CLI, Github native apps, and Atom plugins.

Mostly making sure I'm not just missing something before opening a ticket for it.

答: Update: October 2017: In the latest VSCode as of October 2017 (version 1.18) you can actually stage specific lines really easy just like you would do it with the git CLI git add -p. You just have to click on the edited line from the side like,  watch the diff and apply it or not.


问:
Since Vim 8.0, vim is outputting dotfiles into my directories
I just upgraded to Vim for Windows 8.0, and despite the fact that I have this in my _vimrc:

```<code>set backupdir=C:\Windows\Temp
set backupskip=C:\Windows\Temp
set directory=C:\Windows\Temp
set writebackup
set noswapfile
</code>```

... Vim still writes a file like .myfile.txt.un~ to the same directory when I save the file I'm editing.  How can I get this to save somewhere else so as not to clutter up the directory?

答:
OK I just realized that it's the undo functionality, and therefore I need to set the "undo dir".  Once I do this it stops write the files to the same directory:</p>

```<code>set undodir=C:\Windows\Temp
</code>```

Body:
I just upgraded to Vim for Windows 8.0, and despite the fact that I have this in my _vimrc:

set backupdir=C:\Windows\Temp
set backupskip=C:\Windows\Temp
set directory=C:\Windows\Temp
set writebackup
set noswapfile

... Vim still writes a file like .myfile.txt.un~ to the same directory when I save the file I'm editing.  How can I get this to save somewhere else so as not to clutter up the directory?

Body:
OK I just realized that it's the undo functionality, and therefore I need to set the "undo dir".  Once I do this it stops write the files to the same directory:

set undodir=C:\Windows\Temp


问:
Hyperledger Composer 0.15.0 sharing network with the local Playground
I was wondering if since the 0.15.0 release and switching to cards someone has figured out how to access the same network both locally via the CLI and in the Playground and with the same Fabric runtime.
So far, I have been able to install my network's runtime, start and ping it on the Playground's fabric after creating PeerAdmin card  using the script that came with Playground.
However, importing the newly deployed network's admin card fails in the Playground. If, however, I deploy the network via the Playground, export the admin card, download/import the admin card from the Playground and then try to composer ping it, it just sits there timing out after a while.    This is MacOS High Sierra. So what gives and what can be done?
Thanks much!</p>

答:
You can share the Business Network Cards between Playground and the CLI. However it can be a bit more difficult if you are running Playground in a Docker Container.

With the CLI you connect to your Fabric servers on localhost and Docker deals with the Port fowarding into the Containers for the Fabric.

The Fabric Containers (and the Playground if you start it in a container) connect with eachother on 'fake' addresses managed by docker-compose e.g. orderer.example.com:7050

So if you start composer-playground using the CLI any Card you export will have localhost as the addresses of Fabric servers and other CLI commands will be able to utilise it.  If however you are using Playground in a container the Card will use the fake addresses and you will not be able to connect from the CLI straightaway.

I assume you are using Playground in a Container and hence having the problem.  If you find the connection.json in a location similar to: ~/.composer/cards/admin@*xxxxxx*/connection.json and edit the addresses of the fabric server to be localhost you should be able to use the CLI as expected.


问:
shell interprets quotes as string
I'm new to shell script, so one of the first things to learn is something like:

```<code>echo "Hello there"
</code>```

However, this returns:

```<code>"Hello there"
</code>```

The shell seems to interpret quotes as part of the string.

This is not limited to the echo command, but also, for example: printf or read.

答: These are not equivalent: ¨ and ". In the shell, use " (34, \x22) for double quotes, not “ or ” etc.

Title: shell interprets quotes as string

Body:
I'm new to shell script, so one of the first things to learn is something like:

echo "Hello there"

However, this returns:

"Hello there"

The shell seems to interpret quotes as part of the string.

This is not limited to the echo command, but also, for example: printf or read.


问:
Continuing in Python's unittest when an assertion fails
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

```<code>class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!
</code>```

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.

答:
Do each assert in a separate method.</p>

```<code>class MathTest(unittest.TestCase):
  def test_addition1(self):
    self.assertEqual(1 + 0, 1)

  def test_addition2(self):
    self.assertEqual(1 + 1, 3)

  def test_addition3(self):
    self.assertEqual(1 + (-1), 0)

  def test_addition4(self):
    self.assertEqaul(-1 + (-1), -1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.

Body:
Do each assert in a separate method.

class MathTest(unittest.TestCase):
  def test_addition1(self):
    self.assertEqual(1 + 0, 1)

  def test_addition2(self):
    self.assertEqual(1 + 1, 3)

  def test_addition3(self):
    self.assertEqual(1 + (-1), 0)

  def test_addition4(self):
    self.assertEqaul(-1 + (-1), -1)

ContentLicense: CC BY-SA 2.5


问:
SQL statement to convert dd/mm/yy nvarchar(255) to Date format dd/mm/yyyy
I am struggling with a SQL statement to convert imported data that is in a format dd/mm/yy and of type nvarchar(255) into a date type 'dd/mm/yyyy' format.

The sample data is as follows:

Date:

```<code>'23/10/17'
'24/10/17'
'25/10/17'
'26/10/17'
'27/10/17'
</code>```

To Date Format:

```<code>'23/10/2017'
'24/10/2017'
'25/10/2017'
'26/10/2017'
'27/10/2017'
</code>```

I am using SQL Server 2008 R2

Body:
I am struggling with a SQL statement to convert imported data that is in a format dd/mm/yy and of type nvarchar(255) into a date type 'dd/mm/yyyy' format.

The sample data is as follows:

Date:

'23/10/17'
'24/10/17'
'25/10/17'
'26/10/17'
'27/10/17'

To Date Format:

'23/10/2017'
'24/10/2017'
'25/10/2017'
'26/10/2017'
'27/10/2017'

I am using SQL Server 2008 R2

Body:
Here you go:

WITH CTE AS (
    SELECT '23/10/17' AS MyDate
    UNION
    SELECT '24/10/17'
    UNION
    SELECT '25/10/17'
    UNION
    SELECT '26/10/17'
    UNION
    SELECT '27/10/17'
    )
    SELECT * ,
          CONVERT(DATE, MyDate,3) AS MyDate,
          CONVERT(VARCHAR, CONVERT(DATE, MyDate,3), 103) AS ExactFormat
    FROM CTE;

Results:

+----------+---------------------+-------------+
|  MyDate  |       MyDate        | ExactFormat |
+----------+---------------------+-------------+
| 23/10/17 | 23.10.2017 00:00:00 | 23/10/2017  |
| 24/10/17 | 24.10.2017 00:00:00 | 24/10/2017  |
| 25/10/17 | 25.10.2017 00:00:00 | 25/10/2017  |
| 26/10/17 | 26.10.2017 00:00:00 | 26/10/2017  |
| 27/10/17 | 27.10.2017 00:00:00 | 27/10/2017  |
+----------+---------------------+-------------+

Demo


问:
Create products Google play and in-app billing
I'm doing an app that have a RecyclerView with many items (some of them are fixed and are by default for everyone), but I'd like to make some of them "not free", means that you have to pay (if possible using Google Play) to unlock those items, can you guide to me how do I figure out this scenario? How do I know that the user has items that has paid for them, and when I know that he paid for them.

I do not want to use a Database because I only need two tables I guess, for example;

TABLE USER

Where I'll will store an id (I guess it will be the email if I finally create a Login GMAIL,FACEBOOK)

TABLE BOX

Where I'll put the BOX that are free and not free and as a Foreign Key I'll put the user.id to get references what BOX's he/she owns.

Right?

But, If I have to choose this way, because if the user pays for a box on my APP and then he want to use it in other device, it won't have the box unless he logs in on the new device, correct? So, If I had had to choose a Database and Hosting to do it, what will be your recommendation? (From start, I won't have too much data, so I don't need the best one, I only want to communicate with my Android app).

I hope it's clear now, otherwise, put a comment and I'll try to explain it better.

EDIT

Reading the answers I see that I can use Firebase, as @Haris Qureshi said, well what I'm confused is :

How do I store the product? I mean, I've read and watched videos on YouTube and I have to do it in Console of Google Play but do I need to send the .apk and then add the products?

If I do not need to create a Database, and I have to end up using Firebase, using the Storage stuff from Firebase will store my products? But I can assign it as a PURCHASED, PAID, AVAILABLE? Also I'll need to integrate the Authentication, right? Because he said that once you buy a product, it stores the gmail that has paid for it and you know who paid and not paid, so if he uses another device it will have the same products boughts (if he still with the same gmail).

The products can be dynamics? I mean, you can create for example an "event" and put that product only for x days, as I'll need an Image to show the product, I mean the product will have also an Image to show on the UI, but I see in the Console of Google Play I only can create an id for the product and if I'd have to create it dynamic I could do that, because I have to store the Images on /res/mipmap right?

EDIT2

What I need is what @Alex Mamo told to me :

You cannot store images in your Firebase database. You need to store them in Firebase Storage. In Firebase database you need to store only the urls of those images.

The flow is like this: upload image to Firebase Storage -> get the url of the corresponding image (when uploading) -> store the url in Firebase Database -> use the reference to display the image

I've created the products on google console developer, and I have to connect my app to in-app billing

答:
Add all your products in google play store as in app purchase products.

Pseudocode

Create a class say Products having data members as productID, productType, price, description, tag, etc.

Query for items available for purchase and save them in your Products
with tag AVAILABLE.

Query for purchased items and save them with tag PURCHASED.

Use Firebase to get free products and store them with tag FREE.

Populate your RecyclerView with given ArrayList and show your TextView accordingly in your adapter.

Google stores all purchase history but if you want to add more products you need to add products in google console as well publish new android version.

For more details see this example.


问:
Swift 4 Page Controll Watcher
I'm using xcode 9.1 and swift 4.
I have 2 Buttons in my View Controller, and i want their colors changed when my carousel page is changed.
Here's my code but it.
I want it to check every time my carousel Scrolls.
is there any "OnPageControl" Methods in swift 4?

Here's my code ( in viewDidLoad ) :

```<code>    if (self.carousel.pageControl.currentPage == 0)
    {
        self.registerButton.layer.borderColor = UIColor(red:68/255.0, green:180/255.0, blue:194/255.0, alpha: 1.0).cgColor
        self.loginButton.layer.backgroundColor = UIColor(red:68/255.0, green:180/255.0, blue:194/255.0, alpha: 1.0).cgColor
        NSLog("1")
    }

    else if (self.carousel.pageControl.currentPage == 1)
    {
        self.registerButton.layer.borderColor = UIColor(red:139/255.0, green:21/255.0, blue:21/255.0, alpha: 1.0).cgColor
        self.loginButton.layer.backgroundColor = UIColor(red:139/255.0, green:21/255.0, blue:21/255.0, alpha: 1.0).cgColor
        NSLog("2")
    }

    else if (self.carousel.pageControl.currentPage == 2)
    {
        self.registerButton.layer.borderColor = UIColor(red:174/255.0, green:135/255.0, blue:46/255.0, alpha: 1.0).cgColor
        self.loginButton.layer.backgroundColor = UIColor(red:174/255.0, green:135/255.0, blue:46/255.0, alpha: 1.0).cgColor
        NSLog("3")
    }
</code>```

答: There is nothing like a UIPageControlDelegate but UIScrollViewDelegate offers scrollViewDidScroll for that purpose. Using scrollView.contentOffset.x you can get the current page, assign it to the pageControl.currentPage and update your buttons there.

Title: Swift 4 Page Controll Watcher

Body:
I'm using xcode 9.1 and swift 4.
I have 2 Buttons in my View Controller, and i want their colors changed when my carousel page is changed.
Here's my code but it.
I want it to check every time my carousel Scrolls.
is there any "OnPageControl" Methods in swift 4?

Here's my code ( in viewDidLoad ) :

    if (self.carousel.pageControl.currentPage == 0)
    {
        self.registerButton.layer.borderColor = UIColor(red:68/255.0, green:180/255.0, blue:194/255.0, alpha: 1.0).cgColor
        self.loginButton.layer.backgroundColor = UIColor(red:68/255.0, green:180/255.0, blue:194/255.0, alpha: 1.0).cgColor
        NSLog("1")
    }

    else if (self.carousel.pageControl.currentPage == 1)
    {
        self.registerButton.layer.borderColor = UIColor(red:139/255.0, green:21/255.0, blue:21/255.0, alpha: 1.0).cgColor
        self.loginButton.layer.backgroundColor = UIColor(red:139/255.0, green:21/255.0, blue:21/255.0, alpha: 1.0).cgColor
        NSLog("2")
    }

    else if (self.carousel.pageControl.currentPage == 2)
    {
        self.registerButton.layer.borderColor = UIColor(red:174/255.0, green:135/255.0, blue:46/255.0, alpha: 1.0).cgColor
        self.loginButton.layer.backgroundColor = UIColor(red:174/255.0, green:135/255.0, blue:46/255.0, alpha: 1.0).cgColor
        NSLog("3")
    }


问:
Check if two items are equal
I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.

Is there a good method or query to check if the UserId == ThreadId?

My current code:

```<code>public void deleteThread() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_THREAD, null, null);
    db.close();

    Log.d(TAG, "Deleted all Thread info from sqlite");
}
</code>```

答:
You need to pass correct value to the well-documented delete method to narrow down the scope of deletion to a subset of all entries in the DB table.

```<code>public void deleteThreadById(String threadId) {
    SQLiteDatabase db = this.getWritableDatabase();
    String whereClause = "threadId = " + threadId;
    db.delete(TABLE_THREAD, whereClause, null);
    db.close();
}
</code>```

Deleting all threads of a given user via their userId would be similar but probably doesn't make sense in a forum software.

This is how SQL works in general and it's a bit scary you started development without familiarising yourself with the very basics.

Title: Check if two items are equal

Body:
I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.

Is there a good method or query to check if the UserId == ThreadId?

My current code:

public void deleteThread() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_THREAD, null, null);
    db.close();

    Log.d(TAG, "Deleted all Thread info from sqlite");
}

Body:
You need to pass correct value to the well-documented delete method to narrow down the scope of deletion to a subset of all entries in the DB table.

public void deleteThreadById(String threadId) {
    SQLiteDatabase db = this.getWritableDatabase();
    String whereClause = "threadId = " + threadId;
    db.delete(TABLE_THREAD, whereClause, null);
    db.close();
}

Deleting all threads of a given user via their userId would be similar but probably doesn't make sense in a forum software.

This is how SQL works in general and it's a bit scary you started development without familiarising yourself with the very basics.


问:
how to disable download video option
i want to disable download video link from control panel of video tag.

```<code>     <video oncontextmenu="return false;" id="myVideo" autoplay controls>
        <source src="uploads/videos/<?php echo $vid;?>" type="video/mp4">
    </video>
</code>```

答:
That's very easy it seems that your using the HTML 5 Video and using your sample above, below is the code:

```<code><video oncontextmenu="return false;" id="myVideo" autoplay controls controlsList="nodownload">
    <source src="uploads/videos/<?php echo $vid;?>" type="video/mp4">
</video>
</code>```

Just add controlsList="nodownload" in your video tag.

Title: how to disable download video option

Body:
i want to disable download video link from control panel of video tag.

     <video oncontextmenu="return false;" id="myVideo" autoplay controls>
        <source src="uploads/videos/<?php echo $vid;?>" type="video/mp4">
    </video>

Body:
That's very easy it seems that your using the HTML 5 Video and using your sample above, below is the code:

<video oncontextmenu="return false;" id="myVideo" autoplay controls controlsList="nodownload">
    <source src="uploads/videos/<?php echo $vid;?>" type="video/mp4">
</video>

Just add controlsList="nodownload" in your video tag.


问:
onPause() called before onResume() in BaseActivity
I have 2 activites A and B. Both of them extend BaseActivity. Activity A is the launcher activity. From A when I click a button, it goes to Activity B. But I found something weird and I don't know if it is normal. According to the activity lifecycle, onResume() is called before onPause(). But when I am on Activity B, the baseActivity first pauses and then resumes. Not only that as I press the back button and reach Activity A, the baseActivity pauses, resumes and then destroys. I still can't understand why. Maybe this is a noob question but I'm curious and I couldn't find any answers online. Hope you guys can help me!</p>

答:
I think the onPause came from you first activity and then the OnResume is form the second ... But since they both extends from your BaseActivity you will probably see your base activity events from that order but they are different instances of your BaseActivity

Just to be clear, you have two activities

ActivityA -> BaseActivity

ActivityB -> BaseActivity

If you Log you BaseActivity you will catch events from both activities because they are different instances of BaseActivity and not the same


问:
Unable to send mail via php mail()
I am unable to send an email via php's mail function.

This is the error I receive.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in D:\inetpub\vhosts\southernbatteries.com\httpdocs\includes\utils.php on line 6
Array ( [0] => [1] => Could not send mail, please try later... )

What exactly does this mean ? Does it mean there is not mail server installed on my webserver ? Is it possible to use a different mail server. E.g Gmails mail server to send the mail ?

答:
You need to have a mail server to send mails. If you only have apache, you cannot, unless you edit the php.ini file and set the smpt_server to one that allows you to do so. Note that this will only work depending on your ISP.

If you have a hosting account you can upload the files and online they will work.

Title: Unable to send mail via php mail()


答:
Give this a go</p>

```<code>Sub example()
    Dim str As String
    Dim r As Long
    Dim c

    ' I'd recommend changing this to your actual sheet
    With ActiveSheet
        For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
            str = vbNullString
            For Each c In Range(.Cells(r, 1), .Cells(r, .Cells(r, .Columns.Count).End(xlToLeft).Column))
                str = str & " " & c.Value2
            Next c
            MsgBox WorksheetFunction.Trim(str)
        Next r
    End With
End Sub
</code>```

Title: Row to string with space between items

Body:
Give this a go

Sub example()
    Dim str As String
    Dim r As Long
    Dim c

    ' I'd recommend changing this to your actual sheet
    With ActiveSheet
        For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
            str = vbNullString
            For Each c In Range(.Cells(r, 1), .Cells(r, .Cells(r, .Columns.Count).End(xlToLeft).Column))
                str = str & " " & c.Value2
            Next c
            MsgBox WorksheetFunction.Trim(str)
        Next r
    End With
End Sub


问:
How can I change the docker jwilder/nginx-proxy upload limits?
In my architecture I use the /jwilder/nginx-proxy as a proxy server in my docker and then I installed 3 WordPress websites with MySQL and WordPress.

They are working well but /jwilder/nginx-proxy has a default configuration upload limit to 2MB but my WordPress template is about 20MB.

When I am trying to upload this template

```<code>413 Request Entity Too Large
nginx/1.13.6
</code>```

In addition, I used below code to install /jwilder/nginx-proxy

```<code>docker run -d -p 80:80 --name nginx-proxy  -v /var/run/docker.sock:/tmp/docker.sock jwilder/nginx-proxy
</code>```

How can I configure the upload limits?

Regards

答:
After searching, I create a file outside the container called client_max_body_size.conf with the contents client_max_body_size 25m; (or whatever) and bind mount it into your nginx-proxy container:

```<code>docker run -d --name nginx-proxy -v /var/run/docker.sock:/tmp/docker.sock \
    -v $ <path>/client_max_body_size.conf:/etc/nginx/conf.d/client_max_body_size.conf:ro \
    -p 80:80 jwilder/nginx-proxy
</code>```

Body:
In my architecture I use the /jwilder/nginx-proxy as a proxy server in my docker and then I installed 3 WordPress websites with MySQL and WordPress.

They are working well but /jwilder/nginx-proxy has a default configuration upload limit to 2MB but my WordPress template is about 20MB.

When I am trying to upload this template

413 Request Entity Too Large
nginx/1.13.6

In addition, I used below code to install /jwilder/nginx-proxy

docker run -d -p 80:80 --name nginx-proxy  -v /var/run/docker.sock:/tmp/docker.sock jwilder/nginx-proxy

How can I configure the upload limits?

Regards

Body:
After searching, I create a file outside the container called client_max_body_size.conf with the contents client_max_body_size 25m; (or whatever) and bind mount it into your nginx-proxy container:

docker run -d --name nginx-proxy -v /var/run/docker.sock:/tmp/docker.sock \
    -v $ <path>/client_max_body_size.conf:/etc/nginx/conf.d/client_max_body_size.conf:ro \
    -p 80:80 jwilder/nginx-proxy


问:
Count number of threads used by Parallel.ForEach
How can I determine the number of threads used during a specific call of Parallel.ForEach (or Parallel.Invoke, or Parallel.For)

I know how to limit the maximum number of threads, e.g.

```<code>Parallel.ForEach(myList,
                 new ParallelOptions { MaxDegreeOfParallelism = 4 },
                 item => { doStuff(item); });
</code>```

I know that the Task.Parallel library uses some heuristics to determine the optimal number of additional threadpool threads to use at runtime, in addition to the current thread; some value between 0 and MaxDegreeOfParallelism.

I would like to know how many threads have actually been used, for logging purposes:

```<code>Stopwatch watch = Stopwatch.StartNew();
Parallel.ForEach(myList, item => { doStuff(item); });
trace.TraceInformation("Task finished in {0}ms using {1} threads",
       watch.ElapsedMilliseconds, NUM_THREADS_USED);
</code>```

I mainly want this data logged for curiosity's sake, and to improve my understanding. It does not have to be 100% reliable, since I do not intend to use it for anything else.

Is there a way to get this number, without major performance penalties?

答:
In your DoStuff method you can add the code like this

```<code>    private void DoStuff(T item)
        {
            Logger.Log($"Item {item.ToString()} was handled by thread # {Thread.CurrentThread.ManagedThreadId}");
            // your logic here
        }
</code>```

Body:
How can I determine the number of threads used during a specific call of Parallel.ForEach (or Parallel.Invoke, or Parallel.For)

I know how to limit the maximum number of threads, e.g.

Parallel.ForEach(myList,
                 new ParallelOptions { MaxDegreeOfParallelism = 4 },
                 item => { doStuff(item); });

I know that the Task.Parallel library uses some heuristics to determine the optimal number of additional threadpool threads to use at runtime, in addition to the current thread; some value between 0 and MaxDegreeOfParallelism.

I would like to know how many threads have actually been used, for logging purposes:

Stopwatch watch = Stopwatch.StartNew();
Parallel.ForEach(myList, item => { doStuff(item); });
trace.TraceInformation("Task finished in {0}ms using {1} threads",
       watch.ElapsedMilliseconds, NUM_THREADS_USED);

I mainly want this data logged for curiosity's sake, and to improve my understanding. It does not have to be 100% reliable, since I do not intend to use it for anything else.

Is there a way to get this number, without major performance penalties?

Body:
In your DoStuff method you can add the code like this

    private void DoStuff(T item)
        {
            Logger.Log($"Item {item.ToString()} was handled by thread # {Thread.CurrentThread.ManagedThreadId}");
            // your logic here
        }


问:
How to get tab active on page load -laravel
How can i get my first selected when i land on the page? When i land on the page, i have to select a tab before but is there a way i can have the first tab already selected when i land on the page?

when i load the page, i have my tabs showing but none of them are active until i click on them. Is there a way i can have the first tab active as the page loads.

HTML

```<code><div class="row">
        <div class="col-md-9">

          <div  class="nav-tabs-custom">

            <ul class="nav nav-tabs">
            @foreach($hotels as $hotel)

               <li ><a href="#tab_{{ $hotel->id }}" data-toggle="tab" >{!!$hotel->name!!}</a></li>
               @endforeach

            </ul>
            <div class="tab-content">
            @foreach($hotels as $hotel)

              <div class="tab-pane active" id="tab_{{ $hotel->id }}">

              @foreach($hotel->waiters as $waiter)

            <label class="mylabel" >  {{$waiter->name}} </label>

             </div>
            @endforeach
              </div>

            </div>

          </div>

        </div>
</code>```

答:
I think your problem is in the active class that is added to every tab it should be just for one like this :</p>

```<code><div class="row">
    <div class="col-md-9">

      <div  class="nav-tabs-custom">

        <ul class="nav nav-tabs">
        @foreach($hotels as $hotel)

           <li ><a href="#tab_{{ $hotel->id }}" data-toggle="tab" >{!!$hotel->name!!}</a></li>
           @endforeach

        </ul>
        <div class="tab-content">
        @foreach($hotels as $key => $hotel)
          <div class="tab-pane {{ $key==0 ? 'active' : ''}}" id="tab_{{ $hotel->id }}">
              @foreach($hotel->waiters as $waiter)
                  <label class="mylabel" >  {{$waiter->name}} </label>
              @endforeach
         </div>
        @endforeach
          </div>

        </div>

    </div>
</div>
</code>```

Body:
How can i get my first selected when i land on the page? When i land on the page, i have to select a tab before but is there a way i can have the first tab already selected when i land on the page?

when i load the page, i have my tabs showing but none of them are active until i click on them. Is there a way i can have the first tab active as the page loads.

HTML

            @foreach($hotels as $hotel)

id }}" data-toggle="tab" >{!!$hotel->name!!}

               @endforeach

            @foreach($hotels as $hotel)

id }}">

              @foreach($hotel->waiters as $waiter)

              {{$waiter->name}}

            @endforeach

Body:
I think your problem is in the active class that is added to every tab it should be just for one like this :

<div class="row">
    <div class="col-md-9">

      <div  class="nav-tabs-custom">

        <ul class="nav nav-tabs">
        @foreach($hotels as $hotel)

           <li ><a href="#tab_{{ $hotel->id }}" data-toggle="tab" >{!!$hotel->name!!}</a></li>
           @endforeach

        </ul>
        <div class="tab-content">
        @foreach($hotels as $key => $hotel)
          <div class="tab-pane {{ $key==0 ? 'active' : ''}}" id="tab_{{ $hotel->id }}">
              @foreach($hotel->waiters as $waiter)
                  <label class="mylabel" >  {{$waiter->name}} </label>
              @endforeach
         </div>
        @endforeach
          </div>

        </div>

    </div>
</div>


问:
Type mismatch, expected ListBuffer[Any], actual ListBuffer[CustomClass]
I don't understand the title error knowing that for this function :

```<code>def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}
</code>```

called with these parameters :

```<code>myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)
</code>```

Am i obliged to call function like this :

```<code>myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)
</code>```

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

答:
Mmm, so or this is not the good collection to use and there is a better either I use it badly and must not give it to the function but initialize into the function instead ?

I suppose Seq are covariant because defining function as following, this works :

```<code>def myFunction(objectList: Seq[Any], object: Any): Boolean = {...}
</code>```

Body:
I don't understand the title error knowing that for this function :

def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}

called with these parameters :

myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)

Am i obliged to call function like this :

myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

Body:
Mmm, so or this is not the good collection to use and there is a better either I use it badly and must not give it to the function but initialize into the function instead ?

I suppose Seq are covariant because defining function as following, this works :

def myFunction(objectList: Seq[Any], object: Any): Boolean = {...}


答:
You could use a (thread-safe) list to store the IDs of the used threads and count them:

```<code>ConcurrentBag<int> threadIDs = new ConcurrentBag<int>();
Parallel.ForEach(myList, item => {
    threadIDs.Add(Thread.CurrentThread.ManagedThreadId);
    doStuff(item);
});

int usedThreads = threadIDs.Distinct().Count();
</code>```

This does have a performance impact (especially the thread-safety logic of ConcurrentBag), but I can't tell how big that is. The relative effect depends on how much work doStuff does itself. If that method has only a few commands, this thread counting solution may even change the number of used threads.

Title: Count number of threads used by Parallel.ForEach

Body:
You could use a (thread-safe) list to store the IDs of the used threads and count them:

ConcurrentBag<int> threadIDs = new ConcurrentBag<int>();
Parallel.ForEach(myList, item => {
    threadIDs.Add(Thread.CurrentThread.ManagedThreadId);
    doStuff(item);
});

int usedThreads = threadIDs.Distinct().Count();

This does have a performance impact (especially the thread-safety logic of ConcurrentBag), but I can't tell how big that is. The relative effect depends on how much work doStuff does itself. If that method has only a few commands, this thread counting solution may even change the number of used threads.


问:
Sub Folder is affected by root web.config
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

```<code><pages theme="DefaultTheme">
</code>```

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

答:
You want to add

```<code><clear/>
</code>```

to the subfolder's web.config.  This will clear the parent configs values from whatever section you put clear into.  For instance if you wanted to clear any connection strings from a parent config file you would do this:

```<code><connectionStrings>
    <clear/>
    <!-- add new connection strings here -->
</connectionStrings>
</code>```

OwnerDisplayName: Sypress

Body:
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

<pages theme="DefaultTheme">

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

Body:
You want to add

<clear/>

to the subfolder's web.config.  This will clear the parent configs values from whatever section you put clear into.  For instance if you wanted to clear any connection strings from a parent config file you would do this:

<connectionStrings>
    <clear/>
    <!-- add new connection strings here -->
</connectionStrings>

OwnerDisplayName: Andrew Hare


问:
Why UIActivityViewController doesn't display localized cancel string?
As shown in the following screenshot:

Although the device language has been set to Arabic (you could recognize it by checking the status bar and the activity view controller title). However, the cancel button still has the "Cancel" title; Since we are unable to change its title, I assume it should automatically changed depends on the device language -which is Arabic in my case- (to be localized), as mentioned in the this answer.

What am I missing here?

答:
I found a solution which worked for me with my device language set to Arabic.

Go to your Info.plist and add Localized resources can be mixed with Boolean YES to it.

As mentioned in Core Foundation Keys:

CFBundleAllowMixedLocalizations

CFBundleAllowMixedLocalizations (Boolean - iOS, macOS) specifies
  whether the bundle supports the retrieval of localized strings from
  frameworks. This key is used primarily by Foundation tools that link
  to other system frameworks and want to retrieve localized resources
  from those frameworks.


问:
C++ multiple interfaces inheritance and static_cast
In the following code:

Live

```<code>#include <iostream>
#include <thread>
#include <mutex>
#include <functional>

struct IView {
    virtual void setOnClick() = 0;
};
struct ITextView : IView {
    virtual void setText() = 0;
};
struct IButton : ITextView {
    virtual void setRadius() = 0;
};

struct View : IView {
    int i = 1;
    virtual void setOnClick() override {
        std::cout << "setting OnClick! i: " << i << std::endl;
    };
};

/// Works as is
/// But if make "TextView : View, ITextView" - have segfault on the run
struct TextView : ITextView, View {
    int j = 2;
    virtual void setText() override {
        std::cout << "setting text! i: " << i << " j: " << j << std::endl;
    };

    // forward IView
    virtual void setOnClick() override {
        View::setOnClick();
    }
};

int main() {
    TextView tv;

    void* ptr = &tv;    // I need to pass raw pointer, and then restore "interface" from it

    ITextView* itv = static_cast<ITextView*>(ptr);  // I don't need safety checks here
    itv->setOnClick();
    itv->setText();

    return 0;
}
</code>```

If I change TextViews inheritance order I'll have segfault on itv->setText(); call.

Why is it important? Can I use static_cast here, or I have UB here? As I understand dynamic_cast only required with virtual inheritance, and this, as I can tell, not that case.

答:
Pointers to different class "slices" are different.

So when you tranport via void *, you need to

```<code>void * ptr = static_cast<ITextView *>(&tv);
...
ITextView* itv = static_cast<ITextView*>(ptr)
</code>```

Note that you have two "instances" of IView in your base class hierarchy:

```<code>TextView  <- ITextView <- ... <- IView
          \- View <- IView
</code>```

There is virtual inheritance to turn that into a "diamond": wikipedia

Body:
In the following code:

Live

#include <iostream>
#include <thread>
#include <mutex>
#include <functional>

struct IView {
    virtual void setOnClick() = 0;
};
struct ITextView : IView {
    virtual void setText() = 0;
};
struct IButton : ITextView {
    virtual void setRadius() = 0;
};

struct View : IView {
    int i = 1;
    virtual void setOnClick() override {
        std::cout << "setting OnClick! i: " << i << std::endl;
    };
};

/// Works as is
/// But if make "TextView : View, ITextView" - have segfault on the run
struct TextView : ITextView, View {
    int j = 2;
    virtual void setText() override {
        std::cout << "setting text! i: " << i << " j: " << j << std::endl;
    };

    // forward IView
    virtual void setOnClick() override {
        View::setOnClick();
    }
};

int main() {
    TextView tv;

    void* ptr = &tv;    // I need to pass raw pointer, and then restore "interface" from it

    ITextView* itv = static_cast<ITextView*>(ptr);  // I don't need safety checks here
    itv->setOnClick();
    itv->setText();

    return 0;
}

If I change TextViews inheritance order I'll have segfault on itv->setText(); call.

Why is it important? Can I use static_cast here, or I have UB here? As I understand dynamic_cast only required with virtual inheritance, and this, as I can tell, not that case.

Body:
Pointers to different class "slices" are different.

So when you tranport via void *, you need to

void * ptr = static_cast<ITextView *>(&tv);
...
ITextView* itv = static_cast<ITextView*>(ptr)

Note that you have two "instances" of IView in your base class hierarchy:

TextView  <- ITextView <- ... <- IView
          \- View <- IView

There is virtual inheritance to turn that into a "diamond": wikipedia


问:
How ${application.home} resolved in conf/logback.xml in play framework?
I am using Play Framework 2.4. This is a part of the default conf/logback.xml file Play 2.4

```<code><!--
  ~ Copyright (C) 2009-2016 Lightbend Inc. <https://www.lightbend.com>
  -->
<!-- The default logback configuration that Play uses if no other configuration is provided -->
<configuration>

  <conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" />

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
     <file>${application.home}/logs/application.log</file>
     <encoder>
       <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
     </encoder>
  </appender>
</configuration>
</code>```

You can see full version from here. My question is how exactly that ${application.home} can be resolved? I read this answer, but didn't work.

The exact situation is when I removed ${application.home} from <file></file> tag, the logs folder will be created outside (in Parallel with) the dist(play-restful-docker-1.0-SNAPSHOT) folder. (in production)

I can add the dist-name (play-restful-docker-1.0-SNAPSHOT) replacing ${application.home} and it creates logs folder inside the dist and works perfect. But it is not a good practice since it will have to be changed per every new version.

答:
You could create your own conf/logback.xml and override the default one. The additional ":-." after application.home will cause it to default to the current directory if application.home is not defined.  The default logback.xml of Play 2.5 does this automatically.</p>

```<code><configuration>
  <conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" />
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
     <file>${application.home:-.}/logs/application.log</file>
     <encoder>
       <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
     </encoder>
  </appender>
</configuration>
</code>```

Body:
I am using Play Framework 2.4. This is a part of the default conf/logback.xml file Play 2.4

<configuration>

  <conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" />

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
     <file>${application.home}/logs/application.log</file>
     <encoder>
       <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
     </encoder>
  </appender>
</configuration>

You can see full version from here. My question is how exactly that ${application.home} can be resolved? I read this answer, but didn't work.

The exact situation is when I removed ${application.home} from <file></file> tag, the logs folder will be created outside (in Parallel with) the dist(play-restful-docker-1.0-SNAPSHOT) folder. (in production)

I can add the dist-name (play-restful-docker-1.0-SNAPSHOT) replacing ${application.home} and it creates logs folder inside the dist and works perfect. But it is not a good practice since it will have to be changed per every new version.

Body:
You could create your own conf/logback.xml and override the default one. The additional ":-." after application.home will cause it to default to the current directory if application.home is not defined.  The default logback.xml of Play 2.5 does this automatically.

<configuration>
  <conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" />
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
     <file>${application.home:-.}/logs/application.log</file>
     <encoder>
       <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
     </encoder>
  </appender>
</configuration>


问:
Row to string with space between items
I have this:

```<code>| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |
</code>```

and I want to MsgBox each row like that

```<code>Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend
</code>```

I want 3 MsgBox to appear  5 FA OFF 107 FA ON 96 FO ON.

Therefore, how to get a row properly and add space between items ?

(After i want to call WshShellExec with parameters)

答:
```<code>Sub x()

For i = 1 To 3
a = Application.Transpose(Application.Transpose(Range("a1:c1").Offset(i, 0).Value))
Debug.Print Join(a, "|")
Next i

End Sub
</code>```

Title: Row to string with space between items

Body:
I have this:

| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |

and I want to MsgBox each row like that

Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend

I want 3 MsgBox to appear  5 FA OFF 107 FA ON 96 FO ON.

Therefore, how to get a row properly and add space between items ?

(After i want to call WshShellExec with parameters)


问:
How can I configure SocketCAN to a specific interface?
I'm using a Beaglebone Black with two CAN interfaces as SocketCAN. How can I link i.e the interface can0 to my hardware DCAN0? I need to use both sockets parallel but didn't find to configure the interfaces.</p>

答:
You can check the mapping of interfaces to devices via
ls -la /sys/class/*
while using the corresponding subdirectory for your CAN device.
Ethernet devices for example are listed in /sys/class/net/, terminal emulators/devices in /sys/class/tty/, etc.


问:
Escape MySQL strings in Java... without prepared statements
I am looking for a way to escape strings for MySQL queries with Java.

But WAIT, before some of you jump straight away to the conclusion of "prepared statements", I wish to explain a little more.

The problem is, I don't have a MySQL connection. I am not executing any MySQL queries directly from Java. I don't know much about prepared statement, but AFAIK, prepared statements need a live connection to work.

I want to my code to read in a bunch of CSV/XLS files, get the data and then generate a huge INSERT query for MySQL. BUT this query will be stored in a text file for now. It won't execute just yet until someone gives the green light and dump this text file into the database.

Is there an easy way to do so without employing an overkill framework/library? Thank you all.

答:
Try StringEscapeUtils.escapeSql()
This will do what you are expecting. </p>


问:
Move items with ng2-dragula from special place
I have an angular 4 application with the librairie ng2-dragula. I want to drag and drop some items but just if we take the item from a special place (with an icon) and not from anywhere on the item.

This is my code is my ts file:

```<code>constructor(private dragulaService: DragulaService) {
    dragulaService.drop.subscribe((value) => {
        this.onDrop(value);
    });
}
</code>```

And my html file :

```<code><tbody [dragula]='"other-bag"' [dragulaModel]='commands'>
    ...
</tbody>
</code>```

So, I have something like this picture but I want to allow the move just if we take the item from the 2 vertical bars.

Do you know how I can do it ?

答:
TL:DR Options for dragula bags have a property "moves" which is a function provided with the targeted element of the dragstart event as third parameter (handle)

```<code>  moves: function (el, source, handle, sibling) {
    return true; // elements are always draggable by default
  },
</code>```

so you can check property of the handle element to check if you want to allow the drag

There is a snippet of demo in the docs :

https://valor-software.com/ng2-dragula/index.html

search for "Drag handles float your cruise?" ...

```<code><div [dragula]='"sixth-bag"'></div>
<div [dragula]='"sixth-bag"'></div>

class MuchExample {
  constructor(private dragulaService: DragulaService) {
    dragulaService.setOptions('sixth-bag', {
      moves: function (el, container, handle) {
        return handle.className === 'handle';
      }
    });
  }
}
</code>```

Hope it helps

Body:
I have an angular 4 application with the librairie ng2-dragula. I want to drag and drop some items but just if we take the item from a special place (with an icon) and not from anywhere on the item.

This is my code is my ts file:

constructor(private dragulaService: DragulaService) {
    dragulaService.drop.subscribe((value) => {
        this.onDrop(value);
    });
}

And my html file :

    ...

So, I have something like this picture but I want to allow the move just if we take the item from the 2 vertical bars.

Do you know how I can do it ?

Body:
TL:DR Options for dragula bags have a property "moves" which is a function provided with the targeted element of the dragstart event as third parameter (handle)

  moves: function (el, source, handle, sibling) {
    return true; // elements are always draggable by default
  },

so you can check property of the handle element to check if you want to allow the drag

There is a snippet of demo in the docs :

https://valor-software.com/ng2-dragula/index.html

search for "Drag handles float your cruise?" ...

<div [dragula]='"sixth-bag"'></div>
<div [dragula]='"sixth-bag"'></div>

class MuchExample {
  constructor(private dragulaService: DragulaService) {
    dragulaService.setOptions('sixth-bag', {
      moves: function (el, container, handle) {
        return handle.className === 'handle';
      }
    });
  }
}

Hope it helps


问:
App crashes when Progress Dialog is open and user changes orientation
My application has a Progress Dialog for login process and when the orientation is changed while dialog box is open, app crashes.This all works fine, except when screen orientation changes while the dialog is up. At this point the app crashes. I am figuring out this issue from the last 3 nights but not able to get it, please help.
My fragment:

```<code>public class Example extends Fragment {

private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;

Unbinder unbinder;

@BindView(R.id.input_email) EditText _emailText;
@BindView(R.id.input_password)    EditText _passwordText;
@BindView(R.id.btn_login)    Button _loginButton;
@BindView(R.id.link_signup) TextView _signupLink;

@Override
public void onDestroyView() {
    super.onDestroyView();

    // unbind the view to free some memory
    unbinder.unbind();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.Example, container, false);

    unbinder=ButterKnife.bind(this,rootView);

    _loginButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            login();
        }
    });

    _signupLink.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view)
        {
            Intent create= new Intent(getActivity(),NewAccount.class);
            startActivity(create);
        }

    });
    return rootView;
}

public void login() {
    Log.d(TAG, "Login");

    if (!validate()) {
        onLoginFailed();
        return;
    }

    _loginButton.setEnabled(false);

    final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
            R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Authenticating...");
    progressDialog.show();
    //new YourAsynTask(getActivity()).execute();

    String email = _emailText.getText().toString();
    String password = _passwordText.getText().toString();

    // TODO: Implement your own authentication logic here.

   new android.os.Handler().postDelayed(
            new Runnable() {
                public void run() {
                    // On complete call either onLoginSuccess or onLoginFailed
                    onLoginSuccess();

                    // onLoginFailed();
                    progressDialog.dismiss();

                }
            }, 3000);
}

@Override
public void onPause() {
    Log.e("DEBUG", "OnPause of loginFragment1");
    super.onPause();
}

public void onLoginSuccess() {
    _loginButton.setEnabled(true);
    Intent i=new Intent(getActivity(),SuccessLogin.class);
    startActivity(i);
}

public void onLoginFailed() {
    Toast.makeText(getActivity(), "Login failed", Toast.LENGTH_LONG).show();

    _loginButton.setEnabled(true);
}

public boolean validate() {
    boolean valid = true;

    String email = _emailText.getText().toString();
    String password = _passwordText.getText().toString();

    if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        _emailText.setError("enter a valid email address");
        valid = false;
    } else {
        _emailText.setError(null);
    }

    if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
        _passwordText.setError("between 4 and 10 alphanumeric characters");
        valid = false;
    } else {
        _passwordText.setError(null);
    }

    return valid;
}
</code>```

Logcat output:

```<code>11-16 19:20:10.955 4022-4022/com.example.a1332931.login_application E/WindowManager: android.view.WindowLeaked: Activity com.example.a1332931.login_application.TabActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{42b6135 V.E...... R......D 0,0-683,232} that was originally added here
                                                                                at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
                                                                                at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
                                                                                at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                                at android.app.Dialog.show(Dialog.java:319)
                                                                                at com.example.a1332931.login_application.Example.login(Example.java:156)
                                                                                at com.example.a1332931.login_application.Example$1.onClick(Example.java:67)
                                                                                at android.view.View.performClick(View.java:5201)
                                                                                at android.view.View$PerformClick.run(View.java:21163)
                                                                                at android.os.Handler.handleCallback(Handler.java:746)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-16 19:20:10.957 4022-4095/com.example.a1332931.login_application E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8aa6c60

11-16 19:20:12.512 4022-4022/com.example.a1332931.login_application E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.a1332931.login_application, PID: 4022
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
                                                                                at com.example.a1332931.login_application.Example.onLoginSuccess(Example.java:200)
                                                                                at com.example.a1332931.login_application.Example$3.run(Example.java:168)
                                                                                at android.os.Handler.handleCallback(Handler.java:746)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
</code>```

答:
Add this configuration change in your Android manifest activity:</p>

```<code><activity
            android:name="YourActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"/>
</code>```

Body:
My application has a Progress Dialog for login process and when the orientation is changed while dialog box is open, app crashes.This all works fine, except when screen orientation changes while the dialog is up. At this point the app crashes. I am figuring out this issue from the last 3 nights but not able to get it, please help.
My fragment:

public class Example extends Fragment {

private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;

Unbinder unbinder;

@BindView(R.id.input_email) EditText _emailText;
@BindView(R.id.input_password)    EditText _passwordText;
@BindView(R.id.btn_login)    Button _loginButton;
@BindView(R.id.link_signup) TextView _signupLink;

@Override
public void onDestroyView() {
    super.onDestroyView();

    // unbind the view to free some memory
    unbinder.unbind();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.Example, container, false);

    unbinder=ButterKnife.bind(this,rootView);

    _loginButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            login();
        }
    });

    _signupLink.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view)
        {
            Intent create= new Intent(getActivity(),NewAccount.class);
            startActivity(create);
        }

    });
    return rootView;
}

public void login() {
    Log.d(TAG, "Login");

    if (!validate()) {
        onLoginFailed();
        return;
    }

    _loginButton.setEnabled(false);

    final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
            R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Authenticating...");
    progressDialog.show();
    //new YourAsynTask(getActivity()).execute();

    String email = _emailText.getText().toString();
    String password = _passwordText.getText().toString();

    // TODO: Implement your own authentication logic here.

   new android.os.Handler().postDelayed(
            new Runnable() {
                public void run() {
                    // On complete call either onLoginSuccess or onLoginFailed
                    onLoginSuccess();

                    // onLoginFailed();
                    progressDialog.dismiss();

                }
            }, 3000);
}

@Override
public void onPause() {
    Log.e("DEBUG", "OnPause of loginFragment1");
    super.onPause();
}

public void onLoginSuccess() {
    _loginButton.setEnabled(true);
    Intent i=new Intent(getActivity(),SuccessLogin.class);
    startActivity(i);
}

public void onLoginFailed() {
    Toast.makeText(getActivity(), "Login failed", Toast.LENGTH_LONG).show();

    _loginButton.setEnabled(true);
}

public boolean validate() {
    boolean valid = true;

    String email = _emailText.getText().toString();
    String password = _passwordText.getText().toString();

    if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        _emailText.setError("enter a valid email address");
        valid = false;
    } else {
        _emailText.setError(null);
    }

    if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
        _passwordText.setError("between 4 and 10 alphanumeric characters");
        valid = false;
    } else {
        _passwordText.setError(null);
    }

    return valid;
}

Logcat output:

11-16 19:20:10.955 4022-4022/com.example.a1332931.login_application E/WindowManager: android.view.WindowLeaked: Activity com.example.a1332931.login_application.TabActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{42b6135 V.E...... R......D 0,0-683,232} that was originally added here
                                                                                at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
                                                                                at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
                                                                                at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                                at android.app.Dialog.show(Dialog.java:319)
                                                                                at com.example.a1332931.login_application.Example.login(Example.java:156)
                                                                                at com.example.a1332931.login_application.Example$1.onClick(Example.java:67)
                                                                                at android.view.View.performClick(View.java:5201)
                                                                                at android.view.View$PerformClick.run(View.java:21163)
                                                                                at android.os.Handler.handleCallback(Handler.java:746)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-16 19:20:10.957 4022-4095/com.example.a1332931.login_application E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8aa6c60

11-16 19:20:12.512 4022-4022/com.example.a1332931.login_application E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.a1332931.login_application, PID: 4022
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
                                                                                at com.example.a1332931.login_application.Example.onLoginSuccess(Example.java:200)
                                                                                at com.example.a1332931.login_application.Example$3.run(Example.java:168)
                                                                                at android.os.Handler.handleCallback(Handler.java:746)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

Body:
Add this configuration change in your Android manifest activity:

<activity
            android:name="YourActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"/>


问:
How to use Retrofit and SimpleXML together in downloading and parsing an XML file from a site?
I just started working with Retrofit. I am working on a project that uses SimpleXML. Can somebody provide me an example in which one fetches an XML from a site e.g. http://www.w3schools.com/xml/simple.xml" and reads it out?</p>

答:
Here's how to do it with Retrofit 2.

First you need an interface like (headers annotations are optional) :

```<code>public interface ApiService
{

    @GET("xml/simple.xml")
    @Headers({"Accept: application/xml",
            "User-Agent: Retrofit-Sample-App"})
    Call<BreakfastMenu> getBreakfastMenu();

}
</code>```

The annotated POJOs for XML are the same as in the other answers.

Then you need to make a request to the server :

```<code>    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://www.w3schools.com/")
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .build();

    ApiService apiService = retrofit.create(ApiService.class);
    Call<BreakfastMenu> call = apiService.getBreakfastMenu();
    Response<BreakfastMenu> response = call.execute();
    // response.code() == 200
    BreakfastMenu breakfastMenu = response.body();
</code>```

The needed libraries are :

retrofit 2.3.0

okhttp 3.8.0

converter-simplexml 2.3.0

simple-xml 2.7.1

Java 7

Source available on my GitHub

Body:
Here's how to do it with Retrofit 2.

First you need an interface like (headers annotations are optional) :

public interface ApiService
{

    @GET("xml/simple.xml")
    @Headers({"Accept: application/xml",
            "User-Agent: Retrofit-Sample-App"})
    Call<BreakfastMenu> getBreakfastMenu();

}

The annotated POJOs for XML are the same as in the other answers.

Then you need to make a request to the server :

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://www.w3schools.com/")
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .build();

    ApiService apiService = retrofit.create(ApiService.class);
    Call<BreakfastMenu> call = apiService.getBreakfastMenu();
    Response<BreakfastMenu> response = call.execute();
    // response.code() == 200
    BreakfastMenu breakfastMenu = response.body();

The needed libraries are :

retrofit 2.3.0

okhttp 3.8.0

converter-simplexml 2.3.0

simple-xml 2.7.1

Java 7

Source available on my GitHub


问:
Finding string in file with batch and call other batch
I am on a need to finde if an output log ends with a desired string, and call another batch if it does.

I have already tried some solutions at StackOverflow but it is still not working.

```<code>title Validate daily execution

findstr /C: "Exiting with code 0" .\logs\20171116.log
if %errorlevel%==0 (
BBBB
CALL  AutoLogEmail
) else (
AAAAAAAa

)
</code>```

And the file that I am looking for in a sub folder, with the name above has the values

16-11-2017  6:50:00,75 START PROCESS XXXXXXX.ISPAC Microsoft (R) SQL
  Server Execute Package Utility Version 11.0.2100.60 for 64-bit
  Copyright (C) Microsoft Corporation. All rights reserved.

Started:  06:50:00 DTExec: The package execution returned
  DTSER_SUCCESS (0). Started:  06:50:00 Finished: 06:52:03 Elapsed:
  122.929 seconds 16-11-2017  6:52:04,00 END PROCESS XXXXXXXX.ISPAC : Exiting with code 0

Is there any especific function that I shall use? Can someone point me the error and explain why it is not working?

Thanks in advance
Helder

答:
You could try something like this:

```<code>@echo off
title Validate daily execution

>nul find "Exiting with code 0" .\logs\20171116.log && (
    CALL  AutoLogEmail
) || (
    echo not found
    pause
)
</code>```

In this case, it depends on the find command, which whill cause the && operator (which only executes the command after it if the previous one doesn't fail) to either call autologmail, or echo not found if it didn't find anything.

Body:
I am on a need to finde if an output log ends with a desired string, and call another batch if it does.

I have already tried some solutions at StackOverflow but it is still not working.

title Validate daily execution

findstr /C: "Exiting with code 0" .\logs\20171116.log
if %errorlevel%==0 (
BBBB
CALL  AutoLogEmail
) else (
AAAAAAAa

)

And the file that I am looking for in a sub folder, with the name above has the values

16-11-2017  6:50:00,75 START PROCESS XXXXXXX.ISPAC Microsoft (R) SQL
  Server Execute Package Utility Version 11.0.2100.60 for 64-bit
  Copyright (C) Microsoft Corporation. All rights reserved.

Started:  06:50:00 DTExec: The package execution returned
  DTSER_SUCCESS (0). Started:  06:50:00 Finished: 06:52:03 Elapsed:
  122.929 seconds 16-11-2017  6:52:04,00 END PROCESS XXXXXXXX.ISPAC : Exiting with code 0

Is there any especific function that I shall use? Can someone point me the error and explain why it is not working?

Thanks in advance
Helder

Body:
You could try something like this:

@echo off
title Validate daily execution

>nul find "Exiting with code 0" .\logs\20171116.log && (
    CALL  AutoLogEmail
) || (
    echo not found
    pause
)

In this case, it depends on the find command, which whill cause the && operator (which only executes the command after it if the previous one doesn't fail) to either call autologmail, or echo not found if it didn't find anything.


问:
batch script to send email
How to write a Windows batch script to send a mail? Give an example</p>

答:
You can enable the installed SMTP Server of Windows.
And then run a power shell script:</p>

```<code>$subject = $args[0]

# Create from/to addresses
$from = New-Object system.net.mail.MailAddress "remy@supertext.ch"
$to = New-Object system.net.mail.MailAddress "remy.blaettler@gmail.com"

# Create Message
$message = new-object system.net.mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = @"
Warning message from the Supertext Server
"@

# Set SMTP Server and create SMTP Client
$server = "209.162.190.6"
$client = new-object system.net.mail.smtpclient $server

# SO do it
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}
</code>```

Title: batch script to send email

Body:
You can enable the installed SMTP Server of Windows.
And then run a power shell script:

$subject = $args[0]

# Create from/to addresses
$from = New-Object system.net.mail.MailAddress "remy@supertext.ch"
$to = New-Object system.net.mail.MailAddress "remy.blaettler@gmail.com"

# Create Message
$message = new-object system.net.mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = @"
Warning message from the Supertext Server
"@

# Set SMTP Server and create SMTP Client
$server = "209.162.190.6"
$client = new-object system.net.mail.smtpclient $server

# SO do it
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}


问:
How do I change select2 box height
I love the select2 box from https://github.com/ivaynberg/select2
I am using the format: option to format each element, and it looks great.

Everything is fine except the selected element is bigger than the height of the select box due to an image.

I know how to change the width, but how do I change the height so that AFTER the element is selected, it shows the full thing (about 150px)

Here is my initiation:

```<code><script>
    $("#selboxChild").select2({
        matcher: function(term, text) {
            var t = (js_child_sponsors[text] ? js_child_sponsors[text] : text);
            return t.toUpperCase().indexOf(term.toUpperCase()) >= 0;
        },
        formatResult: formatChild,
        formatSelection: formatChild,
        escapeMarkup: function(m) {
            return m;
        }
    });
</script>
</code>```

and here is my select box

```<code><select id="selboxChild" style="width: 300px; height: 200px">
    <option value="">No child attached</option>
</select>
</code>```

To Clarify: I do NOT want the Height of each option to change
I am looking for the select box to change height after you select a child.

So when the page first loads it says "No child selected"
When you click the drop down and select a child you see the child's image.
NOW i need the select box to expand! Otherwise the picture of the child is cut off.

Does anyone understand?

答:
I know this question is super old, but I was looking for a solution to this same question in 2017 and found one myself.

```<code>.select2-selection {
    height: auto !important;
}
</code>```

This will dynamically adjust the height of your input based on its content.

Title: How do I change select2 box height

Body:
I love the select2 box from https://github.com/ivaynberg/select2
I am using the format: option to format each element, and it looks great.

Everything is fine except the selected element is bigger than the height of the select box due to an image.

I know how to change the width, but how do I change the height so that AFTER the element is selected, it shows the full thing (about 150px)

Here is my initiation:

and here is my select box

<select id="selboxChild" style="width: 300px; height: 200px">
    <option value="">No child attached</option>
</select>

To Clarify: I do NOT want the Height of each option to change
I am looking for the select box to change height after you select a child.

So when the page first loads it says "No child selected"
When you click the drop down and select a child you see the child's image.
NOW i need the select box to expand! Otherwise the picture of the child is cut off.

Does anyone understand?

Body:
I know this question is super old, but I was looking for a solution to this same question in 2017 and found one myself.

.select2-selection {
    height: auto !important;
}

This will dynamically adjust the height of your input based on its content.


问:
How to find the top 5 values of a column according to another column?
I am practising on the IMDB dataset and i would like to find the top genres that had the most budget.

Actually that would be useful in situations where a boxplot is needed and the genres are numerous. Thus, minimising them to the most expensive would make the boxplot more clear.

```<code>i tried this: df.sort_values(by=["genres","budget"])
</code>```

but it isn't right.

答:
If need return all columns:

I think you need sort_values + groupby + head:

```<code>df=df.sort_values(by=["genres","budget"], ascending=[True, False]).groupby("genres").head(5)
</code>```

Or nlargest:

```<code>df = df.groupby('genres', group_keys=False).apply(lambda x: x.nlargest(5, "budget"))
</code>```

If need retun only genres and budget columns:

```<code>df = df.groupby('genres')["budget"].nlargest(2).reset_index(level=1, drop=True).reset_index()
</code>```

Samples:

```<code>df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'budget':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'genres':list('aaabbb')})

print (df)
   A  B  C  E  budget genres
0  a  4  7  5       1      a
1  b  5  8  3       3      a
2  c  4  9  6       5      a
3  d  5  4  9       7      b
4  e  5  2  2       1      b
5  f  4  3  4       0      b
</code>```

```<code>df1=df.sort_values(by=["genres","budget"], ascending=[True, False]).groupby("genres").head(2)

df1 = df.groupby('genres', group_keys=False).apply(lambda x: x.nlargest(2, "budget"))

print (df1)
   A  B  C  E  budget genres
2  c  4  9  6       5      a
1  b  5  8  3       3      a
3  d  5  4  9       7      b
4  e  5  2  2       1      b
</code>```

```<code>df1=df.groupby('genres')["budget"].nlargest(2).reset_index(level=1, drop=True).reset_index()
print (df1)
  genres  budget
0      a       5
1      a       3
2      b       7
3      b       1
</code>```

---

If need top genres with sum of badget per genres:

```<code>df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'budget':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'genres':list('aabbcc')})

print (df)
   A  B  C  E  budget genres
0  a  4  7  5       1      a
1  b  5  8  3       3      a
2  c  4  9  6       5      b
3  d  5  4  9       7      b
4  e  5  2  2       1      c
5  f  4  3  4       0      c

df = df.groupby('genres')['budget'].sum().nlargest(2)
print (df)
genres
b    12
a     4
Name: budget, dtype: int64
</code>```

Detail:

```<code>print (df.groupby('genres')['budget'].sum())
genres
a     4
b    12
c     1
Name: budget, dtype: int64
</code>```

Body:
I am practising on the IMDB dataset and i would like to find the top genres that had the most budget.

Actually that would be useful in situations where a boxplot is needed and the genres are numerous. Thus, minimising them to the most expensive would make the boxplot more clear.

i tried this: df.sort_values(by=["genres","budget"])

but it isn't right.

Body:
If need return all columns:

I think you need sort_values + groupby + head:

df=df.sort_values(by=["genres","budget"], ascending=[True, False]).groupby("genres").head(5)

Or nlargest:

df = df.groupby('genres', group_keys=False).apply(lambda x: x.nlargest(5, "budget"))

If need retun only genres and budget columns:

df = df.groupby('genres')["budget"].nlargest(2).reset_index(level=1, drop=True).reset_index()

Samples:

df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'budget':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'genres':list('aaabbb')})

print (df)
   A  B  C  E  budget genres
0  a  4  7  5       1      a
1  b  5  8  3       3      a
2  c  4  9  6       5      a
3  d  5  4  9       7      b
4  e  5  2  2       1      b
5  f  4  3  4       0      b

df1=df.sort_values(by=["genres","budget"], ascending=[True, False]).groupby("genres").head(2)

df1 = df.groupby('genres', group_keys=False).apply(lambda x: x.nlargest(2, "budget"))

print (df1)
   A  B  C  E  budget genres
2  c  4  9  6       5      a
1  b  5  8  3       3      a
3  d  5  4  9       7      b
4  e  5  2  2       1      b

df1=df.groupby('genres')["budget"].nlargest(2).reset_index(level=1, drop=True).reset_index()
print (df1)
  genres  budget
0      a       5
1      a       3
2      b       7
3      b       1

---

If need top genres with sum of badget per genres:

df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'budget':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'genres':list('aabbcc')})

print (df)
   A  B  C  E  budget genres
0  a  4  7  5       1      a
1  b  5  8  3       3      a
2  c  4  9  6       5      b
3  d  5  4  9       7      b
4  e  5  2  2       1      c
5  f  4  3  4       0      c

df = df.groupby('genres')['budget'].sum().nlargest(2)
print (df)
genres
b    12
a     4
Name: budget, dtype: int64

Detail:

print (df.groupby('genres')['budget'].sum())
genres
a     4
b    12
c     1
Name: budget, dtype: int64


问:
Regular expression to search text "From TableName" using VisualStudio
I am using the below regular expression to search sql script file from VisualStudio find text in files dialogbox:

```<code>from\s+(Table123|\[Table123\])\s*
</code>```

Output:

```<code>FROM [Table123] [i]

FROM Table123 I

FROM Table123Extended t1

FROM Table123";

How can I modify my regular expression to eliminate third result

1. FROM [Table123] [i]         (correct)

2. FROM Table123 I             (correct)

3. FROM Table123Extended t1    (incorrect)

4. FROM Table123";             (correct)
</code>```

Body:
I am using the below regular expression to search sql script file from VisualStudio find text in files dialogbox:

from\s+(Table123|\[Table123\])\s*

Output:

FROM [Table123] [i]

FROM Table123 I

FROM Table123Extended t1

FROM Table123";

How can I modify my regular expression to eliminate third result

1. FROM [Table123] [i]         (correct)

2. FROM Table123 I             (correct)

3. FROM Table123Extended t1    (incorrect)

4. FROM Table123";             (correct)


问:
calloc causes Bad Access
My main function has this:

```<code> int main() {
  //
  double minW, minL, width, length;
  unsigned tileCap = 10;
  auto *tiles = (Tile*)calloc(tileCap, sizeof(Tile) );
  GetInput(&minW, &minL, &tiles, &tileCap);
 }
</code>```

And my GetInput() will read and save into the array of Tiles:

```<code>void GetInput(double *w, double *l, Tile **tiles, unsigned *tileCap) {
  //
  printf("Tile:\n");
  double tileSize, tileJoint;
  int argc;
  unsigned tileCount = 0;

  do {
    argc = scanf("%lf %lf", &tileSize, &tileJoint);
    if (tileSize == 0 || !CorrectSize(tileSize) || !CorrectSize(tileJoint) || argc != 2)
      BadInput();

    bool needTransform = HasFloatingPoint(tileSize);
    if(needTransform) {
      tileSize = MultiplyByTen(tileSize);
      tileJoint = MultiplyByTen(tileJoint);
    }

    tiles[tileCount]->size = (long long)tileSize;
    printf("%lld\n", tiles[tileCount]->size);
    tiles[tileCount]->joint = (long long)tileJoint;

    if(++tileCount == *tileCap) {
      DoubleArray(tiles, tileCap); //f() with realloc
    }
  } while(argc != EOF);
}
</code>```

This program works for first iteration of inputs but always gives exit code 11 and the debugger says BAD_ACCESS at the assignment.

So either I'm accessing or allocating the array incorrectly.

I give my function a double pointer. So in order to access Tile members, I need to dereference it twice. One dereference is [] and the other one is ->. Printing the Tile after assigning confirms it.

And I see nothing wrong with my allocation. Where am I wrong?

EDIT: tiles[index]->size would mean *(tiles[index]).size while I need (*tiles)[index].size. Dereference order and scope is important.

答:
Even though your code seems incomplete and I'm mostly guessing, the issue seems to be in the following line in your main function:

```<code> GetInput(&minW, &minL, &tiles, &tileCap);
</code>```

You should consider that tiles is already a pointer. When you're using &tiles, you're actually passing a pointer to your pointer and not the pointer itself.

In your GetInput function, you're using tiles[tileCount] which indicated you wanted to pass a pointer. If your GetInput was supposed to get a double pointer, you would have used (*tiles)[tileCount].

You can solve many of these issues by listening

I think what you probably meant to do was:

```<code> GetInput(&minW, &minL, tiles, &tileCap);
</code>```

And the function definition should probably look like this:

```<code> void GetInput(double *w, double *l, Tile *tiles, unsigned *tileCap
</code>```

EDIT: (using a double pointer)

Since you need to use a double pointer, than you should remember to dereference the double pointer when you're looking into the data. i.e.:

```<code>*(tiles)[tileCount]->size = (long long)tileSize;
printf("%lld\n", *(tiles)[tileCount]->size);
*(tiles)[tileCount]->joint = (long long)tileJoint;
</code>```

Explanation:

A double pointer needs a double de-referencing. The first dereferencing collects the information on the nested pointer (*tiles) and the second dereferencing collects the data (**tiles).

The double dereferencing can also be achieved using the square brackets ((*tiles)[i] or tiles[0][i]).

Since tiles is a struct you can use the "arrow" as the second dereferencing technique as well: (*tiles)->size

Title: calloc causes Bad Access

Body:
My main function has this:

 int main() {
  //
  double minW, minL, width, length;
  unsigned tileCap = 10;
  auto *tiles = (Tile*)calloc(tileCap, sizeof(Tile) );
  GetInput(&minW, &minL, &tiles, &tileCap);
 }

And my GetInput() will read and save into the array of Tiles:

void GetInput(double *w, double *l, Tile **tiles, unsigned *tileCap) {
  //
  printf("Tile:\n");
  double tileSize, tileJoint;
  int argc;
  unsigned tileCount = 0;

  do {
    argc = scanf("%lf %lf", &tileSize, &tileJoint);
    if (tileSize == 0 || !CorrectSize(tileSize) || !CorrectSize(tileJoint) || argc != 2)
      BadInput();

    bool needTransform = HasFloatingPoint(tileSize);
    if(needTransform) {
      tileSize = MultiplyByTen(tileSize);
      tileJoint = MultiplyByTen(tileJoint);
    }

    tiles[tileCount]->size = (long long)tileSize;
    printf("%lld\n", tiles[tileCount]->size);
    tiles[tileCount]->joint = (long long)tileJoint;

    if(++tileCount == *tileCap) {
      DoubleArray(tiles, tileCap); //f() with realloc
    }
  } while(argc != EOF);
}

This program works for first iteration of inputs but always gives exit code 11 and the debugger says BAD_ACCESS at the assignment.

So either I'm accessing or allocating the array incorrectly.

I give my function a double pointer. So in order to access Tile members, I need to dereference it twice. One dereference is [] and the other one is ->. Printing the Tile after assigning confirms it.

And I see nothing wrong with my allocation. Where am I wrong?

EDIT: tiles[index]->size would mean *(tiles[index]).size while I need (*tiles)[index].size. Dereference order and scope is important.

Body:
Even though your code seems incomplete and I'm mostly guessing, the issue seems to be in the following line in your main function:

 GetInput(&minW, &minL, &tiles, &tileCap);

You should consider that tiles is already a pointer. When you're using &tiles, you're actually passing a pointer to your pointer and not the pointer itself.

In your GetInput function, you're using tiles[tileCount] which indicated you wanted to pass a pointer. If your GetInput was supposed to get a double pointer, you would have used (*tiles)[tileCount].

You can solve many of these issues by listening

I think what you probably meant to do was:

 GetInput(&minW, &minL, tiles, &tileCap);

And the function definition should probably look like this:

 void GetInput(double *w, double *l, Tile *tiles, unsigned *tileCap

EDIT: (using a double pointer)

Since you need to use a double pointer, than you should remember to dereference the double pointer when you're looking into the data. i.e.:

*(tiles)[tileCount]->size = (long long)tileSize;
printf("%lld\n", *(tiles)[tileCount]->size);
*(tiles)[tileCount]->joint = (long long)tileJoint;

Explanation:

A double pointer needs a double de-referencing. The first dereferencing collects the information on the nested pointer (*tiles) and the second dereferencing collects the data (**tiles).

The double dereferencing can also be achieved using the square brackets ((*tiles)[i] or tiles[0][i]).

Since tiles is a struct you can use the "arrow" as the second dereferencing technique as well: (*tiles)->size