问:
Large text is going back of Imageview

```<code> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>
</code>```

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but

答:
Use LinearLayout insest of RelativeLayout, because in LinearLayout you can divide its child view via layout_weight.

try to change your code to:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

<ImageView
    android:id="@+id/Chartimg"
    android:layout_width="50dip"
    android:layout_height="50dip"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:src="@android:drawable/ic_menu_gallery" />

<TextView
    android:id="@+id/InfoView_ItemName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/IvItemID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/InfoView_ItemName"
    android:layout_toRightOf="@id/Chartimg"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<ImageView
    android:layout_width="30dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:scaleType="centerInside"
    android:src="@drawable/ic_action_next_item" />

</LinearLayout>
</FrameLayout>
</code>```

Title: Large text is going back of Imageview

Body:
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but

Body:
Use LinearLayout insest of RelativeLayout, because in LinearLayout you can divide its child view via layout_weight.

try to change your code to:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

<ImageView
    android:id="@+id/Chartimg"
    android:layout_width="50dip"
    android:layout_height="50dip"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:src="@android:drawable/ic_menu_gallery" />

<TextView
    android:id="@+id/InfoView_ItemName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/IvItemID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/InfoView_ItemName"
    android:layout_toRightOf="@id/Chartimg"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<ImageView
    android:layout_width="30dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:scaleType="centerInside"
    android:src="@drawable/ic_action_next_item" />

</LinearLayout>
</FrameLayout>


来源: stackexchange

问:
How to hide a complete DataGrid row?
I have a DataGrid, from which I add and remove items. This is the code I currently have:

```<code>  <DataGrid x:Name="ItemsToDo">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Info>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding IsDone}" Value="True">
                                <Setter Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                        </DataTemplate.Triggers>
                        <TextBlock Text="{Binding Description}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Deadline">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding IsDone}" Value="True">
                                <Setter Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                        </DataTemplate.Triggers>
                        <TextBlock Text="{Binding InputDeadline}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
</code>```

but when both columns of a row are set to collapsed, the row doesn't disappear, but it looks like this:
Entry 2 isn't completely gone

How do I remove this row without using the view model? Is there a better property than visibility?

答:
You should remove the DataTriggers from your cells' templates and apply the visibility trigger on the whole row, not on individual cells.

For example:

```<code><DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsDone}" Value="True">
                    <Setter Property="Visibility" Value="Collapsed"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Info">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Description}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Deadline">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding InputDeadline}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to hide a complete DataGrid row?

Body:
I have a DataGrid, from which I add and remove items. This is the code I currently have:

  <DataGrid x:Name="ItemsToDo">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Info>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding IsDone}" Value="True">
                                <Setter Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                        </DataTemplate.Triggers>
                        <TextBlock Text="{Binding Description}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Deadline">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding IsDone}" Value="True">
                                <Setter Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                        </DataTemplate.Triggers>
                        <TextBlock Text="{Binding InputDeadline}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>

but when both columns of a row are set to collapsed, the row doesn't disappear, but it looks like this:
Entry 2 isn't completely gone

How do I remove this row without using the view model? Is there a better property than visibility?

Body:
You should remove the DataTriggers from your cells' templates and apply the visibility trigger on the whole row, not on individual cells.

For example:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsDone}" Value="True">
                    <Setter Property="Visibility" Value="Collapsed"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Info">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Description}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Deadline">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding InputDeadline}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>


问:
JPA Spring Query sql
I have a query in sql.  I want to write it in JPA Spring.

How can i do it ?

SELECT * FROM user WHERE user.id=3 and user.enabled=1

答:
To perform a native SQL query in JPA you have to do the following:

```<code>EntityManager manager = getEntityManager();
Query query = manager.createNativeQuery("SELECT * FROM user WHERE user.id = :id AND user.enabled = :enabled;");
query.setParameter("id", 3);
query.setParameter("enabled", 1);
Object[] user = query.getSingleResult();
</code>```

If you want a JPQL query:

```<code>EntityManager manager = getEntityManager();
TypedQuery<User> query = manager.createQuery("SELECT u FROM User u WHERE u.id = :id AND user.enabled = :enabled;", User.class);
query.setParameter("id", 3);
query.setParameter("enabled", 1);
User user = query.getSingleResult();
</code>```

Using the JPQL query is the better style because it is type-safe. You can perform the statement directly on the entity without knowing the specific table structure of your database.

Title: JPA Spring Query sql

Body:
To perform a native SQL query in JPA you have to do the following:

EntityManager manager = getEntityManager();
Query query = manager.createNativeQuery("SELECT * FROM user WHERE user.id = :id AND user.enabled = :enabled;");
query.setParameter("id", 3);
query.setParameter("enabled", 1);
Object[] user = query.getSingleResult();

If you want a JPQL query:

EntityManager manager = getEntityManager();
TypedQuery<User> query = manager.createQuery("SELECT u FROM User u WHERE u.id = :id AND user.enabled = :enabled;", User.class);
query.setParameter("id", 3);
query.setParameter("enabled", 1);
User user = query.getSingleResult();

Using the JPQL query is the better style because it is type-safe. You can perform the statement directly on the entity without knowing the specific table structure of your database.


问:
Point to localhost\sqlexpress using only localhost
Working on a common codebase, one developer is running SQL Server Express 2005 and the other 2 are running SQL Server 2005. Everything is working fine, but the connection strings differ. To maintain common configuration and build scripts we're looking to mask "localhost\sqlexpress" to just "localhost" like the other 2 developers.

Can this be done? Or, maybe there's a better way for all 3 to run on the same connection string... The solution sought is for all 3 to be able to run on the same file versions in the code repository.

I might not be 100% clear: basically I want this:

```<code>Data Source=localhost;Initial Catalog=Sample;Integrated Security=True
</code>```

to connect the exact same as this:

```<code>Data Source=localhost\sqlexpress;Initial Catalog=Sample;Integrated Security=True
</code>```

If at all possible.

答:
Just tested things out and got it working.

sql express doesnt enable tcp/ip by default and when enabled doesnt use the default port 1433.

to make this happen you need to open up "Sql server configuration manager" then under protocols enable tcp/ip.  after that double click "tcp/ip", select the "IP Addresses" tab and scroll to the bottom then blank the "TCP Dynamic Ports" and enter 1433 under TCP Port.

after all that restart the sql server service and it should work with the normal connection string.

OwnerDisplayName: Chris Missal

Body:
Working on a common codebase, one developer is running SQL Server Express 2005 and the other 2 are running SQL Server 2005. Everything is working fine, but the connection strings differ. To maintain common configuration and build scripts we're looking to mask "localhost\sqlexpress" to just "localhost" like the other 2 developers.

Can this be done? Or, maybe there's a better way for all 3 to run on the same connection string... The solution sought is for all 3 to be able to run on the same file versions in the code repository.

I might not be 100% clear: basically I want this:

Data Source=localhost;Initial Catalog=Sample;Integrated Security=True

to connect the exact same as this:

Data Source=localhost\sqlexpress;Initial Catalog=Sample;Integrated Security=True

If at all possible.

LastEditorDisplayName: Chris Missal

OwnerDisplayName: John Boker

ContentLicense: CC BY-SA 2.5


问:
getting value in Interger array using for loop
I am new to programming and started android few week back.

```<code>public class MainActivity extends AppCompatActivity {

int a,i,j,k;
 /*char [][] s1= new char[][]
 {
                                     {'A','B','C','D'},
                                     {'E','F','G','H'},
                                     {'I','J','K','L'},
                                     {'M','N','O','P'},
                                     {'Q','R','S','T'},
                                     {'U','V','W','X'},
                                     {' ','Y','Z',' '}};*/

char [][] s2=new char[8][8];
char[][] s3=new char[8][8];
int[] getlist=  new int[10];;
char choice,choice1;
int x,b,c,d;
String[] messageText = new String[10];
String[] messageEdit = new String[10];

public void letterNo(View view) { // Method to show screen for getting number of letters

    setContentView(R.layout.displaylettersno);
}

public void getNumber(View view) { // Method to get Numbers of Letter

    EditText et = (EditText) findViewById(R.id.editText);
    String s = et.getText().toString();
    x = Integer.parseInt(s);

    if (x > 0 && x < 9) {

        et.setText("");
    } else {

        Toast.makeText(getApplicationContext(), "Wrong Entery... Enter again", Toast.LENGTH_LONG).show();

    }
    setContentView(R.layout.gettingcolumnno);

   // Toast.makeText(getApplicationContext(),"Click on Column No in Which 1st Letter Appear",Toast.LENGTH_LONG).show();
    TextView textView = (TextView) findViewById(R.id.textView8);
for (i = 0; i < x; i++){
    textView.setText("Enter Column No. in which Your letters of name is
present:" );
}
}

public void buttondone(View view) {
   EditText op  = (EditText) findViewById(R.id.operator2);
    String num = op.getText().toString();

    for (i = 0; i < x; i++)
    {

        getlist[i] = Integer.parseInt(String.valueOf(op.getText()));

    }

    Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}
</code>```

I want to develop a Name guess game
1- it will ask user to enter the no. of letters he thought
2- it will ask user to enter the column no in which his letter present ( i want this to run according to user enter the no of letter .
suppose user enter 4 digits and it will ask to enter the column no 4 times.
and similarly it has a edit box where user enter column no .
i am using for loop for this purpose but it only show 1 time i am stuck here for 1 week . help me if you understand what i am trying to do . following is my code

答:
Done button has to be pressed number of letters time to get columns.</p>

```<code>TextView textView = (TextView) findViewById(R.id.textView8);
int numberOfColumnsEntered = 0;
public void getNumber(View view) {
   // get number logic then
   textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
}

public void buttondone(View view) {
    EditText op  = (EditText) findViewById(R.id.operator2);
    String num = op.getText().toString();
    getlist[numberofColumnsEntered] = Integer.parseInt(num);
    numberofColumnsEntered++;
    textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
    if(numberofColumnsEntered == x) {
    Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
    }
}
</code>```

Body:
I am new to programming and started android few week back.

public class MainActivity extends AppCompatActivity {

int a,i,j,k;
 /*char [][] s1= new char[][]
 {
                                     {'A','B','C','D'},
                                     {'E','F','G','H'},
                                     {'I','J','K','L'},
                                     {'M','N','O','P'},
                                     {'Q','R','S','T'},
                                     {'U','V','W','X'},
                                     {' ','Y','Z',' '}};*/

char [][] s2=new char[8][8];
char[][] s3=new char[8][8];
int[] getlist=  new int[10];;
char choice,choice1;
int x,b,c,d;
String[] messageText = new String[10];
String[] messageEdit = new String[10];

public void letterNo(View view) { // Method to show screen for getting number of letters

    setContentView(R.layout.displaylettersno);
}

public void getNumber(View view) { // Method to get Numbers of Letter

    EditText et = (EditText) findViewById(R.id.editText);
    String s = et.getText().toString();
    x = Integer.parseInt(s);

    if (x > 0 && x < 9) {

        et.setText("");
    } else {

        Toast.makeText(getApplicationContext(), "Wrong Entery... Enter again", Toast.LENGTH_LONG).show();

    }
    setContentView(R.layout.gettingcolumnno);

   // Toast.makeText(getApplicationContext(),"Click on Column No in Which 1st Letter Appear",Toast.LENGTH_LONG).show();
    TextView textView = (TextView) findViewById(R.id.textView8);
for (i = 0; i < x; i++){
    textView.setText("Enter Column No. in which Your letters of name is
present:" );
}
}

public void buttondone(View view) {
   EditText op  = (EditText) findViewById(R.id.operator2);
    String num = op.getText().toString();

    for (i = 0; i < x; i++)
    {

        getlist[i] = Integer.parseInt(String.valueOf(op.getText()));

    }

    Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}

I want to develop a Name guess game
1- it will ask user to enter the no. of letters he thought
2- it will ask user to enter the column no in which his letter present ( i want this to run according to user enter the no of letter .
suppose user enter 4 digits and it will ask to enter the column no 4 times.
and similarly it has a edit box where user enter column no .
i am using for loop for this purpose but it only show 1 time i am stuck here for 1 week . help me if you understand what i am trying to do . following is my code

Body:
Done button has to be pressed number of letters time to get columns.

TextView textView = (TextView) findViewById(R.id.textView8);
int numberOfColumnsEntered = 0;
public void getNumber(View view) {
   // get number logic then
   textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
}

public void buttondone(View view) {
    EditText op  = (EditText) findViewById(R.id.operator2);
    String num = op.getText().toString();
    getlist[numberofColumnsEntered] = Integer.parseInt(num);
    numberofColumnsEntered++;
    textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
    if(numberofColumnsEntered == x) {
    Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
    }
}


问:
SQL Server 2008 missing thesaurus xml and ftdata folder
I've recently installed SQL Server 2008, and I've tried the full text search and now I need to use the thesaurus for synonymous but I can't find any xmq and the ftdata folder which I read should contain the xml files...thank you!!!</p>

答:
I was facing similar issue. The documentation Path didn't work. The following path worked for me.
C:\SQLData\MSSQL10.MSSQLSERVER\MSSQL\FTData </p>


问:
iOS, re-use AppIcon in assets catalog in my LaunchScreen Storyboard?
I'd like to show my app icon in my launch storyboard.

I've added a UIImageView and I can select other images in my asset catalog, they are shown in the dropdown. However AppIcon is not.

I've tried to trick interface builder and specify the image name directly but that doesn't work either.

I'm guess it can't be reused?

答: The AppIcon files can, in fact, be reused. If you drag a specific file to the Copy Bundle Resources build phase and deselect "Copy items if needed", the icon file will be usable without taking up significantly more space.</p>


问:
Extracting text from a nested JSON file where each JSON object has variable number of entries in Python
I have a json file containing multiple nested json objects which look like this:

```<code>{
"coordinates": null,
"acoustic_features": {
    "instrumentalness": "0.00479",
    "liveness": "0.18",
    "speechiness": "0.0294",
    "danceability": "0.634",
    "valence": "0.342",
    "loudness": "-8.345",
    "tempo": "125.044",
    "acousticness": "0.00035",
    "energy": "0.697",
    "mode": "1",
    "key": "6"
},
"artist_id": "b2980c722a1ace7a30303718ce5491d8",
"place": null,
"geo": null,
"tweet_lang": "en",
"source": "Share.Radionomy.com",
"track_title": "8eeZ",
"track_id": "cd52b3e5b51da29e5893dba82a418a4b",
"artist_name": "Dominion",
"entities": {
    "hashtags": [{
        "text": "nowplaying",
        "indices": [0, 11]
    }, {
        "text": "goth",
        "indices": [51, 56]
    }, {
        "text": "deathrock",
        "indices": [57, 67]
    }, {
        "text": "postpunk",
        "indices": [68, 77]
    }],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "indices": [28, 50],
        "expanded_url": "cathedral13.com/blog13",
        "display_url": "cathedral13.com/blog13",
        "url": "t.co/Tatf4hEVkv"
    }]
},
"created_at": "2014-01-01 05:54:21",
"text": "#nowplaying Dominion - 8eeZ Tatf4hEVkv #goth #deathrock #postpunk",
"user": {
    "location": "middle of nowhere",
    "lang": "en",
    "time_zone": "Central Time (US & Canada)",
    "name": "Cathedral 13",
    "entities": null,
    "id": 81496937,
    "description": "I\u2019m a music junkie who is currently responsible for
Cathedral 13 internet radio (goth, deathrock, post-punk)which has been
online since 06/20/02."
},
"id": 418243774842929150
}
</code>```

Each objects contain variable number of hashtags. I want to obtain a csv file containing the hashtag texts.
I have written the following code to do it:

```<code>import csv
with open('jsonpart.json') as data_file:
    data = json.load(data_file)
    #print (data)
    header = ['hashtags']

# open a file for writing
data_csv = open('hashtags.csv', 'wb')
# create the csv writer object
csvwriter = csv.writer(data_csv)

# write the csv header
csvwriter.writerow(header)

for entry in data:
    csvwriter.writerow([entry['entities']['hashtags']])

data_csv.close()
</code>```

I get the following output file:

```<code>"[{u'indices': [0, 11], u'text': u'nowplaying'}, {u'indices': [51, 56],
 u'text': u'goth'}, {u'indices': [57, 67], u'text': u'deathrock'},
{u'indices': [68, 77], u'text': u'postpunk'}]"
"[{u'indices': [23, 34], u'text': u'NowPlaying'}, {u'indices': [75, 79],
u'text': u'80s'}, {u'indices': [80, 86], u'text': u'Retro'}, {u'indices':
[87, 91], u'text': u'Fun'}]"
"[{u'indices': [0, 11], u'text': u'nowplaying'}]"
"[{u'indices': [54, 65], u'text': u'nowplaying'}, {u'indices': [66, 77],
u'text': u'listenlive'}]"
</code>```

I am stuck from here. How do I get my target file as:

```<code>nowplaying
goth
deathrock
postpunk
NowPlaying
80's
Retro
Fun
nowplaying
nowplaying
listenlive
</code>```

答:
You could use a simple list comprehension. Given that you have json object called json_chunk you could create the list like so:

text_list = [hashtag['text'] for hashtag in json_chunk['entities']['hashtags']]

Now you have a list. Iterate it (some element apparently have a new line character others dont - so strip all and add new line character to all) and write each element to a file like so:

```<code>with open(r'C:\outputfile.csv', 'a', encoding='utf-8') as fd:
    for line in text_list:
    fd.write(line.strip()+'\n')
</code>```

Body:
I have a json file containing multiple nested json objects which look like this:

{
"coordinates": null,
"acoustic_features": {
    "instrumentalness": "0.00479",
    "liveness": "0.18",
    "speechiness": "0.0294",
    "danceability": "0.634",
    "valence": "0.342",
    "loudness": "-8.345",
    "tempo": "125.044",
    "acousticness": "0.00035",
    "energy": "0.697",
    "mode": "1",
    "key": "6"
},
"artist_id": "b2980c722a1ace7a30303718ce5491d8",
"place": null,
"geo": null,
"tweet_lang": "en",
"source": "Share.Radionomy.com",
"track_title": "8eeZ",
"track_id": "cd52b3e5b51da29e5893dba82a418a4b",
"artist_name": "Dominion",
"entities": {
    "hashtags": [{
        "text": "nowplaying",
        "indices": [0, 11]
    }, {
        "text": "goth",
        "indices": [51, 56]
    }, {
        "text": "deathrock",
        "indices": [57, 67]
    }, {
        "text": "postpunk",
        "indices": [68, 77]
    }],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "indices": [28, 50],
        "expanded_url": "cathedral13.com/blog13",
        "display_url": "cathedral13.com/blog13",
        "url": "t.co/Tatf4hEVkv"
    }]
},
"created_at": "2014-01-01 05:54:21",
"text": "#nowplaying Dominion - 8eeZ Tatf4hEVkv #goth #deathrock #postpunk",
"user": {
    "location": "middle of nowhere",
    "lang": "en",
    "time_zone": "Central Time (US & Canada)",
    "name": "Cathedral 13",
    "entities": null,
    "id": 81496937,
    "description": "I\u2019m a music junkie who is currently responsible for
Cathedral 13 internet radio (goth, deathrock, post-punk)which has been
online since 06/20/02."
},
"id": 418243774842929150
}

Each objects contain variable number of hashtags. I want to obtain a csv file containing the hashtag texts.
I have written the following code to do it:

import csv
with open('jsonpart.json') as data_file:
    data = json.load(data_file)
    #print (data)
    header = ['hashtags']

# open a file for writing
data_csv = open('hashtags.csv', 'wb')
# create the csv writer object
csvwriter = csv.writer(data_csv)

# write the csv header
csvwriter.writerow(header)

for entry in data:
    csvwriter.writerow([entry['entities']['hashtags']])

data_csv.close()

I get the following output file:

"[{u'indices': [0, 11], u'text': u'nowplaying'}, {u'indices': [51, 56],
 u'text': u'goth'}, {u'indices': [57, 67], u'text': u'deathrock'},
{u'indices': [68, 77], u'text': u'postpunk'}]"
"[{u'indices': [23, 34], u'text': u'NowPlaying'}, {u'indices': [75, 79],
u'text': u'80s'}, {u'indices': [80, 86], u'text': u'Retro'}, {u'indices':
[87, 91], u'text': u'Fun'}]"
"[{u'indices': [0, 11], u'text': u'nowplaying'}]"
"[{u'indices': [54, 65], u'text': u'nowplaying'}, {u'indices': [66, 77],
u'text': u'listenlive'}]"

I am stuck from here. How do I get my target file as:

nowplaying
goth
deathrock
postpunk
NowPlaying
80's
Retro
Fun
nowplaying
nowplaying
listenlive

Body:
You could use a simple list comprehension. Given that you have json object called json_chunk you could create the list like so:

text_list = [hashtag['text'] for hashtag in json_chunk['entities']['hashtags']]

Now you have a list. Iterate it (some element apparently have a new line character others dont - so strip all and add new line character to all) and write each element to a file like so:

with open(r'C:\outputfile.csv', 'a', encoding='utf-8') as fd:
    for line in text_list:
    fd.write(line.strip()+'\n')


问:
Error when trying to compile Pro*C programs in Linux
I am practicing with a Pro*C program and SQL and I have the following simple program:

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

char user_id[20]="test/test"
char emp_name[20];

main()
{
    EXEC SQL CONNECT :userid;
    printf("Connected\n");

    EXEC SQL DECLARE emp_cursor CURSOR FOR
        SELECT name
        FROM badge;

    EXEC SQL OPEN emp_cursor;

    printf("Employees---------------");
    EXEC SQL WHENEVER NOT FOUND DO break;while (1)
       {
          EXEC SQL FETCH emp_cursor INTO :emp_name;
          printf("%s\n", emp_name);
        }

    EXEC SQL CLOSE emp_cursor;
    EXEC SQL COMMIT WORK RELEASE;

    exit(0);
}
</code>```

It simply retrieves all the names from a table called BADGE:

```<code>CREATE TABLE BADGE
(
    badge_id NUMBER PRIMARY KEY,
    name VARCHAR(20),
    surname VARCHAR(20) NOT NULL,
    birthday DATE
);
</code>```

However, when I try to compile the source I have the following error:

    proc test.pc
    proc: symbol lookup error: proc: undefined symbol: kgsuglo_

Can anyone help me out with the error?

答: I had this problem with instantclient-precomp-linux.x64-12.1.0.1.0.zip and solved it by upgrading to instantclient-precomp-linux.x64-12.1.0.2.0.zip

Body:
I am practicing with a Pro*C program and SQL and I have the following simple program:

#include <stdio.h>
#include <sqlca.h>

char user_id[20]="test/test"
char emp_name[20];

main()
{
    EXEC SQL CONNECT :userid;
    printf("Connected\n");

    EXEC SQL DECLARE emp_cursor CURSOR FOR
        SELECT name
        FROM badge;

    EXEC SQL OPEN emp_cursor;

    printf("Employees---------------");
    EXEC SQL WHENEVER NOT FOUND DO break;while (1)
       {
          EXEC SQL FETCH emp_cursor INTO :emp_name;
          printf("%s\n", emp_name);
        }

    EXEC SQL CLOSE emp_cursor;
    EXEC SQL COMMIT WORK RELEASE;

    exit(0);
}

It simply retrieves all the names from a table called BADGE:

CREATE TABLE BADGE
(
    badge_id NUMBER PRIMARY KEY,
    name VARCHAR(20),
    surname VARCHAR(20) NOT NULL,
    birthday DATE
);

However, when I try to compile the source I have the following error:

    proc test.pc
    proc: symbol lookup error: proc: undefined symbol: kgsuglo_

Can anyone help me out with the error?


问:
Is It Possible to Declare Constant with Associative Array
I am trying to declare a constant for our office names of each country with associative array.

My declaring code is as below:

```<code>define( "OUR_OFFICE", [
    "Japan" => "Tokyo Shibuya Office",
    "Taiwan" => "Taipei Shilin Office",
    "Korea" => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office"
]);
</code>```

However, it just shows message:

Warning: Constants may only evaluate to scalar values

Is it possible to declare a constant with associative array?

Thank you very much!!!

答:
In PHP 7, array values are also accepted.

But prior PHP 7, you maybe can do this, to pass an array elsewhere using define:

```<code>$array = [
    "Japan" => "Tokyo Shibuya Office",
    "Taiwan" => "Taipei Shilin Office",
    "Korea" => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office"
];

$define_array = serialize($array);

define( "OUROFFICE", $define_array );

$our_office = unserialize(OUROFFICE);

print_r($our_office);
</code>```

Body:
I am trying to declare a constant for our office names of each country with associative array.

My declaring code is as below:

define( "OUR_OFFICE", [
    "Japan" => "Tokyo Shibuya Office",
    "Taiwan" => "Taipei Shilin Office",
    "Korea" => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office"
]);

However, it just shows message:

Warning: Constants may only evaluate to scalar values

Is it possible to declare a constant with associative array?

Thank you very much!!!

Body:
In PHP 7, array values are also accepted.

But prior PHP 7, you maybe can do this, to pass an array elsewhere using define:

$array = [
    "Japan" => "Tokyo Shibuya Office",
    "Taiwan" => "Taipei Shilin Office",
    "Korea" => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office"
];

$define_array = serialize($array);

define( "OUROFFICE", $define_array );

$our_office = unserialize(OUROFFICE);

print_r($our_office);


问:
extract xml tag value from clob field using oracle
I have the following XML data stored in DB field:

```<code><FM>
<SectionsList>
<Section>
<SectionId>Section_one</SectionId>
</Section>
<Section>
<SectionId>Section_two</SectionId>
<Fields>
<FormField>
<FieldId>REQUESTID</FieldId>
<FieldValue>ABC1234</FieldValue>
</FormField>
<FormField>
<FieldId>REQUESTNAME</FieldId>
<FieldValue>JASMINE</FieldValue>
</FormField>
</Fields>
</Section>
</SectionsList>
</FM>
</code>```

I want to retrieve the value of FieldValue of FormField tag having FieldId of REQUESTNAME from section having SectionId of Section_two. Result should be JASMINE.

I am executing query in Oracle as:

```<code>SELECT EXTRACTVALUE(xmltype(req_details),
  '/FM/SectionsList/Section[@SectionId="Section_two"]/Fields/FormField/FieldValue[@FieldId="REQUESTNAME"]')
from table
</code>```

But result is NULL. How can i extract the value in Oracle?

答:
You are confusing attribute and node selection. SectionId is not an attribute of the section, which is what your [@SectionId=...] is looking for.

You could do this by identifying the node text values and walking back up the tree:

```<code>select extractvalue(xmltype(req_details),
  '/FM/SectionsList/Section/SectionId[text()="Section_two"]/../Fields/FormField/FieldId[text()="REQUESTNAME"]/../FieldValue')
  as result
from your_table

RESULT
--------------------
JASMINE
</code>```

or as extractvalue() is deprecated, with an XMLQuery instead:

```<code>select xmlquery(
  '/FM/SectionsList/Section/SectionId[text()="Section_two"]/../Fields/FormField/FieldId[text()="REQUESTNAME"]/../FieldValue/text()'
  passing xmltype(req_details)
  returning content) as result
from your_table

RESULT
--------------------
JASMINE
</code>```

Or with a more explicit XPath that avoids having to walk back up the tree (so a little easier to follow, and harder to get lost):

```<code>select xmlquery(
  'for $i in /FM/SectionsList/Section where $i/SectionId="Section_two"
   return
     for $j in $i/Fields/FormField where $j/FieldId="REQUESTNAME"
       return $j/FieldValue/text()'
  passing xmltype(req_details)
  returning content) as result
from your_table;

RESULT
--------------------
JASMINE
</code>```

Body:
I have the following XML data stored in DB field:

<FM>
<SectionsList>

<SectionId>Section_one</SectionId>

<SectionId>Section_two</SectionId>
<Fields>
<FormField>
<FieldId>REQUESTID</FieldId>
<FieldValue>ABC1234</FieldValue>
</FormField>
<FormField>
<FieldId>REQUESTNAME</FieldId>
<FieldValue>JASMINE</FieldValue>
</FormField>
</Fields>

</SectionsList>
</FM>

I want to retrieve the value of FieldValue of FormField tag having FieldId of REQUESTNAME from section having SectionId of Section_two. Result should be JASMINE.

I am executing query in Oracle as:

SELECT EXTRACTVALUE(xmltype(req_details),
  '/FM/SectionsList/Section[@SectionId="Section_two"]/Fields/FormField/FieldValue[@FieldId="REQUESTNAME"]')
from table

But result is NULL. How can i extract the value in Oracle?

Body:
You are confusing attribute and node selection. SectionId is not an attribute of the section, which is what your [@SectionId=...] is looking for.

You could do this by identifying the node text values and walking back up the tree:

select extractvalue(xmltype(req_details),
  '/FM/SectionsList/Section/SectionId[text()="Section_two"]/../Fields/FormField/FieldId[text()="REQUESTNAME"]/../FieldValue')
  as result
from your_table

RESULT
--------------------
JASMINE

or as extractvalue() is deprecated, with an XMLQuery instead:

select xmlquery(
  '/FM/SectionsList/Section/SectionId[text()="Section_two"]/../Fields/FormField/FieldId[text()="REQUESTNAME"]/../FieldValue/text()'
  passing xmltype(req_details)
  returning content) as result
from your_table

RESULT
--------------------
JASMINE

Or with a more explicit XPath that avoids having to walk back up the tree (so a little easier to follow, and harder to get lost):

select xmlquery(
  'for $i in /FM/SectionsList/Section where $i/SectionId="Section_two"
   return
     for $j in $i/Fields/FormField where $j/FieldId="REQUESTNAME"
       return $j/FieldValue/text()'
  passing xmltype(req_details)
  returning content) as result
from your_table;

RESULT
--------------------
JASMINE


答:
The code you posted doesn't work on PHP 5.

Declaring constant arrays using define is a new feature introduced in PHP 7.0.

Since PHP 5.6 it is possible to define a constant array using the const keyword:

```<code>const OUR_OFFICE = [
    "Japan"     => "Tokyo Shibuya Office",
    "Taiwan"    => "Taipei Shilin Office",
    "Korea"     => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office",
];
</code>```

The documentation highlights the differences between define() and const:

As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements or try/catch blocks.

Title: Is It Possible to Declare Constant with Associative Array

Body:
The code you posted doesn't work on PHP 5.

Declaring constant arrays using define is a new feature introduced in PHP 7.0.

Since PHP 5.6 it is possible to define a constant array using the const keyword:

const OUR_OFFICE = [
    "Japan"     => "Tokyo Shibuya Office",
    "Taiwan"    => "Taipei Shilin Office",
    "Korea"     => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office",
];

The documentation highlights the differences between define() and const:

As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements or try/catch blocks.


问:
Company backends in GNU Emacs
In Emacs, I have installed the MELPA company-irony-c-header package. I then did some research on the web, and apparently in order to configure the package, what I took to mean "activating" it, I had to add this:

```<code>(defun company-my-backend (command &optional arg &rest ignored)
  (interactive (list 'interactive))
  (case command
    (interactive (company-begin-backend 'company-my-backend))
    (prefix (when (looking-back "foo\\>") (match-string 0)))
    (candidates (when (equal arg "foo") (list "foobar" "foobaz" "foobarbaz")))
    (meta (format "This value is named %s" arg))))
</code>```

into something called a "back-end" (with foo standing for whatever my filename was). What is a back-end, and how can I to use it?

答:
1. From the official documentation

Company is a text completion framework for Emacs. The name stands for
"complete anything". It uses pluggable back-ends and front-ends to
retrieve and display completion candidates.

That means that "back-ends" are the sources of information (parser, database...) company uses to suggest completion.

As an example, for C/C++ work I use the excellent RTags. Adding this back-end to company is done thanks:

```<code>(push 'company-rtags company-backends)
</code>```

2. Now for your problem

A minimal company-c-headers working example is

```<code>(package-initialize)

(require 'company)
(require 'company-c-headers)

(add-to-list 'company-backends 'company-c-headers)

;; system dirs (for include <...>)
(add-to-list 'company-c-headers-path-system "/usr/include/c++/6")
;; (add-to-list 'company-c-headers-path-system "ANOTHER_SYSTEM_DIR")
;; -> use "gcc -E -Wp,-v -" to get the complete list

;; You can also define (for include "...")
;;(add-to-list 'company-c-headers-path-user "/home/YOUR_PROJECT")

(add-hook 'c++-mode-hook 'company-mode)
(add-hook 'c-mode-hook 'company-mode)
</code>```

Save this file testing_init.el and start Emacs with

```<code>emacs -q --load "testing_init.el" your_prog.cpp
</code>```

Now if you type

```<code> #include<...
</code>```

in your_prog.cpp file, company should trigger an auto completion after the third typed character.

There are plenty of good tutorials to configure Emacs as a C++ editor. I think this one is a good starting point.

ContentLicense: CC BY-SA 4.0

Title: Company backends in GNU Emacs

Body:
In Emacs, I have installed the MELPA company-irony-c-header package. I then did some research on the web, and apparently in order to configure the package, what I took to mean "activating" it, I had to add this:

(defun company-my-backend (command &optional arg &rest ignored)
  (interactive (list 'interactive))
  (case command
    (interactive (company-begin-backend 'company-my-backend))
    (prefix (when (looking-back "foo\\>") (match-string 0)))
    (candidates (when (equal arg "foo") (list "foobar" "foobaz" "foobarbaz")))
    (meta (format "This value is named %s" arg))))

into something called a "back-end" (with foo standing for whatever my filename was). What is a back-end, and how can I to use it?

Body:
1. From the official documentation

Company is a text completion framework for Emacs. The name stands for
"complete anything". It uses pluggable back-ends and front-ends to
retrieve and display completion candidates.

That means that "back-ends" are the sources of information (parser, database...) company uses to suggest completion.

As an example, for C/C++ work I use the excellent RTags. Adding this back-end to company is done thanks:

(push 'company-rtags company-backends)

2. Now for your problem

A minimal company-c-headers working example is

(package-initialize)

(require 'company)
(require 'company-c-headers)

(add-to-list 'company-backends 'company-c-headers)

;; system dirs (for include <...>)
(add-to-list 'company-c-headers-path-system "/usr/include/c++/6")
;; (add-to-list 'company-c-headers-path-system "ANOTHER_SYSTEM_DIR")
;; -> use "gcc -E -Wp,-v -" to get the complete list

;; You can also define (for include "...")
;;(add-to-list 'company-c-headers-path-user "/home/YOUR_PROJECT")

(add-hook 'c++-mode-hook 'company-mode)
(add-hook 'c-mode-hook 'company-mode)

Save this file testing_init.el and start Emacs with

emacs -q --load "testing_init.el" your_prog.cpp

Now if you type

 #include<...

in your_prog.cpp file, company should trigger an auto completion after the third typed character.

There are plenty of good tutorials to configure Emacs as a C++ editor. I think this one is a good starting point.


问:
onBackPressed() and Fragments
I am trying to use onBackPressed() in my Fragment so that I can allow the user to roll back in a pile of fragments he navigated in my app.

The problem is that, when I add the method below to my Fragment, it gives me the error: Method does not override method from its superclass.

```<code>@Override
public void onBackPressed() {

    android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack();

}
</code>```

Would you know why?

Thanks!

Here goes the entire Fragment:

```<code>package it.bitrack.fabio.bitrack;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import android.view.KeyEvent;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AssetMngtView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AssetMngtView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AssetMngtView extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    View view;

    ListView assetMngtListView;
    ArrayAdapter<String> listAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public AssetMngtView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AssetMngtView.
     */
    // TODO: Rename and change types and number of parameters
    public static AssetMngtView newInstance(String param1, String param2) {
        AssetMngtView fragment = new AssetMngtView();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onBackPressed() {

        android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStack();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_asset_mngt_view, container, false);

        assetMngtListView = (ListView) view.findViewById(R.id.assetMngtListView);
        setListView();

        return view;
    }

    public void setListView() {

        String[] options = new String[]{"Bind tag & thing", "Create new thing", "Edit existent thing", "Maintain existent thing", "View things notifications"};

        ArrayList<String> optionsList = new ArrayList<String>();
        optionsList.addAll(Arrays.asList(options));

        listAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, optionsList);

        assetMngtListView.setAdapter(listAdapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
</code>```

答: Use method onBackPressed() and call popBackStack() in your Activity class, not in fragment</p>

Title: onBackPressed() and Fragments

Body:
I am trying to use onBackPressed() in my Fragment so that I can allow the user to roll back in a pile of fragments he navigated in my app.

The problem is that, when I add the method below to my Fragment, it gives me the error: Method does not override method from its superclass.

@Override
public void onBackPressed() {

    android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.popBackStack();

}

Would you know why?

Thanks!

Here goes the entire Fragment:

package it.bitrack.fabio.bitrack;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import android.view.KeyEvent;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AssetMngtView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AssetMngtView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AssetMngtView extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    View view;

    ListView assetMngtListView;
    ArrayAdapter<String> listAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public AssetMngtView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AssetMngtView.
     */
    // TODO: Rename and change types and number of parameters
    public static AssetMngtView newInstance(String param1, String param2) {
        AssetMngtView fragment = new AssetMngtView();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onBackPressed() {

        android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStack();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_asset_mngt_view, container, false);

        assetMngtListView = (ListView) view.findViewById(R.id.assetMngtListView);
        setListView();

        return view;
    }

    public void setListView() {

        String[] options = new String[]{"Bind tag & thing", "Create new thing", "Edit existent thing", "Maintain existent thing", "View things notifications"};

        ArrayList<String> optionsList = new ArrayList<String>();
        optionsList.addAll(Arrays.asList(options));

        listAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, optionsList);

        assetMngtListView.setAdapter(listAdapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}


问:
Yii2 afterDelete won't get called
I have the user page in my application.When i delete the user in user screen the same user records are want to be deleted in other table also.I have done the createCommand.But the function itself won't get called.I have the UserController and User model.

Controller:

```<code>public function actionDelete($id)
{
    $user=$this->findModel($id)->delete();
    return $this->redirect(['index']);
}
</code>```

Model:

```<code>public function afterDelete()
    {
    //print"<script>alert('delete')</script>";
        $id = $this->id;
        parent::afterDelete();
        $connection     = Yii::$app->getDb();
        $tshirtaccessTable  = TshirtAccess::tableName();
        $userRoleTable      = UserRole::tableName();

        $transaction    = $connection->beginTransaction();
        try {
            $sql1 = "DELETE FROM ".$tshirtaccessTable." WHERE userid=:userid";
            $sql2 = "DELETE FROM ".$userRoleTable." WHERE userid=:userid";

            $connection->createCommand($sql1)->bindValue(':userid',$id)->execute();
            $connection->createCommand($sql2)->bindValue(':userid',$id)->execute();

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            //throw $e;
        }
    }
</code>```

答:
Your afterDelete is not getting called because you are executing SQL query directly to perform delete action.
whereas you have written afterDelete in your model.

in order to get this work, you need to find and delete the object of the model.

```<code>$model = TshirtAccess::find()->where(['userid' => $user_id])->one(); //all()
$model->delete(); // this will trigger your afterDelete function and execute your code.
</code>```

this will resolve your issue.

Title: Yii2 afterDelete won't get called

Body:
I have the user page in my application.When i delete the user in user screen the same user records are want to be deleted in other table also.I have done the createCommand.But the function itself won't get called.I have the UserController and User model.

Controller:

public function actionDelete($id)
{
    $user=$this->findModel($id)->delete();
    return $this->redirect(['index']);
}

Model:

public function afterDelete()
    {
    //print"";
        $id = $this->id;
        parent::afterDelete();
        $connection     = Yii::$app->getDb();
        $tshirtaccessTable  = TshirtAccess::tableName();
        $userRoleTable      = UserRole::tableName();

        $transaction    = $connection->beginTransaction();
        try {
            $sql1 = "DELETE FROM ".$tshirtaccessTable." WHERE userid=:userid";
            $sql2 = "DELETE FROM ".$userRoleTable." WHERE userid=:userid";

            $connection->createCommand($sql1)->bindValue(':userid',$id)->execute();
            $connection->createCommand($sql2)->bindValue(':userid',$id)->execute();

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            //throw $e;
        }
    }

Body:
Your afterDelete is not getting called because you are executing SQL query directly to perform delete action.
whereas you have written afterDelete in your model.

in order to get this work, you need to find and delete the object of the model.

$model = TshirtAccess::find()->where(['userid' => $user_id])->one(); //all()
$model->delete(); // this will trigger your afterDelete function and execute your code.

this will resolve your issue.


问:
GWT CellList Horizontal
Does anybody know how to make a CellList oriented horizontally? If possible, please with UiBinder, but this is not necessary.</p>

答: Try to override the CellList.renderRowValues method. You have to be able to create a horizontal presentation template.</p>

Title: GWT CellList Horizontal


问:
How to enable disable sup tag in javascript
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

```<code>  <label>code<sup id="star" disabled>*</sup></label>
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no
</code>```

my javascript:

```<code> function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }
</code>```

i tried this but no change in view. any ideas?

答:
```<code><label>code<sup id="star" style="visibility:hidden">*</sup></label>
Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()"/>yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no
</code>```

<hr>

```<code>function starenable() {

    if (document.getElementById('yes').checked)

        document.getElementById("star").style.visibility = "visible";

    else if (document.getElementById('no').checked)

        document.getElementById("star").style.visibility = "hidden";

    }
</code>```

Body:
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

  code*
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no

my javascript:

 function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }

i tried this but no change in view. any ideas?

Body:
<label>code<sup id="star" style="visibility:hidden">*</sup></label>
Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()"/>yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no

function starenable() {

    if (document.getElementById('yes').checked)

        document.getElementById("star").style.visibility = "visible";

    else if (document.getElementById('no').checked)

        document.getElementById("star").style.visibility = "hidden";

    }


问:
Client-side js: check file encoding
I have to validate on client side that my downloading file is UTF-8 encoded. How can I do it?
Maybe something with FileReader.readAsArrayBuffer()

答:
I happen to be doing some file upload operation and was facing problem with csv file with non-ascii character. However, using ISO-8859-1 solved my problem but not with utf-8 or utf-16. Here is my code snippet.

```<code>     function printTable(file) {
        var reader = new FileReader();
        reader.readAsText(file, 'ISO-8859-1');
        reader.onload = function (event) {
            var csv = event.target.result;
            var data = $.csv.toObjects(csv);
            var html = '';
            for (var row in data) {
                html += '<tr>\r\n';
                for (var item in data[row]) {
                    html += '<td>' + item + ':' + data[row][item] + '</td>\r\n';
                }
                html += '</tr>\r\n';
            }
            $('#contents').html(html);
        };
        reader.onerror = function () { alert('unable to read ' + file.fileName); };
    }
</code>```

Now, I am getting those non-ascii characters when importing even though the csv file is not saved with utf-8 encoding.

Title: Client-side js: check file encoding

Body:
I happen to be doing some file upload operation and was facing problem with csv file with non-ascii character. However, using ISO-8859-1 solved my problem but not with utf-8 or utf-16. Here is my code snippet.

     function printTable(file) {
        var reader = new FileReader();
        reader.readAsText(file, 'ISO-8859-1');
        reader.onload = function (event) {
            var csv = event.target.result;
            var data = $.csv.toObjects(csv);
            var html = '';
            for (var row in data) {
                html += '<tr>\r\n';
                for (var item in data[row]) {
                    html += '<td>' + item + ':' + data[row][item] + '</td>\r\n';
                }
                html += '</tr>\r\n';
            }
            $('#contents').html(html);
        };
        reader.onerror = function () { alert('unable to read ' + file.fileName); };
    }

Now, I am getting those non-ascii characters when importing even though the csv file is not saved with utf-8 encoding.


问:
Execution requests n times with Postman
I need to execute a requests n times which in his body has an id value. Collection runner lets executing complete collection n times but I have not found anything for concrete requests.

Request body:

{
   "idEncargo":XXXXXXXX
}

From previous request I get an array with several idEncargo.

Somebody knows about this?

答:
In your first request, if you get an array with all your idEncargo, you shall save it in a global variable
Then in your second request, you shall loop over this array.

Either inside your second request, if it is possible or if you want to perform the http request for each idEncargo, you could try to use setNextRequest feature (refer to http://blog.getpostman.com/2016/03/23/conditional-workflows-in-postman/)
like doing the following (sorry I'm a beginner in javascript, I just suggest the algorithm):

```<code>request 1 - get my idEncargo array and set it in global // to bypass if array exists
        set global my_index = 0
        setNextRequest("request 2")
request 2 on idEncargo[my_index]
        in request 2 tests part do:
        my_index ++
        if my_index == max value
            setNextRequest("null") // breaks the loop
        else
            setNextRequest("request 2") // processes the next idEncargo
</code>```

Something like that could work ...

hope that helps

Alexandre

Title: Execution requests n times with Postman

Body:
In your first request, if you get an array with all your idEncargo, you shall save it in a global variable
Then in your second request, you shall loop over this array.

Either inside your second request, if it is possible or if you want to perform the http request for each idEncargo, you could try to use setNextRequest feature (refer to http://blog.getpostman.com/2016/03/23/conditional-workflows-in-postman/)
like doing the following (sorry I'm a beginner in javascript, I just suggest the algorithm):

request 1 - get my idEncargo array and set it in global // to bypass if array exists
        set global my_index = 0
        setNextRequest("request 2")
request 2 on idEncargo[my_index]
        in request 2 tests part do:
        my_index ++
        if my_index == max value
            setNextRequest("null") // breaks the loop
        else
            setNextRequest("request 2") // processes the next idEncargo

Something like that could work ...

hope that helps

Alexandre


问:
How can I save a directory tree to an array in PHP?
I'm trying to take a directory with the structure:

```<code>top
    folder1
        file1
    folder2
        file1
        file2
</code>```

And save it into an array like:

```<code>array
(
    'folder1' => array('file1'),
    'folder2' => array('file1', 'file2')
)
</code>```

This way, I can easily resuse the tree throughout my site. I've been playing around with this code but it's still not doing what I want:

```<code>private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
                $output[$relativePath] = array();
        }
    }

    return $output;
}
</code>```

答:
It appears you didn't address the case in which $relativePath is not a directory.  You did not describe your output, but i suppose it consists entirely of empty arrays without the desired files ever being inside.  Is this correct?

You need to handle the end-case where a file is reached instead of a directory.  Take a stab yourself, I can try to post for you later if you are still struggling.

Also, I'm afraid this won't deal with greater depths.  Although I am not sure if you need that based on your example.

--EDIT--

This won't build a full tree, as i explained the comment below, but depending on what you're looking for that might be ok.  A full tree would take some more significant changes.  However, what I post below should at least put the files into the folders.

```<code>private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
            {
                $output[$relativePath] = array();
                $lastDir = $relativePath;
            }
        }
        else
        {
             $p = path_info($file);
             $d = $p['dirname']; $f = $p['basename'];
             $output[$d][] = basename($f);
        }
    }

    return $output;
}
</code>```

Body:
I'm trying to take a directory with the structure:

top
    folder1
        file1
    folder2
        file1
        file2

And save it into an array like:

array
(
    'folder1' => array('file1'),
    'folder2' => array('file1', 'file2')
)

This way, I can easily resuse the tree throughout my site. I've been playing around with this code but it's still not doing what I want:

private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
                $output[$relativePath] = array();
        }
    }

    return $output;
}

Body:
It appears you didn't address the case in which $relativePath is not a directory.  You did not describe your output, but i suppose it consists entirely of empty arrays without the desired files ever being inside.  Is this correct?

You need to handle the end-case where a file is reached instead of a directory.  Take a stab yourself, I can try to post for you later if you are still struggling.

Also, I'm afraid this won't deal with greater depths.  Although I am not sure if you need that based on your example.

--EDIT--

This won't build a full tree, as i explained the comment below, but depending on what you're looking for that might be ok.  A full tree would take some more significant changes.  However, what I post below should at least put the files into the folders.

private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
            {
                $output[$relativePath] = array();
                $lastDir = $relativePath;
            }
        }
        else
        {
             $p = path_info($file);
             $d = $p['dirname']; $f = $p['basename'];
             $output[$d][] = basename($f);
        }
    }

    return $output;
}


问:
Passing value from ArrayAdapter to Activity
I'm working on an Android app for Students where students can attempt and view their test.

I'm displaying a test to student in a listview in an Activity.
I also want to display the total and obtained marks of student.

That's my ArrayAdapter's getView function.

```<code>public View getView(int position, View convertView, ViewGroup parent) {
   Text_Questions questions = getItem(position);
   ViewHolder v = null;
   View view = convertView;
   try {
        if (convertView == null) {
            v = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.text_questions_list_item, parent, false);
            v.title = (TextView)convertView.findViewById(R.id.title);
            v.marks = (TextView)convertView.findViewById(R.id.marks);
            v.answer = (TextView)convertView.findViewById(R.id.answer);
            v.std_answer = (TextView)convertView.findViewById(R.id.std_answer);
            convertView.setTag(v);
        }
        else {
            v = (ViewHolder) convertView.getTag();
        }
        v.title.setText("Q: "+questions.getTitle());
        v.std_answer.setText("Ans: "+ questions.getStd_answer());
        v.answer.setText("Correct: " + questions.getAnswer());
        if(questions.getAnswer().toLowerCase().equals(questions.getStd_answer().toLowerCase())){
            v.marks.setText(""+questions.getMarks() + "/" + questions.getMarks());
        }else{
            v.marks.setText("0/" + questions.getMarks());
        }
        return convertView;
    }catch (Exception e) {
        return null;
    }
}
</code>```

While setting an item to ListView I want to pass that question's marks to my Activity.
I didn't found any solution for this.
Any idea?

Thanks for Your help in advance

答:
You can create a public method in your Activity as follows:

```<code>public void setMarks(int marks){
    this.marks = marks
}
</code>```

Then in your ArrayAdapter you can do the following:

```<code>private YourActivity yourActivity;

public YourArrayAdapter(YourActivity yourActivity) {

    this.yourActivity = yourActivity;

}
</code>```

Then in your getView():

```<code>yourActivity.setMarks(marks);
</code>```

Body:
I'm working on an Android app for Students where students can attempt and view their test.

I'm displaying a test to student in a listview in an Activity.
I also want to display the total and obtained marks of student.

That's my ArrayAdapter's getView function.

public View getView(int position, View convertView, ViewGroup parent) {
   Text_Questions questions = getItem(position);
   ViewHolder v = null;
   View view = convertView;
   try {
        if (convertView == null) {
            v = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.text_questions_list_item, parent, false);
            v.title = (TextView)convertView.findViewById(R.id.title);
            v.marks = (TextView)convertView.findViewById(R.id.marks);
            v.answer = (TextView)convertView.findViewById(R.id.answer);
            v.std_answer = (TextView)convertView.findViewById(R.id.std_answer);
            convertView.setTag(v);
        }
        else {
            v = (ViewHolder) convertView.getTag();
        }
        v.title.setText("Q: "+questions.getTitle());
        v.std_answer.setText("Ans: "+ questions.getStd_answer());
        v.answer.setText("Correct: " + questions.getAnswer());
        if(questions.getAnswer().toLowerCase().equals(questions.getStd_answer().toLowerCase())){
            v.marks.setText(""+questions.getMarks() + "/" + questions.getMarks());
        }else{
            v.marks.setText("0/" + questions.getMarks());
        }
        return convertView;
    }catch (Exception e) {
        return null;
    }
}

While setting an item to ListView I want to pass that question's marks to my Activity.
I didn't found any solution for this.
Any idea?

Thanks for Your help in advance

Body:
You can create a public method in your Activity as follows:

public void setMarks(int marks){
    this.marks = marks
}

Then in your ArrayAdapter you can do the following:

private YourActivity yourActivity;

public YourArrayAdapter(YourActivity yourActivity) {

    this.yourActivity = yourActivity;

}

Then in your getView():

yourActivity.setMarks(marks);


问:
How to turn off mixed data and log in Sybase ASE 15.7?
When I use sp_helpdb in Sybase ASE 15.7 my result:

```<code>db_abc      2054.0 MB   sa  trunc log on chkpt, mixed log and data
db_def      1030.0 MB   sa  trunc log on chkpt, mixed log and data
</code>```

Could I turn off mixed log and data?
I tried with sp_dboption db_abc , 'mixed log and data', false
But show error Sybase Database Error: The database option does not exist or you cannot set the option. While sp_dboption db_abc , 'abort tran on log full', false in other case is Ok.

答:
The mixed log + data is not a switch. It is an effect of the way the database is created (and how pages are mixed in the same area). You can not switch it off. You need separate the LOG from DATA to achieve your goal.

Since on the current devices you have both LOG and DATA pages you need to:

add another device that is planned only for log (alter database .. log on ..)

switch on single user mode

move the log to the new created device with sp_logdevice procedure

switch off single user mode

Code example:

```<code>1> disk init name = dev1, physname = '/tmp/dev1.dat', size = '200M'
2> go
create database db_abc on dev1 = '200M'
2> go
CREATE DATABASE: allocating 102400 logical pages (200.0 megabytes) on disk 'dev1' (102400 logical pages requested).
Database 'db_abc' is now online.
1> exec sp_dboption 'db_abc', 'trunc log on chkpt', true
2> go
Database option 'trunc log on chkpt' turned ON for database 'db_abc'.
Running CHECKPOINT on database 'db_abc' for option 'trunc log on chkpt' to take effect.
(return status = 0)
1> exec sp_helpdb 'db_abc'
2> go
 name   db_size       owner dbid created      durability lobcomplvl inrowlen status
 ------ ------------- ----- ---- ------------ ---------- ---------- -------- --------------------------------------
 db_abc      200.0 MB sa       4 Jul 07, 2017 full                0     NULL trunc log on chkpt, mixed log and data

(1 row affected)

 device_fragments size          usage        created             free_kbytes
 ---------------- ------------- ------------ ------------------- ----------------
 dev1                  200.0 MB data and log Jul  7 2017  9:56AM           202232
(return status = 0)
1> disk init name = dev2, physname = '/tmp/dev2.dat', size = '100M'
2> go
1> alter database db_abc log on dev2 = '100M'
2> go
Extending database by 51200 pages (100.0 megabytes) on disk dev2
Warning: Using ALTER DATABASE to extend the log segment will cause user thresholds on the log segment within 128 pages of the last chance threshold to be disabled.
1> exec sp_dboption 'db_abc', 'single user', true
2> go
Database option 'single user' turned ON for database 'db_abc'.
Running CHECKPOINT on database 'db_abc' for option 'single user' to take effect.
(return status = 0)
1> exec sp_logdevice 'db_abc', 'dev2'
2> go
DBCC execution completed. If DBCC printed error messages, contact a user with System Administrator (SA) role.
DBCC execution completed. If DBCC printed error messages, contact a user with System Administrator (SA) role.
syslogs moved.
The last-chance threshold for database db_abc is now 16 pages.
(return status = 0)
1> exec sp_dboption 'db_abc', 'single user', false
2> go
Database option 'single user' turned OFF for database 'db_abc'.
Running CHECKPOINT on database 'db_abc' for option 'single user' to take effect.
(return status = 0)
1> exec sp_helpdb 'db_abc'
2> go
 name   db_size       owner dbid created      durability lobcomplvl inrowlen status
 ------ ------------- ----- ---- ------------ ---------- ---------- -------- --------------------------------------
 db_abc      300.0 MB sa       4 Jul 07, 2017 full                0     NULL trunc log on chkpt, mixed log and data

(1 row affected)

 device_fragments size          usage     created             free_kbytes
 ---------------- ------------- --------- ------------------- ----------------
 dev1                  200.0 MB data only Jul  7 2017  9:56AM           202248
 dev2                  100.0 MB log only  Jul  7 2017  9:57AM not applicable

 --------------------------------------------------------------------------------------------------------------
 log only free kbytes = 102000
(return status = 0)
</code>```

Body:
When I use sp_helpdb in Sybase ASE 15.7 my result:

db_abc      2054.0 MB   sa  trunc log on chkpt, mixed log and data
db_def      1030.0 MB   sa  trunc log on chkpt, mixed log and data

Could I turn off mixed log and data?
I tried with sp_dboption db_abc , 'mixed log and data', false
But show error Sybase Database Error: The database option does not exist or you cannot set the option. While sp_dboption db_abc , 'abort tran on log full', false in other case is Ok.

Body:
The mixed log + data is not a switch. It is an effect of the way the database is created (and how pages are mixed in the same area). You can not switch it off. You need separate the LOG from DATA to achieve your goal.

Since on the current devices you have both LOG and DATA pages you need to:

add another device that is planned only for log (alter database .. log on ..)

switch on single user mode

move the log to the new created device with sp_logdevice procedure

switch off single user mode

Code example:

1> disk init name = dev1, physname = '/tmp/dev1.dat', size = '200M'
2> go
create database db_abc on dev1 = '200M'
2> go
CREATE DATABASE: allocating 102400 logical pages (200.0 megabytes) on disk 'dev1' (102400 logical pages requested).
Database 'db_abc' is now online.
1> exec sp_dboption 'db_abc', 'trunc log on chkpt', true
2> go
Database option 'trunc log on chkpt' turned ON for database 'db_abc'.
Running CHECKPOINT on database 'db_abc' for option 'trunc log on chkpt' to take effect.
(return status = 0)
1> exec sp_helpdb 'db_abc'
2> go
 name   db_size       owner dbid created      durability lobcomplvl inrowlen status
 ------ ------------- ----- ---- ------------ ---------- ---------- -------- --------------------------------------
 db_abc      200.0 MB sa       4 Jul 07, 2017 full                0     NULL trunc log on chkpt, mixed log and data

(1 row affected)

 device_fragments size          usage        created             free_kbytes
 ---------------- ------------- ------------ ------------------- ----------------
 dev1                  200.0 MB data and log Jul  7 2017  9:56AM           202232
(return status = 0)
1> disk init name = dev2, physname = '/tmp/dev2.dat', size = '100M'
2> go
1> alter database db_abc log on dev2 = '100M'
2> go
Extending database by 51200 pages (100.0 megabytes) on disk dev2
Warning: Using ALTER DATABASE to extend the log segment will cause user thresholds on the log segment within 128 pages of the last chance threshold to be disabled.
1> exec sp_dboption 'db_abc', 'single user', true
2> go
Database option 'single user' turned ON for database 'db_abc'.
Running CHECKPOINT on database 'db_abc' for option 'single user' to take effect.
(return status = 0)
1> exec sp_logdevice 'db_abc', 'dev2'
2> go
DBCC execution completed. If DBCC printed error messages, contact a user with System Administrator (SA) role.
DBCC execution completed. If DBCC printed error messages, contact a user with System Administrator (SA) role.
syslogs moved.
The last-chance threshold for database db_abc is now 16 pages.
(return status = 0)
1> exec sp_dboption 'db_abc', 'single user', false
2> go
Database option 'single user' turned OFF for database 'db_abc'.
Running CHECKPOINT on database 'db_abc' for option 'single user' to take effect.
(return status = 0)
1> exec sp_helpdb 'db_abc'
2> go
 name   db_size       owner dbid created      durability lobcomplvl inrowlen status
 ------ ------------- ----- ---- ------------ ---------- ---------- -------- --------------------------------------
 db_abc      300.0 MB sa       4 Jul 07, 2017 full                0     NULL trunc log on chkpt, mixed log and data

(1 row affected)

 device_fragments size          usage     created             free_kbytes
 ---------------- ------------- --------- ------------------- ----------------
 dev1                  200.0 MB data only Jul  7 2017  9:56AM           202248
 dev2                  100.0 MB log only  Jul  7 2017  9:57AM not applicable

 --------------------------------------------------------------------------------------------------------------
 log only free kbytes = 102000
(return status = 0)


问:
socket.io dont work on server and have 404 error
I create a simple socket.io project in my server but I have errors
my ip that I am work on it is http://5.61.25.90/~socket
on all files are stored in public_html with URL : http://5.61.25.90/~socket/public_html

& here is my codes

```<code><!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.4/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(){
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
          $('#messages').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>
</code>```

the above code was the index.html file and in the bottom we have index.js

```<code> var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var port = process.env.PORT || 3000;

    app.get('/', function(req, res){
      res.sendFile(__dirname + '/index.html');
    });

    io.on('connection', function(socket){
      socket.on('chat message', function(msg){
        io.emit('chat message', msg);
      });
    });

    http.listen(port, function(){
      console.log('listening on *:' + port);
    });
</code>```

and now I have 404 error in the console panel

like this

http://5.61.25.90/socket.io/?EIO=3&transport=polling&t=LqRzAYF   404 not found           socket.io.js(line 4948)

答:
In my opinion this could help:

```<code>app.get('*', function(req, res) {
</code>```

instead of this:

```<code>app.get('/', function(req, res) {
</code>```

Your app router in the backend is only catching the route '/'. So it can't handle requests, that do not match the route exactly.

Body:
I create a simple socket.io project in my server but I have errors
my ip that I am work on it is http://5.61.25.90/~socket
on all files are stored in public_html with URL : http://5.61.25.90/~socket/public_html

& here is my codes

<!doctype html>

    <title>Socket.IO chat</title>

    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

the above code was the index.html file and in the bottom we have index.js

 var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var port = process.env.PORT || 3000;

    app.get('/', function(req, res){
      res.sendFile(__dirname + '/index.html');
    });

    io.on('connection', function(socket){
      socket.on('chat message', function(msg){
        io.emit('chat message', msg);
      });
    });

    http.listen(port, function(){
      console.log('listening on *:' + port);
    });

and now I have 404 error in the console panel

like this

http://5.61.25.90/socket.io/?EIO=3&transport=polling&t=LqRzAYF   404 not found           socket.io.js(line 4948)

Body:
In my opinion this could help:

app.get('*', function(req, res) {

instead of this:

app.get('/', function(req, res) {

Your app router in the backend is only catching the route '/'. So it can't handle requests, that do not match the route exactly.


问:
How to restrict multiple file selection in PickerView
I'm using WKWebView to load one URL. And that URL will open a registration form, in that we have a provision to picking images and videos from device and upload.
Here it is presenting picker view.

But the problem is we are able to select multiple files at a time. But I want to restrict multiple file selection. How can I restrict of selecting multiple files. (I'm using Swift 3.0)

答: image picker controller & didFinishPickingMediaWithInfo this two method  into fire a logic a minimum 10 pic select</p>


问:
Change position of JavaScript object key and data
I am working on javascript object. And I want to pass data to next array in a specific sequence. like I get data like this

```<code>var obj = [{
  0: "Owner Name"
  1: "Mailing Address"
  2: "Situs Address"
  3: "APN"
}]
</code>```

And want this sequence to be like this

```<code>var obj = [{
  3: "APN"
  0: "Owner Name"
  2: "Situs Address"
  1: "Mailing Address"
}];
</code>```

Is it possible to do that, on bases of data? As I don't know from database sequence maybe change.
edit:  For those who are saying I should use array. I am getting data on basis of this object like,

```<code> var data[{
  0:"CHANCE WILLIAM C & KATHRYN L"
  1:"P O BOX 7642 CHICO CA 95927"
  2:"LOT 4 PM 150-99/100"
  3:"040-310-086-000" }]
</code>```

答:
Object not have sorting property

so you can do like this,

Covert the array object arguments into individual object.then sorting with dec order of the key

var obj = [{
  '0': "Owner Name",
  '1': "Mailing Address",
  '2': "Situs Address",
  '3': "APN" ,
}];

var array = Object.keys(obj[0]).map(function(a){
                  return ({[a]:obj[0][a]});
}) //recreate with individual object

var sorted= array.sort((a,b)=> Object.keys(b)-Object.keys(a))
 console.log(sorted) //sorted  object

var res = sorted.map(a=> Object.values(a)[0]) // for array

console.log(res)```

Body:
I am working on javascript object. And I want to pass data to next array in a specific sequence. like I get data like this

var obj = [{
  0: "Owner Name"
  1: "Mailing Address"
  2: "Situs Address"
  3: "APN"
}]

And want this sequence to be like this

var obj = [{
  3: "APN"
  0: "Owner Name"
  2: "Situs Address"
  1: "Mailing Address"
}];

Is it possible to do that, on bases of data? As I don't know from database sequence maybe change.
edit:  For those who are saying I should use array. I am getting data on basis of this object like,

 var data[{
  0:"CHANCE WILLIAM C & KATHRYN L"
  1:"P O BOX 7642 CHICO CA 95927"
  2:"LOT 4 PM 150-99/100"
  3:"040-310-086-000" }]


问:
Why can't Selenium RC see a site on virtual machine
I'm having trouble getting Selenium to see sites hosted on a virtual
machine. The following test causes an error, and I have no idea why:

```<code><?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class ActualTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser("*firefox");
        $this->setBrowserUrl("http://10.48.77.48/"); // IP of virtual machine
        $this->setHost('192.168.101.1'); // IP of my Mac
    }

    public function testGetHomePage()
    {
        $this->open("/", true);
    }
}
</code>```

It returns the following error message, indicating that it couldn't
find the virtual machine:

```<code>$ phpunit ActualTest.php
PHPUnit 3.5.6 by Sebastian Bergmann.

E

Time: 7 seconds, Memory: 6.75Mb

There was 1 error:

1) ActualTest::testGetHomePage
PHPUnit_Framework_Exception: Response from Selenium RC server for testComplete().
XHR ERROR: URL = http://10.48.77.48/ Response_Code = 404 Error_Message = Page Not Found.

/home/craiga/ombudsman/app/systemtests/ActualTest.php:16

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
</code>```

I can access this site any browser anywhere on the network without any
problem, but for some reason the browser launched by Selenium can't.
This error occurs whether I launch the test from the virtual machine
or the Mac.

I can get the following test to connect to Google without any problem:

```<code><?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class VanitySearchTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser("*firefox");
        $this->setBrowserUrl("http://www.google.com.au/");
        $this->setHost('192.168.101.1'); // IP of my Mac
    }

    public function testSearchForSelf()
    {
        $this->open("/");
        $this->type("q", "craig anderson");
        $this->click("btnG");
        $this->waitForPageToLoad("30000");
        try {
                $this->assertTrue($this->isTextPresent("craiga.id.au"));
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
                array_push($this->verificationErrors, $e->toString());
        }
    }
}
</code>```

This test, which connects to my Mac's default page, also passes
without any problems:

```<code><?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class MacTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser("*firefox");
        $this->setBrowserUrl("http://192.168.101.1/");
        $this->setHost('192.168.101.1'); // IP of my Mac
    }

    public function testMacHomePage()
    {
        $this->open("/");
        try {
                $this->assertTrue($this->isTextPresent("It works!"));
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
                array_push($this->verificationErrors, $e->toString());
        }
    }
}
</code>```

Does anyone have any idea why this might be happening? I'm happy to
provide whatever information I can about my setup. I'm using Selenium
Server 1.0.3, and the latest phpunit from pear.

答:
Remove one http from below line

```<code>$this->setBrowserUrl("http://http://10.48.77.48/"); // IP of virtual machine
</code>```

and try...Let me know if it works

Body:
I'm having trouble getting Selenium to see sites hosted on a virtual
machine. The following test causes an error, and I have no idea why:

<?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class ActualTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser("*firefox");
        $this->setBrowserUrl("http://10.48.77.48/"); // IP of virtual machine
        $this->setHost('192.168.101.1'); // IP of my Mac
    }

    public function testGetHomePage()
    {
        $this->open("/", true);
    }
}

It returns the following error message, indicating that it couldn't
find the virtual machine:

$ phpunit ActualTest.php
PHPUnit 3.5.6 by Sebastian Bergmann.

E

Time: 7 seconds, Memory: 6.75Mb

There was 1 error:

1) ActualTest::testGetHomePage
PHPUnit_Framework_Exception: Response from Selenium RC server for testComplete().
XHR ERROR: URL = http://10.48.77.48/ Response_Code = 404 Error_Message = Page Not Found.

/home/craiga/ombudsman/app/systemtests/ActualTest.php:16

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

I can access this site any browser anywhere on the network without any
problem, but for some reason the browser launched by Selenium can't.
This error occurs whether I launch the test from the virtual machine
or the Mac.

I can get the following test to connect to Google without any problem:

<?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class VanitySearchTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser("*firefox");
        $this->setBrowserUrl("http://www.google.com.au/");
        $this->setHost('192.168.101.1'); // IP of my Mac
    }

    public function testSearchForSelf()
    {
        $this->open("/");
        $this->type("q", "craig anderson");
        $this->click("btnG");
        $this->waitForPageToLoad("30000");
        try {
                $this->assertTrue($this->isTextPresent("craiga.id.au"));
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
                array_push($this->verificationErrors, $e->toString());
        }
    }
}

This test, which connects to my Mac's default page, also passes
without any problems:

<?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class MacTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser("*firefox");
        $this->setBrowserUrl("http://192.168.101.1/");
        $this->setHost('192.168.101.1'); // IP of my Mac
    }

    public function testMacHomePage()
    {
        $this->open("/");
        try {
                $this->assertTrue($this->isTextPresent("It works!"));
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
                array_push($this->verificationErrors, $e->toString());
        }
    }
}

Does anyone have any idea why this might be happening? I'm happy to
provide whatever information I can about my setup. I'm using Selenium
Server 1.0.3, and the latest phpunit from pear.

Body:
Remove one http from below line

$this->setBrowserUrl("http://http://10.48.77.48/"); // IP of virtual machine

and try...Let me know if it works