问:
How to construct an XML document out of an XPATH Java
I have the following xpath:

```<code>/Parent/Children/child
</code>```

My goal is to construct the following XML document based solely off the xpath above:

```<code><Parent>
  <Children>
    <child></child>
  </Children>
</Parent>
</code>```

How can I accomplish my goal using Java?

答:
You can Try this:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:variable name="path" select="'/Parent/Children/child'"></xsl:variable>

    <xsl:template match="/">
        <xsl:call-template name="createstructure">
            <xsl:with-param name="xpath" select="$path"></xsl:with-param>
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="createstructure">
        <xsl:param name="xpath" select="."/>
        <xsl:variable name="elementname">
            <xsl:choose>
                <xsl:when test="contains($xpath, '/')">
                    <xsl:value-of select="substring-before(replace($xpath, '^/', ''), '/')"/>
                </xsl:when>
                <xsl:otherwise><xsl:value-of select="normalize-space($xpath)"/></xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        <xsl:element name="{$elementname}">
            <xsl:choose>
                <xsl:when test="contains($xpath, '/')">
                    <xsl:call-template name="createstructure">
                        <xsl:with-param name="xpath" select="substring-after(replace($xpath, '^/', ''), '/')"/>
                    </xsl:call-template>
                </xsl:when>
            </xsl:choose>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>
</code>```

Body:
I have the following xpath:

/Parent/Children/child

My goal is to construct the following XML document based solely off the xpath above:

<Parent>
  <Children>
    <child></child>
  </Children>
</Parent>

How can I accomplish my goal using Java?

Body:
You can Try this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:variable name="path" select="'/Parent/Children/child'"></xsl:variable>

    <xsl:template match="/">
        <xsl:call-template name="createstructure">
            <xsl:with-param name="xpath" select="$path"></xsl:with-param>
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="createstructure">
        <xsl:param name="xpath" select="."/>
        <xsl:variable name="elementname">
            <xsl:choose>
                <xsl:when test="contains($xpath, '/')">
                    <xsl:value-of select="substring-before(replace($xpath, '^/', ''), '/')"/>
                </xsl:when>
                <xsl:otherwise><xsl:value-of select="normalize-space($xpath)"/></xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        <xsl:element name="{$elementname}">
            <xsl:choose>
                <xsl:when test="contains($xpath, '/')">
                    <xsl:call-template name="createstructure">
                        <xsl:with-param name="xpath" select="substring-after(replace($xpath, '^/', ''), '/')"/>
                    </xsl:call-template>
                </xsl:when>
            </xsl:choose>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>


来源: stackexchange

问:
DynamoDB - How to create map and add attribute to it in one update
I want to create a new map if it doesn't exist and then add an attribute to that map. Something like this:

SET #A = if_not_exists(#A, :emptyMap), #A.#B = :somevalue

However doing the above gives me the error saying Two document paths overlap with each other

The only other thing I am thinking to do is do TWO updates, one to create any empty maps and then another to set attributes.

Is there a way to do it in a single update ?

Update

Another use case is creating maps that contain other maps. Currently the only way I can think of to create the following is 3 separate update calls to create the maps if necessary and then another update call to add attributes:

```<code>{
  Entities: { A: { B: {} } },
}
</code>```

There must be a better way.

答:
You can amortize the cost of doing two seperate UpdateItem calls, one to create #A, and the other to add #B to #A by adding #B to #A with a conditional update.

```<code>UpdateExpression: SET #A.#B = :valueOfB
ConditionExpression: attribute_exists(#A)
</code>```

If you add many entries to #A, then you only create #A once, and as the number of entries in #A increases, the amortized time to create #A approaches zero. If you catch a ConditionalCheckFailedException, that is when you would create the map with #B already in it and call UpdateItem:

```<code>UpdateExpression: SET #A = :valueOfMapWithBInIt
ConditionExpression: attribute_not_exists(#A)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create a new map if it doesn't exist and then add an attribute to that map. Something like this:

SET #A = if_not_exists(#A, :emptyMap), #A.#B = :somevalue

However doing the above gives me the error saying Two document paths overlap with each other

The only other thing I am thinking to do is do TWO updates, one to create any empty maps and then another to set attributes.

Is there a way to do it in a single update ?

Update

Another use case is creating maps that contain other maps. Currently the only way I can think of to create the following is 3 separate update calls to create the maps if necessary and then another update call to add attributes:

{
  Entities: { A: { B: {} } },
}

There must be a better way.

Body:
You can amortize the cost of doing two seperate UpdateItem calls, one to create #A, and the other to add #B to #A by adding #B to #A with a conditional update.

UpdateExpression: SET #A.#B = :valueOfB
ConditionExpression: attribute_exists(#A)

If you add many entries to #A, then you only create #A once, and as the number of entries in #A increases, the amortized time to create #A approaches zero. If you catch a ConditionalCheckFailedException, that is when you would create the map with #B already in it and call UpdateItem:

UpdateExpression: SET #A = :valueOfMapWithBInIt
ConditionExpression: attribute_not_exists(#A)


问:
Using object as property of another object
I want to use an object template as a property of another object. My template object is like below

```<code>var tableDataRow ={
    numberOfFiles:parseFloat(0),
    insurerIncurred :parseFloat(0),
    insuredIncurred :parseFloat(0),
    totalIncurred :parseFloat(0)
};
</code>```

I'm using this object like this

```<code>var tableData ={
    firm1 :tableDataRow,
    firm2:tableDataRow,
    firm3:tableDataRow,
    firm4:tableDataRow
};
</code>```

But when I want to change a property value in tableDataRow object, all values in tableData are changing.

```<code>tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;
</code>```

I thought that I can use like object oriented languages but I supposed that this way I have only put a reference of tableDataRow in another object. How can I do this ?

https://jsfiddle.net/0ta0wkho/

答:
Here all the fields are referring to the same object
You may assign a clone of the object to fields of the tableData object.

Corrected code

var tableDataRow = {
  numberOfFiles: parseFloat(0),
  insurerIncurred: parseFloat(0),
  insuredIncurred: parseFloat(0),
  totalIncurred: parseFloat(0)
};

var tableData = {
  firm1: Object.assign({}, tableDataRow),
  firm2: Object.assign({}, tableDataRow),
  firm3: Object.assign({}, tableDataRow),
  firm4: Object.assign({}, tableDataRow),
};

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

console.log(tableData);```
</div>
</div>
</p>

<p>You can otherwise write a constructor for <code>TableDataRow</code> and assign instances of it to all the fields</p>

<p>Here is one of the ways of doing it</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-js lang-js prettyprint-override"><code>function TableDataRow() {
  this.numberOfFiles = parseFloat(0),
    this.insurerIncurred = parseFloat(0),
    this.insuredIncurred = parseFloat(0),
    this.totalIncurred = parseFloat(0)
};

var tableData = {
  firm1: new TableDataRow(),
  firm2: new TableDataRow(),
  firm3: new TableDataRow(),
  firm4: new TableDataRow()
};

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

console.log(tableData);</code>```

Body:
I want to use an object template as a property of another object. My template object is like below

var tableDataRow ={
    numberOfFiles:parseFloat(0),
    insurerIncurred :parseFloat(0),
    insuredIncurred :parseFloat(0),
    totalIncurred :parseFloat(0)
};

I'm using this object like this

var tableData ={
    firm1 :tableDataRow,
    firm2:tableDataRow,
    firm3:tableDataRow,
    firm4:tableDataRow
};

But when I want to change a property value in tableDataRow object, all values in tableData are changing.

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

I thought that I can use like object oriented languages but I supposed that this way I have only put a reference of tableDataRow in another object. How can I do this ?

https://jsfiddle.net/0ta0wkho/

Body:
Here all the fields are referring to the same object
You may assign a clone of the object to fields of the tableData object.

Corrected code

var tableDataRow = {
  numberOfFiles: parseFloat(0),
  insurerIncurred: parseFloat(0),
  insuredIncurred: parseFloat(0),
  totalIncurred: parseFloat(0)
};

var tableData = {
  firm1: Object.assign({}, tableDataRow),
  firm2: Object.assign({}, tableDataRow),
  firm3: Object.assign({}, tableDataRow),
  firm4: Object.assign({}, tableDataRow),
};

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

console.log(tableData);

You can otherwise write a constructor for TableDataRow and assign instances of it to all the fields

Here is one of the ways of doing it

function TableDataRow() {
  this.numberOfFiles = parseFloat(0),
    this.insurerIncurred = parseFloat(0),
    this.insuredIncurred = parseFloat(0),
    this.totalIncurred = parseFloat(0)
};

var tableData = {
  firm1: new TableDataRow(),
  firm2: new TableDataRow(),
  firm3: new TableDataRow(),
  firm4: new TableDataRow()
};

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

console.log(tableData);


问:
RSS pubDate parsing with ROME
I wanted to give ROME a try to parse some feeds, when suddenly it was unable to parse some pubDate fields formatted as <pubDate>2013-08-30 20:23:00</pubDate> with a null result, but it was ok to format that type of fields <pubDate>Fri, 30 Aug 2013 17:42:04 +0300</pubDate>.

So what's the trick? it is possible somehow to get the result even if there is not a format supported by ROME? or maybe there are some another good RSS parsers comparing to ROME?

答:
I also experienced issues with the pubDate field. However the format of Thu, 30 Mar 2017 08:00:57 +0100 yields null. (Rss version 0.91)

However bumping the version to 0.93 solved the issue. This is also according to the specs version 0.91 (and 0.92) that do not have a pubDate at item level, only at feed level.

Title: RSS pubDate parsing with ROME


问:
Cover blank space of image by other elements of Jasper Report
I have an image height of 360px and width of 900px. According to my condition sometimes image will be blank so it does not show in the PDF or EXCEL.

At this point, when image is not their than other element positioned according to their set "y" axis. Because of this a gap is formed.

So how to set their all the other elements position to top when image is not their.

```<code><image isUsingCache="true" onErrorType="Icon">
                <reportElement x="448" y="0" width="402" height="300" uuid="d8d19734-1711-461d-bdb8-c8c7130a6eb2">
                    <printWhenExpression><![CDATA[($P{chartImg2}!=null ? true : false)]]></printWhenExpression>
                </reportElement>
                <imageExpression><![CDATA[$P{chartImg2}]]></imageExpression>
            </image>
            <textField>
                <reportElement style="REPORT_TITLE" mode="Opaque" x="0" y="320" width="850" height="30" uuid="aabbe2ed-96eb-4246-8bda-16187228c116">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                    <property name="com.jaspersoft.studio.unit.y" value="pixel"/>
                    <property name="com.jaspersoft.studio.unit.width" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Center">
                    <font isBold="true"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{campaign_name}+"- Links Report"]]></textFieldExpression>
            </textField>
</code>```

So, now you can see that image is of 300 height than textfield is positioned at 320px so image is not their than still textfield will be shown after 320px. Its looks bad in PDF. So I want if image is not their than all the element shift above.

答:
I got the solution of my problem. You need to add elements into frame which are depends upon the condition. Here in above question like image may or may not be there.

So In this case add this image into frame and changed other elements are positioned to float. (There is a property available in all the elements positionedType="float")

Bingo!!! Problem is solved.

Body:
I have an image height of 360px and width of 900px. According to my condition sometimes image will be blank so it does not show in the PDF or EXCEL.

At this point, when image is not their than other element positioned according to their set "y" axis. Because of this a gap is formed.

So how to set their all the other elements position to top when image is not their.

<image isUsingCache="true" onErrorType="Icon">
                <reportElement x="448" y="0" width="402" height="300" uuid="d8d19734-1711-461d-bdb8-c8c7130a6eb2">
                    <printWhenExpression><![CDATA[($P{chartImg2}!=null ? true : false)]]></printWhenExpression>
                </reportElement>
                <imageExpression><![CDATA[$P{chartImg2}]]></imageExpression>
            </image>
            <textField>
                <reportElement style="REPORT_TITLE" mode="Opaque" x="0" y="320" width="850" height="30" uuid="aabbe2ed-96eb-4246-8bda-16187228c116">
                    <property name="com.jaspersoft.studio.unit.height" value="pixel"/>
                    <property name="com.jaspersoft.studio.unit.y" value="pixel"/>
                    <property name="com.jaspersoft.studio.unit.width" value="pixel"/>
                </reportElement>
                <textElement textAlignment="Center">

                </textElement>
                <textFieldExpression><![CDATA[$P{campaign_name}+"- Links Report"]]></textFieldExpression>
            </textField>

So, now you can see that image is of 300 height than textfield is positioned at 320px so image is not their than still textfield will be shown after 320px. Its looks bad in PDF. So I want if image is not their than all the element shift above.


问:
Last day of DatePickerDialog is not selectable after setting max date
After using setMaxDate to limit the number of days selectable on the DatePickerDialog, the last day is not greyed out but is not selectable. Thank you for your help in advance.</p>

```<code>private void showDatePickerDialog() {
    DateTime dateTime = new DateTime();
    DateTime tomorrow = dateTime.plusDays(1);
    int year = tomorrow.getYear();
    int month = tomorrow.getMonthOfYear() -1; // zero based months
    int day = tomorrow.getDayOfMonth();

    DateTime thirtyDaysInFuture = dateTime.plusDays(30);

    long tomorrowMilliseconds = tomorrow.getMillis();
    long futureMilliseconds = thirtyDaysInFuture.getMillis();

    Log.d(TAG, "YEAR: " + year + ", MONTH: " + month + ", DAY: " + day);

    DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
            Log.d(TAG, i + ", " + i1 + ", " + i2);

        }
    }, year, month, day);

    datePickerDialog.getDatePicker().setMinDate(tomorrowMilliseconds);
    datePickerDialog.getDatePicker().setMaxDate(futureMilliseconds);
    datePickerDialog.show();
}
</code>```

答:
I had same problem and I found an answer. Try to use this code:

First you should reset current date, it's hours, minutes and seconds

```<code>        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        calendar.add(Calendar.DAY_OF_YEAR, 14); //I set max date +2 weeks
        calendar.add(Calendar.HOUR_OF_DAY, 23);
        calendar.add(Calendar.MINUTE, 59);
        calendar.add(Calendar.SECOND, 59);

        dlgDate.getDatePicker().setMaxDate(calendar.getTimeInMillis());
</code>```

Hope I help you

Body:
After using setMaxDate to limit the number of days selectable on the DatePickerDialog, the last day is not greyed out but is not selectable. Thank you for your help in advance.

private void showDatePickerDialog() {
    DateTime dateTime = new DateTime();
    DateTime tomorrow = dateTime.plusDays(1);
    int year = tomorrow.getYear();
    int month = tomorrow.getMonthOfYear() -1; // zero based months
    int day = tomorrow.getDayOfMonth();

    DateTime thirtyDaysInFuture = dateTime.plusDays(30);

    long tomorrowMilliseconds = tomorrow.getMillis();
    long futureMilliseconds = thirtyDaysInFuture.getMillis();

    Log.d(TAG, "YEAR: " + year + ", MONTH: " + month + ", DAY: " + day);

    DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
            Log.d(TAG, i + ", " + i1 + ", " + i2);

        }
    }, year, month, day);

    datePickerDialog.getDatePicker().setMinDate(tomorrowMilliseconds);
    datePickerDialog.getDatePicker().setMaxDate(futureMilliseconds);
    datePickerDialog.show();
}

Body:
I had same problem and I found an answer. Try to use this code:

First you should reset current date, it's hours, minutes and seconds

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        calendar.add(Calendar.DAY_OF_YEAR, 14); //I set max date +2 weeks
        calendar.add(Calendar.HOUR_OF_DAY, 23);
        calendar.add(Calendar.MINUTE, 59);
        calendar.add(Calendar.SECOND, 59);

        dlgDate.getDatePicker().setMaxDate(calendar.getTimeInMillis());

Hope I help you


答:
You can make tableDataRow as a function returning your template object. This way, you can use its individual instance while assigning it to tableData.firm1 and so on.

var tableDataRow = function(){
    return {
      numberOfFiles:parseFloat(0),
      insurerIncurred :parseFloat(0),
      insuredIncurred :parseFloat(0),
      totalIncurred :parseFloat(0)
    }
};
var tableData ={
    firm1: new tableDataRow,
    firm2: new tableDataRow,
    firm3: new tableDataRow,
    firm4: new tableDataRow
};

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

console.log(tableData);```

Title: Using object as property of another object


问:
Forwarding message with TLSharp library (C#)
I'm connecting to Telegram API with this C# library: TLSharp

The resources for this library is not enough, I'm trying to Forward a message to channel .

I'm not quiet sure how to get channel post peer id (for forward function input parameters)

```<code>var store = new FileSessionStore();
            var client = new TelegramClient(Properties.Settings.Default.apiID, Properties.Settings.Default.apiHash, store, "session");
            await client.ConnectAsync();
            var dialogs = (TLDialogs)await client.GetUserDialogsAsync();
            var chat = dialogs.chats.lists
                .OfType<TLChannel>()
                .SingleOrDefault(a=>a.title=="test");
            await client.SendRequestAsync<TLAbsUpdates>(
                               new TLRequestForwardMessage()
                               {
                                   id = 2,
                                   peer = new TLInputPeerChannel() { channel_id = chat.id, access_hash = chat.access_hash.Value },
                                   random_id = Helpers.GenerateRandomLong()
                               });
</code>```

I get this error message :

{"PEER_ID_INVALID"}

Please help me, what is that peer id and how can i access and use that for forwarding a message using TLSharp. Thanks.

答:
You can do that with this nice trick which is hilarious: this code is below: </p>

```<code>new TLInputPeerChannel { channel_id = chat.id, access_hash = cha.access_hash.Value }, offset,
                maxId, limit);
</code>```

Body:
I'm connecting to Telegram API with this C# library: TLSharp

The resources for this library is not enough, I'm trying to Forward a message to channel .

I'm not quiet sure how to get channel post peer id (for forward function input parameters)

var store = new FileSessionStore();
            var client = new TelegramClient(Properties.Settings.Default.apiID, Properties.Settings.Default.apiHash, store, "session");
            await client.ConnectAsync();
            var dialogs = (TLDialogs)await client.GetUserDialogsAsync();
            var chat = dialogs.chats.lists
                .OfType<TLChannel>()
                .SingleOrDefault(a=>a.title=="test");
            await client.SendRequestAsync<TLAbsUpdates>(
                               new TLRequestForwardMessage()
                               {
                                   id = 2,
                                   peer = new TLInputPeerChannel() { channel_id = chat.id, access_hash = chat.access_hash.Value },
                                   random_id = Helpers.GenerateRandomLong()
                               });

I get this error message :

{"PEER_ID_INVALID"}

Please help me, what is that peer id and how can i access and use that for forwarding a message using TLSharp. Thanks.

Body:
You can do that with this nice trick which is hilarious: this code is below:

new TLInputPeerChannel { channel_id = chat.id, access_hash = cha.access_hash.Value }, offset,
                maxId, limit);


问:
Embedding a navigation controller in a container - Objective C
How to embed a Navigation controller in a container View?
When I place the container the first this that shows is a viewController embed to the container, I want to change that viewController to a navigation view and set it rootViewController and other views</p>

答:
The UINavigationController controls the UIViewController . So the "container" is NavigationController not others.

The same as UITabbarController. If you want to change the view architecture even the rootViewControler. I will tell you my experience.

Like this:

We can switch the login page and homeTabbar container freedom.

```<code>if (Boolean conditions) {//show login page
    [self showLoginAndRegisterVC];
} else { //show home Page
    [self showHomeViewController];
}
[self.window makeKeyAndVisible];
</code>```

Body:
The UINavigationController controls the UIViewController . So the "container" is NavigationController not others.

The same as UITabbarController. If you want to change the view architecture even the rootViewControler. I will tell you my experience.

Like this:

We can switch the login page and homeTabbar container freedom.

if (Boolean conditions) {//show login page
    [self showLoginAndRegisterVC];
} else { //show home Page
    [self showHomeViewController];
}
[self.window makeKeyAndVisible];


问:
How to add images on second row after button click if first row is filled
I want to add images on button click in a row wise manner and if first row is filled then it should starts with next row .

I have defined scroll view horizontally with linear layout and it is adding horizontally but I want that the image should be added in next row if first row is already full, then it should starts with second row if second row has full then it should starts with third row and so on .

How can i do this ?

```<code>package neeraj.com.images;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    LinearLayout linearLayout1;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);

    }

    public void onClick(View v){

        ImageView image = new ImageView(MainActivity.this);
            image.setBackgroundResource(R.mipmap.ic_launcher);
        linearLayout1.addView(image);

    }

}
</code>```

xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Button" />

    <HorizontalScrollView
        android:id="@+id/hsv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:fillViewport="true"
        android:measureAllChildren="false"
        android:scrollbars="none" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </HorizontalScrollView>

</LinearLayout>
</code>```

答: I think you Should go with the Grid View, and Keep on adding the path to the GridView Adapted on the Button Click. Once you add the Path to the Adapter, use notifySetDataChange() to reflect the change.</p>

Body:
I want to add images on button click in a row wise manner and if first row is filled then it should starts with next row .

I have defined scroll view horizontally with linear layout and it is adding horizontally but I want that the image should be added in next row if first row is already full, then it should starts with second row if second row has full then it should starts with third row and so on .

How can i do this ?

package neeraj.com.images;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    LinearLayout linearLayout1;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);

    }

    public void onClick(View v){

        ImageView image = new ImageView(MainActivity.this);
            image.setBackgroundResource(R.mipmap.ic_launcher);
        linearLayout1.addView(image);

    }

}

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Button" />

    <HorizontalScrollView
        android:id="@+id/hsv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:fillViewport="true"
        android:measureAllChildren="false"
        android:scrollbars="none" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </HorizontalScrollView>

</LinearLayout>


问:
Convert a Base64 LDIF file to plaintext (for import)
I have a LDIF file which has a multi-value Base64-encoded attribute, and I'd like to convert it in non-Base64-encoded syntax.  How can this be done?

Context

The LDIF file is as such:

```<code>dn: cn=johndoe,ou=clients,ou=management,dc=example,dc=com
changetype: modify
replace: foobarStatus
foobarStatus:: ZW5hYmxl... (Base64 string) ...ZCA9IHRydWU
</code>```

where the decoded Base64 string is as such:

```<code>market = "US"
mgmt.account.mode = "X12"
foo.field = "Something"
bar.field = "Something else"
...
</code>```

Problem

When I try to import this LDIF file into a LDAP server via ldapmodify, I get an error:

```<code>ldapmodify: invalid format (line 4) entry: "cn=johndoe,ou=clients,ou=management,dc=example,dc=com"
</code>```

I've been trying to solve this for a while but couldn't find the error. It could be some spurious character somewhere. Therefore I thought of converting the Base64 part of the LDIF and importing it on this format.  The attribute values  don't contain any non-printable ASCII (e.g. accented letters) so it should work fine.

Note

This could be a XY problem so if anyone has another suggestion, I'm eager to read it.

答:
It turns out ldapmodify doesn't like long lines.  Therefore, after splitting the Base64 code here

```<code>foobarStatus:: ZW5hYmxl... (Base64 string) ...ZCA9IHRydWU
</code>```

into multiple lines of 79 chars or less, ldapmodify was able to import it.

This solved my original problem.  I'm leaving the solution here for future readers.

Body:
I have a LDIF file which has a multi-value Base64-encoded attribute, and I'd like to convert it in non-Base64-encoded syntax.  How can this be done?

Context

The LDIF file is as such:

dn: cn=johndoe,ou=clients,ou=management,dc=example,dc=com
changetype: modify
replace: foobarStatus
foobarStatus:: ZW5hYmxl... (Base64 string) ...ZCA9IHRydWU

where the decoded Base64 string is as such:

market = "US"
mgmt.account.mode = "X12"
foo.field = "Something"
bar.field = "Something else"
...

Problem

When I try to import this LDIF file into a LDAP server via ldapmodify, I get an error:

ldapmodify: invalid format (line 4) entry: "cn=johndoe,ou=clients,ou=management,dc=example,dc=com"

I've been trying to solve this for a while but couldn't find the error. It could be some spurious character somewhere. Therefore I thought of converting the Base64 part of the LDIF and importing it on this format.  The attribute values  don't contain any non-printable ASCII (e.g. accented letters) so it should work fine.

Note

This could be a XY problem so if anyone has another suggestion, I'm eager to read it.

Body:
It turns out ldapmodify doesn't like long lines.  Therefore, after splitting the Base64 code here

foobarStatus:: ZW5hYmxl... (Base64 string) ...ZCA9IHRydWU

into multiple lines of 79 chars or less, ldapmodify was able to import it.

This solved my original problem.  I'm leaving the solution here for future readers.


问:
Html Hyphen (-) New Line Copy Paste Error
I am developping a MVC project and facing a weird problem.

In my view;

If I define a div like this

```<code>  <div class="col-lg-1" style="padding-top: 10px">05931-1</div>
</code>```

Hyphen is displayed in a new line. (second textbox)

When I Copy-paste this text into the text box and submit the form,
everything is fine. I make a web service call and I get the proper results.

When I define the div like this, hyphen is not shown in new line.

```<code><div class="col-lg-1" style="padding-top: 10px">05931‑1</div>
</code>```

When I copy paste this result and debug the code I can also see the same values for the input however, web service returns empty results as if there is a problem.

Any idea about this behavior?

答:
In short

a hypen like in your text equates to - not #8209; they arent comparible texts .. 8209 specifically is NON line breaking, eg, do not wrap the line here

You are getting expected results.

Body:
I am developping a MVC project and facing a weird problem.

In my view;

If I define a div like this

05931-1

Hyphen is displayed in a new line. (second textbox)

When I Copy-paste this text into the text box and submit the form,
everything is fine. I make a web service call and I get the proper results.

When I define the div like this, hyphen is not shown in new line.

05931‑1

When I copy paste this result and debug the code I can also see the same values for the input however, web service returns empty results as if there is a problem.

Any idea about this behavior?


问:
Can I use SQL LocalDB when creating an exe with Visual Basic 2015
I am busy with creating a program for which I want to be able to have a database on the NAS and maybe that from 2 or 3 PC I can get access to. But it should be possible that simultaneously 2-3 PC (not more) will have access to this database.

In Visual Basic 2015 I now am using the SQL LocalDB (from SQL Server 2016). Now I have some questions, because I am not that into SQL Server and how the connection is working.

Can LocalDB make simultaneously connection with 2-3 pc's?

What do I need to do, so I can get a connection that I need. Will the connection string which I now am using in Visual Basic with the LOcalDB automaticly be replaced or do I need to write some extra code for this? Something that I need to write a code to sellect the connection string?

Because in principle I don't realy want to work with an Server, but only want to use for home use with DB on a NAS, is there also some alternative for this?

If anybody can help, then please. For I don't want to spend lot of time, working on the project to find in the end out, that this way is not working.

Regards,
Hans

答:
LocalDB only allows connections from a single PC.

You can use the free SQL Server Express, it must be installed on one of the 2-3 machines sharing data.


问:
Run ruby script and assign to var Groovy/Jenkins
Probably something simple but don't seem to be getting the output i want, but say i have a ruby script

```<code>class SlackNames

def developers
  { "Richard Lewis" => "/@richlewis",
    "Name 2" => "/@name2",
    "Name 3" => "/@name3"
  }
end

def slack_handle
 puts developers["#{ARGV[0]}"] if developers.key?("#{ARGV[0]}")
end

end

SlackNames.new.slack_handle
</code>```

I would run this on the command line

```<code>ruby slack_names.rb "Richard Lewis"
</code>```

Which as you can see will just return a keys given value, when i run this in a Groovy script how can i save that value to a variable?

```<code>-- Groovy
-- DEV_NAME here equals "Richard Lewis"

SLACK_NAME = sh """#!/bin/bash -l
                   ruby ruby_scripts/slack_names.rb \"${DEV_NAME}\"
                """
echo "${SLACK_NAME}"
</code>```

When i echo out SLACK_NAME it comes back as blank

What am i doing wrong here ?

Thanks

答:
Well first of all, you are calling the method from still within the class. (May just be a typo in the post)

Second, why ".key?("#{ARGV[0]}")" thingy? In ruby, if the hash doesn't have a value for a given key, it will just return nil and nil has the boolean value of false.

```<code>class SlackNames

    def developers
      { "Richard Lewis" => "/@richlewis",
        "Name 2" => "/@name2",
        "Name 3" => "/@name3"
      }
    end

    def slack_handle
     developers["#{ARGV[0]}"] if developers["#{ARGV[0]}"]
    end

end

puts SlackNames.new.slack_handle
</code>```

This works correctly for me at least.

```<code>ruby slack_names.rb "Richard Lewis"
=> /@richlewis
</code>```

I hope it helps and that I understood your problem correctly.

Body:
Probably something simple but don't seem to be getting the output i want, but say i have a ruby script

class SlackNames

def developers
  { "Richard Lewis" => "/@richlewis",
    "Name 2" => "/@name2",
    "Name 3" => "/@name3"
  }
end

def slack_handle
 puts developers["#{ARGV[0]}"] if developers.key?("#{ARGV[0]}")
end

end

SlackNames.new.slack_handle

I would run this on the command line

ruby slack_names.rb "Richard Lewis"

Which as you can see will just return a keys given value, when i run this in a Groovy script how can i save that value to a variable?

-- Groovy
-- DEV_NAME here equals "Richard Lewis"

SLACK_NAME = sh """#!/bin/bash -l
                   ruby ruby_scripts/slack_names.rb \"${DEV_NAME}\"
                """
echo "${SLACK_NAME}"

When i echo out SLACK_NAME it comes back as blank

What am i doing wrong here ?

Thanks

Body:
Well first of all, you are calling the method from still within the class. (May just be a typo in the post)

Second, why ".key?("#{ARGV[0]}")" thingy? In ruby, if the hash doesn't have a value for a given key, it will just return nil and nil has the boolean value of false.

class SlackNames

    def developers
      { "Richard Lewis" => "/@richlewis",
        "Name 2" => "/@name2",
        "Name 3" => "/@name3"
      }
    end

    def slack_handle
     developers["#{ARGV[0]}"] if developers["#{ARGV[0]}"]
    end

end

puts SlackNames.new.slack_handle

This works correctly for me at least.

ruby slack_names.rb "Richard Lewis"
=> /@richlewis

I hope it helps and that I understood your problem correctly.


问:
Python - Transform List to List of Lists with each entry containing unique combinations
I have a list of lists as follows:

```<code>mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]
</code>```

What I would like to do is iterate through mylist and produce a new list like this:

```<code>result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]
</code>```

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

答:
Code:

```<code>mylist=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
#- Get Length of mylist which is used in 2nd for loop to iterate items from next item to last item
len_mylist = len(mylist)
#- Final Result Will store in following variable.
output = []
#- this is Index of item which already present in Output List.
remove_index = []

# Iterate every item from mylist with his Index.
for i, item in enumerate(mylist):

    tmp = []
    #- Check item is already present in Remove List of not.
    if i in remove_index:
        continue

    #- Add index to Remove list and add item to tmp which is item in otput list.
    remove_index.append(i)
    tmp.append(item)
    #- Iterate from Next item to last item of mylist.
    for j in range(i+1, len_mylist):
        itemj = mylist[j]
        #- Set insert flag to True on which we are decide to insert item or not.
        inser_flag = True
        # Iterate on inner item
        for tmp_item in tmp:
            #- Check next item letters already present or not.
            if tmp_item[0] in itemj or tmp_item[1] in itemj:
                inser_flag = False
                break
            #- Check item is already present in Remove List of not.
            if j in remove_index:
                inser_flag = False
                break

        #- Add item to inner item if Flag is True.
        if inser_flag:
            remove_index.append(j)
            tmp.append(itemj)
            break
    # append to Final Output
    output.append(tmp)
</code>```

Output:

```<code>>>> output
[[['a', 'b'], ['c', 'd']], [['a', 'c'], ['d', 'e']], [['b', 'c']], [['e', 'c']]]
</code>```

Body:
I have a list of lists as follows:

mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]

What I would like to do is iterate through mylist and produce a new list like this:

result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

Body:
Code:

mylist=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
#- Get Length of mylist which is used in 2nd for loop to iterate items from next item to last item
len_mylist = len(mylist)
#- Final Result Will store in following variable.
output = []
#- this is Index of item which already present in Output List.
remove_index = []

# Iterate every item from mylist with his Index.
for i, item in enumerate(mylist):

    tmp = []
    #- Check item is already present in Remove List of not.
    if i in remove_index:
        continue

    #- Add index to Remove list and add item to tmp which is item in otput list.
    remove_index.append(i)
    tmp.append(item)
    #- Iterate from Next item to last item of mylist.
    for j in range(i+1, len_mylist):
        itemj = mylist[j]
        #- Set insert flag to True on which we are decide to insert item or not.
        inser_flag = True
        # Iterate on inner item
        for tmp_item in tmp:
            #- Check next item letters already present or not.
            if tmp_item[0] in itemj or tmp_item[1] in itemj:
                inser_flag = False
                break
            #- Check item is already present in Remove List of not.
            if j in remove_index:
                inser_flag = False
                break

        #- Add item to inner item if Flag is True.
        if inser_flag:
            remove_index.append(j)
            tmp.append(itemj)
            break
    # append to Final Output
    output.append(tmp)

Output:

>>> output
[[['a', 'b'], ['c', 'd']], [['a', 'c'], ['d', 'e']], [['b', 'c']], [['e', 'c']]]


问:
How to override insall directory with setup.py install
I am using python 2.7 on Mac OSX.

I am trying to install a package using the setup.py file which looks like:

```<code>from distutils.core import setup
setup(packages=['object_recognition_by_parts'], package_dir={'': 'python'})
</code>```

it fails an throws the following error:

```<code>running install
running build
running build_py
running install_lib
creating /usr/lib/python2.7/site-packages
error: could not create '/usr/lib/python2.7/site-packages': Permission denied
</code>```

But my site packages directory is /usr/local/lib/python2.7/site-packages and not /usr/lib/python2.7/site-packages. Can I override this?

If I install using pip, the packages are installed in /usr/local/lib/python2.7/site-packages

答:
You can also use </p>

```<code>python setup.py install --prefix=/usr/local
</code>```

<p>and it will put it in  </p>

```<code>/usr/local/lib/python2.7/site-packages
</code>```

Body:
I am using python 2.7 on Mac OSX.

I am trying to install a package using the setup.py file which looks like:

from distutils.core import setup
setup(packages=['object_recognition_by_parts'], package_dir={'': 'python'})

it fails an throws the following error:

running install
running build
running build_py
running install_lib
creating /usr/lib/python2.7/site-packages
error: could not create '/usr/lib/python2.7/site-packages': Permission denied

But my site packages directory is /usr/local/lib/python2.7/site-packages and not /usr/lib/python2.7/site-packages. Can I override this?

If I install using pip, the packages are installed in /usr/local/lib/python2.7/site-packages

Body:
You can also use

python setup.py install --prefix=/usr/local

and it will put it in

/usr/local/lib/python2.7/site-packages


问:
Creating Query on statement (TSQL)
I've got a log file with different functions and steps:

What I need is the Duration of the whole function.
This is my Statement so far:

```<code>SELECT [Id]
      ,[Func]
      ,[Step]
      ,[Timestamp]
      ,CAST((SELECT [Timestamp]
             FROM [LiPimDb].[dbo].[Log_Export_Catalog]
             WHERE [Id] = [Log].[Id]+1)-[Timestamp]AS TIME(3)) AS Duration

FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]

WHERE Func = 'SP_Create_Export_Catalog'
</code>```

Do I Need to get a subquery and then get the sum of Duration?

答:
From your table I'd say you need just the difference between end and start.

As this seems to be a stored procedure, the easiest might be something like this:

```<code>DECLARE @startTime DATETIME=GETDATE();
...Your code here ...
DECLARE @duration TIME=CAST(GETDATE()-@startTime AS TIME);
SELECT @duration;
</code>```

This last value might be inserted into your log table for easy retrieval...

Title: Creating Query on statement (TSQL)

Body:
I've got a log file with different functions and steps:

What I need is the Duration of the whole function.
This is my Statement so far:

SELECT [Id]
      ,[Func]
      ,[Step]
      ,[Timestamp]
      ,CAST((SELECT [Timestamp]
             FROM [LiPimDb].[dbo].[Log_Export_Catalog]
             WHERE [Id] = [Log].[Id]+1)-[Timestamp]AS TIME(3)) AS Duration

FROM [LiPimDb].[dbo].[Log_Export_Catalog] AS [Log]

WHERE Func = 'SP_Create_Export_Catalog'

Do I Need to get a subquery and then get the sum of Duration?

Body:
From your table I'd say you need just the difference between end and start.

As this seems to be a stored procedure, the easiest might be something like this:

DECLARE @startTime DATETIME=GETDATE();
...Your code here ...
DECLARE @duration TIME=CAST(GETDATE()-@startTime AS TIME);
SELECT @duration;

This last value might be inserted into your log table for easy retrieval...


问:
Retrieve property value from include'd / import'ed project
I am trying to use ant's include or import tasks to use a common build file. I am stuck at retrieving properties from included file.

These are my non-working samples, trying to retrieve "child-property"

Using ant import

parent file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="parent" basedir=".">
    <import file="child.xml" />
    <target name="parent-target">
        <antcall target="child-target" />
        <echo message="(From Parent) ${child-property}" />
    </target>
</project>
</code>```

child file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="child" basedir=".">
    <target name="child-target">
        <property name="child-property" value="i am child value" />
        <echo message="(From Child) ${child-property}" />
    </target>
</project>
</code>```

output

```<code>parent-target:

child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}
</code>```

Using ant include

parent file

```<code><project name="parent" basedir=".">
    <include file="child.xml" />
    <target name="parent-target">
        <antcall target="child.child-target" />
        <echo message="(From Parent) ${child-property}" />
        <echo message="(From Parent2) ${child.child-property}" />
    </target>
</project>
</code>```

child file

same as above

output

```<code>parent-target:

child.child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}
     [echo] (From Parent2) ${child.child-property}
</code>```

How can I access "child-property" from parent?

答:
When you use the antcall task a new Ant cycle is started for the antcall'ed task - but that doesn't affect the context of the caller:

The called target(s) are run in a new
  project; be aware that this means
  properties, references, etc. set by
  called targets will not persist back
  to the calling project.

One way to make your simple example to work would be to change the first parent to:

```<code><target name="parent-target" depends="child-target">
    <echo message="(From Parent) ${child-property}" />
</target>
</code>```

Then the child-target will be executed in the parent context before the parent-target.

But, you may find that there are side affects to running the child task in the context of the parent that you don't want.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use ant's include or import tasks to use a common build file. I am stuck at retrieving properties from included file.

These are my non-working samples, trying to retrieve "child-property"

Using ant import

parent file

<?xml version="1.0" encoding="UTF-8"?>
<project name="parent" basedir=".">
    <import file="child.xml" />
    <target name="parent-target">
        <antcall target="child-target" />
        <echo message="(From Parent) ${child-property}" />
    </target>
</project>

child file

<?xml version="1.0" encoding="UTF-8"?>
<project name="child" basedir=".">
    <target name="child-target">
        <property name="child-property" value="i am child value" />
        <echo message="(From Child) ${child-property}" />
    </target>
</project>

output

parent-target:

child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}

Using ant include

parent file

<project name="parent" basedir=".">
    <include file="child.xml" />
    <target name="parent-target">
        <antcall target="child.child-target" />
        <echo message="(From Parent) ${child-property}" />
        <echo message="(From Parent2) ${child.child-property}" />
    </target>
</project>

child file

same as above

output

parent-target:

child.child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}
     [echo] (From Parent2) ${child.child-property}

How can I access "child-property" from parent?

Body:
When you use the antcall task a new Ant cycle is started for the antcall'ed task - but that doesn't affect the context of the caller:

The called target(s) are run in a new
  project; be aware that this means
  properties, references, etc. set by
  called targets will not persist back
  to the calling project.

One way to make your simple example to work would be to change the first parent to:

<target name="parent-target" depends="child-target">
    <echo message="(From Parent) ${child-property}" />
</target>

Then the child-target will be executed in the parent context before the parent-target.

But, you may find that there are side affects to running the child task in the context of the parent that you don't want.


问:
Postgresql, jsonb query help is needed
I am very, very embarrassed. But I need a help with my query, thanks in advance.

My jsonb (jsonb array) is

```<code> [

   {
      "id_contact":2,
      "contact_data":{
         "NM_EMAIL":[
            "234rtrt@oao.com.ru"
         ],
         "NM_PHONE":[
            "849533574",
            "849533d575"
         ]
      },
      "resp_ls_data":[
         "14",
         "11"
      ],
       "pr_from_head":true
   },
   {
      "id_contact":8,
      "contact_data":{
         "NM_EMAIL":[
            "somfdf11m@a.il"
         ],
         "NM_PHONE":[
            "89234511"
         ]
      },
      "resp_ls_data":[
         null
      ],
       "pr_from_head":false
   }

]
</code>```

I figured out the query as

```<code>select case when pr_from_head then jsonb_build_object('id_head_cont',id_contact)::text
        when not pr_from_head then id_contact::text
        when id_contact is null then NULL end as est_contact_id,
   contact_data,
   nullif(resp_ls_data, '[null]') resp_ls_array
  from jsonb_to_recordset('
  [

   {
      "id_contact":2,
      "contact_data":{
         "NM_EMAIL":[
            "234rtrt@oao.com.ru"
         ],
         "NM_PHONE":[
            "849533574",
            "849533d575"
         ]
      },
      "resp_ls_data":[
         "14",
         "11"
      ],
       "pr_from_head":true
   },
   {
      "id_contact":8,
      "contact_data":{
         "NM_EMAIL":[
            "somfdf11m@a.il"
         ],
         "NM_PHONE":[
            "89234511"
         ]
      },
      "resp_ls_data":[
         null
      ],
       "pr_from_head":false
   }

]
') as ls(id_contact integer, contact_data jsonb, resp_ls_data jsonb,pr_from_head boolean)
</code>```

Got the result as :

```<code>"est_contact_id"       ||   "contact_data"    || resp_ls_array"
"{""id_head_cont"": 2}"||   "{""NM_EMAIL"":.. || "[""14"", ""11""]"
"8"                    ||   "{""NM_EMAIL"":.."|| NULL
</code>```

But the result i want is :

```<code> "est_contact_id"       ||  "contact_data"    || 'resp_ls_array"
  "{""id_head_cont"": 2}"|| "{""NM_EMAIL"":.. || "14"
  "{""id_head_cont"": 2}"|| "{""NM_EMAIL"":.. || "11"
  "8"                    || "{""NM_EMAIL"":.."|| NULL
</code>```

If resp_ls_array is not null I want to separate is to parts.
Any help would be appreciated.

答:
You can transform the result using jsonb_array_elements(), like in this pseudocode:

```<code>select est_contact_id, contact_data, value as resp_ls
from (

    <your query here>

) s
left join jsonb_array_elements(resp_ls_array) on true;
</code>```

Test it here.

Title: Postgresql, jsonb query help is needed

Body:
I am very, very embarrassed. But I need a help with my query, thanks in advance.

My jsonb (jsonb array) is

 [

   {
      "id_contact":2,
      "contact_data":{
         "NM_EMAIL":[
            "234rtrt@oao.com.ru"
         ],
         "NM_PHONE":[
            "849533574",
            "849533d575"
         ]
      },
      "resp_ls_data":[
         "14",
         "11"
      ],
       "pr_from_head":true
   },
   {
      "id_contact":8,
      "contact_data":{
         "NM_EMAIL":[
            "somfdf11m@a.il"
         ],
         "NM_PHONE":[
            "89234511"
         ]
      },
      "resp_ls_data":[
         null
      ],
       "pr_from_head":false
   }

]

I figured out the query as

select case when pr_from_head then jsonb_build_object('id_head_cont',id_contact)::text
        when not pr_from_head then id_contact::text
        when id_contact is null then NULL end as est_contact_id,
   contact_data,
   nullif(resp_ls_data, '[null]') resp_ls_array
  from jsonb_to_recordset('
  [

   {
      "id_contact":2,
      "contact_data":{
         "NM_EMAIL":[
            "234rtrt@oao.com.ru"
         ],
         "NM_PHONE":[
            "849533574",
            "849533d575"
         ]
      },
      "resp_ls_data":[
         "14",
         "11"
      ],
       "pr_from_head":true
   },
   {
      "id_contact":8,
      "contact_data":{
         "NM_EMAIL":[
            "somfdf11m@a.il"
         ],
         "NM_PHONE":[
            "89234511"
         ]
      },
      "resp_ls_data":[
         null
      ],
       "pr_from_head":false
   }

]
') as ls(id_contact integer, contact_data jsonb, resp_ls_data jsonb,pr_from_head boolean)

Got the result as :

"est_contact_id"       ||   "contact_data"    || resp_ls_array"
"{""id_head_cont"": 2}"||   "{""NM_EMAIL"":.. || "[""14"", ""11""]"
"8"                    ||   "{""NM_EMAIL"":.."|| NULL

But the result i want is :

 "est_contact_id"       ||  "contact_data"    || 'resp_ls_array"
  "{""id_head_cont"": 2}"|| "{""NM_EMAIL"":.. || "14"
  "{""id_head_cont"": 2}"|| "{""NM_EMAIL"":.. || "11"
  "8"                    || "{""NM_EMAIL"":.."|| NULL

If resp_ls_array is not null I want to separate is to parts.
Any help would be appreciated.

Body:
You can transform the result using jsonb_array_elements(), like in this pseudocode:

select est_contact_id, contact_data, value as resp_ls
from (

    <your query here>

) s
left join jsonb_array_elements(resp_ls_array) on true;

Test it here.


问:
ios facebook sdk 4.0 login error code 304
I've just updated facebook sdk v4.0

and according the tutorial of Using Custom Login UIs

```<code>-(IBAction)facebookLoginClick:(id)sender {

FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];

[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error) {
        // Process error
    } else if (result.isCancelled) {
        // Handle cancellations
    } else {
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if ([result.grantedPermissions containsObject:@"email"]) {
            // Do work
        }
    }
}];
}
</code>```

BUT the result is always nil and error code is 304, am I missing something?

答:
Single Sign On

I've also found that this issue happens if you have an app that does not require single sign on (i.e. an app which multiple users will create content and share from one device).

You can change single sign on in your app settings https://developers.facebook.com/apps/your-app-id/settings/.

Body:
I've just updated facebook sdk v4.0

and according the tutorial of Using Custom Login UIs

-(IBAction)facebookLoginClick:(id)sender {

FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];

[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error) {
        // Process error
    } else if (result.isCancelled) {
        // Handle cancellations
    } else {
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if ([result.grantedPermissions containsObject:@"email"]) {
            // Do work
        }
    }
}];
}

BUT the result is always nil and error code is 304, am I missing something?


问:
how to redirect to a page from a method by selecting an option in sidemenu
ionic start mySideMenu sidemenu --v2

using this I created a sidemenu ,I am doing some login-logout stuff,so i stored user details in localstorage variable named "userDetails". when i click on logout option from sidemenu ,it  is  redirected to login page.

import { homePage } from '../pages/home/home';

import { DetailsPage } from '../pages/Details/Details';

import { AddclientPage } from '../pages/Addclient/Addclient';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
 @ViewChild(Nav) nav: Nav;
  rootPage: any =  homePage;

  pages: Array<{title: string, component: any,icon:string}>;

  constructor(platform: Platform,public storage:Storage,public mqttservice:Mqttservice) {

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
     this.pages = [
      { title: 'Home ', component: homePage ,icon:"home"},

      { title:'Addclient',component:AddclientPage,icon:'add'},

      {title: 'Users' ,component:DetailsPage,icon:"people"},
      { title:'addclient',component:AddclientPage,icon:"person-add"},
      {title:'Logout',component:LoginPage,icon:"log-out"}

    ];
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

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

<blockquote>
  <p>but what i want is when user clicks on logout ,remove the localstorage vairable and then redirect to login page
  so i wrote a method that removes "userDetails" and redirect to "loginpage" but am getting error like "can not read property 'setRoot' of undefined"</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { homePage } from '../pages/home/home';

import { DetailsPage } from '../pages/Details/Details';

import { AddclientPage } from '../pages/Addclient/Addclient';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
 @ViewChild(Nav) nav: Nav;
  rootPage: any =  homePage;

  pages: Array<{title: string, component: any,icon:string}>;

  constructor(platform: Platform,public storage:Storage,public mqttservice:Mqttservice) {

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
     this.pages = [
      { title: 'Home ', component: homePage ,icon:"home"},

      { title:'Addclient',component:AddclientPage,icon:'add'},

      {title: 'Users' ,component:DetailsPage,icon:"people"},
      { title:'addclient',component:AddclientPage,icon:"person-add"},
      {title:'Logout',component:this.logout(),icon:"log-out"}

    ];
  }
  logout(){
  this.storage.remove('userDetails);
  this.nav.setRoot(LoginPage);
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

}</code>```

答:
You're calling the logout method when trying to create the pages property. Please modify it like this:

```<code>   this.pages = [
      { title: 'Home ', component: homePage, icon:"home" },
      { title:'Addclient', component:AddclientPage, icon:'add' },
      { title: 'Users', component:DetailsPage, icon:"people" },
      { title:'addclient', component:AddclientPage, icon:"person-add" },
      { title:'Logout', component:null, icon:"log-out" }
    ];
</code>```

Notice that the logout option has null as component instead of the logout method. Now in your openPage method:

```<code>  openPage(page) {

    if(!page.component) {
      // Only the logout has the component as null
      this.logout();
    } else {
      // Reset the content nav to have just this page
      // we wouldn't want the back button to show in this scenario
      this.nav.setRoot(page.component);
    }
  }
</code>```

Body:
ionic start mySideMenu sidemenu --v2

using this I created a sidemenu ,I am doing some login-logout stuff,so i stored user details in localstorage variable named "userDetails". when i click on logout option from sidemenu ,it  is  redirected to login page.

import { homePage } from '../pages/home/home';

import { DetailsPage } from '../pages/Details/Details';

import { AddclientPage } from '../pages/Addclient/Addclient';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
 @ViewChild(Nav) nav: Nav;
  rootPage: any =  homePage;

  pages: Array<{title: string, component: any,icon:string}>;

  constructor(platform: Platform,public storage:Storage,public mqttservice:Mqttservice) {

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
     this.pages = [
      { title: 'Home ', component: homePage ,icon:"home"},

      { title:'Addclient',component:AddclientPage,icon:'add'},

      {title: 'Users' ,component:DetailsPage,icon:"people"},
      { title:'addclient',component:AddclientPage,icon:"person-add"},
      {title:'Logout',component:LoginPage,icon:"log-out"}

    ];
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

}

but what i want is when user clicks on logout ,remove the localstorage vairable and then redirect to login page
  so i wrote a method that removes "userDetails" and redirect to "loginpage" but am getting error like "can not read property 'setRoot' of undefined"

import { homePage } from '../pages/home/home';

import { DetailsPage } from '../pages/Details/Details';

import { AddclientPage } from '../pages/Addclient/Addclient';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
 @ViewChild(Nav) nav: Nav;
  rootPage: any =  homePage;

  pages: Array<{title: string, component: any,icon:string}>;

  constructor(platform: Platform,public storage:Storage,public mqttservice:Mqttservice) {

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
     this.pages = [
      { title: 'Home ', component: homePage ,icon:"home"},

      { title:'Addclient',component:AddclientPage,icon:'add'},

      {title: 'Users' ,component:DetailsPage,icon:"people"},
      { title:'addclient',component:AddclientPage,icon:"person-add"},
      {title:'Logout',component:this.logout(),icon:"log-out"}

    ];
  }
  logout(){
  this.storage.remove('userDetails);
  this.nav.setRoot(LoginPage);
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

}

Body:
You're calling the logout method when trying to create the pages property. Please modify it like this:

   this.pages = [
      { title: 'Home ', component: homePage, icon:"home" },
      { title:'Addclient', component:AddclientPage, icon:'add' },
      { title: 'Users', component:DetailsPage, icon:"people" },
      { title:'addclient', component:AddclientPage, icon:"person-add" },
      { title:'Logout', component:null, icon:"log-out" }
    ];

Notice that the logout option has null as component instead of the logout method. Now in your openPage method:

  openPage(page) {

    if(!page.component) {
      // Only the logout has the component as null
      this.logout();
    } else {
      // Reset the content nav to have just this page
      // we wouldn't want the back button to show in this scenario
      this.nav.setRoot(page.component);
    }
  }


问:
How to add beta tester to developer console,when i will get Opt -In URl
Can anyone guide me the whole steps required for creating beta tester group and how to add them as tester on developer console, how can i get link,
i have gone through some posts as i am doing it for very first time,

it will be helpful if anyone can  tell me steps required to get it done?

答:
To add new Google group for Beta testing

1) go to https://groups.google.com/forum/#!overview

2) Select create group and fill the all the details such as Group name,Group email address etc.

3) If you want to add a new tester to existing group go to -> manage -> memebers -> direct add members

If you  want to send email to group member or individual follow below steps:

4) On left panel you will find recently viewed group OR My groups click them

5) For eg. tester_group click on the group -> on top bar find new topic -> click it

6) you can send email on behalf of group or by your play store email id

7) new window will open write your message select type of post as
    -> start discussion    (Two way process)
    -> make an announcement (one way process)
8) and then select post message will be delivered to all members of group.

To Add testers On Play Store

1) go to beta testing tab before uploading new apk for beta

2) select Testing option as
    -> Beta testing using google groups or google+ communities

3) add google group by typing group name in EditBox then select add button

4) your google group now has been added as tester for the app.

5) now upload the apk and rollout from manage release page

6) in few hours  you will get Opt -In URl which is link for beta testers to install app from playstore

Note:
   if you have added google tester group after publishing the app,then this group will not be saved.

As tester group and you have to add it again and again (wont serve any purpose).

so make sure,you add google group before uploading and publishing new apk.

so that after getting Opt -In URl link your group will be able to install the app from playstore.

Hope this helps you :)


问:
What is the MIME type for TTF files?
I can't find correct MIME type for TrueType fonts. I need it because I'm using File Uploading Class (CodeIgniter) to upload files, and I want to allow only TTF to be uploaded. Tried this:

```<code>'ttf'   =>  'font/ttf'
'ttf'   =>  'font/truetype'
</code>```

With no success.

Any ideas ?

答: As of February 2017, RFC 8081 adds font/* media types, which are also listed in the IANA Media Types list. font/ttf is in this list. Browsers may take some time to catch up.

Title: What is the MIME type for TTF files?

Body:
I can't find correct MIME type for TrueType fonts. I need it because I'm using File Uploading Class (CodeIgniter) to upload files, and I want to allow only TTF to be uploaded. Tried this:

'ttf'   =>  'font/ttf'
'ttf'   =>  'font/truetype'

With no success.

Any ideas ?


问:
Bash integer expression on IF statement when retrieving free memory
I am getting the below error while running the script memory.sh script:

```<code>[root@test tmp]# ./memory.sh
./memory.sh: line 3: [: 2.05028: integer expression expected
 Normal
</code>```

The content of the memory.sh script is:

```<code>[root@test tmp]# cat memory.sh
threshold=80
MEMORY=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if [ ${MEMORY} -gt ${threshold} ]; then
    sudo sync;echo 3 > /proc/sys/vm/drop_caches
else
   echo "Normal"
fi
</code>```

Does anyone know how to prevent this error?

答:
Looks like you need to convert the computation result into integer type to be able to compare it. What about that suggestion:

```<code>#!/bin/bash
threshold=80
MEMORY=$(free | grep Mem | awk '{print int($3/$2 * 100.0)}')
if [ ${MEMORY} -gt ${threshold} ]
then
    sudo sync;echo 3 > /proc/sys/vm/drop_caches
else
    echo "Normal"
fi
</code>```

This does not throw an error for me but outputs a friendly "Normal" ;-)

Body:
I am getting the below error while running the script memory.sh script:

[root@test tmp]# ./memory.sh
./memory.sh: line 3: [: 2.05028: integer expression expected
 Normal

The content of the memory.sh script is:

[root@test tmp]# cat memory.sh
threshold=80
MEMORY=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if [ ${MEMORY} -gt ${threshold} ]; then
    sudo sync;echo 3 > /proc/sys/vm/drop_caches
else
   echo "Normal"
fi

Does anyone know how to prevent this error?

Body:
Looks like you need to convert the computation result into integer type to be able to compare it. What about that suggestion:

#!/bin/bash
threshold=80
MEMORY=$(free | grep Mem | awk '{print int($3/$2 * 100.0)}')
if [ ${MEMORY} -gt ${threshold} ]
then
    sudo sync;echo 3 > /proc/sys/vm/drop_caches
else
    echo "Normal"
fi

This does not throw an error for me but outputs a friendly "Normal" ;-)


问:
transparent png not showing video in background
I made a transparent png with a theatre setup thing and i'm putting a 1 second video to play like a gif in the background but instead of seeing the video i see a body background color background, also letting z index be smaller than the other one, but deleting it on inspect element will show the video.

This is not the original one just that to show the problem

 <video style='width:100%;height:100%;' alt='[]' autoplay loop>
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4" />
  Unfortunately, this site cannot run on your computer. Please upgrade your browser/buy a new computer.
</video>

```

答: You can also edit the video if you want to, if you have a video editing software you can place the PNG file ontop of your video, its less programming so its easier for your host to run your site. </p>


问:
Array of type int doesn't get modified from the function call
For some reason that I'm not aware of, array from main() doesn't get to be modified when it should. Isn't  "a" passed by reference? Can someone please guide me a little bit?

Here is the code:

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

void sort(int list[])
{
    //int list[] = { 4, 3, 2, 1, 10 };
    int n = sizeof(list) / sizeof(int);
    int min = 0;
    int temp = 0;
    for (int i = 0; i < n; i++)
    {
        min = i;
        //profiler.countOperation("compSort", n, 1);
        for (int j = i + 1; j < n; j++)
        {
            if (list[j] < list[min])
            {
                min = j;
                //profiler.countOperation("compSort", n, 1);
                    }
        }
        if (min != i)
        {
            //profiler.countOperation("compSort", n, 1);
            temp = list[min];
            list[min] = list[i];
            list[i] = temp;
        }
    }
}

int main()
{
    int a[5] = {4, 3, 2, 1, 10};
    sort(a);
    printf("%d\n", a[0]);
    for (int i = 0; i < 5; i++)
    {
        printf("%d", a[i]);
    }
    return 0;
    /*int arr[MAX_SIZE];
    for(int t = 0; t < 1; t++)
    {
        for (int n = 100; n < 3000; n = n + 300)
        {
            FillRandomArray(arr, n);
            sort();
            printf("done %d \n", n);

            if (!IsSorted(arr, n)
            {
                printf("error sort \n");
            }
        }
    }
    profiler.addSeries("TotalSort", "cmpSel", "atribSel");
    profiler.createGroup("SortMediu", "TotalSort", "cmpSel", "atribSel");
    profiler.showReport();*/
}
</code>```

答:
The problem is with

```<code> int n = sizeof(list) / sizeof(int);
</code>```

arrays, once passed as function arguments decays to the pointer to the first element. They don't have array properties anymore. So, the list here is adjusted as a pointer to int.

Quoting C11, chapter §6.7.6.3

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to
  type’’, where the type qualifiers (if any) are those specified within the [ and ] of the
  array type derivation.

Solution: You need to calculate the size at the caller (before the array decay happens) and pass that as a different argument to the called function.

Body:
For some reason that I'm not aware of, array from main() doesn't get to be modified when it should. Isn't  "a" passed by reference? Can someone please guide me a little bit?

Here is the code:

#include "stdio.h"

void sort(int list[])
{
    //int list[] = { 4, 3, 2, 1, 10 };
    int n = sizeof(list) / sizeof(int);
    int min = 0;
    int temp = 0;
    for (int i = 0; i < n; i++)
    {
        min = i;
        //profiler.countOperation("compSort", n, 1);
        for (int j = i + 1; j < n; j++)
        {
            if (list[j] < list[min])
            {
                min = j;
                //profiler.countOperation("compSort", n, 1);
                    }
        }
        if (min != i)
        {
            //profiler.countOperation("compSort", n, 1);
            temp = list[min];
            list[min] = list[i];
            list[i] = temp;
        }
    }
}

int main()
{
    int a[5] = {4, 3, 2, 1, 10};
    sort(a);
    printf("%d\n", a[0]);
    for (int i = 0; i < 5; i++)
    {
        printf("%d", a[i]);
    }
    return 0;
    /*int arr[MAX_SIZE];
    for(int t = 0; t < 1; t++)
    {
        for (int n = 100; n < 3000; n = n + 300)
        {
            FillRandomArray(arr, n);
            sort();
            printf("done %d \n", n);

            if (!IsSorted(arr, n)
            {
                printf("error sort \n");
            }
        }
    }
    profiler.addSeries("TotalSort", "cmpSel", "atribSel");
    profiler.createGroup("SortMediu", "TotalSort", "cmpSel", "atribSel");
    profiler.showReport();*/
}

Body:
The problem is with

 int n = sizeof(list) / sizeof(int);

arrays, once passed as function arguments decays to the pointer to the first element. They don't have array properties anymore. So, the list here is adjusted as a pointer to int.

Quoting C11, chapter §6.7.6.3

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to
  type’’, where the type qualifiers (if any) are those specified within the [ and ] of the
  array type derivation.

Solution: You need to calculate the size at the caller (before the array decay happens) and pass that as a different argument to the called function.


问:
How to add +1 value on the entire column of my database table?
Just new in programming I created a database using XAMPP with 3 columns (f_name, l_name, age).

I created a index.php page where I have only 1 button present, what I am expecting to happen is that if I click that button the entire column age will commit +1 to all current values inside the age. Is it possible?

But unfortunately I don't know how to create the code. I would like to see a simple example of code that will add +1 to the entire column of age. At lease a base logic that will help me figure it out how to do it.

答:
If you want to increment the ages of everyone in the table:

```<code>mysqli_query($connection, "UPDATE `table` SET `age` = `age` + 1");
</code>```

If you want to update a specific person:

```<code>mysqli_query($connection, "UPDATE `table` SET `age` = `age` + 1 WHERE f_name='firstname' AND l_name='lastname'");
</code>```

(replace 'firstname' & 'lastname' of the person you want to update)

You should add a primary key field (an auto incrementing integer) to your table, it makes updating individual rows much simpler (and much quicker for the database engine to perform):

```<code>mysqli_query($connection, "UPDATE `table` SET `age` = `age` + 1 WHERE id=1");
</code>```

Body:
If you want to increment the ages of everyone in the table:

mysqli_query($connection, "UPDATE `table` SET `age` = `age` + 1");

If you want to update a specific person:

mysqli_query($connection, "UPDATE `table` SET `age` = `age` + 1 WHERE f_name='firstname' AND l_name='lastname'");

(replace 'firstname' & 'lastname' of the person you want to update)

You should add a primary key field (an auto incrementing integer) to your table, it makes updating individual rows much simpler (and much quicker for the database engine to perform):

mysqli_query($connection, "UPDATE `table` SET `age` = `age` + 1 WHERE id=1");


问:
Shell access to Persistent Volume in Google Cloud
I would like to get shell access to the Persistent Volume I created on the Google Cloud Platform.

I tried using Google Cloud Shell for this. But to be able to do that I need to attach the Persistent Volume through the gcloud commands, and the command requires the instance name. But I don't see the instance name of the Google Cloud Shell when I list the instance names (in gcloud).

Is it possible to get shell access over Google Cloud Shell to the persistent disks? If not how can I get access to the Persistent Volume that I created?

答:
You don't see the Cloud Shell's instance name in your list of VMs because it isn't owned by your project (and thus, to answer your question, you won't have permission to attach your persistent disks to it). You can verify this by querying the "/zone" endpoint of the Cloud Shell's metadata server, via curl "http://metadata.google.internal/computeMetadata/v1/instance/zone" as described in the GCE docs.

As Ryank mentioned, you'd need to attach the disk to an instance owned by your project, then SSH into it.


问:
Using object as property of another object
I want to use an object template as a property of another object. My template object is like below

```<code>var tableDataRow ={
    numberOfFiles:parseFloat(0),
    insurerIncurred :parseFloat(0),
    insuredIncurred :parseFloat(0),
    totalIncurred :parseFloat(0)
};
</code>```

I'm using this object like this

```<code>var tableData ={
    firm1 :tableDataRow,
    firm2:tableDataRow,
    firm3:tableDataRow,
    firm4:tableDataRow
};
</code>```

But when I want to change a property value in tableDataRow object, all values in tableData are changing.

```<code>tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;
</code>```

I thought that I can use like object oriented languages but I supposed that this way I have only put a reference of tableDataRow in another object. How can I do this ?

https://jsfiddle.net/0ta0wkho/

答:
You should clone the object first because  javascript passes object be reference. Try this code: </p>

```<code>function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
    if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var tableDataRow ={
numberOfFiles:parseFloat(0),
insurerIncurred :parseFloat(0),
insuredIncurred :parseFloat(0),
totalIncurred :parseFloat(0)
};

var tableData ={
firm1 :clone(tableDataRow),
firm2:clone(tableDataRow),
firm3:clone(tableDataRow),
firm4:clone(tableDataRow)
};

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

console.log(tableData);
</code>```

Body:
I want to use an object template as a property of another object. My template object is like below

var tableDataRow ={
    numberOfFiles:parseFloat(0),
    insurerIncurred :parseFloat(0),
    insuredIncurred :parseFloat(0),
    totalIncurred :parseFloat(0)
};

I'm using this object like this

var tableData ={
    firm1 :tableDataRow,
    firm2:tableDataRow,
    firm3:tableDataRow,
    firm4:tableDataRow
};

But when I want to change a property value in tableDataRow object, all values in tableData are changing.

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

I thought that I can use like object oriented languages but I supposed that this way I have only put a reference of tableDataRow in another object. How can I do this ?

https://jsfiddle.net/0ta0wkho/

Body:
You should clone the object first because  javascript passes object be reference. Try this code:

function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
    if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var tableDataRow ={
numberOfFiles:parseFloat(0),
insurerIncurred :parseFloat(0),
insuredIncurred :parseFloat(0),
totalIncurred :parseFloat(0)
};

var tableData ={
firm1 :clone(tableDataRow),
firm2:clone(tableDataRow),
firm3:clone(tableDataRow),
firm4:clone(tableDataRow)
};

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

console.log(tableData);


问:
Multiple queries on one transaction. C# winforms with SQLite
I'm learning how to use SQLite, and I'm stuck on this problem for more than a week and I didn't find an answer on my web search.

The problem is that I need to register a bill with it's corresponding lines, and update some information of the bought products, all in the same transaction if some query fails.

When I try to register something, I obtain the "Database is locked" exception, but what I found strange is that I kept the program running while I was creating this question and when I saw it again I found that the "continue" button was available, and then the program finally worked.

So I would like to know what I must improve to not have that exception.

Ah, it's a Winforms application, and only one person will use it, so it will not have concurrency problems (or I think so).

First, this is the connectionString (if I need to add something to it):
"Data Source=D:\De disco c\Documents\Visual Studio 2010\Projects\Racion\Racion\bin\Racion.db;Version=3;"

On the Mapper of the bill's class I have this method:

```<code>public static void registrarFactura(Factura f)
{

    SQLiteConnection conn = null;
    SQLiteTransaction trn = null;

    try
    {

        var parametros = new List<SQLiteParameter>();
        var cant = new SQLiteParameter();
        cant.ParameterName = "@Cliente";
        cant.Value = f.cliente;
        parametros.Add(cant);

        cant = new SQLiteParameter();
        cant.ParameterName = "@Fecha";
        cant.Value = DateTime.Now;

        parametros.Add(cant);
        //Here is one query. I need to know the bill's ID to register the lines and make the update.
        String consulta = "Insert into Factura(Cliente, Fecha)  VALUES (@Cliente, @Fecha); SELECT last_insert_rowid();";

        //Open the connection
        conn = ObtenerConection();

        //begin transaction
        using (trn = conn.BeginTransaction())
        {
            //Here I register the bill and obtain it's id
            int codigo = Convert.ToInt32(Mapper.ejecutaScalar(consulta, CommandType.Text, parametros, conn, trn));

            //Now I must register the lines of the bill

             String consulta2 = "";

            foreach (Linea l in f.lineas)
            {
                parametros = new List<SQLiteParameter>();
                cant = new SQLiteParameter();
                cant.ParameterName = "@NLinea";
                cant.Value = l.numeroLinea;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@Cantidad";
                cant.Value = l.cantidad;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@CodigoProd";
                cant.Value = l.producto.Codigo;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@PTotal";
                cant.Value = l.PrecioTotal;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@Codigo";
                cant.Value = codigo;
                parametros.Add(cant);

                //The query to insert the actual line of the foreach
                consulta = "Insert into Linea(IdFactura, IdLinea, IdProducto, Cantidad, Total) VALUES (" + codigo + ", @NLinea, @CodigoProd, @Cantidad, @PTotal)";

                Mapper.EjecutaNonQuery(consulta, CommandType.Text, parametros, conn, null);

                //Update the stock of the product
                if (f.cliente == "")
                {
                    consulta2 = "Update Producto Set Cantidad=Cantidad+@Cantidad Where IdProducto=@CodigoProd;";
                }
                else
                {
                    consulta2 = "Update Producto Set Cantidad=Cantidad-@Cantidad Where IdProducto=@CodigoProd;";
                }

                Mapper.EjecutaNonQuery(consulta2, CommandType.Text, parametros, conn, null);

            }

            //The transaction concludes
            trn.Commit();
        }
    }
    catch (SqlException ex)
    {
        //If there is a problem
        trn.Rollback();
    }
    finally
    {
        //Close the connection
        CerrarConexion(conn);
    }

}
</code>```

And on the mapper class, I have these 2 methods that are used  in the previous one:

```<code>public static object ejecutaScalar(string sentencia, CommandType tipoComando, List<SQLiteParameter> parametros, SQLiteConnection con, SQLiteTransaction trn)
{
    object retorno;
    using (SQLiteCommand cmd = new SQLiteCommand())
    {
        cmd.Connection = con;
        cmd.CommandText = sentencia;
        cmd.CommandType = tipoComando;
        cmd.Parameters.AddRange(parametros.ToArray());
        if (trn != null)
            cmd.Transaction = trn;
        retorno = cmd.ExecuteScalar();

    }

    return retorno;
}

public static int EjecutaNonQuery(string sentencia, CommandType tipoComando, List<SQLiteParameter> parametros, SQLiteConnection con, SQLiteTransaction trn)
{
    int afectadas = -1;

    using (SQLiteCommand cmd = new SQLiteCommand())
    {
        cmd.Connection = con;
        cmd.CommandText = sentencia;
        cmd.CommandType = tipoComando;
        cmd.Parameters.AddRange(parametros.ToArray());
        if (trn != null)
            cmd.Transaction = trn;
        afectadas = cmd.ExecuteNonQuery();
    }
    return afectadas;
}
</code>```

Thanks, and sorry if I couldn't explain me better, English is not my native language and I have some difficulties with it :P

答:
The error message "database is locked" means that there is some other connection that has an active transaction.

To ensure that transactions do not stay active, check that all SQL command and transaction objects are used only with using blocks, or otherwise cleaned up. Furthermore, the entire program should use only a single connection object (unless it has multiple threads); you should not re-open it every time (which just makes everything slower because the page cache gets lost).

Body:
I'm learning how to use SQLite, and I'm stuck on this problem for more than a week and I didn't find an answer on my web search.

The problem is that I need to register a bill with it's corresponding lines, and update some information of the bought products, all in the same transaction if some query fails.

When I try to register something, I obtain the "Database is locked" exception, but what I found strange is that I kept the program running while I was creating this question and when I saw it again I found that the "continue" button was available, and then the program finally worked.

So I would like to know what I must improve to not have that exception.

Ah, it's a Winforms application, and only one person will use it, so it will not have concurrency problems (or I think so).

First, this is the connectionString (if I need to add something to it):
"Data Source=D:\De disco c\Documents\Visual Studio 2010\Projects\Racion\Racion\bin\Racion.db;Version=3;"

On the Mapper of the bill's class I have this method:

public static void registrarFactura(Factura f)
{

    SQLiteConnection conn = null;
    SQLiteTransaction trn = null;

    try
    {

        var parametros = new List<SQLiteParameter>();
        var cant = new SQLiteParameter();
        cant.ParameterName = "@Cliente";
        cant.Value = f.cliente;
        parametros.Add(cant);

        cant = new SQLiteParameter();
        cant.ParameterName = "@Fecha";
        cant.Value = DateTime.Now;

        parametros.Add(cant);
        //Here is one query. I need to know the bill's ID to register the lines and make the update.
        String consulta = "Insert into Factura(Cliente, Fecha)  VALUES (@Cliente, @Fecha); SELECT last_insert_rowid();";

        //Open the connection
        conn = ObtenerConection();

        //begin transaction
        using (trn = conn.BeginTransaction())
        {
            //Here I register the bill and obtain it's id
            int codigo = Convert.ToInt32(Mapper.ejecutaScalar(consulta, CommandType.Text, parametros, conn, trn));

            //Now I must register the lines of the bill

             String consulta2 = "";

            foreach (Linea l in f.lineas)
            {
                parametros = new List<SQLiteParameter>();
                cant = new SQLiteParameter();
                cant.ParameterName = "@NLinea";
                cant.Value = l.numeroLinea;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@Cantidad";
                cant.Value = l.cantidad;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@CodigoProd";
                cant.Value = l.producto.Codigo;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@PTotal";
                cant.Value = l.PrecioTotal;
                parametros.Add(cant);

                cant = new SQLiteParameter();
                cant.ParameterName = "@Codigo";
                cant.Value = codigo;
                parametros.Add(cant);

                //The query to insert the actual line of the foreach
                consulta = "Insert into Linea(IdFactura, IdLinea, IdProducto, Cantidad, Total) VALUES (" + codigo + ", @NLinea, @CodigoProd, @Cantidad, @PTotal)";

                Mapper.EjecutaNonQuery(consulta, CommandType.Text, parametros, conn, null);

                //Update the stock of the product
                if (f.cliente == "")
                {
                    consulta2 = "Update Producto Set Cantidad=Cantidad+@Cantidad Where IdProducto=@CodigoProd;";
                }
                else
                {
                    consulta2 = "Update Producto Set Cantidad=Cantidad-@Cantidad Where IdProducto=@CodigoProd;";
                }

                Mapper.EjecutaNonQuery(consulta2, CommandType.Text, parametros, conn, null);

            }

            //The transaction concludes
            trn.Commit();
        }
    }
    catch (SqlException ex)
    {
        //If there is a problem
        trn.Rollback();
    }
    finally
    {
        //Close the connection
        CerrarConexion(conn);
    }

}

And on the mapper class, I have these 2 methods that are used  in the previous one:

public static object ejecutaScalar(string sentencia, CommandType tipoComando, List<SQLiteParameter> parametros, SQLiteConnection con, SQLiteTransaction trn)
{
    object retorno;
    using (SQLiteCommand cmd = new SQLiteCommand())
    {
        cmd.Connection = con;
        cmd.CommandText = sentencia;
        cmd.CommandType = tipoComando;
        cmd.Parameters.AddRange(parametros.ToArray());
        if (trn != null)
            cmd.Transaction = trn;
        retorno = cmd.ExecuteScalar();

    }

    return retorno;
}

public static int EjecutaNonQuery(string sentencia, CommandType tipoComando, List<SQLiteParameter> parametros, SQLiteConnection con, SQLiteTransaction trn)
{
    int afectadas = -1;

    using (SQLiteCommand cmd = new SQLiteCommand())
    {
        cmd.Connection = con;
        cmd.CommandText = sentencia;
        cmd.CommandType = tipoComando;
        cmd.Parameters.AddRange(parametros.ToArray());
        if (trn != null)
            cmd.Transaction = trn;
        afectadas = cmd.ExecuteNonQuery();
    }
    return afectadas;
}

Thanks, and sorry if I couldn't explain me better, English is not my native language and I have some difficulties with it :P