问:
C program recursive call to main() with and without parameters
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

```<code>#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}
</code>```

-

```<code>#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}
</code>```

答:
In the first case:

"i" is never incremented therefore you run in an infinite loop and get an overflow.

In the second case:

You call the recursion before displaying the value of "i", after four calls "i" equals to 0 and your recursion stack unwinds.

Modify your condition and perform outputs before the recursion call.

Body:
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}

-

#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}


来源: stackexchange

问:
Output of the SQLite's foreign_key_list pragma
Using SQLite3 with the following schema:

```<code>CREATE TABLE Customers(ID INTEGER PRIMARY KEY, Company TEXT NOT NULL UNIQUE, Country TEXT NOT NULL, City TEXT NOT NULL);
CREATE TABLE Orders(ID INTEGER PRIMARY KEY, CustomerID INTEGER NOT NULL, FOREIGN KEY(CustomerID) REFERENCES Customers(ID) ON DELETE RESTRICT ON UPDATE RESTRICT);
</code>```

and issuing this command:

```<code>PRAGMA foreign_key_list(Orders);
</code>```

results in the following output:

```<code>0|0|Customers|CustomerID|ID|RESTRICT|RESTRICT|NONE
</code>```

As the documentation says nothing about the meaning of the output of this pragma, apart from the obvious (Customers - Parent table, CustomerID - Child key, ID - Parent key, RESTRICT - ON DELETE and the second RESTRICT - ON UPDATE) I presume that NONE coresponds to the unsupported MATCH clause.

The thing which I can't figure out by myself is the meaning of the first two zeros. Could someone tell me what it is?

答:
The output of PRAGMA foreign_key_list() consists of following columns in order -

id, seq, table, from, to, on_update, on_delete, match

So, in the output you got the first two 0s are for id and seq.

Take below example executed in sqlite3 cli with header and column option on -

```<code>CREATE TABLE Test (first INTEGER, second INTEGER, FOREIGN KEY (first) REFERENCES A(a) ON DELETE CASCADE, FOREIGN KEY (second) REFERENCES B(x) ON DELETE CASCADE);
sqlite>
sqlite> PRAGMA foreign_key_list(Test);
id          seq         table       from        to          on_update   on_delete   match
----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------
0           0           B           second      x           NO ACTION   CASCADE     NONE
1           0           A           first       a           NO ACTION   CASCADE     NONE
</code>```

I know the table Test look like a nightmare, but just ignore the horrible schema for a moment.

You can see there are two foreign keys in table Test and so there are two entries shown in PRAGMA foreign_key_list() output. You can see the id fields value are 0 and 1 respectively but the seq values are all 0.

As you may know sqlite allows multiple column names in foreign key statement.
So if you take the next example -

```<code>sqlite> CREATE TABLE Test2 (first INTEGER, second INTEGER, FOREIGN KEY (first, second) REFERENCES A(a, b) ON DELETE CASCADE);
sqlite>
sqlite> PRAGMA foreign_key_list(Test2);
id          seq         table       from        to          on_update   on_delete   match
----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------
0           0           A           first       a           NO ACTION   CASCADE     NONE
0           1           A           second      b           NO ACTION   CASCADE     NONE
</code>```

So, the multiple column key results in multiple rows in the output where id is same as this is actually one key. But the seq value differs as there are multiple columns in the key.

ContentLicense: CC BY-SA 3.0

Body:
Using SQLite3 with the following schema:

CREATE TABLE Customers(ID INTEGER PRIMARY KEY, Company TEXT NOT NULL UNIQUE, Country TEXT NOT NULL, City TEXT NOT NULL);
CREATE TABLE Orders(ID INTEGER PRIMARY KEY, CustomerID INTEGER NOT NULL, FOREIGN KEY(CustomerID) REFERENCES Customers(ID) ON DELETE RESTRICT ON UPDATE RESTRICT);

and issuing this command:

PRAGMA foreign_key_list(Orders);

results in the following output:

0|0|Customers|CustomerID|ID|RESTRICT|RESTRICT|NONE

As the documentation says nothing about the meaning of the output of this pragma, apart from the obvious (Customers - Parent table, CustomerID - Child key, ID - Parent key, RESTRICT - ON DELETE and the second RESTRICT - ON UPDATE) I presume that NONE coresponds to the unsupported MATCH clause.

The thing which I can't figure out by myself is the meaning of the first two zeros. Could someone tell me what it is?

Body:
The output of PRAGMA foreign_key_list() consists of following columns in order -

id, seq, table, from, to, on_update, on_delete, match

So, in the output you got the first two 0s are for id and seq.

Take below example executed in sqlite3 cli with header and column option on -

CREATE TABLE Test (first INTEGER, second INTEGER, FOREIGN KEY (first) REFERENCES A(a) ON DELETE CASCADE, FOREIGN KEY (second) REFERENCES B(x) ON DELETE CASCADE);
sqlite>
sqlite> PRAGMA foreign_key_list(Test);
id          seq         table       from        to          on_update   on_delete   match
----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------
0           0           B           second      x           NO ACTION   CASCADE     NONE
1           0           A           first       a           NO ACTION   CASCADE     NONE

I know the table Test look like a nightmare, but just ignore the horrible schema for a moment.

You can see there are two foreign keys in table Test and so there are two entries shown in PRAGMA foreign_key_list() output. You can see the id fields value are 0 and 1 respectively but the seq values are all 0.

As you may know sqlite allows multiple column names in foreign key statement.
So if you take the next example -

sqlite> CREATE TABLE Test2 (first INTEGER, second INTEGER, FOREIGN KEY (first, second) REFERENCES A(a, b) ON DELETE CASCADE);
sqlite>
sqlite> PRAGMA foreign_key_list(Test2);
id          seq         table       from        to          on_update   on_delete   match
----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------
0           0           A           first       a           NO ACTION   CASCADE     NONE
0           1           A           second      b           NO ACTION   CASCADE     NONE

So, the multiple column key results in multiple rows in the output where id is same as this is actually one key. But the seq value differs as there are multiple columns in the key.


问:
How to delete Image from NSMutableArray and UI in objective C
I am new in iOS and I am facing problem regarding to delete image from mutable array and also from UIImage.

To add an image in array my code is like this:

In connectionDidFinishLoading

```<code>   imageArray =[[NSMutableArray alloc]init];
    for (int i=0; i<idarray.count; i++) {
        [imageArray addObject:[UIImage new]];
    }

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    CGSize newSizeClient=CGSizeMake(200,200); // I am giving resolution 50*50 , you can change your need
    UIGraphicsBeginImageContext(newSizeClient);
    [image drawInRect:CGRectMake(0, 0, newSizeClient.width, newSizeClient.height)];
    UIImage* newImageClient = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    captureimg.image = newImageClient;

    [imageArray replaceObjectAtIndex:index withObject:captureimg.image];

    dispatch_async(dispatch_get_main_queue(), ^{
        [Audittable reloadData];
    });

    NSData *imgData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((newImageClient), 0.5)];
    OCSSignString = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    [picker dismissModalViewControllerAnimated:YES];

    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 30,40,40)];
    UIImage *wonImage = captureimg.image;
    imageView.contentMode=UIViewContentModeCenter;
    [imageView setImage:wonImage];
}

</code>```

In cellForRowAtIndexPath

```<code>cell.CaptureImage.image = [imageArray objectAtIndex:indexPath.row];
</code>```

When deleting I am using code like this

```<code>[imageArray removeObjectAtIndex:index];
</code>```

But it crashes. I am using a custom TableView.

How can I remove image from mutable array?

More code:

CellForrowAtIndexPath

```<code>cell.btnRemove.tag=indexPath.row;
 [cell.btnRemove addTarget:self action:@selector(btnRemoveClick:) forControlEvents:UIControlEventTouchUpInside];
</code>```

On Button Click

```<code>-(void)btnRemoveClick:(UIButton *)sender
{
    AuditNextTableViewCell *cell = sender.superview.superview;
    // NSLog(@"%@",cell.actuallbl.text);

    NSIndexPath *indexPath = [Audittable indexPathForCell:cell];
    CurrentIndexPath=indexPath.row;

    UIAlertView *Alertview =[[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Are You Sure you want to delete Image" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
    CheckStringShow=@"7";
    [Alertview show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
            [imageArray removeObjectAtIndex:CurrentIndexPath];
            [Audittable reloadData];
}
</code>```

It is removing current object only means last added object in array. I want to remove image at current index.

答:
Please confirm below:

Object must be present in your imageArray  of that index.

Use your code [imageArray removeObjectAtIndex:index]; outside the
tableview datasource method.

and last

Reload UITableView [tableView reloadData] after remove object from array.

ContentLicense: CC BY-SA 4.0

Body:
I am new in iOS and I am facing problem regarding to delete image from mutable array and also from UIImage.

To add an image in array my code is like this:

In connectionDidFinishLoading

   imageArray =[[NSMutableArray alloc]init];
    for (int i=0; i<idarray.count; i++) {
        [imageArray addObject:[UIImage new]];
    }

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    CGSize newSizeClient=CGSizeMake(200,200); // I am giving resolution 50*50 , you can change your need
    UIGraphicsBeginImageContext(newSizeClient);
    [image drawInRect:CGRectMake(0, 0, newSizeClient.width, newSizeClient.height)];
    UIImage* newImageClient = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    captureimg.image = newImageClient;

    [imageArray replaceObjectAtIndex:index withObject:captureimg.image];

    dispatch_async(dispatch_get_main_queue(), ^{
        [Audittable reloadData];
    });

    NSData *imgData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((newImageClient), 0.5)];
    OCSSignString = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    [picker dismissModalViewControllerAnimated:YES];

    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 30,40,40)];
    UIImage *wonImage = captureimg.image;
    imageView.contentMode=UIViewContentModeCenter;
    [imageView setImage:wonImage];
}

In cellForRowAtIndexPath

cell.CaptureImage.image = [imageArray objectAtIndex:indexPath.row];

When deleting I am using code like this

[imageArray removeObjectAtIndex:index];

But it crashes. I am using a custom TableView.

How can I remove image from mutable array?

More code:

CellForrowAtIndexPath

cell.btnRemove.tag=indexPath.row;
 [cell.btnRemove addTarget:self action:@selector(btnRemoveClick:) forControlEvents:UIControlEventTouchUpInside];

On Button Click

-(void)btnRemoveClick:(UIButton *)sender
{
    AuditNextTableViewCell *cell = sender.superview.superview;
    // NSLog(@"%@",cell.actuallbl.text);

    NSIndexPath *indexPath = [Audittable indexPathForCell:cell];
    CurrentIndexPath=indexPath.row;

    UIAlertView *Alertview =[[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Are You Sure you want to delete Image" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
    CheckStringShow=@"7";
    [Alertview show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
            [imageArray removeObjectAtIndex:CurrentIndexPath];
            [Audittable reloadData];
}

It is removing current object only means last added object in array. I want to remove image at current index.


问:
Search a particular String in entire Mysql table(All fields)
I am currently working with below query with single field search

```<code>SELECT *
FROM user_college_tbl
WHERE college_name LIKE '%Impulse%';
</code>```

How to Search a particular String in entire table(All fields)?

答:
You could look into using full text search:

```<code>SELECT *
FROM user_college_tbl
WHERE MATCH(col1, col2, ...) AGAINST ('Impulse' IN NATURAL LANGUAGE MODE)
</code>```

This would assume that you had full text indices setup on all the text columns you wanted to be included in the search:

```<code>CREATE TABLE user_college_tbl (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    college_name VARCHAR(200),
    col1 TEXT,
    col2 TEXT,
    -- ... more text columns
    FULLTEXT(college_name, col1, col2, ...)
) ENGINE=InnoDB;
</code>```

If you are using a version of MySQL earlier than 5.6 or you don't want full text search, then you may be limited to ORing together LIKE expressions for each text column in the table, e.g.

```<code>SELECT *
FROM user_college_tbl
WHERE college_name LIKE '%Impulse%' OR
      col1 LIKE '%Impulse%' OR
      col2 LIKE '%Impulse%'
</code>```

Body:
I am currently working with below query with single field search

SELECT *
FROM user_college_tbl
WHERE college_name LIKE '%Impulse%';

How to Search a particular String in entire table(All fields)?

Body:
You could look into using full text search:

SELECT *
FROM user_college_tbl
WHERE MATCH(col1, col2, ...) AGAINST ('Impulse' IN NATURAL LANGUAGE MODE)

This would assume that you had full text indices setup on all the text columns you wanted to be included in the search:

CREATE TABLE user_college_tbl (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    college_name VARCHAR(200),
    col1 TEXT,
    col2 TEXT,
    -- ... more text columns
    FULLTEXT(college_name, col1, col2, ...)
) ENGINE=InnoDB;

If you are using a version of MySQL earlier than 5.6 or you don't want full text search, then you may be limited to ORing together LIKE expressions for each text column in the table, e.g.

SELECT *
FROM user_college_tbl
WHERE college_name LIKE '%Impulse%' OR
      col1 LIKE '%Impulse%' OR
      col2 LIKE '%Impulse%'


问:
Convert List<MyDTO> to List<Map<String,String>> using Gson
I have DTO as below :

```<code>     public class MyDTO {
           private String MEValueName;
           private String MyId;

          // getters and setters

     }

     Gson gson = new Gson();
     List<MyDTO> list = new ArrayList<MyDTO>();
     MyDTO dto = new MyDTO();

     dto.setMEValueName("raghu");
     dto.setMyId("qwer");

     MyDTO dto1 = new MyDTO();

     dto1.setMEValueName("raghuveer");
     dto1.setMyId("qwer1");

     list.add(dto);
     list.add(dto1);

     String json = gson.toJson(list);
     System.out.println(json);

     // below line is failing
     List<Map<String, String>> list1 = gson.fromJson(json, new TypeToken<List<Map<String, String>>>(){}.getType());
     System.out.println(list1);
</code>```

when i run this i get the follow error :

java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 11 path $[0].

Also i want to use a generic type so that i can use other DTOs also to convert to list of map. Kindly suggest.

答:
I see two immediate problems...
The json-string is of an object of type List<MyDTO>.
gson.fromJson must have a TypeToken of that same object type.
And even if the fromJson worked, you cant assign List<MyDTO> to a list of type List<Map<String,String>>.

Edit (doing this by memory so it might need some fine tuning to compile):

```<code>List<Map<String, String>> list1 = new List();
Map<String,String> map = new HashMap<>();
list1.add(map);
map.add("some key",json);
</code>```

Body:
I have DTO as below :

     public class MyDTO {
           private String MEValueName;
           private String MyId;

          // getters and setters

     }

     Gson gson = new Gson();
     List<MyDTO> list = new ArrayList<MyDTO>();
     MyDTO dto = new MyDTO();

     dto.setMEValueName("raghu");
     dto.setMyId("qwer");

     MyDTO dto1 = new MyDTO();

     dto1.setMEValueName("raghuveer");
     dto1.setMyId("qwer1");

     list.add(dto);
     list.add(dto1);

     String json = gson.toJson(list);
     System.out.println(json);

     // below line is failing
     List<Map<String, String>> list1 = gson.fromJson(json, new TypeToken<List<Map<String, String>>>(){}.getType());
     System.out.println(list1);

when i run this i get the follow error :

java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 11 path $[0].

Also i want to use a generic type so that i can use other DTOs also to convert to list of map. Kindly suggest.

Body:
I see two immediate problems...
The json-string is of an object of type List<MyDTO>.
gson.fromJson must have a TypeToken of that same object type.
And even if the fromJson worked, you cant assign List<MyDTO> to a list of type List<Map<String,String>>.

Edit (doing this by memory so it might need some fine tuning to compile):

List<Map<String, String>> list1 = new List();
Map<String,String> map = new HashMap<>();
list1.add(map);
map.add("some key",json);


问:
Android - Prevent white screen at startup
As we all know, many Android apps display a white screen very briefly before their first Activity comes into focus. This problem is observed in the following cases:

Android apps that extend the global Application class and
perform major initializations therein. The Application
object is always created before the first Activity (a fact that can
be observed in the debugger), so this makes sense. This is the cause of the delay in my case.

Android apps that display the default preview window before the splash screen.

Setting android:windowDisablePreview = "true" obviously does not work here. Nor can I set the parent theme of the splash screen to Theme.Holo.NoActionBar as described here, because [unfortunately] my splash screen makes use of an ActionBar.

Meanwhile, apps that do not extend the Application class do not show the white screen at startup.

The thing is, ideally the initializations performed in the Application object need to occur before the first Activity is shown. So my question is, how can I perform these initializations on app startup without using an Application object? Possibly using a Thread or Service, I suppose?

This is an interesting problem to think about. I can't bypass it the usual way (by setting the NoActionBar theme), as tragically my Splash screen actually has an ActionBar due to some unrelated reasons.

Note:

I have already referred to the following questions:

How To fix white screen on app Start
up?

Android splash screen is white in the
beginning?

White screen before
splashscreen

White background when Android app start up

Why there is a white screen appears for 1sec when starting to run the apps in Android?

References:

Patterns – Launch screens.

Branded launch screen: the new splash for Android.

Splash Screens the Right Way.

答:
I had same issue, you have to update your style.

style.xml

```<code><!-- Base application theme. -->
 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <!-- Customize your theme here. -->
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowDisablePreview">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="android:windowIsTranslucent">true</item>

 </style>
</code>```

Your manifest file should looks like below.

```<code><application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
     // Other stuff
</application>
</code>```

Outout:

Hope this would help you.

Body:
I had same issue, you have to update your style.

style.xml

<!-- Base application theme. -->
 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <!-- Customize your theme here. -->
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowDisablePreview">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="android:windowIsTranslucent">true</item>

 </style>

Your manifest file should looks like below.

<application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
     // Other stuff
</application>

Outout:

Hope this would help you.


问:
Show/Hide input field inside appended element
I have the following JS/jQuery code to append rows to an existing table. Upon appending, I want to show the input field only when "select" or "radio" is selected as the option type.

When I add multiple rows, the input field appearance/disappearance is dependent upon the first added row. I want it to show/hide only on the row(s) where any of the two options are selected.

Hope that made sense. Any suggestion would be helpful. Thanks!

HTML:

```<code><table id="tbl-formfields" class="table vertical-align table-condensed" >
    <thead>
        <tr>
            <th>Input Type</th>
            <th>Make Required</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody id="tbody">
        <tr id="tr-formField">
            <td>
                <div>
                    <select name="formOptionType[]" id="formOptionType">
                        <option value="">-------------------------------------</option>
                        <option value="text">Text</option>
                        <option value="textarea">Textarea</option>
                        <option value="select">Select Options (Dropdown)</option>
                        <option value="radio">Radio Buttons</option>
                        <option value="checkbox">Checkbox</option>
                    </select>
                </div>
                <div id="block-optionsInput" style="display:none">
                    <label>Options:</label><br>
                    <input id="options" type="text" name="fieldOptions[]" data-role="tagsinput"/>
                </div>
            </td>
            <td>
                <label><input type="checkbox" name="fieldRequired[]"/> Required</label>
            </td>
            <td></td>
        </tr>
    </tbody>
</table>
</code>```

jQuery:

```<code>    //****Repeat form field block****
    var repeatBlock = "#tbody";
    var repeatText = '<tr class="trRepeat">\n\
        <td>\n\
            <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\
            <div class="optBlock" style="display:none">\n\
                <label>Options:</label><br>\n\
                <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\
            </div>\n\
        </td>\n\
        <td><label><input type="checkbox" name="fieldRequired[]"/> Required</label></td>\n\
        <td><a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">\n\
            <span class="glyphicon glyphicon-remove"></span></a>\n\
        </td></tr>';

    $("#btn-addfield").click(function (e) {
        e.preventDefault();
        $(repeatBlock).append(repeatText);
    });
    $(repeatBlock).on('click', '.removeField', function (e) {
        e.preventDefault();
        $(this).parent().parent().remove();
    });

    //****Show input field when dropdown/radio is selected****
    $(repeatBlock).on('change', $(".optType").val(), function (e) {
        e.preventDefault();
        if ($(this).find(".optType").val() === "radio" || $(this).find(".optType").val() === "select") {
            $(this).find(".optBlock").show();
            $(".optInput").tagsinput('refresh');
        } else {
            $(this).find(".optBlock").hide();
        }
    });
</code>```

答:
Wrap all your input in td inside a otpBlock

```<code> <tr class="trRepeat">
  <td>
    <select class="optType" name="formOptionType[]">
                    <option value="">-------------------------------------</option>
                    <option value="text">Text</option>
                    <option value="textarea">Textarea</option>
                    <option value="select">Select Options (Dropdown)</option>
                    <option value="radio">Radio Buttons</option>
                    <option value="checkbox">Checkbox</option>
                </select>
    <div class="optBlock" style="display:none">
      <label>Options:</label><br>
      <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput" />
    </div>
  </td>
  <td>
    <div class="optBlock" style="display:none">
      <label><input type="checkbox" name="fieldRequired[]"/> Required</label>
     </div>
  </td>
  <td>
    <div>
      <a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">
        <span class="glyphicon glyphicon-remove"></span>Remove</a>
    </div>
  </td>
</tr>
</code>```

Use the following JS

```<code>//****Show input field when dropdown/radio is selected****
$(repeatBlock).on('change', ".optType", function(e) {
  e.preventDefault();
  var type = $(this).val();   //Fetch the input type
  var container = $(this).closest('tr'); // Get the closest container
  container.find('.optBlock').hide(); // Hide all optBlock
  container.find('input').filter('[type=' + type + ']').closest('.optBlock').show(); // Show optBlock containing input of type.
});
</code>```

To Remove

```<code>$(repeatBlock).on('click', '.removeField', function(e) {
  e.preventDefault();
  $(this).closest('tr').remove(); // select the closest tr
});
</code>```

SNIPPET

var repeatBlock = "#tbody";
var repeatText = '
\n\
  \n\
    <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\

\n\
      Options:
\n\
      <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput" />\n\

\n\
  	\n\
  \n\

\n\
  <input type="checkbox" name="fieldRequired[]"/> Required
	\n\

\n\
            Remove\n\

	\

';

$("#btn-addfield").click(function(e) {
  e.preventDefault();
  $(repeatBlock).append($(repeatText));
});
$(repeatBlock).on('click', '.removeField', function(e) {
  e.preventDefault();
  $(this).closest('tr').remove();
});

//****Show input field when dropdown/radio is selected****
$(repeatBlock).on('change', ".optType", function(e) {
  e.preventDefault();
  var type = $(this).val();
  var container = $(this).closest('tr');
  container.find('.optBlock').hide();
  container.find('input').filter('[type=' + type + ']').closest('.optBlock').show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody id="tbody"></tbody>
</table>
<button id="btn-addfield">ADD</button></code>```

Body:
I have the following JS/jQuery code to append rows to an existing table. Upon appending, I want to show the input field only when "select" or "radio" is selected as the option type.

When I add multiple rows, the input field appearance/disappearance is dependent upon the first added row. I want it to show/hide only on the row(s) where any of the two options are selected.

Hope that made sense. Any suggestion would be helpful. Thanks!

HTML:

            Input Type
            Make Required
            Action

                    <select name="formOptionType[]" id="formOptionType">
                        <option value="">-------------------------------------</option>
                        <option value="text">Text</option>
                        <option value="textarea">Textarea</option>
                        <option value="select">Select Options (Dropdown)</option>
                        <option value="radio">Radio Buttons</option>
                        <option value="checkbox">Checkbox</option>
                    </select>

                    Options:

                    <input id="options" type="text" name="fieldOptions[]" data-role="tagsinput"/>

                <input type="checkbox" name="fieldRequired[]"/> Required

jQuery:

    //****Repeat form field block****
    var repeatBlock = "#tbody";
    var repeatText = '
\n\
        \n\
            <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\

\n\
                Options:
\n\
                <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput"/>\n\

\n\
        	\n\
        <input type="checkbox" name="fieldRequired[]"/> Required	\n\
        \n\
            \n\

';

    $("#btn-addfield").click(function (e) {
        e.preventDefault();
        $(repeatBlock).append(repeatText);
    });
    $(repeatBlock).on('click', '.removeField', function (e) {
        e.preventDefault();
        $(this).parent().parent().remove();
    });

    //****Show input field when dropdown/radio is selected****
    $(repeatBlock).on('change', $(".optType").val(), function (e) {
        e.preventDefault();
        if ($(this).find(".optType").val() === "radio" || $(this).find(".optType").val() === "select") {
            $(this).find(".optBlock").show();
            $(".optInput").tagsinput('refresh');
        } else {
            $(this).find(".optBlock").hide();
        }
    });

Body:
Wrap all your input in td inside a otpBlock

 <tr class="trRepeat">
  <td>
    <select class="optType" name="formOptionType[]">
                    <option value="">-------------------------------------</option>
                    <option value="text">Text</option>
                    <option value="textarea">Textarea</option>
                    <option value="select">Select Options (Dropdown)</option>
                    <option value="radio">Radio Buttons</option>
                    <option value="checkbox">Checkbox</option>
                </select>
    <div class="optBlock" style="display:none">
      <label>Options:</label><br>
      <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput" />
    </div>
  </td>
  <td>
    <div class="optBlock" style="display:none">
      <label><input type="checkbox" name="fieldRequired[]"/> Required</label>
     </div>
  </td>
  <td>
    <div>
      <a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">
        <span class="glyphicon glyphicon-remove"></span>Remove</a>
    </div>
  </td>
</tr>

Use the following JS

//****Show input field when dropdown/radio is selected****
$(repeatBlock).on('change', ".optType", function(e) {
  e.preventDefault();
  var type = $(this).val();   //Fetch the input type
  var container = $(this).closest('tr'); // Get the closest container
  container.find('.optBlock').hide(); // Hide all optBlock
  container.find('input').filter('[type=' + type + ']').closest('.optBlock').show(); // Show optBlock containing input of type.
});

To Remove

$(repeatBlock).on('click', '.removeField', function(e) {
  e.preventDefault();
  $(this).closest('tr').remove(); // select the closest tr
});

SNIPPET

var repeatBlock = "#tbody";
var repeatText = '<tr class="trRepeat">\n\
  <td>\n\
    <select class="optType" name="formOptionType[]">\n\
                <option value="">-------------------------------------</option>\n\
                <option value="text">Text</option>\n\
                <option value="textarea">Textarea</option>\n\
                <option value="select">Select Options (Dropdown)</option>\n\
                <option value="radio">Radio Buttons</option>\n\
                <option value="checkbox">Checkbox</option>\n\
            </select>\n\
    <div class="optBlock" style="display:none">\n\
      <label>Options:</label><br>\n\
      <input class="optInput" type="text" name="fieldOptions[]" data-role="tagsinput" />\n\
    </div>\n\
  </td>\n\
  <td>\n\
   <div class="optBlock" style="display:none">\n\
  <label><input type="checkbox" name="fieldRequired[]"/> Required</label></div></td>\n\
  <td><div class=""><a href="javascript:void(0)" class="removeField" style="color:red" title="Remove this field">\n\
            <span class="glyphicon glyphicon-remove"></span>Remove</a>\n\
  </div></td>\
</tr>';

$("#btn-addfield").click(function(e) {
  e.preventDefault();
  $(repeatBlock).append($(repeatText));
});
$(repeatBlock).on('click', '.removeField', function(e) {
  e.preventDefault();
  $(this).closest('tr').remove();
});

//****Show input field when dropdown/radio is selected****
$(repeatBlock).on('change', ".optType", function(e) {
  e.preventDefault();
  var type = $(this).val();
  var container = $(this).closest('tr');
  container.find('.optBlock').hide();
  container.find('input').filter('[type=' + type + ']').closest('.optBlock').show();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody id="tbody"></tbody>
</table>
<button id="btn-addfield">ADD</button>


问:
Dynamically selecting map Ecto
I have so far created the query:

```<code>query = from page in "wagtailcore_page",
      where: page.url_path == ^url_path,
      join: h in ^table_name,
      where: h.page_ptr_id == page.id
</code>```

I now would like to dynamically select properties on h

For example if I pass in [:body, :footer] I would like to run:

```<code>query = from [_page, h] in query,
      select: %{body: h.body, footer: h.footer}
</code>```

I found Ecto.Query.API.map which looks like it could be used in the solution to this problem.

But when I run:

```<code>from [_page, h] in query, select: EctoApi.map(h, [:body])
</code>```

I get the error:

```<code>** (Ecto.Query.CompileError) `EctoApi.map(h, [:alphatext])` is not a valid query expression
</code>```

According to the IMPORTANT message at the bottom of the map documentation we have to include the foreign keys used in the relationship when performing the join which we are not doing, but I don't know how to do this type of assoc for the type of dynamic join which we are doing

答:
map can be used without importing anything. The actual function is implemented inside Ecto, Ecto.Query.API.map/2 is just for documentation purposes. The following should work:

```<code>from [_page, h] in query, select: map(h, [:body, :footer])
</code>```

Title: Dynamically selecting map Ecto

Body:
I have so far created the query:

query = from page in "wagtailcore_page",
      where: page.url_path == ^url_path,
      join: h in ^table_name,
      where: h.page_ptr_id == page.id

I now would like to dynamically select properties on h

For example if I pass in [:body, :footer] I would like to run:

query = from [_page, h] in query,
      select: %{body: h.body, footer: h.footer}

I found Ecto.Query.API.map which looks like it could be used in the solution to this problem.

But when I run:

from [_page, h] in query, select: EctoApi.map(h, [:body])

I get the error:

** (Ecto.Query.CompileError) `EctoApi.map(h, [:alphatext])` is not a valid query expression

According to the IMPORTANT message at the bottom of the map documentation we have to include the foreign keys used in the relationship when performing the join which we are not doing, but I don't know how to do this type of assoc for the type of dynamic join which we are doing

Body:
map can be used without importing anything. The actual function is implemented inside Ecto, Ecto.Query.API.map/2 is just for documentation purposes. The following should work:

from [_page, h] in query, select: map(h, [:body, :footer])


问:
How to remove project in PyCharm?
If I'm closing a project and then just delete the project folder, after PyCharm restarts an empty project folder is created again.</p>

答:
Version 2017.2.1

Press Alt+1 to bring the project pane, and make sure you're in
Project view (not Project Files view).

Select the desired project, and choose "Delete from project
view" from the context menu (right click). You can also use Delete
key.

Title: How to remove project in PyCharm?


问:
How to use ng-repeat and filter to hide some columns in a dynamic table?
I have a dynamic data set returned from a database for which I am trying to create a generic table that can always list it, no matter the number of columns or rows.

It works fine but the problem I am having is that I want to be able to hide some columns, like the ID for example.

This is how the data looks like:

```<code>scope.columns = [
    {
        'Name': 'ID',
        Visible: false,
    },
    {
        'Name': 'Name',
        Visible: true,
    },
    {
        'Name': 'Description',
        Visible: true,
    },
];

scope.rows = [
    {
        ID: 1, // should be hidden because ID column above is set to Visible - false
        Name: 'Test',
        Description: 'Its a test',
    },
    {
        ID: 2, // should be hidden because ID column above is set to Visible - false
        Name: 'Test 2',
        Description: 'Its a test 2',
    }
];
</code>```

And this is HTML for the table generation:

```<code><table class="table">
    <!-- This part works fine and doesn't show some of the columns -->
    <tr>
        <th ng-repeat="column in columns | filter: { Visible: 'true'}">
            <span ng-bind="column.Name"></span>
        </th>
    </tr>
    <tr ng-repeat="row in rows">
        <td ng-repeat="col in row"> <!-- This is the part where I need filter the cols based on the column.Visible above -->
            {{col}}
        </td>
    </tr>
</table>
</code>```

I tried adding a filter on the  but I am not sure how to filter based on the scope.columns array.

答:
You could do it with ng-if -> ng-if="columns[$index].Visible" in your case like in this DEMO FIDDLE. Your attribute order  in $scope.rows must be the same as in $scope.columns to ensure it is working correct.

```<code><div ng-controller="MyCtrl">
  <table class="table">
    <!-- This part works fine and doesn't show some of the columns -->
    <tr>
      <th ng-repeat="column in columns | filter: { Visible: true}">
        <span ng-bind="column.Name"></span>
      </th>
    </tr>
    <tr ng-repeat="row in rows">
      <td ng-repeat="col in row" ng-if="columns[$index].Visible">
        {{col}}
      </td>
    </tr>
  </table>
</div>
</code>```

Body:
I have a dynamic data set returned from a database for which I am trying to create a generic table that can always list it, no matter the number of columns or rows.

It works fine but the problem I am having is that I want to be able to hide some columns, like the ID for example.

This is how the data looks like:

scope.columns = [
    {
        'Name': 'ID',
        Visible: false,
    },
    {
        'Name': 'Name',
        Visible: true,
    },
    {
        'Name': 'Description',
        Visible: true,
    },
];

scope.rows = [
    {
        ID: 1, // should be hidden because ID column above is set to Visible - false
        Name: 'Test',
        Description: 'Its a test',
    },
    {
        ID: 2, // should be hidden because ID column above is set to Visible - false
        Name: 'Test 2',
        Description: 'Its a test 2',
    }
];

And this is HTML for the table generation:

            {{col}}

I tried adding a filter on the  but I am not sure how to filter based on the scope.columns array.

Body:
You could do it with ng-if -> ng-if="columns[$index].Visible" in your case like in this DEMO FIDDLE. Your attribute order  in $scope.rows must be the same as in $scope.columns to ensure it is working correct.

<div ng-controller="MyCtrl">
  <table class="table">
    <!-- This part works fine and doesn't show some of the columns -->
    <tr>
      <th ng-repeat="column in columns | filter: { Visible: true}">
        <span ng-bind="column.Name"></span>
      </th>
    </tr>
    <tr ng-repeat="row in rows">
      <td ng-repeat="col in row" ng-if="columns[$index].Visible">
        {{col}}
      </td>
    </tr>
  </table>
</div>


问:
Count digits for -1 return 12 instead of 32
For the following simple function to calculate the number of 1 in a 32-bit integer, it is expected to return 32 for input -1, but got 12 instead.

```<code>class Solution:
    def bitNum(self, n):
        bm = {
            0:0, 1:1, 2:1, 3:2, 4:1, 5:2, 6:2, 7:3,
            8:1, 9:2, 10:2, 11:3, 12:2, 13:3, 14:3,
            15:4
            }
        return bm[n & 0xF] + bm[(n>>4) & 0xF] + bm[(n>>8) & 0xF]
        + bm[(n>>12) & 0xF] + bm[(n>>16) & 0xF] + bm[(n>>20) & 0xF]
        + bm[(n>>24) & 0xF] + bm[(n>>28) & 0xF]
</code>```

But if a var is used to store the result, and split plus to several parts, the correct answer will be returned. Why?

```<code>class Solution:
    def bitNum(self, n):
        bm = {
            0:0, 1:1, 2:1, 3:2, 4:1, 5:2, 6:2, 7:3,
            8:1, 9:2, 10:2, 11:3, 12:2, 13:3, 14:3,
            15:4
            }
        bits =  bm[n & 0xF]
        bits += bm[(n>>4) & 0xF] + bm[(n>>8) & 0xF]
        bits += bm[(n>>12) & 0xF] + bm[(n>>16) & 0xF] + bm[(n>>20) & 0xF]
        bits += bm[(n>>24) & 0xF] + bm[(n>>28) & 0xF]
        return bits
</code>```

答:
may be to surround all into '(' and ')'? :)
Or to use backslash at line end:</p>

```<code>return (a + b
+ c + d)
</code>```

Body:
For the following simple function to calculate the number of 1 in a 32-bit integer, it is expected to return 32 for input -1, but got 12 instead.

class Solution:
    def bitNum(self, n):
        bm = {
            0:0, 1:1, 2:1, 3:2, 4:1, 5:2, 6:2, 7:3,
            8:1, 9:2, 10:2, 11:3, 12:2, 13:3, 14:3,
            15:4
            }
        return bm[n & 0xF] + bm[(n>>4) & 0xF] + bm[(n>>8) & 0xF]
        + bm[(n>>12) & 0xF] + bm[(n>>16) & 0xF] + bm[(n>>20) & 0xF]
        + bm[(n>>24) & 0xF] + bm[(n>>28) & 0xF]

But if a var is used to store the result, and split plus to several parts, the correct answer will be returned. Why?

class Solution:
    def bitNum(self, n):
        bm = {
            0:0, 1:1, 2:1, 3:2, 4:1, 5:2, 6:2, 7:3,
            8:1, 9:2, 10:2, 11:3, 12:2, 13:3, 14:3,
            15:4
            }
        bits =  bm[n & 0xF]
        bits += bm[(n>>4) & 0xF] + bm[(n>>8) & 0xF]
        bits += bm[(n>>12) & 0xF] + bm[(n>>16) & 0xF] + bm[(n>>20) & 0xF]
        bits += bm[(n>>24) & 0xF] + bm[(n>>28) & 0xF]
        return bits

Body:
may be to surround all into '(' and ')'? :)
Or to use backslash at line end:

return (a + b
+ c + d)


问:
Notepad 2 insert character after regular expression search
I am having an issue with trying to figure out how to insert some text after I perform a regex search. I know there is a replace function, but I am not looking for that option, just inserting. The text editor I am using is Notepad2, but I am willing to try this in other text editors.

Here is the example that I have.

```<code>TEST|Test2|Test3|Test4
</code>```

This is what I am looking for

```<code>Test|Test2|PrefixTest3|Test4
</code>```

Notice that I am trying to insert the the phrase "Prefix" after the 2nd pipe and leave everything else alone.

I can successfully query the result by using this regex:

```<code>^[^|]*\|[^|]*|
</code>```

But then I do not know how I can retain everything prior and after the search point. Any ideas?

答:
You may easily do that in Notepad2 using the regex-based Replace feature.

Find:       ^\([^|]*|[^|]*|\)

Replace: \1Prefix

Details:

^ - start of a line (Notepad2 never overflows line boundaries!)

\([^|]*|[^|]*|\) - Capturing group 1 matching a sequence of:

[^|]* - zero or more chars other than |

| - a literal (yes, no escaping is necessary, both escaped and unescaped | match a literal |) pipe symbol

[^|]*| - see above, gets to the second |.

The replacement contains a \1 backreference that inserts what was captured with the capturing group 1.

NOTE that Notepad2 regex engine is very limited. Here is what the Notepad2 documentation says:

Notepad2 supports only a limited subset of regular expressions, as provided by built-in engine of the Scintilla source code editing component. The advantage is that it has a very small footprint. There's currently no plans to integrate a more advanced regular expressions engine, but this may be an option for future development.

Note: Regular expression search is limited to single lines, only.

Also, you may refer to the inline comments inside Scintilla RESearch.cxx file describing the supported syntax. Bear in mind that the regex type used in the Notepad2 S&R tool is that of POSIX and not all of the described Scintilla regex features will work in the tool.

Note that Notepad2 does not seem to support alternation and limiting quantifiers (similar to Lua patterns), but \w matches Unicode letters together with ASCII ones. Sadly, I could not make ? quantifier work.

Body:
I am having an issue with trying to figure out how to insert some text after I perform a regex search. I know there is a replace function, but I am not looking for that option, just inserting. The text editor I am using is Notepad2, but I am willing to try this in other text editors.

Here is the example that I have.

TEST|Test2|Test3|Test4

This is what I am looking for

Test|Test2|PrefixTest3|Test4

Notice that I am trying to insert the the phrase "Prefix" after the 2nd pipe and leave everything else alone.

I can successfully query the result by using this regex:

^[^|]*\|[^|]*|

But then I do not know how I can retain everything prior and after the search point. Any ideas?


问:
Is it OK to retrieve cellular location when location setting is OFF?
On Android, we can retrieve CellLocation using this API

This API requires location(Coarse or Fine) permission to be granted.

We observed that API returns valid CellLocation even if global location-setting is OFF.  Ideally, it should not give cell-location when location-setting is OFF.

Is the current API behavior intentional? Is it a bug in Android? Is it OK to access CellularLocation even if location setting is OFF?

答:
There are two separate systems here:

App permissions

User toggles

If an app received the Location permission, it's allowed to use the API to get location whenever and however is wants (you should obviously take battery and data usage in consideration, but that's up to you).

If a certain settings toggle is switched on or off by the user, it's up to the API to turn off certain features from apps, it's not the app's responsibility to check system settings whenever it wants to use an API.

In your case the location setting can be toggled by the user to prevent usage of the GPS component to prevent accurate location tracking and to save battery.
This does not apply to cell-tower location as it's definitely not accurate and the data already exists on the phone so no battery power is needed either.
Android may in the future turn off cell-tower location when this setting is off, but until then you're allowed to use whatever the API gives you.


问:
How do I change the file creation date of a Windows file?
How do I change the file creation date of a Windows file from Python?</p>

答:
install pywin32 extension first https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/

```<code>import win32file
import pywintypes

# main logic function
def changeFileCreateTime(path, ctime):
    # path: your file path
    # ctime: Unix timestamp

    # open file and get the handle of file
    # API: http://timgolden.me.uk/pywin32-docs/win32file__CreateFile_meth.html
    handle = win32file.CreateFile(
        path,                          # file path
        win32file.GENERIC_WRITE,       # must opened with GENERIC_WRITE access
        0,
        None,
        win32file.OPEN_EXISTING,
        0,
        0
    )

    # create a PyTime object
    # API: http://timgolden.me.uk/pywin32-docs/pywintypes__Time_meth.html
    PyTime = pywintypes.Time(ctime)

    # reset the create time of file
    # API: http://timgolden.me.uk/pywin32-docs/win32file__SetFileTime_meth.html
    win32file.SetFileTime(
        handle,
        PyTime
    )

# example
changeFileCreateTime('C:/Users/percy/Desktop/1.txt',1234567789)
</code>```

Body:
install pywin32 extension first https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/

import win32file
import pywintypes

# main logic function
def changeFileCreateTime(path, ctime):
    # path: your file path
    # ctime: Unix timestamp

    # open file and get the handle of file
    # API: http://timgolden.me.uk/pywin32-docs/win32file__CreateFile_meth.html
    handle = win32file.CreateFile(
        path,                          # file path
        win32file.GENERIC_WRITE,       # must opened with GENERIC_WRITE access
        0,
        None,
        win32file.OPEN_EXISTING,
        0,
        0
    )

    # create a PyTime object
    # API: http://timgolden.me.uk/pywin32-docs/pywintypes__Time_meth.html
    PyTime = pywintypes.Time(ctime)

    # reset the create time of file
    # API: http://timgolden.me.uk/pywin32-docs/win32file__SetFileTime_meth.html
    win32file.SetFileTime(
        handle,
        PyTime
    )

# example
changeFileCreateTime('C:/Users/percy/Desktop/1.txt',1234567789)


问:
Edited CSS isn't overwriting original theme CSS
I am adding custom CSS to a wordpress theme (www.ronanmart.in) to get the effect I want.

For the .hero-inner div on the homepage, I am trying to edit the padding however it seems to keep defaulting to the theme settings. Anything else I've edited has overwritten the theme CSS.

Original padding:

```<code>padding: 121px 2em;
</code>```

New padding:

```<code>padding: 261px 2em 0 2em;
</code>```

Is there something I'm missing?

答:
Make sure you write a more specific CSS rule:

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

  source: https://developer.mozilla.org/en/docs/Web/CSS/Specificity

For a quick test you can use !important first to see the rules are matching. If the element is styled expected you should remove !important and try to write a more specific rule.

```<code>.class-name {
    padding: 261px 2em 0 2em !important;
}

/* the same rule, more specific */
div .parent-class .class-name {
    padding: 261px 2em 0 2em;
}
</code>```

Note: You should avoid using !important!

Body:
I am adding custom CSS to a wordpress theme (www.ronanmart.in) to get the effect I want.

For the .hero-inner div on the homepage, I am trying to edit the padding however it seems to keep defaulting to the theme settings. Anything else I've edited has overwritten the theme CSS.

Original padding:

padding: 121px 2em;

New padding:

padding: 261px 2em 0 2em;

Is there something I'm missing?

Body:
Make sure you write a more specific CSS rule:

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

  source: https://developer.mozilla.org/en/docs/Web/CSS/Specificity

For a quick test you can use !important first to see the rules are matching. If the element is styled expected you should remove !important and try to write a more specific rule.

.class-name {
    padding: 261px 2em 0 2em !important;
}

/* the same rule, more specific */
div .parent-class .class-name {
    padding: 261px 2em 0 2em;
}

Note: You should avoid using !important!


问:
how to restart horizontal progressbar
I've a horizontal progressbar which shows progress from 0 to 100. What I want is to restart the progressbar again from 0 when it reaches 100. I'll be showing this in a Fragmentdialog. For now I'm checking it in activity itself. How to do that?</p>

```<code>    public class MainActivity extends AppCompatActivity{
    private Button startbtn, stopbtn;
    ProgressBar pb;
    private TextView progressTxt;

    int progressBarValue = 0;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        show = new CShowProgress(MainActivity.this);

        btn = (Button)findViewById(R.id.btn);
        startbtn = (Button)findViewById(R.id.startbtn);
        stopbtn = (Button)findViewById(R.id.stopbtn);
        pb = (ProgressBar)findViewById(R.id.progressBar);
        progressTxt = (TextView)findViewById(R.id.progressTxt);

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(true);
            }
        });

        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(false);
            }
        });
    }

    private void myprogress(final Boolean isStart){
        handler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                if(isStart && progressBarValue<100)
                {
                    progressBarValue+=1;
                    pb.setProgress(progressBarValue);
                    progressTxt.setText(String.valueOf(progressBarValue));

                    handler.sendEmptyMessageDelayed(0, 100);
                }

            }
        };

        handler.sendEmptyMessage(0);
    }
}
</code>```

答:
First, you should use a counter mechanizm (run a delayed handler, timer, thread or something else)to check current progress periodically.

```<code> (progressTxt.getProgress == 100)
</code>```

will do the trick.

Another way is using this answer.

Title: how to restart horizontal progressbar

Body:
I've a horizontal progressbar which shows progress from 0 to 100. What I want is to restart the progressbar again from 0 when it reaches 100. I'll be showing this in a Fragmentdialog. For now I'm checking it in activity itself. How to do that?

    public class MainActivity extends AppCompatActivity{
    private Button startbtn, stopbtn;
    ProgressBar pb;
    private TextView progressTxt;

    int progressBarValue = 0;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        show = new CShowProgress(MainActivity.this);

        btn = (Button)findViewById(R.id.btn);
        startbtn = (Button)findViewById(R.id.startbtn);
        stopbtn = (Button)findViewById(R.id.stopbtn);
        pb = (ProgressBar)findViewById(R.id.progressBar);
        progressTxt = (TextView)findViewById(R.id.progressTxt);

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(true);
            }
        });

        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(false);
            }
        });
    }

    private void myprogress(final Boolean isStart){
        handler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                if(isStart && progressBarValue<100)
                {
                    progressBarValue+=1;
                    pb.setProgress(progressBarValue);
                    progressTxt.setText(String.valueOf(progressBarValue));

                    handler.sendEmptyMessageDelayed(0, 100);
                }

            }
        };

        handler.sendEmptyMessage(0);
    }
}

Body:
First, you should use a counter mechanizm (run a delayed handler, timer, thread or something else)to check current progress periodically.

 (progressTxt.getProgress == 100)

will do the trick.

Another way is using this answer.


问:
App engine use symmetric password
I want to use Aes to encrypt some data and decrypt them later. I created a jks keystore, the problem is where to read the keystore and keys password. Putting the master password in the code seems not really secure. Same thing if I put in the properties file or environment variable. I could use jasypt library to keep encrypted the master password in the properties but again I need another password and the problem again where to store it. What is the best way or guidelines in these cases? I can't use a command line input neither a command line parameter.

Another question: if I keep my keys into the Google memcache, is it secure?

答:
Check Vault project.

I don't recommend you to use Google Memcache for such things. It's pretty similar to situation, when you store your master key in database or file. However, you decide, what level of security for data you need. Sometimes, properties file is enough.

Title: App engine use symmetric password


问:
Exiting a procedure
I have some very simple code, but I cannot figure this out. I'm calling a procedure that will (hopefully) exit the process. But it doesn't exactly do that:

```<code>procedure quit;
begin
    exit;
end;
</code>```

And here's where i'm calling it:

If (Ch2 = #13) and (Bar2 = 5) and (Five) Then Quit;

Bar2 is basically a byte variable that holds an array with different elements, like "display", "help", "next" and "prev", and of course, quit, Which all have their own code based on what they do.
Ch2 is a variable for ReadKey that takes in various key presses, and then allows it to do whatever is defined for that specfic command. In this case, it requires that the return key is used.
Five is a boolean operator, and is there as a prerequisite to run the quit command. I guess it isn't really necessary.

BTW, if it helps, this is a unit, not a standalone program.

Anyone know why this exit command isn't working? Hopefully this post is verbose enough.

Thank you.

答:
The exit statement exits from the function or procedure in which it is found. It then returns execution to the calling function or procedure.

To terminate the process use halt.

Title: Exiting a procedure

Body:
I have some very simple code, but I cannot figure this out. I'm calling a procedure that will (hopefully) exit the process. But it doesn't exactly do that:

procedure quit;
begin
    exit;
end;

And here's where i'm calling it:

If (Ch2 = #13) and (Bar2 = 5) and (Five) Then Quit;

Bar2 is basically a byte variable that holds an array with different elements, like "display", "help", "next" and "prev", and of course, quit, Which all have their own code based on what they do.
Ch2 is a variable for ReadKey that takes in various key presses, and then allows it to do whatever is defined for that specfic command. In this case, it requires that the return key is used.
Five is a boolean operator, and is there as a prerequisite to run the quit command. I guess it isn't really necessary.

BTW, if it helps, this is a unit, not a standalone program.

Anyone know why this exit command isn't working? Hopefully this post is verbose enough.

Thank you.


问:
How do I count checked checkboxes across all pages of a gridview using jquery?
I want to instantly update a status line indicating the number of checked checkboxes across all pages of an asp.net gridview.  Right now I am only ably to count the number of checkboxes that are checked on the current gridview page.

Here is my code:

```<code>$(document).ready(initAll);

function initAll(){
   countChecked();
    $(".activeBoxes").click(countChecked);
}

function countChecked() {

      var n = $(".activeBoxes input:checked").length;
      $("#checkboxStatus").text(n + (n == 1 ? " vehicle is" : " vehicles are") + " selected on this page.  ");
      if( n == 0){
           $(".activateButton").hide();
           $("#checkboxStatus").hide();

      }else{
        $("#checkboxStatus").show();
        $(".activateButton").show();
      }

}
</code>```

答:
You can track the total selection in viewstate (or something similar) on page change.  I did something similar tracking the selected row ID's in an array.  In my case I had to re-check the items when they returned to the page.  Additionally if you allow sorting the selection may move across pages.

Edit: Sorry this doesn't actually your Jquery question, but maybe it will help...

OwnerDisplayName: Bryan

Body:
I want to instantly update a status line indicating the number of checked checkboxes across all pages of an asp.net gridview.  Right now I am only ably to count the number of checkboxes that are checked on the current gridview page.

Here is my code:

$(document).ready(initAll);

function initAll(){
   countChecked();
    $(".activeBoxes").click(countChecked);
}

function countChecked() {

      var n = $(".activeBoxes input:checked").length;
      $("#checkboxStatus").text(n + (n == 1 ? " vehicle is" : " vehicles are") + " selected on this page.  ");
      if( n == 0){
           $(".activateButton").hide();
           $("#checkboxStatus").hide();

      }else{
        $("#checkboxStatus").show();
        $(".activateButton").show();
      }

}

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: steve

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: steve


问:
How to show the same font which in photoshop on my webpage?
I have a text in photoshop with font: "Arial 17 pt regular strong" how can I write it in css to show the same?

My 2 problems are:

1- the pt unit in photoshop, what is it in css?

2- if the font is bold strong in photoshop, how it will look like in css?

答:
```<code>    .someclass{
     font: bold 17px Arial, Helvetica, sans-serif;
    }
</code>```

And if you need to change the color:

```<code>.someclass{
     font: bold 17px Arial, Helvetica, sans-serif;
     color: #333;
    }
</code>```

Body:
    .someclass{
     font: bold 17px Arial, Helvetica, sans-serif;
    }

And if you need to change the color:

.someclass{
     font: bold 17px Arial, Helvetica, sans-serif;
     color: #333;
    }


问:
Convert string dates in java
I need to compare two string dates in java:

```<code>String date1 = "2017-05-02";
String date2 = "5/2/2017";
//formatter for the first date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date formattedDate1 = formatter.parse(date1);
//formatter for the second date
formatter = new SimpleDateFormat("m/d/yyyy");
Date formattedDate2 = formatter.parse(date2);
//Wrong results
String formatted1 = formattedDate1.toString(); //Mon Jan 02 00:05:00 EET 2017
String formatted2 = formattedDate2.toString(); //Mon Jan 02 00:05:00 EET 2017
</code>```

Actually if i compare those 2 i probably will get 'true' but my dates are not the January, it's 'May 5th 2017'.

The other question is that I can't use Date object, I need to actually convert "2017-05-02" into "5/2/2017" and then pass it to another function

答:
Read the SimpleDateFormat javadoc:

Month is uppercase M:

```<code>SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
</code>```

...

```<code>formatter = new SimpleDateFormat("M/d/yyyy");
</code>```

Lower case m is minute.

Title: Convert string dates in java

Body:
I need to compare two string dates in java:

String date1 = "2017-05-02";
String date2 = "5/2/2017";
//formatter for the first date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date formattedDate1 = formatter.parse(date1);
//formatter for the second date
formatter = new SimpleDateFormat("m/d/yyyy");
Date formattedDate2 = formatter.parse(date2);
//Wrong results
String formatted1 = formattedDate1.toString(); //Mon Jan 02 00:05:00 EET 2017
String formatted2 = formattedDate2.toString(); //Mon Jan 02 00:05:00 EET 2017

Actually if i compare those 2 i probably will get 'true' but my dates are not the January, it's 'May 5th 2017'.

The other question is that I can't use Date object, I need to actually convert "2017-05-02" into "5/2/2017" and then pass it to another function

Body:
Read the SimpleDateFormat javadoc:

Month is uppercase M:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

...

formatter = new SimpleDateFormat("M/d/yyyy");

Lower case m is minute.


问:
Add another user in Microsoft Azure Database for Mysql Server
I am using Microsoft Azure database for Mysql server in my mysql workbench. Now I have dynamic IP set so every time when changing the place I have to open the Azure and enter my IP manually.

Now I want to give access to a friend but I don't want to go through the pain stacking processing of adding IP address and also I don't want to give him my user ID and password to the friend.

So is there any way to give access to my friend to the mysql server?

Thank you in adance.

答:
I don't want to give him my user ID and password to the friend.

You could create a new user as you normally do, and grant proper privileges to it.

so every time when changing the place I have to open the Azure and enter my IP manually.

I have a script for you, but not for your friend. Unless you are willing to let him access your subscription.

This script requires you have Azure CLI installed/configured(since there is no powershell cmdlet for Azure database for MySQL) and it's a powershell script:

```<code>$ip = Invoke-RestMethod http://ipinfo.io/json | Select -exp ip

$command = @'
cmd.exe /C az mysql server firewall-rule update --resource-group RESOURCEGROUPNAME --
server SERVERNAME --name "FIREWALLRULENAME" --start-ip-address $ip --end-ip-
address $ip
'@

Invoke-Expression -Command:$command
</code>```

Body:
I don't want to give him my user ID and password to the friend.

You could create a new user as you normally do, and grant proper privileges to it.

so every time when changing the place I have to open the Azure and enter my IP manually.

I have a script for you, but not for your friend. Unless you are willing to let him access your subscription.

This script requires you have Azure CLI installed/configured(since there is no powershell cmdlet for Azure database for MySQL) and it's a powershell script:

$ip = Invoke-RestMethod http://ipinfo.io/json | Select -exp ip

$command = @'
cmd.exe /C az mysql server firewall-rule update --resource-group RESOURCEGROUPNAME --
server SERVERNAME --name "FIREWALLRULENAME" --start-ip-address $ip --end-ip-
address $ip
'@

Invoke-Expression -Command:$command


问:
Conway Game Of Life Weird Results
for a homework, I have to reproduce Conway's Game of Life project.

Unfortunately, I got weird result, I suppose because C language is new to me, I'm more focus on php recently.

First I give the specs of the project :

```<code> * The Game of Life
 * http://en.wikipedia.org/wiki/Conway's_Game_of_Life
 *
 * Key requirements :
 * - Limit the size of the world to 10x10 cells
 * - The world (grid) must be a struct composed by cells
 * - A cell must be a struct
 * - Each cell is in one of two possible states : Live or Dead
 * - Any live cell with fewer than two live neighbours dies, as if caused by under-population
 * - Any live cell with two or three live neighbours lives on to the next generation
 * - Any live cell with more than three live neighbours dies, as if by overcrowding
 * - Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction
 * - Between each generation, ask if it's necessary to restart the next generation or to leave the game
 * - Having dedicated function displayWorld() to display a representation of this world
 * - Having dedicated function newGeneration() to generate next step of the world
 * - In the function above, implement conditions based on cell's neighbors to define if each cell is alive or dead
 * - Alive cells are represented by a "+"
 * - Dead cells are represented by a "-"
 * - New borned cells are represented by a "0"
 */
</code>```

To give more details on the weird result I get :

I have hardcoded values from loadInitData function but sometime it display a 0 lost somewhere in the grid in a random location I * never * specified...

Quickly, the Conway Game's of Life terminate quickly, and any live cells disappears

I'm sure some bad habits have been used by myself and I'm ready to hear about more experienced developer that could point out what I've missed or did badly.

I'm close to the result (I'm sure of it !) so thanks for any help brought here.

Here is the code of my homework project.

```<code>#include <stdio.h>
#define NEW '0'
#define LIVE '+'
#define DEAD '-'
#define xSize 10
#define ySize 10

typedef struct {
    char status;
} Cell;

typedef struct {
    int sizeX;
    int sizeY;
    Cell cell[xSize][ySize];
} World;

void displayWorld(World grid) {
    int x, y;
    for (y = 0; y < grid.sizeY; y++) {
        for (x = 0; x < grid.sizeX; x++) {
            if (grid.cell[y][x].status == NEW) {
                printf("0");
            } else if (grid.cell[y][x].status == LIVE) {
                printf("+");
            } else {
                printf("-");
            }
        }
        printf("\n");
    }
    printf("\n");
}

int getNeighborValue(World grid, int row, int col) {
    if (row < 0 || row >= grid.sizeY
            || col < 0 || col >= grid.sizeX
            || grid.cell[row][col].status != LIVE )
    {
        return 0;
    } else {
        return 1;
    }
}

int getNeighborCount(World grid, int row, int col) {
    int neighbor = 0;

    neighbor += getNeighborValue(grid, row - 1, col - 1);
    neighbor += getNeighborValue(grid, row - 1, col);
    neighbor += getNeighborValue(grid, row - 1, col + 1);
    neighbor += getNeighborValue(grid, row, col - 1);
    neighbor += getNeighborValue(grid, row, col + 1);
    neighbor += getNeighborValue(grid, row + 1, col - 1);
    neighbor += getNeighborValue(grid, row + 1, col);
    neighbor += getNeighborValue(grid, row + 1, col + 1);

    return neighbor;
}

World newGeneration(World grid) {
    int neighbor, x, y;

    for (y = 0; y < grid.sizeY; y++) {
        for (x = 0; x < grid.sizeX; x++) {
            neighbor = getNeighborCount(grid, y, x);

            if (grid.cell[y][x].status == NEW || grid.cell[y][x].status == LIVE) {
                if (neighbor > 3) {
                    grid.cell[y][x].status = DEAD;
                } else if (neighbor == 2 || neighbor == 3) {
                    grid.cell[y][x].status = LIVE;
                } else {
                    grid.cell[y][x].status = DEAD;
                }
            } else {
                if (neighbor == 3) {
                    grid.cell[y][x].status = NEW;
                }
            }
        }
    }

    return grid;
}

void clearWorld(World grid) {
    int x, y;
    for (y = 0; y < grid.sizeY; y++) {
        for (x = 0; x < grid.sizeX; x++) {
            Cell cell;
            cell.status = DEAD;
            grid.cell[y][x] = cell;
        }
    }
}

World loadInitData(World grid) {
    int x, y, i, n, v;

    printf("Enter the amount of initial organisms: ");
    scanf("%d", &n);

    printf("Would you like organisms randomly generated or defined by you (0: random; 1: you)? ");
    scanf("%d", &v);

    if (v == 1) {
        for (i = 0; i < n; i++) {
            printf("Enter dimensions (x y) where organism %d will live: ", i + 1);
            scanf("%d %d", &x, &y);
            grid.cell[y][x].status = LIVE;
        }
    } else {
        // for (i = 0; i < n; i++) {
        //  x = rand() % grid.sizeX;
        //  y = rand() % grid.sizeY;
        //  grid.cell[y][x].status = LIVE;
        // }

        grid.cell[3][4].status = LIVE;
        grid.cell[3][5].status = LIVE;
        grid.cell[3][6].status = LIVE;
        grid.cell[6][4].status = LIVE;
        grid.cell[6][5].status = LIVE;
        grid.cell[6][6].status = LIVE;
        grid.cell[7][6].status = LIVE;
        grid.cell[8][5].status = LIVE;
    }

    return grid;
}

int main() {
    World grid;
    grid.sizeX = xSize;
    grid.sizeY = ySize;
    char end;
    int generation = 0;
    clearWorld(grid);
    grid = loadInitData(grid);
    displayWorld(grid);
    printf("Generation %d\n", 0);
    printf("Press q to quit or 1 to continue: ");
    scanf(" %c", &end);

    do {
        grid = newGeneration(grid);
        displayWorld(grid);
        printf("Generation %d\n", ++generation);
        printf("Press q to quit or 1 to continue: ");
        scanf(" %c", &end);
    } while (end != 'q') ;

    return 0;
}
</code>```

答:
I think, you have a major mis-understanding:

In C: structs are passed to functions by value (i.e. by copy, in opposition to arrays which are always passed "by reference" – actually, by it's start address). This is true even in your case where the struct contains an array.

I took some code of your sample to demonstrate this:

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

enum {
  NEW = '0',
  LIVE = '+',
  DEAD = '-'
};

typedef struct {
  char status;
} Cell;

enum { xSize = 3, ySize = 3 };

typedef struct {
  int sizeX, sizeY;
  Cell cell[ySize][xSize];
} World;

void displayWorld(World world)
{
  for (int y = 0; y < ySize; ++y) {
    for (int x = 0; x < xSize; ++x) printf("+-");
    printf("+\n");
    for (int x = 0; x < xSize; ++x) {
      printf("|%c", world.cell[y][x].status);
    }
    printf("|\n");
  }
  for (int x = 0; x < xSize; ++x) printf("+-");
  printf("+\n");
}

void modifyWorld(World world, int x, int y, char status)
{
  world.cell[y][x].status = status;
  printf("Modified:\n");
  displayWorld(world);
}

int main()
{
  World world = {
    xSize, ySize
  };
  /* init world */
  for (int y = 0; y < ySize; ++y) {
    for (int x = 0; x < xSize; ++x) world.cell[y][x].status = NEW;
  }
  /* display world */
  printf("Before call of modifyWorld():\n");
  displayWorld(world);
  /* modify world */
  modifyWorld(world, xSize / 2, ySize / 2, LIVE);
  /* display world */
  printf("After call of modifyWorld():\n");
  displayWorld(world);
  /* done */
  return 0;
}
</code>```

The output is:

```<code>Before call of modifyWorld():
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
Modified:
+-+-+-+
|0|0|0|
+-+-+-+
|0|+|0|
+-+-+-+
|0|0|0|
+-+-+-+
After call of modifyWorld():
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
Drücken Sie eine beliebige Taste . . .
</code>```

This shows that modifyWorld() does change its local copy but not the original world declared in main().

To change this, the 1st parameter had to become a World *world.
Accordingly, its contents had to be accessed by -> instead of ., e.g.

```<code>world->cell[y][x].status = status;
</code>```

This affects your function clearWorld() exclusively.

Every other function of your sample uses a "functional approach" returning changed local copies as result which is assigned on caller site.

This is not very C-stylish and inefficient but it's working correctly (concerning the storage).

Considering this and what's suggested by the comments about updating of states you should be able to master it.

Title: Conway Game Of Life Weird Results

Body:
for a homework, I have to reproduce Conway's Game of Life project.

Unfortunately, I got weird result, I suppose because C language is new to me, I'm more focus on php recently.

First I give the specs of the project :

 * The Game of Life
 * http://en.wikipedia.org/wiki/Conway's_Game_of_Life
 *
 * Key requirements :
 * - Limit the size of the world to 10x10 cells
 * - The world (grid) must be a struct composed by cells
 * - A cell must be a struct
 * - Each cell is in one of two possible states : Live or Dead
 * - Any live cell with fewer than two live neighbours dies, as if caused by under-population
 * - Any live cell with two or three live neighbours lives on to the next generation
 * - Any live cell with more than three live neighbours dies, as if by overcrowding
 * - Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction
 * - Between each generation, ask if it's necessary to restart the next generation or to leave the game
 * - Having dedicated function displayWorld() to display a representation of this world
 * - Having dedicated function newGeneration() to generate next step of the world
 * - In the function above, implement conditions based on cell's neighbors to define if each cell is alive or dead
 * - Alive cells are represented by a "+"
 * - Dead cells are represented by a "-"
 * - New borned cells are represented by a "0"
 */

To give more details on the weird result I get :

I have hardcoded values from loadInitData function but sometime it display a 0 lost somewhere in the grid in a random location I * never * specified...

Quickly, the Conway Game's of Life terminate quickly, and any live cells disappears

I'm sure some bad habits have been used by myself and I'm ready to hear about more experienced developer that could point out what I've missed or did badly.

I'm close to the result (I'm sure of it !) so thanks for any help brought here.

Here is the code of my homework project.

#include <stdio.h>
#define NEW '0'
#define LIVE '+'
#define DEAD '-'
#define xSize 10
#define ySize 10

typedef struct {
    char status;
} Cell;

typedef struct {
    int sizeX;
    int sizeY;
    Cell cell[xSize][ySize];
} World;

void displayWorld(World grid) {
    int x, y;
    for (y = 0; y < grid.sizeY; y++) {
        for (x = 0; x < grid.sizeX; x++) {
            if (grid.cell[y][x].status == NEW) {
                printf("0");
            } else if (grid.cell[y][x].status == LIVE) {
                printf("+");
            } else {
                printf("-");
            }
        }
        printf("\n");
    }
    printf("\n");
}

int getNeighborValue(World grid, int row, int col) {
    if (row < 0 || row >= grid.sizeY
            || col < 0 || col >= grid.sizeX
            || grid.cell[row][col].status != LIVE )
    {
        return 0;
    } else {
        return 1;
    }
}

int getNeighborCount(World grid, int row, int col) {
    int neighbor = 0;

    neighbor += getNeighborValue(grid, row - 1, col - 1);
    neighbor += getNeighborValue(grid, row - 1, col);
    neighbor += getNeighborValue(grid, row - 1, col + 1);
    neighbor += getNeighborValue(grid, row, col - 1);
    neighbor += getNeighborValue(grid, row, col + 1);
    neighbor += getNeighborValue(grid, row + 1, col - 1);
    neighbor += getNeighborValue(grid, row + 1, col);
    neighbor += getNeighborValue(grid, row + 1, col + 1);

    return neighbor;
}

World newGeneration(World grid) {
    int neighbor, x, y;

    for (y = 0; y < grid.sizeY; y++) {
        for (x = 0; x < grid.sizeX; x++) {
            neighbor = getNeighborCount(grid, y, x);

            if (grid.cell[y][x].status == NEW || grid.cell[y][x].status == LIVE) {
                if (neighbor > 3) {
                    grid.cell[y][x].status = DEAD;
                } else if (neighbor == 2 || neighbor == 3) {
                    grid.cell[y][x].status = LIVE;
                } else {
                    grid.cell[y][x].status = DEAD;
                }
            } else {
                if (neighbor == 3) {
                    grid.cell[y][x].status = NEW;
                }
            }
        }
    }

    return grid;
}

void clearWorld(World grid) {
    int x, y;
    for (y = 0; y < grid.sizeY; y++) {
        for (x = 0; x < grid.sizeX; x++) {
            Cell cell;
            cell.status = DEAD;
            grid.cell[y][x] = cell;
        }
    }
}

World loadInitData(World grid) {
    int x, y, i, n, v;

    printf("Enter the amount of initial organisms: ");
    scanf("%d", &n);

    printf("Would you like organisms randomly generated or defined by you (0: random; 1: you)? ");
    scanf("%d", &v);

    if (v == 1) {
        for (i = 0; i < n; i++) {
            printf("Enter dimensions (x y) where organism %d will live: ", i + 1);
            scanf("%d %d", &x, &y);
            grid.cell[y][x].status = LIVE;
        }
    } else {
        // for (i = 0; i < n; i++) {
        //  x = rand() % grid.sizeX;
        //  y = rand() % grid.sizeY;
        //  grid.cell[y][x].status = LIVE;
        // }

        grid.cell[3][4].status = LIVE;
        grid.cell[3][5].status = LIVE;
        grid.cell[3][6].status = LIVE;
        grid.cell[6][4].status = LIVE;
        grid.cell[6][5].status = LIVE;
        grid.cell[6][6].status = LIVE;
        grid.cell[7][6].status = LIVE;
        grid.cell[8][5].status = LIVE;
    }

    return grid;
}

int main() {
    World grid;
    grid.sizeX = xSize;
    grid.sizeY = ySize;
    char end;
    int generation = 0;
    clearWorld(grid);
    grid = loadInitData(grid);
    displayWorld(grid);
    printf("Generation %d\n", 0);
    printf("Press q to quit or 1 to continue: ");
    scanf(" %c", &end);

    do {
        grid = newGeneration(grid);
        displayWorld(grid);
        printf("Generation %d\n", ++generation);
        printf("Press q to quit or 1 to continue: ");
        scanf(" %c", &end);
    } while (end != 'q') ;

    return 0;
}

Body:
I think, you have a major mis-understanding:

In C: structs are passed to functions by value (i.e. by copy, in opposition to arrays which are always passed "by reference" – actually, by it's start address). This is true even in your case where the struct contains an array.

I took some code of your sample to demonstrate this:

#include <stdio.h>

enum {
  NEW = '0',
  LIVE = '+',
  DEAD = '-'
};

typedef struct {
  char status;
} Cell;

enum { xSize = 3, ySize = 3 };

typedef struct {
  int sizeX, sizeY;
  Cell cell[ySize][xSize];
} World;

void displayWorld(World world)
{
  for (int y = 0; y < ySize; ++y) {
    for (int x = 0; x < xSize; ++x) printf("+-");
    printf("+\n");
    for (int x = 0; x < xSize; ++x) {
      printf("|%c", world.cell[y][x].status);
    }
    printf("|\n");
  }
  for (int x = 0; x < xSize; ++x) printf("+-");
  printf("+\n");
}

void modifyWorld(World world, int x, int y, char status)
{
  world.cell[y][x].status = status;
  printf("Modified:\n");
  displayWorld(world);
}

int main()
{
  World world = {
    xSize, ySize
  };
  /* init world */
  for (int y = 0; y < ySize; ++y) {
    for (int x = 0; x < xSize; ++x) world.cell[y][x].status = NEW;
  }
  /* display world */
  printf("Before call of modifyWorld():\n");
  displayWorld(world);
  /* modify world */
  modifyWorld(world, xSize / 2, ySize / 2, LIVE);
  /* display world */
  printf("After call of modifyWorld():\n");
  displayWorld(world);
  /* done */
  return 0;
}

The output is:

Before call of modifyWorld():
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
Modified:
+-+-+-+
|0|0|0|
+-+-+-+
|0|+|0|
+-+-+-+
|0|0|0|
+-+-+-+
After call of modifyWorld():
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
|0|0|0|
+-+-+-+
Drücken Sie eine beliebige Taste . . .

This shows that modifyWorld() does change its local copy but not the original world declared in main().

To change this, the 1st parameter had to become a World *world.
Accordingly, its contents had to be accessed by -> instead of ., e.g.

world->cell[y][x].status = status;

This affects your function clearWorld() exclusively.

Every other function of your sample uses a "functional approach" returning changed local copies as result which is assigned on caller site.

This is not very C-stylish and inefficient but it's working correctly (concerning the storage).

Considering this and what's suggested by the comments about updating of states you should be able to master it.


问:
No public port '22/tcp' published for test_sshd
I'm trying to execute this:

https://hub.docker.com/r/rastasheep/ubuntu-sshd/

Namely, I run:

```<code>sudo docker run -d -P --name test_sshd rastasheep/ubuntu-sshd:16.04
</code>```

Then

```<code>sudo docker port test_sshd 22
</code>```

I can see something like:

```<code>0.0.0.0:49154
</code>```

And I can run:

```<code>ssh root@localhost -p 49154
</code>```

But as soon as I restart my computer, I see this:

```<code>sudo docker port test_sshd 22
Error: No public port '22/tcp' published for test_sshd
</code>```

Could you give me a kick here?

答:
The option -P binds a port dynamically and randomly, that's why you need another step to associate a port, using docker port.
I would use instead a free static port to access ssh port to this container :

```<code>docker container run -d -p 2222:22 --name test_sshd rastasheep/ubuntu-sshd:16.04
ssh root@localhost -p 2222
</code>```

This port setting persists when dockerd is restarted.

Body:
I'm trying to execute this:

https://hub.docker.com/r/rastasheep/ubuntu-sshd/

Namely, I run:

sudo docker run -d -P --name test_sshd rastasheep/ubuntu-sshd:16.04

Then

sudo docker port test_sshd 22

I can see something like:

0.0.0.0:49154

And I can run:

ssh root@localhost -p 49154

But as soon as I restart my computer, I see this:

sudo docker port test_sshd 22
Error: No public port '22/tcp' published for test_sshd

Could you give me a kick here?

Body:
The option -P binds a port dynamically and randomly, that's why you need another step to associate a port, using docker port.
I would use instead a free static port to access ssh port to this container :

docker container run -d -p 2222:22 --name test_sshd rastasheep/ubuntu-sshd:16.04
ssh root@localhost -p 2222

This port setting persists when dockerd is restarted.


问:
access textfield text from another viewController
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
```

<p>and here is my <code>profileController</code> prepare func:</p>

<pre class="lang-swift prettyprint-override"><code>    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }
</code>```

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.

答:
Data flow from one controller to another is the very popular theme for ios beginners. There are several approaches to achieve this goal: segues, delegate pattern, notifications, initialization of new instance of controller, saving data to local storage etc.

You should user prepare(for segue: sender:) method only when you have segue from you current controller to another. You can get access to destination controller instance via destination property of segue parameter.

Also never call IBOutlet properties of destination controller in prepareForSegue - it can be cause of crash, because Outlets may be uninitilized at this time. Instead use String property for example.

Here is sample code:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if (segue.identifier == "mainMenu") {
            if let destinationVC = segue.destination as? ViewController {
               destinationVC.login = self.myLabel.text
            }
        }
}
</code>```

Where login in destinationVC is the String variable to store login.

Body:
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

and here is my profileController prepare func:

    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.

Body:
Data flow from one controller to another is the very popular theme for ios beginners. There are several approaches to achieve this goal: segues, delegate pattern, notifications, initialization of new instance of controller, saving data to local storage etc.

You should user prepare(for segue: sender:) method only when you have segue from you current controller to another. You can get access to destination controller instance via destination property of segue parameter.

Also never call IBOutlet properties of destination controller in prepareForSegue - it can be cause of crash, because Outlets may be uninitilized at this time. Instead use String property for example.

Here is sample code:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if (segue.identifier == "mainMenu") {
            if let destinationVC = segue.destination as? ViewController {
               destinationVC.login = self.myLabel.text
            }
        }
}

Where login in destinationVC is the String variable to store login.


问:
Value Suggestion for SAP Dynpro input field
I need to show suggestions when someone types something into my input field.
It's a field for a transport request. So if someone starts to type something in it shows at the moment last entered entries but it should make suggestions what to type in (like it happens for example in transaciton VA02 ). I want a dropdown of a selection of the table E070 where I can see the request and the short text.

I did use google but i just found this, but i've got a normal dynpro and no WebDynpro.

答: The keyword you are looking for is Enhanced Search. You can provide your own enhanced search implementation by creating a search help and activating the proposal search feature. Note that the enhanced search can be turned off in the GUI Settings, though - and many users and organizations do so because it tends to be irritating for long-time experienced users.


问:
Removing records with blank field through a named_scope
I have created a Ruby on Rails app that allows users to track workouts. I allow them to make a workout private or public which is denoted by passing integer 1 to Workout.share.

Now I am trying to display certain subsets of those public_workouts. I call all public_workouts through a named_scope:

```<code># workouts_controller.rb
@workouts = Workout.public_workouts.all
</code>```

...

```<code># workout.rb
named_scope :public_workouts, :conditions => {:share => 1}
</code>```

The Workout table also has a column for rounds. I want to limit the output of public_workouts to only records that have something in workout.rounds. Another words, if workout.rounds is blank then I don't want that included.

What is the best way to do this?

UPDATE:

I should have mentioned that I am using rails 2.3.8

答:
i think it should work:</p>

```<code>named_scope :published, lambda {
{ :conditions =>
  ["workouts.rounds IS NOT NULL AND workouts.share = ?", 1]
}}
</code>```

Body:
I have created a Ruby on Rails app that allows users to track workouts. I allow them to make a workout private or public which is denoted by passing integer 1 to Workout.share.

Now I am trying to display certain subsets of those public_workouts. I call all public_workouts through a named_scope:

# workouts_controller.rb
@workouts = Workout.public_workouts.all

...

# workout.rb
named_scope :public_workouts, :conditions => {:share => 1}

The Workout table also has a column for rounds. I want to limit the output of public_workouts to only records that have something in workout.rounds. Another words, if workout.rounds is blank then I don't want that included.

What is the best way to do this?

UPDATE:

I should have mentioned that I am using rails 2.3.8

Body:
i think it should work:

named_scope :published, lambda {
{ :conditions =>
  ["workouts.rounds IS NOT NULL AND workouts.share = ?", 1]
}}


问:
How to use LibGDX?
I am just getting started with coding and app development using LibGDX and i´ve got some general and some more specific questions about it.

Before I start: I know that some of my questions might have already been asked somewhere on the internet but I found it really hard to get a straight answer to them.

So, the most basic question first:

Is it possible to create an average application (like angry birds or doodle jump) in LibGDX in a reasonable amount of time?
Browsing the internet I came across many people stating that engines like Unity are "just so much easier to use" and that you can create a game in a fraction of the time it would take you to code a game in LibGDX.
Is that really the case?

My second question connects to the first:

Is LibGDX really worth the time? Picking up any engine or Framework seems like a lot of work, so I wondered if LibGDX is a growing platform worth learning or just an irrelevant framework of many.

The third question is a bit more specific (and the most important one for me):

How can I make LibGDX game pretty?
I know, that sounds weird at first but looking at hundreds of apps in all kind of appstores I´ve noticed that most unity apps look really neat whereas most apps found in the Badlogic gallery look just awful to be honest.

So I wondered is there a simple way to add animations, particle effects, shadows, etc. to a LibGDX application. If I was coding a 2048 clone (just as an example) how can I make my tiles slide together and blend nicely?

Creating good looking animations is something I struggle with the most...

(If you want you can have a look at what I created)

I would really appreciate any answer to any of my questions!
Thank you for making it through this huge post.

MrMorph

答:
Yes it is very possible to create a simple game in libgdx. I used to use this framework all the time. If you are semi new to it YouTube has some awesome tutorials.
Now I use unity primarily, and here is why:

It is easier from a productivity standpoint yes.

Libgdx can be a lot of work when trying to work with graphics.

Plus it was an easy transition from Java to c#.

And yes in most cases unity can move a bit faster, again from a productivity standpoint, in libgdx there is more of a process to setting up graphics and viewports and etc.

libgdx is 100% worth it. A big part of what libgdx helped me with was grasping how the backed of these applications work. This has helped me a great deal in debugging problems in unity and just advancing my knowledge overall.

If you have good graphics and understanding of the framework then you can make a libgdx game that does look beautiful. The difference is that unity simplifies the process for you. And all the demos you see are from a huge pool of projects. With libgdx being such a good start to game development, there are going to be plenty of projects, with no proof of how much work and or time was put in.

Title: How to use LibGDX?