问:
Why doesn't TypeScript catch that a const is being used before assignment?
I have a very simple example where TypeScript (3.5.1) is fine with the code, but it immediately throws an error when run.

I believe the issue here is that essentially value is declared but not initialized prior to getValue running.  This is pretty unintuitive imo but I understand this is how JS works.

However, why can't TS detect this issue in such a simple example?  Since value is a const, it seems to me TS should be able to determine exactly when it's set and predict that this code crashes.

console.log(getValue());

const value = "some string";

function getValue() {
  return value;
}
```

<p>In a second example without a function call, TS does catch that the variable is used before assignment:</p>

<pre class="lang-js prettyprint-override"><code>console.log(value);
const value = "some string";
</code>```

TSLint's no-use-before-declare also does not appear applicable.

Assuming TS/linting will not be able to catch this, is there a best practice to apply in the initial example that will avoid this crash?  "Always declare module-level consts at top of file" for example.

答:
You could enable tslint's only-arrow-functions and then replace your function getValue() with

const getValue = function(): string {
  return value;
}
```

<p>or even</p>

<pre class="lang-js prettyprint-override"><code>const getValue = (): string => value;
</code>```

At that point your first line will be a compiler error:

```<code>Block-scoped variable 'getValue' used before its declaration
</code>```

Body:
I have a very simple example where TypeScript (3.5.1) is fine with the code, but it immediately throws an error when run.

I believe the issue here is that essentially value is declared but not initialized prior to getValue running.  This is pretty unintuitive imo but I understand this is how JS works.

However, why can't TS detect this issue in such a simple example?  Since value is a const, it seems to me TS should be able to determine exactly when it's set and predict that this code crashes.

console.log(getValue());

const value = "some string";

function getValue() {
  return value;
}

In a second example without a function call, TS does catch that the variable is used before assignment:

console.log(value);
const value = "some string";

TSLint's no-use-before-declare also does not appear applicable.

Assuming TS/linting will not be able to catch this, is there a best practice to apply in the initial example that will avoid this crash?  "Always declare module-level consts at top of file" for example.

Body:
You could enable tslint's only-arrow-functions and then replace your function getValue() with

const getValue = function(): string {
  return value;
}

or even

const getValue = (): string => value;

At that point your first line will be a compiler error:

Block-scoped variable 'getValue' used before its declaration


来源: stackexchange

问:
Covert a dataframe into a matrix form
I have a dataset looks like this:

```<code>state VDM  MDM  OM
AP     1    2   5
GOA    1    2   1
GU     1    2   4
KA     1    5   1
MA     1    4   4
</code>```

I have tried this code:

```<code>aMat=df1000.as_matrix()
print(aMat)
</code>```

here df1000 is the dataset.

But the above code gives this output:

```<code>[['AP' 1 2 5]
 ['GOA' 1 2 1]
 ['GU' 1 2 4]
 ['KA' 1 5 1]
 ['MA' 1 4 4]]
</code>```

I want to create a 2d list or matrix which looks like this:

```<code>[[1, 2, 5], [1, 2, 1], [1,  2,  4], [1, 5, 1], [1, 4, 4]]
</code>```

答:
Select all columns without first by DataFrame.iloc and convert integer values to strings by DataFrame.astype, last convert to numpy array by to_numpy or DataFrame.values:

```<code>#pandas 0.24+
aMat=df1000.iloc[:, 1:].astype(str).to_numpy()
#pandas below
aMat=df1000.iloc[:, 1:].astype(str).values
</code>```

Or remove first column by DataFrame.drop:

```<code>#pandas 0.24+
aMat=df1000.drop('state', axis=1).astype(str).to_numpy()
#pandas below
aMat=df1000.drop('state', axis=1).astype(str).values
</code>```

ContentLicense: CC BY-SA 4.0

Title: Covert a dataframe into a matrix form

Body:
I have a dataset looks like this:

state VDM  MDM  OM
AP     1    2   5
GOA    1    2   1
GU     1    2   4
KA     1    5   1
MA     1    4   4

I have tried this code:

aMat=df1000.as_matrix()
print(aMat)

here df1000 is the dataset.

But the above code gives this output:

[['AP' 1 2 5]
 ['GOA' 1 2 1]
 ['GU' 1 2 4]
 ['KA' 1 5 1]
 ['MA' 1 4 4]]

I want to create a 2d list or matrix which looks like this:

[[1, 2, 5], [1, 2, 1], [1,  2,  4], [1, 5, 1], [1, 4, 4]]

Body:
Select all columns without first by DataFrame.iloc and convert integer values to strings by DataFrame.astype, last convert to numpy array by to_numpy or DataFrame.values:

#pandas 0.24+
aMat=df1000.iloc[:, 1:].astype(str).to_numpy()
#pandas below
aMat=df1000.iloc[:, 1:].astype(str).values

Or remove first column by DataFrame.drop:

#pandas 0.24+
aMat=df1000.drop('state', axis=1).astype(str).to_numpy()
#pandas below
aMat=df1000.drop('state', axis=1).astype(str).values


答:
You can use df.iloc[]:

```<code>df.iloc[:,1:].to_numpy()
</code>```

```<code>array([[1, 2, 5],
   [1, 2, 1],
   [1, 2, 4],
   [1, 5, 1],
   [1, 4, 4]], dtype=int64)
</code>```

Or for string matrix:

```<code>df.astype(str).iloc[:,1:].to_numpy()
</code>```

```<code>array([['1', '2', '5'],
   ['1', '2', '1'],
   ['1', '2', '4'],
   ['1', '5', '1'],
   ['1', '4', '4']], dtype=object)
</code>```

Note why we are not using as_matrix()

".as_matrix will be removed in a future version. Use .values instead."

Title: Covert a dataframe into a matrix form

Body:
You can use df.iloc[]:

df.iloc[:,1:].to_numpy()

array([[1, 2, 5],
   [1, 2, 1],
   [1, 2, 4],
   [1, 5, 1],
   [1, 4, 4]], dtype=int64)

Or for string matrix:

df.astype(str).iloc[:,1:].to_numpy()

array([['1', '2', '5'],
   ['1', '2', '1'],
   ['1', '2', '4'],
   ['1', '5', '1'],
   ['1', '4', '4']], dtype=object)

Note why we are not using as_matrix()

".as_matrix will be removed in a future version. Use .values instead."


问:
Oreo: Stop notification from getting removed on swipe
My Code:

```<code>mNotifyBuilder.setSmallIcon(R.drawable.ic_status_bar)
                .setContentTitle("")
                .setOngoing(true)
                .setAutoCancel(false)
                .setTicker("")
                .setColor(ContextCompat.getColor(mContext, R.color.folderlist_bg_music))
                .setChannelId(CHANNEL_ID)
                .setContent(remoteViews).build();
</code>```

Working fine on other phones, but not working on Vivo V7.
On first swipe the notification is removed and it reappears. But on second swipe, it dismisses completely.

答:
This is phone specific issue. Same thing works for other phones but not for Vivo phones.
OEMs shouldn't deviate from basic implementation that has been provided by stock Android.</p>

Body:
My Code:

mNotifyBuilder.setSmallIcon(R.drawable.ic_status_bar)
                .setContentTitle("")
                .setOngoing(true)
                .setAutoCancel(false)
                .setTicker("")
                .setColor(ContextCompat.getColor(mContext, R.color.folderlist_bg_music))
                .setChannelId(CHANNEL_ID)
                .setContent(remoteViews).build();

Working fine on other phones, but not working on Vivo V7.
On first swipe the notification is removed and it reappears. But on second swipe, it dismisses completely.


问:
Remove character from dynamic string
I have a file with some junk values and i need to get rid of them while loading that file into a table.
Giving here some example. File is semicolon separated, and last column has those junk values.

```<code>2019-02-20;05377378;ABC+xY+++Rohit Anita Chicago
2019-02-20;05201343;ABC+xY++Gustav Russia
2019-02-20;07348738;ABC+xy+++Jain Ram Ambarnath
</code>```

Now the last column I have to load without ABC+xY+++  value.
but some row i have ABC+xY+++ and some ABC+xY++. any suggestion to get rid of this. which means 2 times or 3 times + is available

I am using informatica powercenter for loading this file.
in expression i need to create some substr/instr function. which i can put test here in oracle sql as well to understand quickly if the value coming is properly.

and my expected output is

Any suggestion please.

Thanks,
Bithun

答:
Informatica PowerCenter provides a handful of functions to work with regular expression. In this case you'll need REG_EXTRACT.

There's a nice description of the function already available - check and upvote :)

According to it you'll most likely need to define a port like:

```<code>your_output_port=REG_EXTRACT(ADDRESS, '([^\+]+)$', 1)
</code>```

Here's how I've tested it.

Title: Remove character from dynamic string

Body:
I have a file with some junk values and i need to get rid of them while loading that file into a table.
Giving here some example. File is semicolon separated, and last column has those junk values.

2019-02-20;05377378;ABC+xY+++Rohit Anita Chicago
2019-02-20;05201343;ABC+xY++Gustav Russia
2019-02-20;07348738;ABC+xy+++Jain Ram Ambarnath

Now the last column I have to load without ABC+xY+++  value.
but some row i have ABC+xY+++ and some ABC+xY++. any suggestion to get rid of this. which means 2 times or 3 times + is available

I am using informatica powercenter for loading this file.
in expression i need to create some substr/instr function. which i can put test here in oracle sql as well to understand quickly if the value coming is properly.

and my expected output is

Any suggestion please.

Thanks,
Bithun

Body:
Informatica PowerCenter provides a handful of functions to work with regular expression. In this case you'll need REG_EXTRACT.

There's a nice description of the function already available - check and upvote :)

According to it you'll most likely need to define a port like:

your_output_port=REG_EXTRACT(ADDRESS, '([^\+]+)$', 1)

Here's how I've tested it.


问:
How do you write a image to browser as a binary stream in coldfusion?
I have a service on a Coldfusion 9 server that creates image banners on the fly for us. A separate machine has to save these files with something like:

```<code>wget http://myserver.com/services/local/bannerCreator/250x250-v3.cfm?prodID=3&percentSaving=19
</code>```

The problem is that I can't think of how to get coldfusion to write out binary data without using a temporary file. At the minute the image is just displayed as an image tag like this:

```<code><cfimage action = "writeToBrowser" source="#banner#" width="#banner.width#" height="#banner.height#" />
</code>```

Any ideas? Or should I just use a temporary file?

答:
I can't test because you're not giving any example code for how your images are generated, but have you tried something along this line?

```<code><cfcontent reset="true" variable="#imageData#" type="image/jpg" />
</code>```

Update: So I went ahead and created my own image; I'll assume you're doing something similar. This works perfectly for me:

```<code><cfset img = imageNew("",200,200,"rgb","red") />
<cfcontent variable="#toBinary(toBase64(img))#" type="image/png" reset="true" />
</code>```

This works without writing to file, and without using a virtual file system ("ramdisk")

ContentLicense: CC BY-SA 3.0

Body:
I have a service on a Coldfusion 9 server that creates image banners on the fly for us. A separate machine has to save these files with something like:

wget http://myserver.com/services/local/bannerCreator/250x250-v3.cfm?prodID=3&percentSaving=19

The problem is that I can't think of how to get coldfusion to write out binary data without using a temporary file. At the minute the image is just displayed as an image tag like this:

<cfimage action = "writeToBrowser" source="#banner#" width="#banner.width#" height="#banner.height#" />

Any ideas? Or should I just use a temporary file?

Body:
I can't test because you're not giving any example code for how your images are generated, but have you tried something along this line?

<cfcontent reset="true" variable="#imageData#" type="image/jpg" />

Update: So I went ahead and created my own image; I'll assume you're doing something similar. This works perfectly for me:

<cfset img = imageNew("",200,200,"rgb","red") />
<cfcontent variable="#toBinary(toBase64(img))#" type="image/png" reset="true" />

This works without writing to file, and without using a virtual file system ("ramdisk")


问:
.NET UnitTest Project Build and Test in DevOps pipeline failed?
I have written the unit test, All the unit tests in this solution require a database connection

I have Created VSTS devops build and test pipeline but failed tests for database connection.

UnitTest functionality working fine in local but VSTS Devops unittest failed. kindly refer below screen

Kindly give me any idea to solve this issue.

Thanks

答:
the error message is clearly saying that it cannot connect to that database. Just because you can establish the connection from your local machine that doesn't mean that another environment can also connect to the same db. You need to make sure that the server you deployed to, can connect using that connection string.

Now, you keep saying unit tests. Unit tests are not meant to connect to databases, what you have are integration tests. Issues like this are one of the reasons why unit tests are meant to not use any kind of external things, they are meant to test functionality and not work with real databases.


问:
Select range of two columns which are also greater
I have a case where there is a table with order value and those limits and ranges like below

```<code>Id       Value       Range_From         Range_To

1        360.0         500               1000
2        1001.0        1001              2000
3        3000.0        1001              2000
</code>```

I need an output of 3rd record where the 2nd and 3rd records fall between 1001 and 2000. But when I query that using SQL BETWEEN I am only getting the record 2 because that is falling under Range_From and Range_To for Between condition.

Example:

```<code>SELECT * FROM Table WHERE Value BETWEEN Range_From AND Range_To;
</code>```

The above query will only give the 2nd record. How to get the third record as this is also satisfying the condition.

Also I only need to get the record as output which ever value is highest and it should also fall in the Range_From and Range_To

答:
Try this

SELECT * FROM Table WHERE (Value > Range_To);

Body:
I have a case where there is a table with order value and those limits and ranges like below

Id       Value       Range_From         Range_To

1        360.0         500               1000
2        1001.0        1001              2000
3        3000.0        1001              2000

I need an output of 3rd record where the 2nd and 3rd records fall between 1001 and 2000. But when I query that using SQL BETWEEN I am only getting the record 2 because that is falling under Range_From and Range_To for Between condition.

Example:

SELECT * FROM Table WHERE Value BETWEEN Range_From AND Range_To;

The above query will only give the 2nd record. How to get the third record as this is also satisfying the condition.

Also I only need to get the record as output which ever value is highest and it should also fall in the Range_From and Range_To


问:
SQL Insert Additional Field in Distinct Filter
I would like to insert an additional field to be used in conjunction with an existing one when retrieving records from SQL database.

Current query:

```<code>SELECT CONVERT(date, [DateTime]) 'Date of Download',
       ActionBy AS 'User Full Name',
       COUNT(DISTINCT Identifier) 'Number of Downloads'
FROM [dbo].[AuditLog]
WHERE ActionTaken = 'Clicked'
    AND Type = 'Attachment Link'
    AND CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
    AND CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
GROUP BY CONVERT(date, [DateTime]), ActionBy
HAVING COUNT(DISTINCT Identifier) > " + limit + "
ORDER BY COUNT(DISTINCT Identifier) DESC";
</code>```

I would like to insert an additional filter Remarks with the existing Identifier in the DISTINCT filter.

Example:
COUNT(DISTINCT Identifier + Remarks) 'Number of Downloads'

May I know how can I modify my current statement?

Thank you

Sample Data:

Other columns were minimised to maximise visibility.

答:
You can select field as below, by casting FileID to NVARCHAR</p>

```<code>COUNT(DISTINCT CAST(FileID AS NVARCHAR(10)) + Title) 'Number of Downloads'
</code>```

Body:
I would like to insert an additional field to be used in conjunction with an existing one when retrieving records from SQL database.

Current query:

SELECT CONVERT(date, [DateTime]) 'Date of Download',
       ActionBy AS 'User Full Name',
       COUNT(DISTINCT Identifier) 'Number of Downloads'
FROM [dbo].[AuditLog]
WHERE ActionTaken = 'Clicked'
    AND Type = 'Attachment Link'
    AND CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
    AND CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
GROUP BY CONVERT(date, [DateTime]), ActionBy
HAVING COUNT(DISTINCT Identifier) > " + limit + "
ORDER BY COUNT(DISTINCT Identifier) DESC";

I would like to insert an additional filter Remarks with the existing Identifier in the DISTINCT filter.

Example:
COUNT(DISTINCT Identifier + Remarks) 'Number of Downloads'

May I know how can I modify my current statement?

Thank you

Sample Data:

Other columns were minimised to maximise visibility.

Body:
You can select field as below, by casting FileID to NVARCHAR

COUNT(DISTINCT CAST(FileID AS NVARCHAR(10)) + Title) 'Number of Downloads'


问:
Apache-POI not saving excel workbook even after doing fileoutputstream.close()
I am trying to generate new excel files based on a common template. I am opening the template excel file, editing it and saving it in a new location. To write the file I am using FileOutputStream and i am closing the stream after writing to save it. The entire process works correctly, but the newly created excel file is not saved properly. My template file is of 35kb and my newly created excel file shows 30kb only. When I open the newly created excel file, I can see the data written, and I need to save it and close it to reflect the correct size of 36kb.

The new excels are required to be uploaded to an external application which shows "no data found" when directly uploading the 30kb, unsaved excel whereas the 36kb saved file successfully uploads the file.

I tried various different ways suggested on internet to do the same thing and none of them are generating proper excel files. I am using java 1.7 and apache-poi version 3.17.

Following is a sample of my code:-

```<code>public void createExcelFiles() throws ParseException, IOException {

    File file = new File(ExcelTemplatePath);
    FileInputStream fip = new FileInputStream(file);
    FileOutputStream fos = new FileOutputStream(excelOutputFile);

    XSSFWorkbook workbookOld = new XSSFWorkbook(fip);
    try (SXSSFWorkbook workbook = new SXSSFWorkbook(workbookOld, rowAccessWindowSize)) {

        if (makeLargeFiles) {
            SXSSFSheet sheet = (SXSSFSheet) workbook.getSheetAt(0);
            makeExcelFile.makeLargeFile(sheet);
            workbook.write(fos);
        } else {
            Sheet sheet = workbookOld.getSheetAt(0);
            makeExcelFile.makeNormalFile(sheet);
            workbookOld.write(fos);

        }
        fos.close();
        fip.close();
        workbook.close();
    }
    workbookOld.close();

}
</code>```

答:
The issue was resolved using by shared string property of excel. I updated the workbook constructor call as below:

SXSSFWorkbook workbook = new SXSSFWorkbook(workbookOld, rowAccessWindowSize, true, true)

The second true parameter is for the use of shared strings. Using this property makes the data visible to the external application without the need to open and save it again. However the size issue still remains and why the use of shared string works is still unclear.
For more info on shared string check this out.

Body:
I am trying to generate new excel files based on a common template. I am opening the template excel file, editing it and saving it in a new location. To write the file I am using FileOutputStream and i am closing the stream after writing to save it. The entire process works correctly, but the newly created excel file is not saved properly. My template file is of 35kb and my newly created excel file shows 30kb only. When I open the newly created excel file, I can see the data written, and I need to save it and close it to reflect the correct size of 36kb.

The new excels are required to be uploaded to an external application which shows "no data found" when directly uploading the 30kb, unsaved excel whereas the 36kb saved file successfully uploads the file.

I tried various different ways suggested on internet to do the same thing and none of them are generating proper excel files. I am using java 1.7 and apache-poi version 3.17.

Following is a sample of my code:-

public void createExcelFiles() throws ParseException, IOException {

    File file = new File(ExcelTemplatePath);
    FileInputStream fip = new FileInputStream(file);
    FileOutputStream fos = new FileOutputStream(excelOutputFile);

    XSSFWorkbook workbookOld = new XSSFWorkbook(fip);
    try (SXSSFWorkbook workbook = new SXSSFWorkbook(workbookOld, rowAccessWindowSize)) {

        if (makeLargeFiles) {
            SXSSFSheet sheet = (SXSSFSheet) workbook.getSheetAt(0);
            makeExcelFile.makeLargeFile(sheet);
            workbook.write(fos);
        } else {
            Sheet sheet = workbookOld.getSheetAt(0);
            makeExcelFile.makeNormalFile(sheet);
            workbookOld.write(fos);

        }
        fos.close();
        fip.close();
        workbook.close();
    }
    workbookOld.close();

}


问:
How can I use formik "arrayHelper" outside of FieldArray?
I trying to create 2 FieldArray containers with arrayHelpers. Each of them working with different object. Obj1 and Obj2 have their arrayHelper and each of them know how to add and remove objects to/from array.

I want to do some kind of toolbar with two buttons "Add Obj1" and "Add Obj2" outside of these two containers.
The question is how can I work with arrayHelper outside of these containers? Or could you suggest another flow how can change my array?
The problem is if I change my array from parent - I can't work with props.values only with props.obj1 but in this case my changes are not saving.

```<code><FieldArray name="obj1"
                    render={arrayHelpers => {}/>
<FieldArray name="obj2"
                    render={arrayHelpers => {}/>

<div class="toolbar">...buttons</div>

</code>```

答:
To access arrayHelpers outside of a FieldArray, you can use refs.

I've created a code sandbox, showing how you can do this:

https://codesandbox.io/s/using-refs-to-access-child-methods-cps7w

Body:
I trying to create 2 FieldArray containers with arrayHelpers. Each of them working with different object. Obj1 and Obj2 have their arrayHelper and each of them know how to add and remove objects to/from array.

I want to do some kind of toolbar with two buttons "Add Obj1" and "Add Obj2" outside of these two containers.
The question is how can I work with arrayHelper outside of these containers? Or could you suggest another flow how can change my array?
The problem is if I change my array from parent - I can't work with props.values only with props.obj1 but in this case my changes are not saving.

<FieldArray name="obj1"
                    render={arrayHelpers => {}/>
<FieldArray name="obj2"
                    render={arrayHelpers => {}/>

...buttons


问:
Django, get all required fields?
How can I get all the fields that is required for a model to be created?

(same as django migrations check before running migrations?)

答:
Here is a more thorough way of getting a list of all required fields.

First, it gets all the fields from the model where blank=False.
Second, it checks to see if you set required=False for any base fields in the form class.
Third, it updates the list to give you all required fields.

One thing this function does not do is check whether you manually set required=True to any fields in the form class' init method.

```<code>def get_required_fields(form_class):
    """Get the required fields of a form. Returns a list of field names."""

    def get_blank_not_allowed_fields(model):
        """Get the list of field names where 'blank=False' for the given model."""
        blank_not_allowed_fields = []
        for field in model._meta.get_fields():
            if hasattr(field, 'blank') and field.blank is False:
                blank_not_allowed_fields.append(field.name)
        blank_not_allowed_fields.remove('id')
        return blank_not_allowed_fields

    blank_not_allowed_fields = get_blank_not_allowed_fields(form_class.Meta.model)

    # Even though, for certain fields, blanks are designated to be allowed (aka blank=True)
    # in the model class, they can have 'required' != True in the form class.
    # So, remove all fields where required is not True.
    for field_name, value in form_class.base_fields.items():
        if value.required is not True:
            blank_not_allowed_fields.remove(field_name)

    # At this point, if we are being precise, this variable should be named required_fields
    # but, there is no point in changing the name of an already declared list.
    return blank_not_allowed_fields
</code>```

Title: Django, get all required fields?

Body:
Here is a more thorough way of getting a list of all required fields.

First, it gets all the fields from the model where blank=False.
Second, it checks to see if you set required=False for any base fields in the form class.
Third, it updates the list to give you all required fields.

One thing this function does not do is check whether you manually set required=True to any fields in the form class' init method.

def get_required_fields(form_class):
    """Get the required fields of a form. Returns a list of field names."""

    def get_blank_not_allowed_fields(model):
        """Get the list of field names where 'blank=False' for the given model."""
        blank_not_allowed_fields = []
        for field in model._meta.get_fields():
            if hasattr(field, 'blank') and field.blank is False:
                blank_not_allowed_fields.append(field.name)
        blank_not_allowed_fields.remove('id')
        return blank_not_allowed_fields

    blank_not_allowed_fields = get_blank_not_allowed_fields(form_class.Meta.model)

    # Even though, for certain fields, blanks are designated to be allowed (aka blank=True)
    # in the model class, they can have 'required' != True in the form class.
    # So, remove all fields where required is not True.
    for field_name, value in form_class.base_fields.items():
        if value.required is not True:
            blank_not_allowed_fields.remove(field_name)

    # At this point, if we are being precise, this variable should be named required_fields
    # but, there is no point in changing the name of an already declared list.
    return blank_not_allowed_fields


问:
absolute layout in scroll view on android
i want to Android xml design in the following format i did but it does not work.

xml layout:coding

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <TableLayout android:id="@+id/widget836"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView android:id="@+id/widget837" android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </ImageView>
        </TableLayout>
        <ScrollView android:id="@+id/ScrollView111"
            android:layout_width="fill_parent" android:layout_height="fill_parent">

            <AbsoluteLayout android:id="@+id/widget883"
                android:layout_width="wrap_content" android:layout_height="wrap_content">

                <EditText android:id="@+id/email" android:layout_width="303px"
                    android:layout_height="56px" android:text="Email" android:textSize="18sp"
                    android:layout_x="1px" android:layout_y="15px">
                </EditText>
                <EditText android:id="@+id/pass" android:layout_width="303px"
                    android:layout_height="56px" android:text="password"
                    android:textSize="18sp" android:layout_x="3px" android:layout_y="57px">
                </EditText>

                <TextView android:id="@+id/enter" android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:text="Enter an email address and password above, and your accout will be created."
                    android:layout_x="0px" android:layout_y="65px">
                </TextView>
                <TextView android:id="@+id/primarydisplay"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Primary Display" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="75px">
                </TextView>
                <TextView android:id="@+id/gps" android:layout_width="100px"
                    android:layout_height="40px" android:text="Speed >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="75px">
                </TextView>
            </AbsoluteLayout>
            <AbsoluteLayout android:id="@+id/widget884"
                android:layout_width="wrap_content" android:layout_height="wrap_content">
                <TextView android:id="@+id/distanceunit"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Distance Unit" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="85px">
                </TextView>
                <TextView android:id="@+id/miles" android:layout_width="100px"
                    android:layout_height="40px" android:text="Miles >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="85px">
                </TextView>
            </AbsoluteLayout>
        </ScrollView>
    </LinearLayout>
</code>```

Log cat error:

Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child

pleae correct me.

答:
You can only have one direct child element in a Scrollview so you should either combine your two AbsoluteLayout elements or you should wrap them in another element such as another AbsoluteLayout element.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TableLayout android:id="@+id/widget836"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="vertical">
        <ImageView android:id="@+id/widget837" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </ImageView>
    </TableLayout>
    <ScrollView android:id="@+id/ScrollView111"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <!-- Wrap -->
        <AbsoluteLayout
             android:layout_width="wrap_content" android:layout_height="wrap_content">

            <AbsoluteLayout android:id="@+id/widget883"
              android:layout_width="wrap_content" android:layout_height="wrap_content">

              <EditText android:id="@+id/email" android:layout_width="303px"
                android:layout_height="56px" android:text="Email" android:textSize="18sp"
                android:layout_x="1px" android:layout_y="15px">
              </EditText>
              <EditText android:id="@+id/pass" android:layout_width="303px"
                android:layout_height="56px" android:text="password"
                android:textSize="18sp" android:layout_x="3px" android:layout_y="57px">
              </EditText>

              <TextView android:id="@+id/enter" android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="Enter an email address and password above, and your accout will be created."
                android:layout_x="0px" android:layout_y="65px">
              </TextView>
              <TextView android:id="@+id/primarydisplay"
                android:layout_width="100px" android:layout_height="40px"
                android:text="Primary Display" android:textStyle="bold"
                android:layout_x="0px" android:layout_y="75px">
              </TextView>
              <TextView android:id="@+id/gps" android:layout_width="100px"
                android:layout_height="40px" android:text="Speed >"
                android:textStyle="bold" android:layout_x="200px" android:layout_y="75px">
              </TextView>
          </AbsoluteLayout>
          <AbsoluteLayout android:id="@+id/widget884"
            android:layout_width="wrap_content" android:layout_height="wrap_content">
              <TextView android:id="@+id/distanceunit"
                android:layout_width="100px" android:layout_height="40px"
                android:text="Distance Unit" android:textStyle="bold"
                android:layout_x="0px" android:layout_y="85px">
              </TextView>
              <TextView android:id="@+id/miles" android:layout_width="100px"
                android:layout_height="40px" android:text="Miles >"
                android:textStyle="bold" android:layout_x="200px" android:layout_y="85px">
              </TextView>
          </AbsoluteLayout>

        </AbsoluteLayout>
        <!-- /Wrap -->
    </ScrollView>
</LinearLayout>
</code>```

Body:
i want to Android xml design in the following format i did but it does not work.

xml layout:coding

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <TableLayout android:id="@+id/widget836"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView android:id="@+id/widget837" android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </ImageView>
        </TableLayout>
        <ScrollView android:id="@+id/ScrollView111"
            android:layout_width="fill_parent" android:layout_height="fill_parent">

            <AbsoluteLayout android:id="@+id/widget883"
                android:layout_width="wrap_content" android:layout_height="wrap_content">

                <EditText android:id="@+id/email" android:layout_width="303px"
                    android:layout_height="56px" android:text="Email" android:textSize="18sp"
                    android:layout_x="1px" android:layout_y="15px">
                </EditText>
                <EditText android:id="@+id/pass" android:layout_width="303px"
                    android:layout_height="56px" android:text="password"
                    android:textSize="18sp" android:layout_x="3px" android:layout_y="57px">
                </EditText>

                <TextView android:id="@+id/enter" android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:text="Enter an email address and password above, and your accout will be created."
                    android:layout_x="0px" android:layout_y="65px">
                </TextView>
                <TextView android:id="@+id/primarydisplay"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Primary Display" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="75px">
                </TextView>
                <TextView android:id="@+id/gps" android:layout_width="100px"
                    android:layout_height="40px" android:text="Speed >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="75px">
                </TextView>
            </AbsoluteLayout>
            <AbsoluteLayout android:id="@+id/widget884"
                android:layout_width="wrap_content" android:layout_height="wrap_content">
                <TextView android:id="@+id/distanceunit"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Distance Unit" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="85px">
                </TextView>
                <TextView android:id="@+id/miles" android:layout_width="100px"
                    android:layout_height="40px" android:text="Miles >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="85px">
                </TextView>
            </AbsoluteLayout>
        </ScrollView>
    </LinearLayout>

Log cat error:

Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child

pleae correct me.

Body:
You can only have one direct child element in a Scrollview so you should either combine your two AbsoluteLayout elements or you should wrap them in another element such as another AbsoluteLayout element.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TableLayout android:id="@+id/widget836"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="vertical">
        <ImageView android:id="@+id/widget837" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </ImageView>
    </TableLayout>
    <ScrollView android:id="@+id/ScrollView111"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <!-- Wrap -->
        <AbsoluteLayout
             android:layout_width="wrap_content" android:layout_height="wrap_content">

            <AbsoluteLayout android:id="@+id/widget883"
              android:layout_width="wrap_content" android:layout_height="wrap_content">

              <EditText android:id="@+id/email" android:layout_width="303px"
                android:layout_height="56px" android:text="Email" android:textSize="18sp"
                android:layout_x="1px" android:layout_y="15px">
              </EditText>
              <EditText android:id="@+id/pass" android:layout_width="303px"
                android:layout_height="56px" android:text="password"
                android:textSize="18sp" android:layout_x="3px" android:layout_y="57px">
              </EditText>

              <TextView android:id="@+id/enter" android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="Enter an email address and password above, and your accout will be created."
                android:layout_x="0px" android:layout_y="65px">
              </TextView>
              <TextView android:id="@+id/primarydisplay"
                android:layout_width="100px" android:layout_height="40px"
                android:text="Primary Display" android:textStyle="bold"
                android:layout_x="0px" android:layout_y="75px">
              </TextView>
              <TextView android:id="@+id/gps" android:layout_width="100px"
                android:layout_height="40px" android:text="Speed >"
                android:textStyle="bold" android:layout_x="200px" android:layout_y="75px">
              </TextView>
          </AbsoluteLayout>
          <AbsoluteLayout android:id="@+id/widget884"
            android:layout_width="wrap_content" android:layout_height="wrap_content">
              <TextView android:id="@+id/distanceunit"
                android:layout_width="100px" android:layout_height="40px"
                android:text="Distance Unit" android:textStyle="bold"
                android:layout_x="0px" android:layout_y="85px">
              </TextView>
              <TextView android:id="@+id/miles" android:layout_width="100px"
                android:layout_height="40px" android:text="Miles >"
                android:textStyle="bold" android:layout_x="200px" android:layout_y="85px">
              </TextView>
          </AbsoluteLayout>

        </AbsoluteLayout>
        <!-- /Wrap -->
    </ScrollView>
</LinearLayout>


问:
Python multiprocessing code running slower than single threaded one
The Python Multiprocessing performance on my i7 7700HQ is significantly slower than non-parallel one.

While planning to parallelize my Select and Update code for my single table database in mssql, I tried to first parallelize a simple code. The program simply prints multiples of the argument.
I tried single-threaded, multi-process with Process object and also with Pool object. Single threaded always performed best.

import time

def foobar(a):
    for i in range(1,10000):
        print(a*i)
    return
if __name__ == "__main__":
   Tthreading = time.clock()
    p1= Process(target= foobar, args=(3,))
    p2 = Process(target= foobar, args= (2,))
    p3 = Process(target= foobar, args= (4,))
    p4 = Process(target=foobar, args=(123,))

    allprocess.start

    allprocess.join

    print(time.clock() - Tthreading)

    #Single-threaded
    Tsingle = time.clock()
    foobar(3)
    foobar(2)
    foobar(4)
    foobar(123)
    print(time.clock() - Tsingle)

```

I expected the multi-process to be much faster since there are no shared resources(no functions, variables that need to be accessed between threads) and IPC.

Single Threaded time: 0.32s

Multi-Process time: 0.53s

答:
Actually, there is one important shared resource in your example, your monitor (or stdout).

print is a relatively slow operation (compared to CPU cycles...), and it causes contention between your proccesses.

Benchmarking parallel work correctly is a tough task, it is affected by the great many factors and features of a CPU (e.g. cache).

Try to replace your workload with one that is very suited for multiprocessing (e.g. working in a parallel on different parts of an array, matrix multiplication...)

One more important thing: spawning the new processes also takes time, and for it to pay off the work done in each process needs to be significant.
If you increase your loop's range a little bit, the difference should be in favor of the Multi-process version:

import time
from multiprocessing import Process

def foobar(a):
    for i in range(1,10000000):
        a*i
    return

if __name__ == "__main__":
    Tthreading = time.time()
    p1= Process(target= foobar, args=(3,))
    p2 = Process(target= foobar, args= (2,))
    p3 = Process(target= foobar, args= (4,))
    p4 = Process(target=foobar, args=(123,))

    allprocess = [p1,p2,p3,p4]
    for p in allprocess:
        p.start()

    for p in allprocess:
        p.join()

    print(time.time() - Tthreading)

    #Single-threaded
    Tsingle = time.time()
    foobar(3)
    foobar(2)
    foobar(4)
    foobar(123)
    print(time.time() - Tsingle)
```

on my machine this outputs:

0.44509196281433105

1.3775699138641357

Body:
The Python Multiprocessing performance on my i7 7700HQ is significantly slower than non-parallel one.

While planning to parallelize my Select and Update code for my single table database in mssql, I tried to first parallelize a simple code. The program simply prints multiples of the argument.
I tried single-threaded, multi-process with Process object and also with Pool object. Single threaded always performed best.

import time

def foobar(a):
    for i in range(1,10000):
        print(a*i)
    return
if __name__ == "__main__":
   Tthreading = time.clock()
    p1= Process(target= foobar, args=(3,))
    p2 = Process(target= foobar, args= (2,))
    p3 = Process(target= foobar, args= (4,))
    p4 = Process(target=foobar, args=(123,))

    allprocess.start

    allprocess.join

    print(time.clock() - Tthreading)

    #Single-threaded
    Tsingle = time.clock()
    foobar(3)
    foobar(2)
    foobar(4)
    foobar(123)
    print(time.clock() - Tsingle)

I expected the multi-process to be much faster since there are no shared resources(no functions, variables that need to be accessed between threads) and IPC.

Single Threaded time: 0.32s

Multi-Process time: 0.53s

Body:
Actually, there is one important shared resource in your example, your monitor (or stdout).

print is a relatively slow operation (compared to CPU cycles...), and it causes contention between your proccesses.

Benchmarking parallel work correctly is a tough task, it is affected by the great many factors and features of a CPU (e.g. cache).

Try to replace your workload with one that is very suited for multiprocessing (e.g. working in a parallel on different parts of an array, matrix multiplication...)

One more important thing: spawning the new processes also takes time, and for it to pay off the work done in each process needs to be significant.
If you increase your loop's range a little bit, the difference should be in favor of the Multi-process version:

import time
from multiprocessing import Process

def foobar(a):
    for i in range(1,10000000):
        a*i
    return

if __name__ == "__main__":
    Tthreading = time.time()
    p1= Process(target= foobar, args=(3,))
    p2 = Process(target= foobar, args= (2,))
    p3 = Process(target= foobar, args= (4,))
    p4 = Process(target=foobar, args=(123,))

    allprocess = [p1,p2,p3,p4]
    for p in allprocess:
        p.start()

    for p in allprocess:
        p.join()

    print(time.time() - Tthreading)

    #Single-threaded
    Tsingle = time.time()
    foobar(3)
    foobar(2)
    foobar(4)
    foobar(123)
    print(time.time() - Tsingle)

on my machine this outputs:

0.44509196281433105

1.3775699138641357