问:
how to read the data without database name
If possible to read the data from sql without database name only Server name and table name using c#?? </p>

答:
Assuming you mean SQL Server (and most Database platforms that I'm familiar with)... No.  You would need to find the database name.

There are ways to find so  that you CAN know it by querying the server, but the best way is to ask the database administrator or someone who has the authority to give you permission.


来源: stackexchange

问:
How can I print values inside an array made from a string? (Explode)
I'm not looking for a var dump, I just want the actual data inside each key of my array.

Original String: (meta_value) 1698, 4655, 4215, 1225, 5454, 698, 410, 122, 107, 7412, 3654, 1120

```<code>$explodeme = $serial['meta_value'];
$exploded = explode(",",$explodeme[0]);
var_dump($exploded);
</code>```

Returns:

```<code>array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "9" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "9" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" }
</code>```

I want to print the strings for every single key of my array. IE)

```<code>Serial Number: 42848 <- From Array
Serial Number: 48281 <- From Array
</code>```

I have tried:

```<code>echo $exploded;
print_r($exploded);
</code>```

All return the same value (See Returns: above)

I've also tried a for each loop, but it doesn't output the serial number string I have stored inside the array.

```<code>foreach ($exploded as $item) {
  echo $item . "<br>";
}
</code>```

I've also tried (to no avail):

```<code>foreach ($exploded as $item) {
  echo $item['string(1)'] . "<br>";
}
</code>```

Please help!

答:
If $serial['meta_value'] holds the comma separated string, like this:

```<code>$serial['meta_value'] = '1698, 4655, 4215, 1225, 5454, 698, 410, 122, 107, 7412, 3654, 1120';
</code>```

Then your error was using $explodeme[0] in this expression:

```<code>$exploded = explode(",",$explodeme[0]);
</code>```

$explodeme[0] is the first character of the string. (See the PHP documentation for String access and modification by character.) Instead you should just use $explodeme to get the entire string.

```<code>$explodeme = $serial['meta_value'];
$exploded = explode(",", $explodeme);

foreach ($exploded as $item) {
    echo $item . "<br>";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm not looking for a var dump, I just want the actual data inside each key of my array.

Original String: (meta_value) 1698, 4655, 4215, 1225, 5454, 698, 410, 122, 107, 7412, 3654, 1120

$explodeme = $serial['meta_value'];
$exploded = explode(",",$explodeme[0]);
var_dump($exploded);

Returns:

array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "9" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "9" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" }

I want to print the strings for every single key of my array. IE)

Serial Number: 42848 <- From Array
Serial Number: 48281 <- From Array

I have tried:

echo $exploded;
print_r($exploded);

All return the same value (See Returns: above)

I've also tried a for each loop, but it doesn't output the serial number string I have stored inside the array.

foreach ($exploded as $item) {
  echo $item . "
";
}

I've also tried (to no avail):

foreach ($exploded as $item) {
  echo $item['string(1)'] . "
";
}

Please help!

Body:
If $serial['meta_value'] holds the comma separated string, like this:

$serial['meta_value'] = '1698, 4655, 4215, 1225, 5454, 698, 410, 122, 107, 7412, 3654, 1120';

Then your error was using $explodeme[0] in this expression:

$exploded = explode(",",$explodeme[0]);

$explodeme[0] is the first character of the string. (See the PHP documentation for String access and modification by character.) Instead you should just use $explodeme to get the entire string.

$explodeme = $serial['meta_value'];
$exploded = explode(",", $explodeme);

foreach ($exploded as $item) {
    echo $item . "<br>";
}


问:
SQL Server - Map column of same table
I have this table:

I'd like to get to this:

```<code>EMPID  NAME  MANAGER
  1     a      0
  2     b      a
  3     c      a
  4     d      b
  5     e      c
</code>```

This is what I have tried, but it isn't producing the expected output:

```<code>SELECT A.Empid, A.Name, REPLACE(A.Name,A.Empid,1)
FROM ChethanQuery A
INNER JOIN ChethanQuery B on A.Empid=B.Empid
</code>```

答:
Your query is close, you just need to select the other name and tweak your join condition:

```<code>SELECT T.EmpID, T.Name, COALESCE(T2.Name,'0') AS ManagerName
FROM YourTable T
LEFT JOIN YourTable T2 ON T.Manager = T2.EmpID
</code>```

A LEFT JOIN is needed since the 'head' manager will not join to anything, same with the COALESCE(T2.Name,'0')

Title: SQL Server - Map column of same table

Body:
I have this table:

I'd like to get to this:

EMPID  NAME  MANAGER
  1     a      0
  2     b      a
  3     c      a
  4     d      b
  5     e      c

This is what I have tried, but it isn't producing the expected output:

SELECT A.Empid, A.Name, REPLACE(A.Name,A.Empid,1)
FROM ChethanQuery A
INNER JOIN ChethanQuery B on A.Empid=B.Empid

Body:
Your query is close, you just need to select the other name and tweak your join condition:

SELECT T.EmpID, T.Name, COALESCE(T2.Name,'0') AS ManagerName
FROM YourTable T
LEFT JOIN YourTable T2 ON T.Manager = T2.EmpID

A LEFT JOIN is needed since the 'head' manager will not join to anything, same with the COALESCE(T2.Name,'0')


问:
VSTS Rest API environemnt ID incorrect
I'm using the REST API for VSTS to kick off a release for a specific environment.  Retrieving the environment and such works, however, when I make the REST call to actually start the deployment, I get the following error message:

```<code>[DBG]: PS C:\Users\mmulhe200>>
executeRequest : {"$id":"1","innerException":null,"message":"Environment with ID '16' is not valid. Valid environments have IDs
'1288,1289'. Specify a valid environment and try
again.","typeName":"Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException,
Microsoft.VisualStudio.Services.ReleaseManagement2.Data","typeKey":"InvalidRequestException","errorCode":0,"eventId":3000}
At C:\Users\mmulhe200\Desktop\VSTS release task\test\Untitled1.ps1:58 char:12
+     return executeRequest $request;
+            ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,executeRequest
</code>```

What's interesting about that is the response from the REST operation to retrieve a release definition with its environments returns such:

```<code>...
"id": 16,
"name": "Environment 2",
"rank": 2,
...
</code>```

In fact, in the entire response, I can't find the ID 1288 nor 1289 anywhere.  Any thoughts on why VSTS is telling me my environment ID of 16 is wrong even though it's what's returned from their service?

答:
This is the way to see the environment ID on the page. It would be great to display this on the tooltip or on the page. This is what it takes.

Step 1 Open chrome inspection tool

Step 2 Click on the environment

Step 3 Get the related id

Title: VSTS Rest API environemnt ID incorrect

Body:
I'm using the REST API for VSTS to kick off a release for a specific environment.  Retrieving the environment and such works, however, when I make the REST call to actually start the deployment, I get the following error message:

[DBG]: PS C:\Users\mmulhe200>>
executeRequest : {"$id":"1","innerException":null,"message":"Environment with ID '16' is not valid. Valid environments have IDs
'1288,1289'. Specify a valid environment and try
again.","typeName":"Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException,
Microsoft.VisualStudio.Services.ReleaseManagement2.Data","typeKey":"InvalidRequestException","errorCode":0,"eventId":3000}
At C:\Users\mmulhe200\Desktop\VSTS release task\test\Untitled1.ps1:58 char:12
+     return executeRequest $request;
+            ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,executeRequest

What's interesting about that is the response from the REST operation to retrieve a release definition with its environments returns such:

...
"id": 16,
"name": "Environment 2",
"rank": 2,
...

In fact, in the entire response, I can't find the ID 1288 nor 1289 anywhere.  Any thoughts on why VSTS is telling me my environment ID of 16 is wrong even though it's what's returned from their service?


问:
MySQL Join Scenario
I know there are many "similar" questions, but I cannot figure out how to make this work. I am hoping it is quite simple for someone else!

I have a query that looks like the following:

```<code>SELECT
    d.name DishName,
    alt.name AllergyName
FROM meals_dish d
JOIN meals_dishingredient di ON di.dish_id = d.id
LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
GROUP BY d.id, alt.id
ORDER BY d.name
</code>```

that is giving me table similar to the following:

```<code>Dish Name               |    AllergyName
-----------------------------------------
Almond Pudding          |     NULL
Almond Pudding          |     Egg
Apple Cake              |     Milk
Apple Cake              |     Lactose
Apple Cake              |     Egg
Apple Cake              |     NULL
Avocado Chocolate Cream |     Milk
Avocado Chocolate Cream |     Lactose
Avocado Chocolate Cream |     NULL
Avocado Chocolate Cream |     Peanuts
Avocado Chocolate Cream |     Tree Nuts
Avocado Chocolate Cream |     Soy
Avocado Egg             |     NULL
Avocado Egg             |     Egg
Bacon Wrapped Asparagus |     NULL
Baked Cauliflower       |     NULL
Baked Cauliflower       |     Milk
Baked Cauliflower       |     Lactose
Baked Salmon            |     NULL
Baked Salmon            |     Milk
Baked Salmon            |     Lactose
</code>```

Now, what I would like to do, is to make a list of all dishes where any of the allergy names for a specific dish is not 'Egg', or etc.

For example, if I wanted to only get dishes that someone who could not eat Egg was, then I would run this query and should get back the dishes of Avocado Chocolate Cream, Bacon Wrapped Asparagus, Baked Cauliflower and Baked Salmon.

I have tried to set up some WHERE NOT IN, and other similar ones, but I continue to only remove a certain ingredient from the dish instead of just not selecting the dish. For example, in my attempted queries, with the 'Egg' example, Apple Cake would simply still return, but the specific row of 'Egg' would now not show.

答:
you could use NOT  IN this way  for Dish Name  eg  for Egg:</p>

```<code>  select name
  from meals_dish
  where  name not in (
  SELECT distinct d.name
  FROM meals_dish d
  JOIN meals_dishingredient di ON di.dish_id = d.id
  LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
  LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
             AND alt .AllergyName = 'Egg'
  )
</code>```

Title: MySQL Join Scenario

Body:
I know there are many "similar" questions, but I cannot figure out how to make this work. I am hoping it is quite simple for someone else!

I have a query that looks like the following:

SELECT
    d.name DishName,
    alt.name AllergyName
FROM meals_dish d
JOIN meals_dishingredient di ON di.dish_id = d.id
LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
GROUP BY d.id, alt.id
ORDER BY d.name

that is giving me table similar to the following:

Dish Name               |    AllergyName
-----------------------------------------
Almond Pudding          |     NULL
Almond Pudding          |     Egg
Apple Cake              |     Milk
Apple Cake              |     Lactose
Apple Cake              |     Egg
Apple Cake              |     NULL
Avocado Chocolate Cream |     Milk
Avocado Chocolate Cream |     Lactose
Avocado Chocolate Cream |     NULL
Avocado Chocolate Cream |     Peanuts
Avocado Chocolate Cream |     Tree Nuts
Avocado Chocolate Cream |     Soy
Avocado Egg             |     NULL
Avocado Egg             |     Egg
Bacon Wrapped Asparagus |     NULL
Baked Cauliflower       |     NULL
Baked Cauliflower       |     Milk
Baked Cauliflower       |     Lactose
Baked Salmon            |     NULL
Baked Salmon            |     Milk
Baked Salmon            |     Lactose

Now, what I would like to do, is to make a list of all dishes where any of the allergy names for a specific dish is not 'Egg', or etc.

For example, if I wanted to only get dishes that someone who could not eat Egg was, then I would run this query and should get back the dishes of Avocado Chocolate Cream, Bacon Wrapped Asparagus, Baked Cauliflower and Baked Salmon.

I have tried to set up some WHERE NOT IN, and other similar ones, but I continue to only remove a certain ingredient from the dish instead of just not selecting the dish. For example, in my attempted queries, with the 'Egg' example, Apple Cake would simply still return, but the specific row of 'Egg' would now not show.

Body:
you could use NOT  IN this way  for Dish Name  eg  for Egg:

  select name
  from meals_dish
  where  name not in (
  SELECT distinct d.name
  FROM meals_dish d
  JOIN meals_dishingredient di ON di.dish_id = d.id
  LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
  LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
             AND alt .AllergyName = 'Egg'
  )


答:
I've just tested this and the below seems to be working with a simple foreach loop.</p>

```<code><?php
$string = "1698, 4655, 4215, 1225, 5454, 698, 410, 122, 107, 7412, 3654, 1120";

$exploded = explode(',', $string);

foreach ($exploded as $item ) {
    echo $item;
}
?>
</code>```

Title: How can I print values inside an array made from a string? (Explode)

Body:
I've just tested this and the below seems to be working with a simple foreach loop.

<?php
$string = "1698, 4655, 4215, 1225, 5454, 698, 410, 122, 107, 7412, 3654, 1120";

$exploded = explode(',', $string);

foreach ($exploded as $item ) {
    echo $item;
}
?>


问:
How to pass the results from a rendered directive as variable to angular-translate
I have a (rather complex) directive that can render amounts in a currency. It formats the currency based on the rules of that currency (e.g. if a currency has cents etc.) and formats the number and symbol based on the locale, it adds the sign and classes if an amount is negative and so on and so on.

I'd like to use the outcome of the directive as a variable in a translation.

There is a plunker with a simplified setup here

In short, what I'd want:

```<code>Your balance: <strong currency data-amount="-1337" data-symbol="'€'"></strong>
<p translate translate-values="{ currency: '€', amount: 1337, beneficiary: 'carol' }">PAY_TO</p>
</code>```

With the translation being something like:

```<code>var translations = {
  PAY_TO: "You must pay {{ amount }} to {{ beneficiary}}"
};
</code>```

(in the plunker the key is PAY_TO_PROPER)

The goal is the replace {{ amount }} with a formatted piece of HTML as returned from the directive.

Note that in the plunker, the directive is simplified, in reality it takes a lot of things into consideration, things that I really don't want to add to a template. e.g. fallback symbols based on an ISO_CODE, determining how many fractionals to render, based on the currency (there are currencies with 0, 2, 3, 5, or even 8 digits, to name some; this stuff is complex)

What would a common pattern for this be? Is passing the result from a rendered directive as variable a proper way in Angular, or would that be an ugly hack?

Am I using translations or directives wrong? I can hardly beleive that this is so hard and that I cannot find anyone else looking for how to do this on google or stackoverflow.

答:
There is an angular-translate option, called translate-compile, that you can use to compile values passed into the translation in the context of the current scope (https://angular-translate.github.io/docs/#/guide/05_using-translate-directive#using-translate-directive_post-compiling).

You can use it like this:

```<code><p translate translate-values="{ amount: '<currency data-amount=\'1337\' data-symbol="\'€\'"></currency>', beneficiary: 'carol' }" translate-compile>PAY_TO_PROPER</p>
</code>```

See the attached fiddle: http://plnkr.co/edit/IRFzWU2Qfw7zxdBNSl4L

Body:
I have a (rather complex) directive that can render amounts in a currency. It formats the currency based on the rules of that currency (e.g. if a currency has cents etc.) and formats the number and symbol based on the locale, it adds the sign and classes if an amount is negative and so on and so on.

I'd like to use the outcome of the directive as a variable in a translation.

There is a plunker with a simplified setup here

In short, what I'd want:

Your balance:

PAY_TO

With the translation being something like:

var translations = {
  PAY_TO: "You must pay {{ amount }} to {{ beneficiary}}"
};

(in the plunker the key is PAY_TO_PROPER)

The goal is the replace {{ amount }} with a formatted piece of HTML as returned from the directive.

Note that in the plunker, the directive is simplified, in reality it takes a lot of things into consideration, things that I really don't want to add to a template. e.g. fallback symbols based on an ISO_CODE, determining how many fractionals to render, based on the currency (there are currencies with 0, 2, 3, 5, or even 8 digits, to name some; this stuff is complex)

What would a common pattern for this be? Is passing the result from a rendered directive as variable a proper way in Angular, or would that be an ugly hack?

Am I using translations or directives wrong? I can hardly beleive that this is so hard and that I cannot find anyone else looking for how to do this on google or stackoverflow.

Body:
There is an angular-translate option, called translate-compile, that you can use to compile values passed into the translation in the context of the current scope (https://angular-translate.github.io/docs/#/guide/05_using-translate-directive#using-translate-directive_post-compiling).

You can use it like this:

<p translate translate-values="{ amount: '<currency data-amount=\'1337\' data-symbol=&quot;\'€\'&quot;></currency>', beneficiary: 'carol' }" translate-compile>PAY_TO_PROPER</p>

See the attached fiddle: http://plnkr.co/edit/IRFzWU2Qfw7zxdBNSl4L


问:
MS Access Reporting - can it be pretty?
I am working on a project converting a "spreadsheet application" to a database solution.  A macro was written that takes screen shots of each page and pastes them into a PowerPoint presentation.  Because of the nice formatting options in Excel, the presentation looks very pretty.

The problem I'm having is that I haven't ever seen an Access report that would be pretty enough to display to upper management.  I think the output still has to be a PowerPoint presentation.  It needs to look as close as possible to the original output.

I am currently trying to write some code to use a .pot (presentation template) and fill in the data programmatically.  Putting the data into a PowerPoint table has been tricky because the tables are not easy to manipulate.  For example, if a particular description is too long, I need to break into the next cell down (word-wrap isn't allowed because I can only have n lines per page).

Is there a way to make an Access report pretty, am I headed down the right path, or should I just try to programmatically fill in the Excel spreadsheet and use the code that already exists there to produce the presentation?  (I'd still need to figure out how to know when to break a line when using a non-monospaced font, as the users are currently doing that manually when they enter the data in the spreadsheet)

Jason Z:
If I set it to wrap, and I already have n lines, it would make n+1 or 2 lines on the slide, which is unacceptable.

Dennis:
That article looks very good, I should be able to glean something from it.  Thanks!

答:
Rather than filling in the excel spreadsheet programmatically, you may want to use the external data features of Excel and Access.  Generally I put a query on each tab, which of course may be hidden. An "update all" causes all the queries to be updated. Then summary tabs show the pretty results from all the individual queries.

For one particularly complex system, a bit of excel vba programmatically changed a query and then walked through the tabs updating each one.

Finally, rather than doing screen shots, Excel has a "copy cells as a image" copy that populates the copy buffer with a resizeable image.  This could give you better looking results than a pure screenshot since a screenshot can have various deficiencies depending on pixel density.

OwnerDisplayName: Knobloch

ContentLicense: CC BY-SA 2.5

Title: MS Access Reporting - can it be pretty?

LastEditorDisplayName: Knobloch


问:
Add line near TextView
I would like to add a line near a textView like the img below in android:

line near text view

here is my xml code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey">
    <Switch
        android:id="@+id/bluetoothSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:paddingBottom="8dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="8dp"
        android:text="Bluetooth"
        android:textSize="30sp"
        android:background="@android:color/white"/>
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/bluetoothSwitch"
        android:layout_marginTop="20dp"
        android:background="@android:color/white"
        android:divider="?android:dividerVertical"
        android:dividerPadding="8dp"
        android:orientation="vertical"
        android:showDividers="middle">
        <Button
            android:id="@+id/btn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/bluetoothSwitch"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Scan"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn1"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Show Paired Device"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />
    </LinearLayout>
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linearLayout1"
        android:layout_marginTop="20dp"
        android:paddingLeft="16dp"
        android:text="PAIRED DEVICE: "
        android:background="@android:color/white"
        android:paddingBottom="8dp"
        android:paddingTop="8dp"/>
</RelativeLayout>
</code>```

and my app screen:

where a would like to add line

i took this screenshot from my samsung settings. i would add the line near the textview "paired device".
i read to use view but i can't do it.
Can someone help me?
thank you all

答:
This will work and will be always aligned to textview

```<code>  <RelativeLayout
        android:padding="8dp"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_weight="1"
            android:layout_marginRight="8dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Wifi Cellular"
            android:textSize="20sp"/>

        <View
            android:layout_toRightOf="@+id/tvTitle"
            android:layout_centerVertical="true"
            android:layout_weight="1"
            android:background="#636363"
            android:layout_width="match_parent"
            android:layout_height="2dp"/>

    </RelativeLayout>
</code>```

sample work

Title: Add line near TextView

Body:
I would like to add a line near a textView like the img below in android:

line near text view

here is my xml code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey">
    <Switch
        android:id="@+id/bluetoothSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:paddingBottom="8dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="8dp"
        android:text="Bluetooth"
        android:textSize="30sp"
        android:background="@android:color/white"/>
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/bluetoothSwitch"
        android:layout_marginTop="20dp"
        android:background="@android:color/white"
        android:divider="?android:dividerVertical"
        android:dividerPadding="8dp"
        android:orientation="vertical"
        android:showDividers="middle">
        <Button
            android:id="@+id/btn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/bluetoothSwitch"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Scan"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn1"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Show Paired Device"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />
    </LinearLayout>
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linearLayout1"
        android:layout_marginTop="20dp"
        android:paddingLeft="16dp"
        android:text="PAIRED DEVICE: "
        android:background="@android:color/white"
        android:paddingBottom="8dp"
        android:paddingTop="8dp"/>
</RelativeLayout>

and my app screen:

where a would like to add line

i took this screenshot from my samsung settings. i would add the line near the textview "paired device".
i read to use view but i can't do it.
Can someone help me?
thank you all

Body:
This will work and will be always aligned to textview

  <RelativeLayout
        android:padding="8dp"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_weight="1"
            android:layout_marginRight="8dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Wifi Cellular"
            android:textSize="20sp"/>

        <View
            android:layout_toRightOf="@+id/tvTitle"
            android:layout_centerVertical="true"
            android:layout_weight="1"
            android:background="#636363"
            android:layout_width="match_parent"
            android:layout_height="2dp"/>

    </RelativeLayout>

sample work


问:
 element not working between div and input
Below is the code that I am using. For some reason I cannot get the br in between the div.chatBox and input to show. Can anyone give me any suggestions.

```<code><div class="container-fluid col-xs-12">
    <div class="row">
        <br>
        <div class="chatBox col-xs-5 col-xs-offset-3" id="chatBox">
        </div>

        <br>

        <input type="text" class="col-xs-offset-4 col-xs-3">
    </div>
</div>
</code>```

答:
As evolutionxbox says, you have to use css to display corectly your elements.

however your br tag works fine, it's just that your first div is empty, so you do not see the difference, try this two sample, with and without br.

        <input type="text" class="col-xs-offset-4 col-xs-3">

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid col-xs-12">
    <div class="row">
        <br>
        <div class="chatBox col-xs-5 col-xs-offset-3" id="chatBox" style="background-color:red;width:160px;height:100px">
        </div>

        <input type="text" class="col-xs-offset-4 col-xs-3">
    </div>
</div></code>```

Title: <br> element not working between div and input

Body:
Below is the code that I am using. For some reason I cannot get the br in between the div.chatBox and input to show. Can anyone give me any suggestions.

        <input type="text" class="col-xs-offset-4 col-xs-3">

Body:
As evolutionxbox says, you have to use css to display corectly your elements.

however your br tag works fine, it's just that your first div is empty, so you do not see the difference, try this two sample, with and without br.

<div class="container-fluid col-xs-12">
    <div class="row">
        <br>
        <div class="chatBox col-xs-5 col-xs-offset-3" id="chatBox" style="background-color:red;width:160px;height:100px">
        </div>

        <br/>

        <input type="text" class="col-xs-offset-4 col-xs-3">
    </div>
</div>

<div class="container-fluid col-xs-12">
    <div class="row">
        <br>
        <div class="chatBox col-xs-5 col-xs-offset-3" id="chatBox" style="background-color:red;width:160px;height:100px">
        </div>

        <input type="text" class="col-xs-offset-4 col-xs-3">
    </div>
</div>


问:
Where do I find the unit tests for the .NET Framework?
I've heard that Microsoft release the unit tests for the .NET Framework. Is that true?
If so, how do I get them?

I'd like to implement classes similar to ones implemented by .NET and I would like to reuse their unit tests.

答:
You can get the sources for the .NET framework here: http://referencesource.microsoft.com/.
You also might find this post from Scott Guthrie helpful. But I'm not sure if there are unit test included. I only know for sure they are for the ASP.NET MVC source.</p>


问:
Why am i getting the error "Unparseable date" from SimpleDateFormat?
Im trying to parse a Date-String without timezone to a new Date with time-Zone but im getting the error:

java.text.ParseException: Unparseable date: "2017-11-17 10:49:39.772 "

Here´s my code:

```<code> String date = "2017-11-17 10:49:39.772 "
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
 sdf.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam"));
 sdf.parse(date);  //here´s the error
 return date.getTime();
</code>```

Any suggestions?

答:
If you want the string to be parsed correctly it must match the SimpleDateFormat pattern you supplied in the constructor:

Old line:

```<code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
</code>```

New line:

```<code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS ");
</code>```

Body:
Im trying to parse a Date-String without timezone to a new Date with time-Zone but im getting the error:

java.text.ParseException: Unparseable date: "2017-11-17 10:49:39.772 "

Here´s my code:

 String date = "2017-11-17 10:49:39.772 "
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
 sdf.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam"));
 sdf.parse(date);  //here´s the error
 return date.getTime();

Any suggestions?

Body:
If you want the string to be parsed correctly it must match the SimpleDateFormat pattern you supplied in the constructor:

Old line:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");

New line:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS ");


问:
Difference between Angular-cli.json , webpack.conf & tsconfig.json
I am building an angular4/typescript desktop app & confused in-between

angular-cli.json

tsconfig.json

webpack.conf.js

Can someone please explain main conceptual differences in above 3 configurtation files & what are they for?

Do I have to define all 3 of them in my project, or only one
would be sufficient.

For example: path ALIAS can be defined inside all 3 of them
webpack/tsconfig/angular-cli. But which one has benefit over others? or They all same , does not matter which you use.

So in general, they all can provide project configuration so which
one is best performant & recommneded as best practice.

angular-cli.json

```<code>{
    "project": {
        "version": "1.0.0-beta",
        "name": "project"
    },
    "apps": [
        {
            "root": "src",
            "outDir": "dist",
            "assets": [
                "images",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.json",
            "prefix": "app",
            "mobile": false,
            "styles": [
                "styles.css"
            ],
            "scripts": [
                "../node_modules/core-js/client/shim.min.js",
                "../node_modules/mutationobserver-shim/dist/mutationobserver.min.js",
                "../node_modules/@webcomponents/custom-elements/custom-elements.min.js",
                "../node_modules/web-animations-js/web-animations.min.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "addons": [],
    "packages": [],
    "e2e": {
        "protractor": {
            "config": "./protractor.config.js"
        }
    },
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "prefixInterfaces": false,
        "inline": {
            "style": false,
            "template": false
        },
        "spec": {
            "class": false,
            "component": true,
            "directive": true,
            "module": false,
            "pipe": true,
            "service": true
        }
    }
}
</code>```

tsconfig.json

```<code>{
    "compileOnSave": false,
    "compilerOptions": {
        "rootDir": "../",
        "baseUrl": "",
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
            "es6",
            "dom"
        ],
        "mapRoot": "src",
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "dist/out-tsc",
        "sourceMap": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "types": [
          "jasmine",
          "core-js",
          "node"
        ]
    },
    "exclude": [
        "node_modules",
        "dist",
        "test.ts"
    ]
}
</code>```

webpack.config.js

```<code>var webpack = require('webpack');
var path = require('path');
var webpackMerge = require('webpack-merge');
var HtmlWebpackPlugin = require('html-webpack-plugin');

// Webpack Config
var webpackConfig = {
  entry: {
    'main': './src/main.browser.ts',
  },

  output: {
    publicPath: '',
    path: path.resolve(__dirname, './dist'),
  },

  plugins: [
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)@angular/,
      path.resolve(__dirname, '../src'),
      {
        // your Angular Async Route paths relative to this root directory
      }
    ),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    }),

  ],

  module: {
    loaders: [
      // .ts files for TypeScript
      {
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader',
          'angular2-router-loader'
        ]
      },
      { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] },
      { test: /\.html$/, loader: 'raw-loader' }
    ]
  }

};

    var defaultConfig = {
      devtool: 'source-map',

      output: {
        filename: '[name].bundle.js',
        sourceMapFilename: '[name].map',
        chunkFilename: '[id].chunk.js'
      },

      resolve: {
        extensions: [ '.ts', '.js' ],
        modules: [ path.resolve(__dirname, 'node_modules') ]
      },

      devServer: {
        historyApiFallback: true,
        watchOptions: { aggregateTimeout: 300, poll: 1000 },
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
          "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
        }
      },

      node: {
        global: true,
        crypto: 'empty',
        __dirname: true,
        __filename: true,
        process: true,
        Buffer: false,
        clearImmediate: false,
        setImmediate: false
      }
    };

    module.exports = webpackMerge(defaultConfig, webpackConfig);
</code>```

答:
1) As Angular4 can be preferably use with typescript but you can also use dart and ES5 javascript well for developing an application. Now

angular-cli.json

tsconfig.json

webpack.conf.js

angular-cli.json

Angular CLI is a Command Line Interface (CLI) to automate your development workflow. It allows you to:

Create a new Angular application

run a development server with LiveReload support to preview your
application during development

add features to your existing Angular application

build your application for deployment to production

So automating the angular application from cli requires angular-cli.json to loads its configuration.

TypeScript is a primary language for Angular application development. It is a superset of JavaScript with design-time support for type safety and tooling.

Browsers can't execute TypeScript directly. Typescript must be "transpiled" into JavaScript using the tsc compiler,
tsconfig.json— file is required for TypeScript compiler configuration.

webpack.conf.js its also a bundler and it provide the same configuration functionality as angular cli, but in webpack you have to do it
manually as in case of angular cli you can take advantage of Angular CLI command line help without knowing detail information

2) You are required angular-cli.json and tsconfig.json if u developing an angular app through CLI

if using own bundler like webpack or systemjs you can have tsconfig.json and bundler configuration file in this case webpack.config.js

3) For best practises it would prefer to use ANGULAR CLI you can check out the official documentation

Body:
I am building an angular4/typescript desktop app & confused in-between

angular-cli.json

tsconfig.json

webpack.conf.js

Can someone please explain main conceptual differences in above 3 configurtation files & what are they for?

Do I have to define all 3 of them in my project, or only one
would be sufficient.

For example: path ALIAS can be defined inside all 3 of them
webpack/tsconfig/angular-cli. But which one has benefit over others? or They all same , does not matter which you use.

So in general, they all can provide project configuration so which
one is best performant & recommneded as best practice.

angular-cli.json

{
    "project": {
        "version": "1.0.0-beta",
        "name": "project"
    },
    "apps": [
        {
            "root": "src",
            "outDir": "dist",
            "assets": [
                "images",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.json",
            "prefix": "app",
            "mobile": false,
            "styles": [
                "styles.css"
            ],
            "scripts": [
                "../node_modules/core-js/client/shim.min.js",
                "../node_modules/mutationobserver-shim/dist/mutationobserver.min.js",
                "../node_modules/@webcomponents/custom-elements/custom-elements.min.js",
                "../node_modules/web-animations-js/web-animations.min.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "addons": [],
    "packages": [],
    "e2e": {
        "protractor": {
            "config": "./protractor.config.js"
        }
    },
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "prefixInterfaces": false,
        "inline": {
            "style": false,
            "template": false
        },
        "spec": {
            "class": false,
            "component": true,
            "directive": true,
            "module": false,
            "pipe": true,
            "service": true
        }
    }
}

tsconfig.json

{
    "compileOnSave": false,
    "compilerOptions": {
        "rootDir": "../",
        "baseUrl": "",
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
            "es6",
            "dom"
        ],
        "mapRoot": "src",
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "dist/out-tsc",
        "sourceMap": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "types": [
          "jasmine",
          "core-js",
          "node"
        ]
    },
    "exclude": [
        "node_modules",
        "dist",
        "test.ts"
    ]
}

webpack.config.js

var webpack = require('webpack');
var path = require('path');
var webpackMerge = require('webpack-merge');
var HtmlWebpackPlugin = require('html-webpack-plugin');

// Webpack Config
var webpackConfig = {
  entry: {
    'main': './src/main.browser.ts',
  },

  output: {
    publicPath: '',
    path: path.resolve(__dirname, './dist'),
  },

  plugins: [
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)@angular/,
      path.resolve(__dirname, '../src'),
      {
        // your Angular Async Route paths relative to this root directory
      }
    ),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    }),

  ],

  module: {
    loaders: [
      // .ts files for TypeScript
      {
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader',
          'angular2-router-loader'
        ]
      },
      { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] },
      { test: /\.html$/, loader: 'raw-loader' }
    ]
  }

};

    var defaultConfig = {
      devtool: 'source-map',

      output: {
        filename: '[name].bundle.js',
        sourceMapFilename: '[name].map',
        chunkFilename: '[id].chunk.js'
      },

      resolve: {
        extensions: [ '.ts', '.js' ],
        modules: [ path.resolve(__dirname, 'node_modules') ]
      },

      devServer: {
        historyApiFallback: true,
        watchOptions: { aggregateTimeout: 300, poll: 1000 },
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
          "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
        }
      },

      node: {
        global: true,
        crypto: 'empty',
        __dirname: true,
        __filename: true,
        process: true,
        Buffer: false,
        clearImmediate: false,
        setImmediate: false
      }
    };

    module.exports = webpackMerge(defaultConfig, webpackConfig);


问:
How to pause and then return setInterval
I'm fixing some errors in the chat that is in development here in the company. Currently what has happened is that the messages loaded in the chat window do not belong to the selected chat. Queries in DB and Java methods are correct.

Since a setInterval () is being used, I believe that when I select a different chat, if the setInterval method has already been triggered, messages are loaded incorrectly.

Is there a way to trigger the setInterval only after loading the messages and pausing it when clicking another chat?

Method I want to update:
PS: Without the setInterval, it does not show incoming messages. Just by clicking on chat again.

```<code> function atualizarChat(idChat,nomeChat)
                    {
                        // Parametros
                            var dados = "Token=" + encodeURIComponent(token);
                            if(idMensagemUltima != 0){
                                dados += "&idChatMensagem="+encodeURIComponent(idMensagemUltima);
                            }
                            dados += "&idChat="+encodeURIComponent(idChat);

                            $.ajax({
                                type : "POST",
                                url : "/ListarMensagensServlet",
                                data : dados,
                                dataType : "json",
                                success : function(resultado) {

                                idChatEscolhido = idChat;

                                    // Troca nome do chat
                                    if(nomeChat != ''){
                                        $('#NomeUsuarioChat').text(nomeChat);
                                    }

                                    var mensagemAntiga = idMensagemUltima;

                                    // Adiciona as mensagens na tabela
                                    for(mensagem of resultado){

                                        if(mensagem['bool'] == 1){
                                            mostrarSuaMensagem(mensagem['mensagem']);
                                        }
                                        else{
                                            mostrarRespostaMensagem(mensagem['mensagem']);
                                        }
                                        // troca data da ultima mensagem
                                        idMensagemUltima = mensagem['idChatMensagem'];
                                    }

                                    if(idMensagemUltima > mensagemAntiga){
                                        // Joga chat para baixo
                                        $('#CaixaDeChat').stop().animate({
                                            scrollTop: $('#CaixaDeChat')[0].scrollHeight
                                        }, 800);
                                    }
                                }

                            });
                    }
</code>```

答:
First of all, please move your question to Portuguese StackOverflow (pt.stackoverflow.com).
About your solution,

I suggest create a small function to handle this behavior, you just need to create a setInterval and set their value into a variable.

```<code>var interval = null;

var intervalHandler = function(status, yourFunction, intervalTime) {
   if(status) {
     interval = setInterval(yourFunction, intervalTime);
   }
   else {
     clearInterval(interval);
   }
}
</code>```

So, status is a boolean variable with value true/false. Value false will execute clearInterval condition and true will execute the setInterval condition.

Using:

```<code>intervalHandler(true, yourFunction, 1000);  // for set

intervalHandler(false);  // for clear
</code>```

Body:
I'm fixing some errors in the chat that is in development here in the company. Currently what has happened is that the messages loaded in the chat window do not belong to the selected chat. Queries in DB and Java methods are correct.

Since a setInterval () is being used, I believe that when I select a different chat, if the setInterval method has already been triggered, messages are loaded incorrectly.

Is there a way to trigger the setInterval only after loading the messages and pausing it when clicking another chat?

Method I want to update:
PS: Without the setInterval, it does not show incoming messages. Just by clicking on chat again.

 function atualizarChat(idChat,nomeChat)
                    {
                        // Parametros
                            var dados = "Token=" + encodeURIComponent(token);
                            if(idMensagemUltima != 0){
                                dados += "&idChatMensagem="+encodeURIComponent(idMensagemUltima);
                            }
                            dados += "&idChat="+encodeURIComponent(idChat);

                            $.ajax({
                                type : "POST",
                                url : "/ListarMensagensServlet",
                                data : dados,
                                dataType : "json",
                                success : function(resultado) {

                                idChatEscolhido = idChat;

                                    // Troca nome do chat
                                    if(nomeChat != ''){
                                        $('#NomeUsuarioChat').text(nomeChat);
                                    }

                                    var mensagemAntiga = idMensagemUltima;

                                    // Adiciona as mensagens na tabela
                                    for(mensagem of resultado){

                                        if(mensagem['bool'] == 1){
                                            mostrarSuaMensagem(mensagem['mensagem']);
                                        }
                                        else{
                                            mostrarRespostaMensagem(mensagem['mensagem']);
                                        }
                                        // troca data da ultima mensagem
                                        idMensagemUltima = mensagem['idChatMensagem'];
                                    }

                                    if(idMensagemUltima > mensagemAntiga){
                                        // Joga chat para baixo
                                        $('#CaixaDeChat').stop().animate({
                                            scrollTop: $('#CaixaDeChat')[0].scrollHeight
                                        }, 800);
                                    }
                                }

                            });
                    }

Body:
First of all, please move your question to Portuguese StackOverflow (pt.stackoverflow.com).
About your solution,

I suggest create a small function to handle this behavior, you just need to create a setInterval and set their value into a variable.

var interval = null;

var intervalHandler = function(status, yourFunction, intervalTime) {
   if(status) {
     interval = setInterval(yourFunction, intervalTime);
   }
   else {
     clearInterval(interval);
   }
}

So, status is a boolean variable with value true/false. Value false will execute clearInterval condition and true will execute the setInterval condition.

Using:

intervalHandler(true, yourFunction, 1000);  // for set

intervalHandler(false);  // for clear


问:
Render dynamic text onto CVPixelBufferRef while recording video
I'm recording video and audio using AVCaptureVideoDataOutput and AVCaptureAudioDataOutput and in the captureOutput:didOutputSampleBuffer:fromConnection: delegate method, I want to draw text onto each individual sample buffer I'm receiving from the video connection. The text changes with about every frame (it's a stopwatch label) and I want that to be recorded on top of the video data that's captured.

Here's what I've been able to come up with so far:

```<code>//1.
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

//2.
UIImage *textImage = [self createTextImage];
CIImage *maskImage = [CIImage imageWithCGImage:textImage.CGImage];

//3.
CVPixelBufferLockBaseAddress(pixelBuffer, 0);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSDictionary *options = [NSDictionary dictionaryWithObject:(__bridge id)colorSpace forKey:kCIImageColorSpace];
CIImage *inputImage = [CIImage imageWithCVPixelBuffer:pixelBuffer options:options];

//4.
CIFilter *filter = [CIFilter filterWithName:@"CIBlendWithMask"];
[filter setValue:inputImage forKey:@"inputImage"];
[filter setValue:maskImage forKey:@"inputMaskImage"];
CIImage *outputImage = [filter outputImage];
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);

//5.
[self.renderContext render:outputImage toCVPixelBuffer:pixelBuffer bounds:[outputImage extent] colorSpace:CGColorSpaceCreateDeviceRGB()];

//6.
[self.pixelBufferAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:timestamp];
</code>```

Here I grab the pixel buffer, easy as pie.

I use core graphics to write text to a blank UIImage (that's what createTextImage does. I was able to verify that this step works; I saved an image with text drawn to it to my photos.

I create a CGImage from the pixel buffer.

I make a CIFilter for CIBlendWithMask, setting the input image as the one created from the original pixel buffer and the input mask as the CIImage made from the image with text drawn on it.

Finally, I render the filter output image to the pixelBuffer. The CIContext was created beforehand with [CIContext contextWithOptions:nil];.

After all that, I append the pixel buffer to my pixelBufferAdaptor with the appropriate timestamp.

The video that's saved at the end of recording has no visible changes to it i.e. no mask image has been drawn onto the pixel buffers.

Anyone have any idea where I'm going wrong here? I've been stuck on this for days, any help would be so appreciated.

EDIT:

```<code>- (UIImage *)createTextImage {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height), NO, 1.0);
    NSMutableAttributedString *timeStamp = [[NSMutableAttributedString alloc]initWithString:self.timeLabel.text attributes:@{NSForegroundColorAttributeName:self.timeLabel.textColor, NSFontAttributeName: self.timeLabel.font}];
    NSMutableAttributedString *countDownString = [[NSMutableAttributedString alloc]initWithString:self.cDownLabel.text attributes:@{NSForegroundColorAttributeName:self.cDownLabel.textColor, NSFontAttributeName:self.cDownLabel.font}];
    [timeStamp drawAtPoint:self.timeLabel.center];
    [countDownString drawAtPoint:self.view.center];
    UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return blank;
}
</code>```

答:
I asked Apple DTS about this same issue as all approaches I had were running really slow or doing odd things and they sent me this:

https://developer.apple.com/documentation/avfoundation/avasynchronousciimagefilteringrequest?language=objc

Which got me to a working solution really quickly! you can bypass the CVPixelBuffer altogether using CIFilters, which IMHO is much easier to work with. So if you don't actually NEED to use CVPixelBuffer, then this approach will become your new friend quickly.

A combination of CIFilter(s) to composite the source image and the image with the text I generated for each frame did the trick.

I hope this helps someone else!

Body:
I'm recording video and audio using AVCaptureVideoDataOutput and AVCaptureAudioDataOutput and in the captureOutput:didOutputSampleBuffer:fromConnection: delegate method, I want to draw text onto each individual sample buffer I'm receiving from the video connection. The text changes with about every frame (it's a stopwatch label) and I want that to be recorded on top of the video data that's captured.

Here's what I've been able to come up with so far:

//1.
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

//2.
UIImage *textImage = [self createTextImage];
CIImage *maskImage = [CIImage imageWithCGImage:textImage.CGImage];

//3.
CVPixelBufferLockBaseAddress(pixelBuffer, 0);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSDictionary *options = [NSDictionary dictionaryWithObject:(__bridge id)colorSpace forKey:kCIImageColorSpace];
CIImage *inputImage = [CIImage imageWithCVPixelBuffer:pixelBuffer options:options];

//4.
CIFilter *filter = [CIFilter filterWithName:@"CIBlendWithMask"];
[filter setValue:inputImage forKey:@"inputImage"];
[filter setValue:maskImage forKey:@"inputMaskImage"];
CIImage *outputImage = [filter outputImage];
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);

//5.
[self.renderContext render:outputImage toCVPixelBuffer:pixelBuffer bounds:[outputImage extent] colorSpace:CGColorSpaceCreateDeviceRGB()];

//6.
[self.pixelBufferAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:timestamp];

Here I grab the pixel buffer, easy as pie.

I use core graphics to write text to a blank UIImage (that's what createTextImage does. I was able to verify that this step works; I saved an image with text drawn to it to my photos.

I create a CGImage from the pixel buffer.

I make a CIFilter for CIBlendWithMask, setting the input image as the one created from the original pixel buffer and the input mask as the CIImage made from the image with text drawn on it.

Finally, I render the filter output image to the pixelBuffer. The CIContext was created beforehand with [CIContext contextWithOptions:nil];.

After all that, I append the pixel buffer to my pixelBufferAdaptor with the appropriate timestamp.

The video that's saved at the end of recording has no visible changes to it i.e. no mask image has been drawn onto the pixel buffers.

Anyone have any idea where I'm going wrong here? I've been stuck on this for days, any help would be so appreciated.

EDIT:

- (UIImage *)createTextImage {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height), NO, 1.0);
    NSMutableAttributedString *timeStamp = [[NSMutableAttributedString alloc]initWithString:self.timeLabel.text attributes:@{NSForegroundColorAttributeName:self.timeLabel.textColor, NSFontAttributeName: self.timeLabel.font}];
    NSMutableAttributedString *countDownString = [[NSMutableAttributedString alloc]initWithString:self.cDownLabel.text attributes:@{NSForegroundColorAttributeName:self.cDownLabel.textColor, NSFontAttributeName:self.cDownLabel.font}];
    [timeStamp drawAtPoint:self.timeLabel.center];
    [countDownString drawAtPoint:self.view.center];
    UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return blank;
}


问:
MVC Check if Model in View Has Records
I am struggling to determine if a Model passed to a View actually has any records.

The code below loops through the parent recordset and passes a parent parameter to a child recordset. I've tried if (Model.Content != null) but that doesn't seems to work, the code just thinks there are records, when actually there aren't.

Can somebody please review the code below and let me know what I am doing wrong?

```<code><ul class="nav sf-menu clearfix">
    @foreach (var navigation in Model.Navigation)
    {
        if (Model.Content != null)
        {
            @Html.SubMenuLink(navigation.Title, navigation.Action, navigation.Controller)
            @Html.Raw("<ul>")
            foreach (var content in Model.Content.Where(c => c.NavigationId == navigation.Id))
            {
                if (string.IsNullOrEmpty(content.Url))
                {
                    if (string.IsNullOrEmpty(content.Content1))
                    {
                    }
                    else
                    {
                        @Html.MenuLink(content.Title, "Home/Article/" + content.Id + "/" + ToFriendlyUrl(content.Title), "Home");
                    }
                }
                else
                {
                    @Html.MenuLink(content.Title, content.Url, "Home");
                }
            }
            @Html.Raw("</ul>")
            @Html.Raw("</li>")
        }
        else
        {
            @Html.MenuLink(navigation.Title, navigation.Action, navigation.Controller)
        }
    }
</ul>
</code>```

Any help would be much appreciated :-)

NavigationViewModel

```<code>namespace WebApplication1.Models
{
    public class NavigationViewModel
    {
        public List<Navigation> Navigation { get; set; }
        public List<Content> Content { get; set; }
    }
}
</code>```

HomeController

```<code>public ActionResult Navigation()
{
    var navigationModel = new NavigationViewModel();
    navigationModel.Navigation = (from m in db.Navigations where (m.Main == true) orderby m.Position select m).ToList();
    navigationModel.Content = (from n in db.Contents where (n.Active == true) orderby n.Position select n).ToList();

    return View(navigationModel);
}
</code>```

答:
```<code>@if (!Model.Any())
{
    Response.Redirect("Create");
}
</code>```

Title: MVC Check if Model in View Has Records

Body:
I am struggling to determine if a Model passed to a View actually has any records.

The code below loops through the parent recordset and passes a parent parameter to a child recordset. I've tried if (Model.Content != null) but that doesn't seems to work, the code just thinks there are records, when actually there aren't.

Can somebody please review the code below and let me know what I am doing wrong?

    @foreach (var navigation in Model.Navigation)
    {
        if (Model.Content != null)
        {
            @Html.SubMenuLink(navigation.Title, navigation.Action, navigation.Controller)
            @Html.Raw("
")
            foreach (var content in Model.Content.Where(c => c.NavigationId == navigation.Id))
            {
                if (string.IsNullOrEmpty(content.Url))
                {
                    if (string.IsNullOrEmpty(content.Content1))
                    {
                    }
                    else
                    {
                        @Html.MenuLink(content.Title, "Home/Article/" + content.Id + "/" + ToFriendlyUrl(content.Title), "Home");
                    }
                }
                else
                {
                    @Html.MenuLink(content.Title, content.Url, "Home");
                }
            }
            @Html.Raw("
")
            @Html.Raw("
")
        }
        else
        {
            @Html.MenuLink(navigation.Title, navigation.Action, navigation.Controller)
        }
    }

Any help would be much appreciated :-)

NavigationViewModel

namespace WebApplication1.Models
{
    public class NavigationViewModel
    {
        public List<Navigation> Navigation { get; set; }
        public List<Content> Content { get; set; }
    }
}

HomeController

public ActionResult Navigation()
{
    var navigationModel = new NavigationViewModel();
    navigationModel.Navigation = (from m in db.Navigations where (m.Main == true) orderby m.Position select m).ToList();
    navigationModel.Content = (from n in db.Contents where (n.Active == true) orderby n.Position select n).ToList();

    return View(navigationModel);
}


问:
Using parameters in QString insert function
I'm trying to create a project in QT in which I want to edit a speicific line in a text file, using the parameters given in my function. The current function has no paramaters, but my goal is for a function that looks something like this:

```<code>setSettings(int x, QString y)
{
    QString command="ssh root@192.168.0.110 ";
    command.insert(command.length(), QString("'sed -i '2s/.*/OFF/' car.txt'"));
}
</code>```

This works as I want it to, but I want to use the parameters x and y to replace "2" and "OFF" in the case of the above example. How do I use those inside the quotation marks?

答:
You have to use arg, in your case:

```<code>QString command="ssh root@192.168.0.110 ";
command.append(QString("'sed -i '%1s/.*/%2/' car.txt'").arg(x).arg(y));
</code>```

Body:
I'm trying to create a project in QT in which I want to edit a speicific line in a text file, using the parameters given in my function. The current function has no paramaters, but my goal is for a function that looks something like this:

setSettings(int x, QString y)
{
    QString command="ssh root@192.168.0.110 ";
    command.insert(command.length(), QString("'sed -i '2s/.*/OFF/' car.txt'"));
}

This works as I want it to, but I want to use the parameters x and y to replace "2" and "OFF" in the case of the above example. How do I use those inside the quotation marks?

Body:
You have to use arg, in your case:

QString command="ssh root@192.168.0.110 ";
command.append(QString("'sed -i '%1s/.*/%2/' car.txt'").arg(x).arg(y));


问:
AWS S3: Setting a bucket policy for multiple users in an account
I have an S3 bucket. And I have several IAM users in this account. I would like to set a bucket policy that multiple users can access this bucket.

For access to a single user, my bucket policy looks like so:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::8474632:user/personA"
            },
            "Action": [
                "s3:getObject",
                "s3:PutObject",
                "s3:DeleteObject",
                "s3:getObjectAcl",
                "s3:GetObjectVersion"
            ],
            "Resource": "arn:aws:s3:::thisbucket/*"
        }
    ]
}
</code>```

I tried to change this line:

"AWS": "arn:aws:iam::8474632:user/personA"

to

"AWS": "arn:aws:iam::8474632:user/*"

to allow access to all users, but that doesn't work.

I could list all/some users one by one:

```<code>  "Principal": {
    "AWS": ["arn:aws:iam::111122223333:user/PersonA",
            "arn:aws:iam::111122223333:user/PersonB"]
  },
</code>```

Is there a better way to allow access of a bucket to a group of users or all users?

答:
Probably an alternative way of doing this would be to use an IAM policy that is attached to all users. You would create a policy like:

```<code>    "Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetObject",
            "s3:GetObjectAcl",
            "s3:GetObjectVersion",
            "s3:GetObjectVersionAcl",
            "s3:GetObjectVersionTagging",
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:PutObjectVersionAcl"
        ],
        "Resource": [
            "arn:aws:s3:::bucket_name/*"
        ]
    }
]
</code>```

}

Then add that policy to a new role, and then associate that role with the users you want access.

Body:
I have an S3 bucket. And I have several IAM users in this account. I would like to set a bucket policy that multiple users can access this bucket.

For access to a single user, my bucket policy looks like so:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::8474632:user/personA"
            },
            "Action": [
                "s3:getObject",
                "s3:PutObject",
                "s3:DeleteObject",
                "s3:getObjectAcl",
                "s3:GetObjectVersion"
            ],
            "Resource": "arn:aws:s3:::thisbucket/*"
        }
    ]
}

I tried to change this line:

"AWS": "arn:aws:iam::8474632:user/personA"

to

"AWS": "arn:aws:iam::8474632:user/*"

to allow access to all users, but that doesn't work.

I could list all/some users one by one:

  "Principal": {
    "AWS": ["arn:aws:iam::111122223333:user/PersonA",
            "arn:aws:iam::111122223333:user/PersonB"]
  },

Is there a better way to allow access of a bucket to a group of users or all users?

Body:
Probably an alternative way of doing this would be to use an IAM policy that is attached to all users. You would create a policy like:

    "Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetObject",
            "s3:GetObjectAcl",
            "s3:GetObjectVersion",
            "s3:GetObjectVersionAcl",
            "s3:GetObjectVersionTagging",
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:PutObjectVersionAcl"
        ],
        "Resource": [
            "arn:aws:s3:::bucket_name/*"
        ]
    }
]

}

Then add that policy to a new role, and then associate that role with the users you want access.


问:
spark streaming different value decoder per kafka topic
I need to create a Spark streaming that reads from several topic, and uses a different decoder per each topic (each topic contains a different avro-encoded obect):

```<code>def decode_avro(message):
    schem = avro.schema.parse(open("error_list.avsc").read())
    bytes_reader = io.BytesIO(message)
    decoder = avro.io.BinaryDecoder(bytes_reader)
    reader = avro.io.DatumReader(schem)
    return reader.read(decoder)

ssc = StreamingContext(sc, 2)
kvs = KafkaUtils.createDirectStream(ssc, [topic, topic2], {
    "metadata.broker.list": brokers}, valueDecoder = decode_avro)
</code>```

I wan't to know if it is possible to specify different decoder callbacks per topic, or if it is possible to know the topic name on the decoder function (on this way I could used the topic name for the avro schema file and decode all messages in the same function)

Thank you

答:
We also have this case where we read from different topics, with different message formats, and then process each topic and store the output into dedicated storage per source topic.
The right way to go here, is to create multiple streams. Stream per topic, in the same application, with the same Spark context.
Each stream will get the relevant ValueDecoder, and you may still read from multiple topics if they share the same format.</p>

Body:
I need to create a Spark streaming that reads from several topic, and uses a different decoder per each topic (each topic contains a different avro-encoded obect):

def decode_avro(message):
    schem = avro.schema.parse(open("error_list.avsc").read())
    bytes_reader = io.BytesIO(message)
    decoder = avro.io.BinaryDecoder(bytes_reader)
    reader = avro.io.DatumReader(schem)
    return reader.read(decoder)

ssc = StreamingContext(sc, 2)
kvs = KafkaUtils.createDirectStream(ssc, [topic, topic2], {
    "metadata.broker.list": brokers}, valueDecoder = decode_avro)

I wan't to know if it is possible to specify different decoder callbacks per topic, or if it is possible to know the topic name on the decoder function (on this way I could used the topic name for the avro schema file and decode all messages in the same function)

Thank you


问:
Query to delete sql table row based on attribute in xml file c#
I currently have 3 different xml elements to "Add", "Update", and "Delete".  Following these elements, I have a few attributes that will either add, update, or delete from my sql table.  I was able to use  "LOAD XML LOCAL INFILE" query for the "add" and "update" elements, but there is no remove/delete options for the "LOAD XML LOCAL INFILE" query.  The following is my get/set method, Class1 class and my main method class.

Main Class

```<code>using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string conString = "Driver={MySQL ODBC 5.3 ANSI Driver};"
                + "Server=WWW;Port=XXX;"
                + "Database=inventory;"
                + "uid=YYY;pwd=ZZZ";
            OdbcConnection connection = new OdbcConnection(conString);

            {
                XDocument theFile = XDocument.Load("C:\\Users\\Bob\\Documents\\Update.xml");
                foreach (XElement el in theFile.Root.Elements())
                {
                    if (el.Name == "ADD")
                    {
                       Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully added.");
                        Console.ReadLine();

                        OdbcCommand Command1 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' INTO TABLE item ROWS IDENTIFIED BY '<ADD>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command1.ExecuteReader();
                        connection.Close();
                    }
                    else if (el.Name == "UPDATE")
                    {
                        Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully updated.");
                        Console.ReadLine();

                        OdbcCommand Command2 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' REPLACE INTO TABLE item ROWS IDENTIFIED BY '<UPDATE>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command2.ExecuteReader();
                        connection.Close();
                    }
                    else if (el.Name == "DELETE")
                    {
                        Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully deleted."); ;
                        Console.ReadLine();

                        OdbcCommand Command3 = new OdbcCommand("", connection, connection);
                        connection.Open();
                        OdbcDataReader reader = Command3.ExecuteReader();
                        connection.Close();
                    }
                    else
                    {
                       Console.WriteLine( "Nothing to do");
                    }
                }
            }
        }
    }
}
</code>```

Class1 Class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    public class Class1
    {
        public static object Item_ID { get; set; }
        public static object Invent_id { get; set; }
        public static object Itemsize { get; set; }
        public static object Color { get; set; }
        public static decimal Curr_price { get; set; }
        public static object Qoh { get; set; }
    }
    public class transactions
    {
        [XmlRoot(ElementName = "UPDATE")]
        public class UPDATE
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "ADD")]
        public class ADD
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "DELETE")]
        public class DELETE
        {
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "transactions")]
        public class Transactions
        {
            [XmlElement(ElementName = "UPDATE")]
            public UPDATE UPDATE { get; set; }
            [XmlElement(ElementName = "ADD")]
            public List<ADD> ADD { get; set; }
            [XmlElement(ElementName = "DELETE")]
            public DELETE DELETE { get; set; }
        }
    }
}
</code>```

答:
I was able to solve this by adding my attribute and value to the query like so

```<code>OdbcCommand Command3 = new OdbcCommand("DELETE FROM item WHERE item_id = " + el.Attribute("item_id").Value, connection);
</code>```

Also, since my queries pull the information straight from my xml file, there is no need for my get and set methods.

Body:
I currently have 3 different xml elements to "Add", "Update", and "Delete".  Following these elements, I have a few attributes that will either add, update, or delete from my sql table.  I was able to use  "LOAD XML LOCAL INFILE" query for the "add" and "update" elements, but there is no remove/delete options for the "LOAD XML LOCAL INFILE" query.  The following is my get/set method, Class1 class and my main method class.

Main Class

using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string conString = "Driver={MySQL ODBC 5.3 ANSI Driver};"
                + "Server=WWW;Port=XXX;"
                + "Database=inventory;"
                + "uid=YYY;pwd=ZZZ";
            OdbcConnection connection = new OdbcConnection(conString);

            {
                XDocument theFile = XDocument.Load("C:\\Users\\Bob\\Documents\\Update.xml");
                foreach (XElement el in theFile.Root.Elements())
                {
                    if (el.Name == "ADD")
                    {
                       Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully added.");
                        Console.ReadLine();

                        OdbcCommand Command1 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' INTO TABLE item ROWS IDENTIFIED BY '<ADD>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command1.ExecuteReader();
                        connection.Close();
                    }
                    else if (el.Name == "UPDATE")
                    {
                        Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully updated.");
                        Console.ReadLine();

                        OdbcCommand Command2 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' REPLACE INTO TABLE item ROWS IDENTIFIED BY '<UPDATE>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command2.ExecuteReader();
                        connection.Close();
                    }
                    else if (el.Name == "DELETE")
                    {
                        Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully deleted."); ;
                        Console.ReadLine();

                        OdbcCommand Command3 = new OdbcCommand("", connection, connection);
                        connection.Open();
                        OdbcDataReader reader = Command3.ExecuteReader();
                        connection.Close();
                    }
                    else
                    {
                       Console.WriteLine( "Nothing to do");
                    }
                }
            }
        }
    }
}

Class1 Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    public class Class1
    {
        public static object Item_ID { get; set; }
        public static object Invent_id { get; set; }
        public static object Itemsize { get; set; }
        public static object Color { get; set; }
        public static decimal Curr_price { get; set; }
        public static object Qoh { get; set; }
    }
    public class transactions
    {
        [XmlRoot(ElementName = "UPDATE")]
        public class UPDATE
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "ADD")]
        public class ADD
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "DELETE")]
        public class DELETE
        {
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "transactions")]
        public class Transactions
        {
            [XmlElement(ElementName = "UPDATE")]
            public UPDATE UPDATE { get; set; }
            [XmlElement(ElementName = "ADD")]
            public List<ADD> ADD { get; set; }
            [XmlElement(ElementName = "DELETE")]
            public DELETE DELETE { get; set; }
        }
    }
}

Body:
I was able to solve this by adding my attribute and value to the query like so

OdbcCommand Command3 = new OdbcCommand("DELETE FROM item WHERE item_id = " + el.Attribute("item_id").Value, connection);

Also, since my queries pull the information straight from my xml file, there is no need for my get and set methods.


问:
patching text files
I'm trying to successively build up a text file with diff patches.
starting from an empty text file I need to apply 600+ patches to end up with the final document (a text I have written + tracked the changes with mercurial). to each change in the file extra information needs to be added, so I can't simply use diff and patch in the commandline.

I have spent all day to write (and re-write) a tool that parses the diff files and makes changes to the text file accordingly, but one of the diff files makes my program behave in a way that I can't make any sense of.

this function gets called for each of the diff files:

```<code># filename = name of the diff file
# date = extra information to be added as a prefix to each added line
def process_diff(filename, date):
    # that's the file all the patches will be applied to
    merge_file = open("thesis_merged.txt", "r")
    # map its content to a list to manipulate it in memory
    merge_file_lines = []
    for line in merge_file:
        line = line.rstrip()
        merge_file_lines.append(line)
    merge_file.close()

    # open for writing:
    merge_file = open("thesis_merged.txt", "w")

    # that's the diff file, containing all the changes
    diff_file = open(filename, "r")
    print "-", filename, "-" * 20

    # also map it to a list
    diff_file_lines = []
    for line in diff_file:
        line = line.rstrip()

        if not line.startswith("\\ No newline at end of file"): # useless information ... or not?
        diff_file_lines.append(line)

    # ignore header:
    #--- thesis_words_0.txt 2010-12-04 18:16:26.020000000 +0100
    #+++ thesis_words_1.txt 2010-12-04 18:16:26.197000000 +0100
    diff_file_lines = diff_file_lines[2:]

    hunks = []
    for i, line in enumerate(diff_file_lines):
        if line.startswith("@@"):
            hunks.append( get_hunk(diff_file_lines, i) )

    for hunk in hunks:
        head = hunk[0]
        # @@ -252,10 +251,9 @@
        tmp = head[3:-3].split(" ") # [-252,10] [+251,9]
        line_nr_minus = tmp[0].split(",")[0]
        line_nr_minus = int(line_nr_minus[1:]) # 252
        line_nr_plus = tmp[1].split(",")[0]
        line_nr_plus = int(line_nr_plus[1:]) # 251

        for j, line in enumerate(hunk[1:]):
            if line.startswith("-"):
            # delete line from the file in memory
            del merge_file_lines[line_nr_minus-1]

        plus_counter = 0 # counts the number of added lines
        for k, line in enumerate(hunk[1:]):
            if line.startswith("+"):
                # insert line, one after another
                merge_file_lines.insert((line_nr_plus-1)+plus_counter, line[1:])
                plus_counter += 1

    for line in merge_file_lines:
        # write the updated file back to the disk
        merge_file.write(line.rstrip() + "\n")

    merge_file.close()
    diff_file.close()
    print "\n\n"

    def get_hunk(lines, i):
        hunk = []
        hunk.append(lines[i])
        # @@ -252,10 +251,9 @@

        lines = lines[i+1:]

        for line in lines:
            if line.startswith("@@"):
                # next hunk begins, so stop here
                break
            else:
                hunk.append(line)

            return hunk
</code>```

the diff files look like this -- here the trouble maker:

```<code>--- thesis_words_12.txt 2011-01-17 20:35:50.804000000 +0100
+++ thesis_words_13.txt 2011-01-17 20:35:51.057000000 +0100
@@ -245 +245,2 @@
-As
+Per
+definition
@@ -248,3 +249 @@
-already
-proposes,
-"generative"
+generative
@@ -252,10 +251,9 @@
-that
-something
-is
-created
-based
-on
-a
-set
-of
-rules.
+"having
+the
+ability
+to
+originate,
+produce,
+or
+procreate."
+<http://www.thefreedictionary.com/generative>
</code>```

output:

```<code>[...]

Per
definition
the
"generative"
generative
means
"having
the
ability
to
originate,
produce,
or
procreate."
<http://www.thefreedictionary.com/generative>
that

[...]
</code>```

all the previous patches reproduce the text just as expected. I have rewritten this many times, but that buggy behavior persists -- so right now I am clueless.

I'd be very thankful for hints and tips on how to do this differently. thanks a lot in advance!

EDIT:
- in the end each line is supposed to look like this: {date_and_time_of_text_change}word

it's basicly about keeping track at what date and time a word was added to the text.

答:
there was indeed a bug in the code -- I wasn't interpreting the diff files correctly (didn't realize there needed to be a line shift, when there are multiple hunks in one diff file)</p>

```<code>def process_diff(filename, date, step_nr):
    merge_file = open("thesis_merged.txt", "r")
    merge_file_lines = [line.rstrip() for line in merge_file]
    merge_file.close()

    diff_file = open(filename, "r")
    print "-", filename, "-"*2, step_nr, "-"*2, date

    diff_file_lines = [line.rstrip() for line in diff_file]
    hunks = []
    for i, line in enumerate(diff_file_lines):
        if line.startswith("@@"):
            hunks.append( get_hunk(diff_file_lines, i) )
    diff_file.close()

    line_shift = 0
    for hunk in hunks:
        head = hunk[0]
        # @@ -252,10 +251,9 @@
        tmp = head[3:-3].split(" ") # [-252,10] [+251,9]

        line_nr_minus = tmp[0].split(",")[0]
        minusses = 1
        if len( tmp[0].split(",") ) > 1:
            minusses = int( tmp[0].split(",")[1] )
        line_nr_minus = int(line_nr_minus[1:]) # 252

        line_nr_plus = tmp[1].split(",")[0]
        plusses = 1
        if len( tmp[1].split(",") ) > 1:
            plusses = int( tmp[1].split(",")[1] )
        line_nr_plus = int(line_nr_plus[1:]) # 251

        line_nr_minus += line_shift

        #@@ -248,3 +249 @@
        #-already
        #-proposes,
        #-"generative"
        #+generative

        if hunk[1]: # -
            for line in hunk[1]:
                del merge_file_lines[line_nr_minus-1]

        plus_counter = 0
        if hunk[2]: # +
            for line in hunk[2]:
                prefix = ""
                if len(line) > 1:
                    prefix = "{" + date + "}"
                merge_file_lines.insert((line_nr_plus-1)+plus_counter, prefix + line[1:])
                plus_counter += 1

        line_shift += plusses - minusses
</code>```

Title: patching text files

Body:
I'm trying to successively build up a text file with diff patches.
starting from an empty text file I need to apply 600+ patches to end up with the final document (a text I have written + tracked the changes with mercurial). to each change in the file extra information needs to be added, so I can't simply use diff and patch in the commandline.

I have spent all day to write (and re-write) a tool that parses the diff files and makes changes to the text file accordingly, but one of the diff files makes my program behave in a way that I can't make any sense of.

this function gets called for each of the diff files:

# filename = name of the diff file
# date = extra information to be added as a prefix to each added line
def process_diff(filename, date):
    # that's the file all the patches will be applied to
    merge_file = open("thesis_merged.txt", "r")
    # map its content to a list to manipulate it in memory
    merge_file_lines = []
    for line in merge_file:
        line = line.rstrip()
        merge_file_lines.append(line)
    merge_file.close()

    # open for writing:
    merge_file = open("thesis_merged.txt", "w")

    # that's the diff file, containing all the changes
    diff_file = open(filename, "r")
    print "-", filename, "-" * 20

    # also map it to a list
    diff_file_lines = []
    for line in diff_file:
        line = line.rstrip()

        if not line.startswith("\\ No newline at end of file"): # useless information ... or not?
        diff_file_lines.append(line)

    # ignore header:
    #--- thesis_words_0.txt 2010-12-04 18:16:26.020000000 +0100
    #+++ thesis_words_1.txt 2010-12-04 18:16:26.197000000 +0100
    diff_file_lines = diff_file_lines[2:]

    hunks = []
    for i, line in enumerate(diff_file_lines):
        if line.startswith("@@"):
            hunks.append( get_hunk(diff_file_lines, i) )

    for hunk in hunks:
        head = hunk[0]
        # @@ -252,10 +251,9 @@
        tmp = head[3:-3].split(" ") # [-252,10] [+251,9]
        line_nr_minus = tmp[0].split(",")[0]
        line_nr_minus = int(line_nr_minus[1:]) # 252
        line_nr_plus = tmp[1].split(",")[0]
        line_nr_plus = int(line_nr_plus[1:]) # 251

        for j, line in enumerate(hunk[1:]):
            if line.startswith("-"):
            # delete line from the file in memory
            del merge_file_lines[line_nr_minus-1]

        plus_counter = 0 # counts the number of added lines
        for k, line in enumerate(hunk[1:]):
            if line.startswith("+"):
                # insert line, one after another
                merge_file_lines.insert((line_nr_plus-1)+plus_counter, line[1:])
                plus_counter += 1

    for line in merge_file_lines:
        # write the updated file back to the disk
        merge_file.write(line.rstrip() + "\n")

    merge_file.close()
    diff_file.close()
    print "\n\n"

    def get_hunk(lines, i):
        hunk = []
        hunk.append(lines[i])
        # @@ -252,10 +251,9 @@

        lines = lines[i+1:]

        for line in lines:
            if line.startswith("@@"):
                # next hunk begins, so stop here
                break
            else:
                hunk.append(line)

            return hunk

the diff files look like this -- here the trouble maker:

--- thesis_words_12.txt 2011-01-17 20:35:50.804000000 +0100
+++ thesis_words_13.txt 2011-01-17 20:35:51.057000000 +0100
@@ -245 +245,2 @@
-As
+Per
+definition
@@ -248,3 +249 @@
-already
-proposes,
-"generative"
+generative
@@ -252,10 +251,9 @@
-that
-something
-is
-created
-based
-on
-a
-set
-of
-rules.
+"having
+the
+ability
+to
+originate,
+produce,
+or
+procreate."
+<http://www.thefreedictionary.com/generative>

output:

[...]

Per
definition
the
"generative"
generative
means
"having
the
ability
to
originate,
produce,
or
procreate."
<http://www.thefreedictionary.com/generative>
that

[...]

all the previous patches reproduce the text just as expected. I have rewritten this many times, but that buggy behavior persists -- so right now I am clueless.

I'd be very thankful for hints and tips on how to do this differently. thanks a lot in advance!

EDIT:
- in the end each line is supposed to look like this: {date_and_time_of_text_change}word

it's basicly about keeping track at what date and time a word was added to the text.

Body:
there was indeed a bug in the code -- I wasn't interpreting the diff files correctly (didn't realize there needed to be a line shift, when there are multiple hunks in one diff file)

def process_diff(filename, date, step_nr):
    merge_file = open("thesis_merged.txt", "r")
    merge_file_lines = [line.rstrip() for line in merge_file]
    merge_file.close()

    diff_file = open(filename, "r")
    print "-", filename, "-"*2, step_nr, "-"*2, date

    diff_file_lines = [line.rstrip() for line in diff_file]
    hunks = []
    for i, line in enumerate(diff_file_lines):
        if line.startswith("@@"):
            hunks.append( get_hunk(diff_file_lines, i) )
    diff_file.close()

    line_shift = 0
    for hunk in hunks:
        head = hunk[0]
        # @@ -252,10 +251,9 @@
        tmp = head[3:-3].split(" ") # [-252,10] [+251,9]

        line_nr_minus = tmp[0].split(",")[0]
        minusses = 1
        if len( tmp[0].split(",") ) > 1:
            minusses = int( tmp[0].split(",")[1] )
        line_nr_minus = int(line_nr_minus[1:]) # 252

        line_nr_plus = tmp[1].split(",")[0]
        plusses = 1
        if len( tmp[1].split(",") ) > 1:
            plusses = int( tmp[1].split(",")[1] )
        line_nr_plus = int(line_nr_plus[1:]) # 251

        line_nr_minus += line_shift

        #@@ -248,3 +249 @@
        #-already
        #-proposes,
        #-"generative"
        #+generative

        if hunk[1]: # -
            for line in hunk[1]:
                del merge_file_lines[line_nr_minus-1]

        plus_counter = 0
        if hunk[2]: # +
            for line in hunk[2]:
                prefix = ""
                if len(line) > 1:
                    prefix = "{" + date + "}"
                merge_file_lines.insert((line_nr_plus-1)+plus_counter, prefix + line[1:])
                plus_counter += 1

        line_shift += plusses - minusses