问:
View model issue in Asp.net mvc C#
I have two models data .
please take a look

```<code> public class StoreTransactionAngular
    {
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int StoreId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int TargetId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public DateTime TransactionDate { get; set; }

        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        [MustHaveOneElementAttribute(ErrorMessage = "At least a task is required")]
        [MinLength(1)]
        [EnsureOneElement(ErrorMessage = "At least a person is required")]
        public List<StoreTransactionDetails> Details { get; set; }
    }

    public class StoreTransactionDetails
    {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
        public bool IsUsed { get; set; }
        public string IsUsedText { get; set; }
        public double Quantity { get; set; }
        public string Unit { get; set; }
    }
</code>```

I want to store my data to another table

```<code>public class StoreTransaction
    {
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int StoreId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int TargetId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public DateTime TransactionDate { get; set; }

        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        //public List<StoreTransactionDetails> Details { get; set; }
        public string ItemIds { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public string Quantities { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public string IsUseds { get; set; }
    }
</code>```

Is it possible to do so , I have a following view.cshtml code

```<code>@model  StoresManagement.ViewModel.StoreTransactionAngular
@{
    ViewBag.Title = "Store Transaction Manage";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "ajaxForm", ng_controller = "IncomeController" }))
{
    @Html.AntiForgeryToken()

    <div class="panel panel-info">
        <div class="panel-heading">
            Transaction Data
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-sm-4">
                    @Html.DropDownListFor(x => x.StoreId, (SelectList)ViewBag.StoreList, "Select Store", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.StoreId, "", new { @class = "text-danger" })
                </div>
                <div class="col-sm-4">
                    @Html.DropDownListFor(x => x.TargetId, (SelectList)ViewBag.VendorList, "Select Vendor", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.TargetId, "", new { @class = "text-danger" })
                </div>
                <div class="col-sm-4">
                    @Html.TextBoxFor(x => x.TransactionDate, new { @class = "form-control", placeholder = "Enter Date", ng_model = "date" })
                    @Html.ValidationMessageFor(model => model.TransactionDate, "", new { @class = "text-danger" })

                </div>
            </div>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-heading">
            Transaction Details
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-sm-4">
                    @Html.DropDownList("CategoryId", (SelectList)ViewBag.CategoryList, "Select Category", new { @class = "form-control" })

                </div>
                <div class="col-sm-4">
                    <select ng_model="ItemId" ng-options="p as p.label for p in ItemId" id="ItemId" name="ItemId" class="form-control">
                        <option unit="" value="">Select Item</option>
                    </select>
                </div>
                <div class="col-sm-1">
                    <label class="checkbox">
                        <input type="checkbox" ng_model="IsUsed" name="IsUsed" id="IsUsed" />
                        Is Used؟
                    </label>
                </div>
                <div class="col-sm-2 relative">
                    <input type="number" ng_model="Quantity" step="0.01" min="0" max="9999999999" id="Quantity" name="Quantity" placeholder="Quanitity" class="form-control" />
                    <span ng_model="Unit" class="Unit"></span>
                </div>
                <div class="col-sm-1">
                    <button id="btnAddItem" class="btn btn-success"><i class="fa fa-plus"></i></button>

                </div>

            </div>
            <hr />
            <table id="tblItems" class="table table-hover table-striped">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th width="20%">Status</th>
                        <th width="20%">Quantity</th>
                        <th width="3%"></th>
                    </tr>
                </thead>
                <tbody>

                    @foreach (var item in Model.Details)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.ItemId)<br />
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.ItemName)<br />
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Quantity)<br />
                            </td>

                        </tr>
                    }
                    <tr ng-repeat="ItemModel in ListItem">
                        <td>{{ItemModel.ItemName}}</td>
                        <td>{{ItemModel.IsUsedText }}</td>
                        <td>{{ItemModel.Quantity}} {{ ItemModel.Unit }}</td>

                        <td width="10%" class="text-right">
                            <div classn-group btn-group-justified">
                                <a class="btn btn-xs btn-primary" ng-click="getCustomer(ItemModel)">
                                    <i class="glyphicon glyphicon-edit"></i>
                                </a>
                                <a class="btn btn-xs btn-warning" ng-click="deleteCustomer(ItemModel)">
                                    <i class="glyphicon glyphicon-trash"></i>
                                </a>
                            </div>
                        </td>

                    </tr>
                </tbody>
            </table>
            <div class="alert alert-warning">
                There is no Item selected
            </div>
            @*@Html.HiddenFor(x => x.ItemIds)
            @Html.HiddenFor(x => x.Quantities)
            @Html.HiddenFor(x => x.IsUseds)*@
            @Html.ValidationMessageFor(model => model.Details, "", new { @class = "text-danger" })

        </div>
    </div>
    <button class="btn btn-primary btn-lg" type="submit"><i class="fa fa-save"> </i> Save</button>
        @Html.ActionLink("Cancle", "Index", null, new { @class = "btn btn-lg btn-default", data_dismiss = "modal" })
}
</code>```

This part is not working

```<code>@*@Html.HiddenFor(x => x.ItemIds)
  @Html.HiddenFor(x => x.Quantities)
  @Html.HiddenFor(x => x.IsUseds)*@
</code>```

can anyone help me with this part to make it working , as these values are necessary to do so .

Thanks in advance, Need more details you can ask via comments

答:
Adjust your view model to

```<code>public class StoreTransactionAngular
{
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public int StoreId { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public int TargetId { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public DateTime TransactionDate { get; set; }

    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    [MustHaveOneElementAttribute(ErrorMessage = "At least a task is required")]
    [MinLength(1)]
    [EnsureOneElement(ErrorMessage = "At least a person is required")]
    public List<StoreTransactionDetails> Details { get; set; }

    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public string ItemIds { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public string Quantities { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public string IsUseds { get; set; }
}
</code>```

Open the comment for

```<code>@Html.HiddenFor(x => x.ItemIds)
@Html.HiddenFor(x => x.Quantities)
@Html.HiddenFor(x => x.IsUseds)
</code>```

Now you can use JS to set value to ItemIds, Quantities, and IsUseds. Once you click the submit, you will get the values in your view model as the parameter in your backend action.

Updated above.

Your view model is StoreTransactionAngular and it doesn't contain ItemIds, Quantities, and IsUseds. That's why the error occured.

The simplest way is adding the "StoreTransaction" into your view model. Then your can popuate and handle the values after your click the submit button in your action.

Title: View model issue in Asp.net mvc C#

Body:
I have two models data .
please take a look

 public class StoreTransactionAngular
    {
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int StoreId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int TargetId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public DateTime TransactionDate { get; set; }

        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        [MustHaveOneElementAttribute(ErrorMessage = "At least a task is required")]
        [MinLength(1)]
        [EnsureOneElement(ErrorMessage = "At least a person is required")]
        public List<StoreTransactionDetails> Details { get; set; }
    }

    public class StoreTransactionDetails
    {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
        public bool IsUsed { get; set; }
        public string IsUsedText { get; set; }
        public double Quantity { get; set; }
        public string Unit { get; set; }
    }

I want to store my data to another table

public class StoreTransaction
    {
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int StoreId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public int TargetId { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public DateTime TransactionDate { get; set; }

        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        //public List<StoreTransactionDetails> Details { get; set; }
        public string ItemIds { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public string Quantities { get; set; }
        [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
        public string IsUseds { get; set; }
    }

Is it possible to do so , I have a following view.cshtml code

@model  StoresManagement.ViewModel.StoreTransactionAngular
@{
    ViewBag.Title = "Store Transaction Manage";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "ajaxForm", ng_controller = "IncomeController" }))
{
    @Html.AntiForgeryToken()

            Transaction Data

                    @Html.DropDownListFor(x => x.StoreId, (SelectList)ViewBag.StoreList, "Select Store", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.StoreId, "", new { @class = "text-danger" })

                    @Html.DropDownListFor(x => x.TargetId, (SelectList)ViewBag.VendorList, "Select Vendor", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.TargetId, "", new { @class = "text-danger" })

                    @Html.TextBoxFor(x => x.TransactionDate, new { @class = "form-control", placeholder = "Enter Date", ng_model = "date" })
                    @Html.ValidationMessageFor(model => model.TransactionDate, "", new { @class = "text-danger" })

            Transaction Details

                    @Html.DropDownList("CategoryId", (SelectList)ViewBag.CategoryList, "Select Category", new { @class = "form-control" })

                    <select ng_model="ItemId" ng-options="p as p.label for p in ItemId" id="ItemId" name="ItemId" class="form-control">
                        <option unit="" value="">Select Item</option>
                    </select>

                        <input type="checkbox" ng_model="IsUsed" name="IsUsed" id="IsUsed" />
                        Is Used؟

                    <input type="number" ng_model="Quantity" step="0.01" min="0" max="9999999999" id="Quantity" name="Quantity" placeholder="Quanitity" class="form-control" />

                    <button id="btnAddItem" class="btn btn-success"></button>

                        Item
                        Status
                        Quantity

                    @foreach (var item in Model.Details)
                    {

                                @Html.DisplayFor(modelItem => item.ItemId)

                                @Html.DisplayFor(modelItem => item.ItemName)

                                @Html.DisplayFor(modelItem => item.Quantity)

                    }

                        {{ItemModel.ItemName}}
                        {{ItemModel.IsUsedText }}
                        {{ItemModel.Quantity}} {{ ItemModel.Unit }}

                There is no Item selected

            @*@Html.HiddenFor(x => x.ItemIds)
            @Html.HiddenFor(x => x.Quantities)
            @Html.HiddenFor(x => x.IsUseds)*@
            @Html.ValidationMessageFor(model => model.Details, "", new { @class = "text-danger" })

    <button class="btn btn-primary btn-lg" type="submit">  Save</button>
        @Html.ActionLink("Cancle", "Index", null, new { @class = "btn btn-lg btn-default", data_dismiss = "modal" })
}

This part is not working

@*@Html.HiddenFor(x => x.ItemIds)
  @Html.HiddenFor(x => x.Quantities)
  @Html.HiddenFor(x => x.IsUseds)*@

can anyone help me with this part to make it working , as these values are necessary to do so .

Thanks in advance, Need more details you can ask via comments

Body:
Adjust your view model to

public class StoreTransactionAngular
{
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public int StoreId { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public int TargetId { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public DateTime TransactionDate { get; set; }

    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    [MustHaveOneElementAttribute(ErrorMessage = "At least a task is required")]
    [MinLength(1)]
    [EnsureOneElement(ErrorMessage = "At least a person is required")]
    public List<StoreTransactionDetails> Details { get; set; }

    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public string ItemIds { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public string Quantities { get; set; }
    [Required(ErrorMessageResourceType = typeof(App_GlobalResources.Labels), ErrorMessageResourceName = "Required")]
    public string IsUseds { get; set; }
}

Open the comment for

@Html.HiddenFor(x => x.ItemIds)
@Html.HiddenFor(x => x.Quantities)
@Html.HiddenFor(x => x.IsUseds)

Now you can use JS to set value to ItemIds, Quantities, and IsUseds. Once you click the submit, you will get the values in your view model as the parameter in your backend action.

Updated above.

Your view model is StoreTransactionAngular and it doesn't contain ItemIds, Quantities, and IsUseds. That's why the error occured.

The simplest way is adding the "StoreTransaction" into your view model. Then your can popuate and handle the values after your click the submit button in your action.


来源: stackexchange

问:
Joomla - delay on publishing new things
If I disable the cache on Joomla 1.5 and I publish a new menu item or any other information on the site the new element don't appear immediately after.

If I enable the cache on Joomla 1.5 and I set it to 1 minute delay, and I publish a new menu item, I wait a minute, I do refresh, and I see no menu item.

I only see those new elements, after a certain period of time, regardless joomla configuration options on cache page.

What could this be?

Thanks a lot,
MEM

答:
This could be a broswer issue. I use firefox and used to have a delay in publishing so i got an addon that clears cache with one click. </p>

<p>https://addons.mozilla.org/en-US/firefox/addon/1801/ < that is the link to the one i use. I dont get any issues with delayed publishing.
They are other addons that clear cache and also cookie sessions.
Web developer toolkit is also worthy of a download to help you look at tags, image alts, etc.
Hope this helps. </p>

ContentLicense: CC BY-SA 2.5

Title: Joomla - delay on publishing new things

Body:
This could be a broswer issue. I use firefox and used to have a delay in publishing so i got an addon that clears cache with one click.

https://addons.mozilla.org/en-US/firefox/addon/1801/ < that is the link to the one i use. I dont get any issues with delayed publishing.
They are other addons that clear cache and also cookie sessions.
Web developer toolkit is also worthy of a download to help you look at tags, image alts, etc.
Hope this helps.


问:
How to correctly perform all-VS-all row-by-row comparisons between series in two pandas dataframes?
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

```<code>Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00
</code>```

df2

```<code>Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01
</code>```

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

```<code>Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01
</code>```

I am not familiar with row-by-row operations in pandas.
When I am doing:

```<code>for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()
</code>```

The result I get is a ValueError:

```<code>ValueError: operands could not be broadcast together with shapes(3,) (4,)
</code>```

How to correctly perform row-by-row comparisons between two pandas dataframes?

答:
What about using merge_asof to get the closest events?

Make sure your data types are correct:

```<code>df1.Timestamp_A = df1.Timestamp_A.apply(pd.to_datetime)
df2.Timestamp_B = df2.Timestamp_B.apply(pd.to_datetime)
</code>```

Sort by the times:

```<code>df1.sort_values('Timestamp_A', inplace=True)
df2.sort_values('Timestamp_B', inplace=True)
</code>```

Now you can merge the two dataframes on the closest time:

```<code>df3 = pd.merge_asof(df2, df1,
                left_on='Timestamp_B',
                right_on='Timestamp_A',
                suffixes=('_df2', '_df1'))
#clean up the datetime formats
df3[['Timestamp_A', 'Timestamp_B']] = df3[['Timestamp_A', 'Timestamp_B']] \
                                          .applymap(pd.datetime.time)
#put df1 columns on the right
df3 = df3.iloc[:,::-1]

print(df3)
  Timestamp_A  Number_df1 Event_df1 Timestamp_B  Number_df2 Event_df2
0    07:00:00           1         A    07:01:00           3         B
1    08:00:00           2         A    08:01:00           2         B
2    09:00:00           3         A    09:01:00           1         B
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00

df2

Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01

I am not familiar with row-by-row operations in pandas.
When I am doing:

for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()

The result I get is a ValueError:

ValueError: operands could not be broadcast together with shapes(3,) (4,)

How to correctly perform row-by-row comparisons between two pandas dataframes?

Body:
What about using merge_asof to get the closest events?

Make sure your data types are correct:

df1.Timestamp_A = df1.Timestamp_A.apply(pd.to_datetime)
df2.Timestamp_B = df2.Timestamp_B.apply(pd.to_datetime)

Sort by the times:

df1.sort_values('Timestamp_A', inplace=True)
df2.sort_values('Timestamp_B', inplace=True)

Now you can merge the two dataframes on the closest time:

df3 = pd.merge_asof(df2, df1,
                left_on='Timestamp_B',
                right_on='Timestamp_A',
                suffixes=('_df2', '_df1'))
#clean up the datetime formats
df3[['Timestamp_A', 'Timestamp_B']] = df3[['Timestamp_A', 'Timestamp_B']] \
                                          .applymap(pd.datetime.time)
#put df1 columns on the right
df3 = df3.iloc[:,::-1]

print(df3)
  Timestamp_A  Number_df1 Event_df1 Timestamp_B  Number_df2 Event_df2
0    07:00:00           1         A    07:01:00           3         B
1    08:00:00           2         A    08:01:00           2         B
2    09:00:00           3         A    09:01:00           1         B


问:
GMSMapView custom my location button image
I would like to know if it is possible to change the my location button image from GMSMapView to a custom image.</p>

答:
1) Know frame location button:

```<code>   for (UIView *object in self.mapView.subviews) {
    if([[[object class] description] isEqualToString:@"GMSUISettingsView"] )
    {
        for(UIView *view in object.subviews) {
            if([view.accessibilityIdentifier isEqual:@"my_location"] ) {

                frame = view.frame;

            }
        }

    }
   }
</code>```

Use debug to see correct frame!!!

2) Don't use self.mapView.settings.myLocationButton = YES;

3) Create own button to this frame:

```<code>    UIButton *buttonLocation = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonLocation.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 66, [UIScreen mainScreen].bounds.size.height - frame.size.height, frame.size.width, frame.size.height);
[buttonLocation addTarget:self
           action:@selector(bLocations:)
 forControlEvents:UIControlEventTouchUpInside];
[buttonLocation setImage:[[UIImage imageNamed:@"image.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];

[self.mapView addSubview:buttonLocation];
</code>```

Body:
1) Know frame location button:

   for (UIView *object in self.mapView.subviews) {
    if([[[object class] description] isEqualToString:@"GMSUISettingsView"] )
    {
        for(UIView *view in object.subviews) {
            if([view.accessibilityIdentifier isEqual:@"my_location"] ) {

                frame = view.frame;

            }
        }

    }
   }

Use debug to see correct frame!!!

2) Don't use self.mapView.settings.myLocationButton = YES;

3) Create own button to this frame:

    UIButton *buttonLocation = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonLocation.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 66, [UIScreen mainScreen].bounds.size.height - frame.size.height, frame.size.width, frame.size.height);
[buttonLocation addTarget:self
           action:@selector(bLocations:)
 forControlEvents:UIControlEventTouchUpInside];
[buttonLocation setImage:[[UIImage imageNamed:@"image.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];

[self.mapView addSubview:buttonLocation];


问:
Export AS400 database tables into flat files using SSIS
I need to transfer around 7 databases in AS400 to text format using SSIS, each DB has over 200 tables, and from on of the DB, I have to get specific tables(about 300).

Any suggestions on how to implement it?

答:
The IBM i has it's own utilities to copy data from a table to a stream file.

Copy To Import File (CPYTOIMPF) command on the IBM i.


问:
The android gradle plugin version 3.0.0-alpha1 is too old
While building a default project (black template) on Android Studio 3.0 Canary 1, I got the below error.

```<code>The android gradle plugin version 3.0.0-alpha1 is too old, please update to the latest version. To override this check from the command line please set the
ANDROID_DAILY_OVERRIDE environment variable to "d27b293f4c7c48dfe922ba160164f3fa511cb3b9"
Upgrade plugin to version 3.0.0-alpha1 and sync project Open File
</code>```

What's wrong with the default setting?

答:
After trying this solutions, I came with this:

```<code>buildscript {
  repositories {
    jcenter()
    maven { url 'https://maven.google.com' }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
  }
}
</code>```

add

```<code>maven { url 'https://maven.google.com' }
</code>```

to buldscript repositories.

Body:
While building a default project (black template) on Android Studio 3.0 Canary 1, I got the below error.

The android gradle plugin version 3.0.0-alpha1 is too old, please update to the latest version. To override this check from the command line please set the
ANDROID_DAILY_OVERRIDE environment variable to "d27b293f4c7c48dfe922ba160164f3fa511cb3b9"
Upgrade plugin to version 3.0.0-alpha1 and sync project Open File

What's wrong with the default setting?

Body:
After trying this solutions, I came with this:

buildscript {
  repositories {
    jcenter()
    maven { url 'https://maven.google.com' }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
  }
}

add

maven { url 'https://maven.google.com' }

to buldscript repositories.


问:
Creating a link through button
Anybody please explain how to create a button which redirects to a link/website by clicking on it.
Please provide a code as example.</p>

答:
You can use the btn class for  with bootstrap like this

```<code><a href = "http://yourlink.com" class = "btn btn-danger">Link button</a>
</code>```

Don't forget to use bootstrap cdn in :

```<code><link rel = "stylesheet"  href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css">
</code>```

Title: Creating a link through button

Body:
You can use the btn class for <a> with bootstrap like this

<a href = "http://yourlink.com" class = "btn btn-danger">Link button</a>

Don't forget to use bootstrap cdn in <head>:

<link rel = "stylesheet"  href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css">


问:
Swagger UI: pass custom Authorization header
I'm using Swashbuckle and Swagger on an ASP.NET Web API. I'm trying to find a way to pass an Authorization header containing a Bearer token through Swagger UI. I've been searching around, but all the answers seem to point at this link.

However, this assumes that the content of the header is known upfront. I really need a way to change the header within Swagger UI (right before hitting the 'Try it out!' button), because the Bearer token expires every hour. Something similar to the way Postman allows you to add headers.

It seems like such a ridiculously simple problem, but what is the answer?

答:
Create a new operation filter that implements IOperationFilter.

public class AuthorizationHeaderOperationFilter : IOperationFilter
{
    ///
    /// Adds an authorization header to the given operation in Swagger.
    ///
    /// <param name="operation">The Swashbuckle operation.</param>
    /// <param name="context">The Swashbuckle operation filter context.</param>
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
        {
            operation.Parameters = new List<IParameter>();
        }

        var authorizeAttributes = context.ApiDescription
            .ControllerAttributes()
            .Union(context.ApiDescription.ActionAttributes())
            .OfType<AuthorizeAttribute>();
        var allowAnonymousAttributes = context.ApiDescription.ActionAttributes().OfType<AllowAnonymousAttribute>();

        if (!authorizeAttributes.Any() && !allowAnonymousAttributes.Any())
        {
            return;
        }

        var parameter = new NonBodyParameter
        {
            Name = "Authorization",
            In = "header",
            Description = "The bearer token",
            Required = true,
            Type = "string"
        };

        operation.Parameters.Add(parameter);
    }
}
```

<p>Configure the service in your <code>Startup.cs</code> file.</p>

<pre class="lang-cs prettyprint-override"><code>        services.ConfigureSwaggerGen(options =>
        {
            options.OperationFilter<AuthorizationHeaderOperationFilter>();
        });
</code>```

Body:
Create a new operation filter that implements IOperationFilter.

public class AuthorizationHeaderOperationFilter : IOperationFilter
{
    /// <summary>
    /// Adds an authorization header to the given operation in Swagger.
    /// </summary>
    /// <param name="operation">The Swashbuckle operation.</param>
    /// <param name="context">The Swashbuckle operation filter context.</param>
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
        {
            operation.Parameters = new List<IParameter>();
        }

        var authorizeAttributes = context.ApiDescription
            .ControllerAttributes()
            .Union(context.ApiDescription.ActionAttributes())
            .OfType<AuthorizeAttribute>();
        var allowAnonymousAttributes = context.ApiDescription.ActionAttributes().OfType<AllowAnonymousAttribute>();

        if (!authorizeAttributes.Any() && !allowAnonymousAttributes.Any())
        {
            return;
        }

        var parameter = new NonBodyParameter
        {
            Name = "Authorization",
            In = "header",
            Description = "The bearer token",
            Required = true,
            Type = "string"
        };

        operation.Parameters.Add(parameter);
    }
}

Configure the service in your Startup.cs file.

        services.ConfigureSwaggerGen(options =>
        {
            options.OperationFilter<AuthorizationHeaderOperationFilter>();
        });


问:
The day PyCharm thought int / float does not implement __div__
UPDATE
This issue is solved in PyCharm 2017.2

```<code>def foo(x):
    return x / (60 * 60)

z = 1
y = 2
bar = 0 if y == 0 else z / y

foo(bar)
</code>```

This causes PyCharm 2017.1.4 with pretty much default analyzer settings (I believe) show the following warning:

Expected type '{__div__}', got 'Union[int, float]' instead.

This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases

Now, of course Python doesn't have static type checking, but it is obvious here that bar will always be int or float (and PyCharm understands it as evident by got Union[int, float] in the above warning).

So, is this a bug in PyCharm with this specific use case in which it fails to see that int and float do implement __div__, or is there something else that I'm missing here?

UPDATE

Oddly enough, if foo is modified to return x * 60 * 60 the warning goes away and PyCharm doesn't warn about x not implementing __mul__.

UPDATE 2

Changing foo to return float(x) / (60 * 60) obviously makes the warning disappear, but x is already inferred as int or float as evident by the warning itself.

Definitely seems like a bug in PyCharm.

答:
This seems to be a bug of your PyCharm Version, I can't reproduce it in 2017.1.2

Edit: Which Python compiler do you use? 2.7x or 3.x?

Body:
UPDATE
This issue is solved in PyCharm 2017.2

def foo(x):
    return x / (60 * 60)

z = 1
y = 2
bar = 0 if y == 0 else z / y

foo(bar)

This causes PyCharm 2017.1.4 with pretty much default analyzer settings (I believe) show the following warning:

Expected type '{__div__}', got 'Union[int, float]' instead.

This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases

Now, of course Python doesn't have static type checking, but it is obvious here that bar will always be int or float (and PyCharm understands it as evident by got Union[int, float] in the above warning).

So, is this a bug in PyCharm with this specific use case in which it fails to see that int and float do implement __div__, or is there something else that I'm missing here?

UPDATE

Oddly enough, if foo is modified to return x * 60 * 60 the warning goes away and PyCharm doesn't warn about x not implementing __mul__.

UPDATE 2

Changing foo to return float(x) / (60 * 60) obviously makes the warning disappear, but x is already inferred as int or float as evident by the warning itself.

Definitely seems like a bug in PyCharm.


问:
Nashorn NativeDate conversion to java.util.Date
When returning Javascript Date objects to Java with Nashorn on Java 8 like so:

```<code>ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
Object js = engine.eval("new Date();");
</code>```

With the following attempts I get exceptions:

Date javaDate = (Date)js;

jdk.nashorn.api.scripting.ScriptObjectMirror cannot be cast to java.util.Date

Date javaDate = js.to(Date.class);

Cannot cast jdk.nashorn.internal.objects.NativeDate to java.util.Date

Date javaDate = (Date)ScriptUtils.convert(js.to(NativeDate.class), Date.class);

Cannot cast jdk.nashorn.internal.objects.NativeDate to java.util.Date

Back with Rhino I was simply using context.jsToJava(nativeDateObj, Date.class);.

Any ideas how I can actually cast this NativeDate when it's returned to Java?

P.S. If I do js.toString() then it gives me "[Date 2012-01-01T19:00:00.000Z]". I guess I could regex parse that ... but why-oh-why ...

答:
I do this in my project:</p>

```<code>retValue = new Date(value.to(Long.class));
</code>```

Body:
When returning Javascript Date objects to Java with Nashorn on Java 8 like so:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
Object js = engine.eval("new Date();");

With the following attempts I get exceptions:

Date javaDate = (Date)js;

jdk.nashorn.api.scripting.ScriptObjectMirror cannot be cast to java.util.Date

Date javaDate = js.to(Date.class);

Cannot cast jdk.nashorn.internal.objects.NativeDate to java.util.Date

Date javaDate = (Date)ScriptUtils.convert(js.to(NativeDate.class), Date.class);

Cannot cast jdk.nashorn.internal.objects.NativeDate to java.util.Date

Back with Rhino I was simply using context.jsToJava(nativeDateObj, Date.class);.

Any ideas how I can actually cast this NativeDate when it's returned to Java?

P.S. If I do js.toString() then it gives me "[Date 2012-01-01T19:00:00.000Z]". I guess I could regex parse that ... but why-oh-why ...

Body:
I do this in my project:

retValue = new Date(value.to(Long.class));


问:
Why does the original list change?
Running this:

```<code>a = [[1], [2]]
for i in a:
    i *= 2
print(a)
</code>```

Gives

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

I would expect to get the original list, as happens here:

```<code>a = [1, 2]
for i in a:
    i *= 2
print(a)
</code>```

Which gives:

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

Why is the list in the first example being modified?

答:
In the first case your i in the for loop is a list. So you're telling python hey, take the ith list and repeat it twice. You're basically repeating the list 2 times, this is what the * operator does to a list.
In the second case your i is a value, so you're applying * to a value, not a list.

Title: Why does the original list change?

Body:
Running this:

a = [[1], [2]]
for i in a:
    i *= 2
print(a)

Gives

[[1, 1], [2, 2]]

I would expect to get the original list, as happens here:

a = [1, 2]
for i in a:
    i *= 2
print(a)

Which gives:

[1, 2]

Why is the list in the first example being modified?


问:
docker makes port of container open to public
I have on centos7 docker container with nginx.

Port 80 is available from outside despite on that this port NOT opened in firewalld.
here rules for public zone:

```<code># firewall-cmd --zone=public --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eno3
  sources:
  services: dhcpv6-client ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  sourceports:
  icmp-blocks:
  rich rules:
</code>```

but there is a automatic rule for this port in chain DOCKER:

```<code># iptables -L DOCKER
Chain DOCKER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             172.17.0.2           tcp dpt:http
</code>```

how to CLOSE this port from outside?
I've ran the command but it not helped:

```<code># firewall-cmd --zone=public --remove-port=80/tcp --permanent
Warning: NOT_ENABLED: 80:tcp
success
</code>```

I've read docs - https://docs.docker.com/engine/userguide/networking/
but still don't get it..
Actually I need open this port 80 only for my specified network 1.2.3.4/24.

答:
Docker sets iptables rules per default. See Docker's Understand container communication for more information. You can also disable this in the Docker daemon with --iptables=false.

Alternativly with docker-compose file version 2+ you could use the expose keyword instead of ports to open this port only within the Docker network in your docker-compose.yml file.

That said, you should probably disable iptables if you want to use firewalld.

Body:
I have on centos7 docker container with nginx.

Port 80 is available from outside despite on that this port NOT opened in firewalld.
here rules for public zone:

# firewall-cmd --zone=public --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eno3
  sources:
  services: dhcpv6-client ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  sourceports:
  icmp-blocks:
  rich rules:

but there is a automatic rule for this port in chain DOCKER:

# iptables -L DOCKER
Chain DOCKER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             172.17.0.2           tcp dpt:http

how to CLOSE this port from outside?
I've ran the command but it not helped:

# firewall-cmd --zone=public --remove-port=80/tcp --permanent
Warning: NOT_ENABLED: 80:tcp
success

I've read docs - https://docs.docker.com/engine/userguide/networking/
but still don't get it..
Actually I need open this port 80 only for my specified network 1.2.3.4/24.


问:
How can I make substitutions only within the scope of certain LaTeX command arguments?
The below Latex is written in one line, but it could have been over several.

The problem is # in caption commands have to be escaped, so the question is how to do this only within captions?

Or does there exist a Perl/Ruby module that can find the closing } in such a complicated case?

\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}

答:
Just Try this:

```<code>my $str = '\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K
}_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10
\cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{
20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}';
</code>```

You can modify this regex (This is what I am using in my live)

```<code>my $reg = qw/((?:[^{}]*(?:{(?:[^{}]*(?:{(?:[^{}]*(?:{[^{}]*})*[^{}]*)*})*[^{}]*)*})*[^{}]*)*)/;

$str=~s/$reg/$1=~s{\#}{\\#}gr; /seg;

print $str;
</code>```

Output:

```<code> \caption{\small{Et elliptisk omrσde i planen er afgrµnset af en ellipse som er niveaukurven $\mathcal{K
 }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10
 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf\#evncount.20.1}{
 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
</code>```

Body:
Just Try this:

my $str = '\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K
}_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10
\cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{
20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}';

You can modify this regex (This is what I am using in my live)

my $reg = qw/((?:[^{}]*(?:{(?:[^{}]*(?:{(?:[^{}]*(?:{[^{}]*})*[^{}]*)*})*[^{}]*)*})*[^{}]*)*)/;

$str=~s/$reg/$1=~s{\#}{\\#}gr; /seg;

print $str;

Output:

 \caption{\small{Et elliptisk omrσde i planen er afgrµnset af en ellipse som er niveaukurven $\mathcal{K
 }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10
 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf\#evncount.20.1}{
 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}


问:
The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located
It's a WebApi project using VS2015.

Step to reproduce:

Create an empty WebApi project

Change Build output path from "bin\" to "bin\Debug\"

Run

Everything is working perfectly until I changed Build Output path from "bin\" to "bin\Debug\"
In fact, any Output path other than "bin\" won't work.

One little additional thing is that, having another output path to anywhere would work as long as I left a build in "bin\".

Please help providing solution to solve this.
I guess that'll cost problem on actual deployment.

答:
It stopped after publishing on the production server.
The reason why it showed me this error was because it was deployed to a subfolder. In IIS i clicked right on the subfolder and excuted "Convert to application" and after this it worked.


问:
How to speed up Android Studio 2.3 or 3?
My System has 8 GB RAM, i5 Haswell Processor, 2GB Nvidia Graphics card and 512 GB HDD, still my system is unable to deal with Android Studio (both stable and canary versions).

It's frustratingly slow and hangs the entire system. Is it supposed to be like that? Do I need a more powerful system to develop Android apps? It kills the productivity and I am thinking about leaving Android development altogether, due to the amount of time wastage and frustration of dealing with Gradle.

Is there any way I can develop Android apps without getting frustrated, every single time?

Edit
There is a similar question
Android Studio is slow (how to speed up)?, but I am asking about newer versions of Android Studio, where Google claimed (they say that, every year) to have made significant enhancements to build and whatever processes .

Update May 01, 2018
I upgraded my system to 250 GB SSD and now Android Studio seems to load faster by an order of magnitude.

答:
Answer by user: https://stackoverflow.com/users/624706/sergii-pechenizkyi

Source: Building and running app via Gradle and Android Studio is slower than via Eclipse

Hardware

I'm sorry, but upgrading development station to SSD and tons of ram has probably a bigger influence than points below combined.

Tools versions

Increasing build performance has major priority for the development teams, so make sure you are using latest Gradle and Android Gradle Plugin.

Configuration File

Create a file named gradle.properties in whatever directory applies:

/home/<username>/.gradle/ (Linux)

/Users/<username>/.gradle/ (Mac)

C:\Users\<username>\.gradle (Windows)

Append:

```<code># IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# The Gradle daemon aims to improve the startup and execution time of Gradle.
# When set to true the Gradle daemon is to run the build.
# TODO: disable daemon on CI, since builds should be clean and reliable on servers
org.gradle.daemon=true

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.krd1mm27v
org.gradle.jvmargs=-Xmx5120m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true

# Enables new incubating mode that makes Gradle selective when configuring projects.
# Only relevant projects are configured which results in faster builds for large multi-projects.
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true

# Set to true or false to enable or disable the build cache.
# If this parameter is not set, the build cache is disabled by default.
# http://tools.android.com/tech-docs/build-cache
android.enableBuildCache=true
</code>```

Gradle properties works local if you place them at projectRoot\gradle.properties and globally if you place them at user_home\.gradle\gradle.properties. Properties applied if you run gradle tasks from console or directly from idea:

IDE Settings

It is possible to tweak Gradle-IntelliJ integration from the IDE settings GUI. Enabling "offline work" (check answer from yava below) will disable real network requests on every "sync gradle file".

Native multi-dex

One of the slowest steps of the apk build is converting java bytecode into single dex file. Enabling native multidex (minSdk 21 for debug builds only) will help the tooling to reduce an amount of work (check answer from Aksel Willgert below).

Dependencies

Prefer @aar dependencies over library sub-projects.

Search aar package on mavenCentral, jCenter or use jitpack.io to build any library from github. If you are not editing sources of the dependency library you should not build it every time with your project sources.

Antivirus

Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security (don't try this at home!). But if you switch between branches a lot, then antivirus will rescan files before allowing gradle process to use it, which slows build time (in particular AndroidStudio sync project with gradle files and indexing tasks). Measure build time and process CPU with and without antivirus enabled to see if it is related.

Profiling a build

Gradle has built-in support for profiling projects. Different projects are using a different combination of plugins and custom scripts. Using --profile will help to find bottlenecks.

ContentLicense: CC BY-SA 4.0

Body:
Answer by user: https://stackoverflow.com/users/624706/sergii-pechenizkyi

Source: Building and running app via Gradle and Android Studio is slower than via Eclipse

Hardware

I'm sorry, but upgrading development station to SSD and tons of ram has probably a bigger influence than points below combined.

Tools versions

Increasing build performance has major priority for the development teams, so make sure you are using latest Gradle and Android Gradle Plugin.

Configuration File

Create a file named gradle.properties in whatever directory applies:

/home/<username>/.gradle/ (Linux)

/Users/<username>/.gradle/ (Mac)

C:\Users\<username>\.gradle (Windows)

Append:

# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# The Gradle daemon aims to improve the startup and execution time of Gradle.
# When set to true the Gradle daemon is to run the build.
# TODO: disable daemon on CI, since builds should be clean and reliable on servers
org.gradle.daemon=true

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.krd1mm27v
org.gradle.jvmargs=-Xmx5120m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true

# Enables new incubating mode that makes Gradle selective when configuring projects.
# Only relevant projects are configured which results in faster builds for large multi-projects.
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true

# Set to true or false to enable or disable the build cache.
# If this parameter is not set, the build cache is disabled by default.
# http://tools.android.com/tech-docs/build-cache
android.enableBuildCache=true

Gradle properties works local if you place them at projectRoot\gradle.properties and globally if you place them at user_home\.gradle\gradle.properties. Properties applied if you run gradle tasks from console or directly from idea:

IDE Settings

It is possible to tweak Gradle-IntelliJ integration from the IDE settings GUI. Enabling "offline work" (check answer from yava below) will disable real network requests on every "sync gradle file".

Native multi-dex

One of the slowest steps of the apk build is converting java bytecode into single dex file. Enabling native multidex (minSdk 21 for debug builds only) will help the tooling to reduce an amount of work (check answer from Aksel Willgert below).

Dependencies

Prefer @aar dependencies over library sub-projects.

Search aar package on mavenCentral, jCenter or use jitpack.io to build any library from github. If you are not editing sources of the dependency library you should not build it every time with your project sources.

Antivirus

Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security (don't try this at home!). But if you switch between branches a lot, then antivirus will rescan files before allowing gradle process to use it, which slows build time (in particular AndroidStudio sync project with gradle files and indexing tasks). Measure build time and process CPU with and without antivirus enabled to see if it is related.

Profiling a build

Gradle has built-in support for profiling projects. Different projects are using a different combination of plugins and custom scripts. Using --profile will help to find bottlenecks.


问:
Use of sizeof operator in C
I wrote a code to print size of different data types in C .

```<code>#include<stdio.h>
int main()
{
     printf("%d", sizeof(int));//size of integer
     printf("%d", sizeof(float));
     printf("%d", sizeof(double));
     printf("%d", sizeof(char));
}
</code>```

This does not work , but if I replace %d with %ld, it works. I did not understand why I have to take long int to print a small range number.

答:
Both of those are wrong you must use %zu to print values of type size_t, which is what sizeof return.

This is because different values have different size, and you must match them.

It's undefined behavior to mismatch like you do, so anything could happen.

Title: Use of sizeof operator in C

Body:
I wrote a code to print size of different data types in C .

#include<stdio.h>
int main()
{
     printf("%d", sizeof(int));//size of integer
     printf("%d", sizeof(float));
     printf("%d", sizeof(double));
     printf("%d", sizeof(char));
}

This does not work , but if I replace %d with %ld, it works. I did not understand why I have to take long int to print a small range number.


答:
This is because sizes mismatch. By either using %zu or using %u and casting to unsigned you may fix the problem.

Currently, your implementation is undefined behaviour.

```<code> printf("%u", (unsigned)sizeof(int));//size of integer
 printf("%u", (unsigned)sizeof(float));
 printf("%u", (unsigned)sizeof(double));
 printf("%u", (unsigned)sizeof(char));
</code>```

Since stdout is new line buffered, don't forget to print \n at the end to get anything to screen.

Title: Use of sizeof operator in C

Body:
This is because sizes mismatch. By either using %zu or using %u and casting to unsigned you may fix the problem.

Currently, your implementation is undefined behaviour.

 printf("%u", (unsigned)sizeof(int));//size of integer
 printf("%u", (unsigned)sizeof(float));
 printf("%u", (unsigned)sizeof(double));
 printf("%u", (unsigned)sizeof(char));

Since stdout is new line buffered, don't forget to print \n at the end to get anything to screen.


问:
Where can I find diagrams for drupal?
I need some diagrams, especially logic database diagram (Entity Relationship Diagram) of Drupal. I've tried http://drupal.org/node/1161 but all the links are broken.</p>

答:
When you install Drupal with MySQL as database, I suggest using the fine "MySQL Workbench" and reverse engineer the database. No matter the structure, you will find a nice ER-diagramm no matter the Drupal version.

For more figures: Look through the docs and the community pages. There is, for example, a nice illustration how the forms are working.

Title: Where can I find diagrams for drupal?


问:
What is the rails way equivalent of mailto: and tel:?
My model has contact:string and email:string attributes. In pure HTML, we can write

email us

and

```<code><a href="tel:123-456">123-456</a>
</code>```

How do we convert these two into rails code assuming my model name is @sample. My guess would be something like

```<code><%= link_to @sample.email, "#" %>

<%= link_to @sample.contact, "#" %>
</code>```

What should be in the "#" ?

答:
A simple tel_to helper for tel: links:

```<code>def tel_to(phone_number)
  phone_number = number_to_phone(phone_number)
  link_to phone_number, "tel:#{phone_number}"
end

tel_to(8424176704)
# => <a href="tel:842-417-6704">842-417-6704</a>
</code>```

And the existing mail_to for mailto:

```<code>mail_to("Dorian", "dorian@doma.io")
# => "<a href=\"mailto:Dorian\">dorian@doma.io</a>"
</code>```

Body:
My model has contact:string and email:string attributes. In pure HTML, we can write

email us

and

123-456

How do we convert these two into rails code assuming my model name is @sample. My guess would be something like

<%= link_to @sample.email, "#" %>

<%= link_to @sample.contact, "#" %>

What should be in the "#" ?

Body:
A simple tel_to helper for tel: links:

def tel_to(phone_number)
  phone_number = number_to_phone(phone_number)
  link_to phone_number, "tel:#{phone_number}"
end

tel_to(8424176704)
# => <a href="tel:842-417-6704">842-417-6704</a>

And the existing mail_to for mailto:

mail_to("Dorian", "dorian@doma.io")
# => "<a href=\"mailto:Dorian\">dorian@doma.io</a>"


问:
How i can optimize Xpath expression?
I need to concat first 5 symbols of string with 4 last and divide them with '_'.
I came up with this, but it looks so ugly. Can it be rewritten better? I am new to Xpath, so maybe its ok(but i dont think so)</p>

```<code>concat(substring(//element1/element2/text(),1,5),"_",substring(//element1/element2/text(),string-length(//element1/element2/text())-4))
</code>```

答:
As for me,it's pretty OK.
But your code takes 5 last symbols. In order to fix that, I use string-length(//element1/element2)-3
Maybe, text() is not necessary, but I've processed the code via xslt.

Whole expression looks like that:

concat(substring(//element1/element2,1,5),"_",substring(//element1/element2,string-length(//element1/element2)-3))

Title: How i can optimize Xpath expression?

Body:
I need to concat first 5 symbols of string with 4 last and divide them with '_'.
I came up with this, but it looks so ugly. Can it be rewritten better? I am new to Xpath, so maybe its ok(but i dont think so)

concat(substring(//element1/element2/text(),1,5),"_",substring(//element1/element2/text(),string-length(//element1/element2/text())-4))


问:
pausing node-osmosis between scrapes
I am reading the links from csv and using it to scrape. I want the node-osmosis to wait between the scrapes may be after scraping 10 sites. I tried using sleep but it seems to sleep at the wrong time while a the next site is being scraped causing it to fail.

```<code>const osmosis = require('osmosis');
const fs = require('fs');
const stream = fs.createReadStream("data.csv");
const csv = require('fast-csv');

let ii = 0;

const scrapeData = (row) => {

  osmosis
    .get(row[0])
    .set({
      'data': '#data',
    })
    .data(function (listing) {
        fs.appendFileSync('out2.ssv',listing.data);

       if(ii%10 == 0 && ii!==0){
           console.log('ss',ii);
          sleep.sleep(1000);
     }

      }
    })
}

let csvStream = csv()
  .on("data", function (data) {
      scrapeData(data)
      ii++;
  });

  stream.pipe(csvStream);
</code>```

how do I proceed with this problem. thanks in advance.

答:
Your problem is that node is asynchronous. Your query is going to run everything in parallel and sleep after it has done. Perhaps what you want to do is use setInterval or setTimeout. Something like this?</p>

```<code> var shouldPauseForTenSeconds = false
var listOfDataItems = []
var numberOfProcessedItems = 0

function scrapeData (row) {
    if(shouldPauseForTenSeconds) {
        shouldPauseForTenSeconds = false;
        setTimeout(scrapeData.bind(null,row), 10000);
    }
    listOfDataItems.push(row)
    numberOfProcessedItems++;
    if(numberOfProcessedItems % 10 == 0 && numberOfProcessedItems > 0) {
        numberOfProcessedItems = 0;
        shouldPauseForTenSeconds = true;
    }

    osmosis
        .get(row[0])
        .set({
            'data': '#data',
        })
        .data(function (listing) {
            fs.appendFileSync('out2.ssv',listing.data);
        })
}

let csvStream = csv()
.on("data", function (data) {
    scrapeData(data)
    ii++;
});

stream.pipe(csvStream);
</code>```

Title: pausing node-osmosis between scrapes

Body:
I am reading the links from csv and using it to scrape. I want the node-osmosis to wait between the scrapes may be after scraping 10 sites. I tried using sleep but it seems to sleep at the wrong time while a the next site is being scraped causing it to fail.

const osmosis = require('osmosis');
const fs = require('fs');
const stream = fs.createReadStream("data.csv");
const csv = require('fast-csv');

let ii = 0;

const scrapeData = (row) => {

  osmosis
    .get(row[0])
    .set({
      'data': '#data',
    })
    .data(function (listing) {
        fs.appendFileSync('out2.ssv',listing.data);

       if(ii%10 == 0 && ii!==0){
           console.log('ss',ii);
          sleep.sleep(1000);
     }

      }
    })
}

let csvStream = csv()
  .on("data", function (data) {
      scrapeData(data)
      ii++;
  });

  stream.pipe(csvStream);

how do I proceed with this problem. thanks in advance.

Body:
Your problem is that node is asynchronous. Your query is going to run everything in parallel and sleep after it has done. Perhaps what you want to do is use setInterval or setTimeout. Something like this?

 var shouldPauseForTenSeconds = false
var listOfDataItems = []
var numberOfProcessedItems = 0

function scrapeData (row) {
    if(shouldPauseForTenSeconds) {
        shouldPauseForTenSeconds = false;
        setTimeout(scrapeData.bind(null,row), 10000);
    }
    listOfDataItems.push(row)
    numberOfProcessedItems++;
    if(numberOfProcessedItems % 10 == 0 && numberOfProcessedItems > 0) {
        numberOfProcessedItems = 0;
        shouldPauseForTenSeconds = true;
    }

    osmosis
        .get(row[0])
        .set({
            'data': '#data',
        })
        .data(function (listing) {
            fs.appendFileSync('out2.ssv',listing.data);
        })
}

let csvStream = csv()
.on("data", function (data) {
    scrapeData(data)
    ii++;
});

stream.pipe(csvStream);


问:
Objective-c Novice - Needs help with UIViews
Im new to iphone development and after lots of reading on it im still trying to figure out how UIViews operate properly. I have been playing about with it and i this is where i am at so far:

I have created a new xcode project using the view-based application. I have my MMAppViewController classes and i created a new UIViewController subclass called "Level1View".

There is a button titled "Level 1" that takes me to the "Level1View" viewController. In this viewController there is there is a "next" button, a "main menu" button (that returns to MMAppViewController) and there is a label, currently titled "Level 1".

My problem is that the code i have used to change the title of label does not work! Does anyone know why this is? Here is my code:

```<code>@class MMAppViewController;

@interface MMAppAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    MMAppViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MMAppViewController *viewController;

@end
</code>```

and

```<code>@implementation MMAppViewController

-(IBAction)pushLevel1{

    Level1View *level1View = [[Level1View alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:level1View animated:YES];
}
...
</code>```

and

```<code>#import <UIKit/UIKit.h>

@interface Level1View : UIViewController {
    IBOutlet UILabel *labelTitle;

}
-(IBAction)pushBack;
-(IBAction)pushNext;
@end
</code>```

and

```<code> #import "Level1View.h"
    #import "MMAppViewController.h"

    @implementation Level1View

    -(IBAction)pushBack{

        MMAppViewController *MainView = [[MMAppViewController alloc] initWithNibName:nil bundle:nil];
        [self presentModalViewController:MainView animated:YES];

    }
    -(IBAction)pushNext{

        [labelTitle setText:(@"Thanks for playing :)")];

    }

    - (void)didReceiveMemoryWarning {
    ...
</code>```

Currently the app runs but the label wont change when i hit the "next" button. Can anyone help?

答:
are you sure a UINavigationController isn't a better tool for the job you want to do? That will make it easy for you to manage a stack of UIView objects.

That said, have you tried adding logging to make sure your pushNext method is getting called? where is labelTitle declared? Did you use a XIB or not?

Body:
Im new to iphone development and after lots of reading on it im still trying to figure out how UIViews operate properly. I have been playing about with it and i this is where i am at so far:

I have created a new xcode project using the view-based application. I have my MMAppViewController classes and i created a new UIViewController subclass called "Level1View".

There is a button titled "Level 1" that takes me to the "Level1View" viewController. In this viewController there is there is a "next" button, a "main menu" button (that returns to MMAppViewController) and there is a label, currently titled "Level 1".

My problem is that the code i have used to change the title of label does not work! Does anyone know why this is? Here is my code:

@class MMAppViewController;

@interface MMAppAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    MMAppViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MMAppViewController *viewController;

@end

and

@implementation MMAppViewController

-(IBAction)pushLevel1{

    Level1View *level1View = [[Level1View alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:level1View animated:YES];
}
...

and

#import <UIKit/UIKit.h>

@interface Level1View : UIViewController {
    IBOutlet UILabel *labelTitle;

}
-(IBAction)pushBack;
-(IBAction)pushNext;
@end

and

 #import "Level1View.h"
    #import "MMAppViewController.h"

    @implementation Level1View

    -(IBAction)pushBack{

        MMAppViewController *MainView = [[MMAppViewController alloc] initWithNibName:nil bundle:nil];
        [self presentModalViewController:MainView animated:YES];

    }
    -(IBAction)pushNext{

        [labelTitle setText:(@"Thanks for playing :)")];

    }

    - (void)didReceiveMemoryWarning {
    ...

Currently the app runs but the label wont change when i hit the "next" button. Can anyone help?


问:
Retrieve .csr file from jks/cer file
I want to retrieve the csr file from jks or cer file (have lost the .csr file). Please let know if it's possible from keytool command.</p>

答:
You cannot generate a certificate request from a certificate file. You can only do it for a KeyPair that is in your keystore (jks). You can run this keytool command to generate a csr (pkcs#10)

keytool -certreq -keystore [KEYSTORE_PATH] -storepass [KEYSTORE_PASSWORD] -alias [KEYPAIR_ALIAS] -file [CSR_FILE]

You can see the content of the csr you generated by using the below command.

keytool -printcertreq -file [CSR_FILE]

Title: Retrieve .csr file from jks/cer file


问:
Image has extra space at the top
I have an image on my website and there is about 50px of extra white space at the top. I have tried padding none and margin none, display block but none of them work. Here is a working jsfiddle of it.
Here's my HTML

     h1 {
     font-size: 100px;
     color: white;
     text-align: center;
     opacity: none;
     font-family: 'Noto Sans', sans-serif;
      }

    p {
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 70px;
    color: black;
    text-align: center;
    }

      .rotate {
       float: left;
      -webkit-transform: rotate(180deg) 2s;
      transform: rotate(180deg) 2s;
      transition: all 2s ease;
      transition-delay: 0.4s;
        }

      .rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
         }

    .container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
    z-index: 150;
     margin-bottom: -80px;
      }

    .container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
       }

    .dropdown {
    float: right;
    overflow: hidden;
     }

    .dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
      }

       .container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
        }

     .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
     }

    .dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
      }

    .dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
     }

    .dropdown:hover .dropdown-content {
    display: block;
         }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>     <body>
      <div class="active">
      <div id="background">
     <div class="opacity">
     <div class="container">
     <div class="rotate">
     <img class="chiz" src="kkk.png" alt="Vortex Games">
    </div>
       Home
       About
      FAQ
       Games
       <div class="dropdown">
      <button class="dropbtn"
       onclick="window.location.href='store.html'">Store</button>
      <div class="dropdown-content">
        Powerups
        Coins
      </div>
      </div>
       </div>
      </div>
       <p class="title">
       We're a top-of-the-line high tech <br>game company
      <br>
      <span style="color:white;font-size:20px;padding:none;display:inline-
       block;">
      <span style="color:red;font-size:100px;padding-top:none;">
      –<br></span>Driven by passion. Always at our best.</span>
    </p>
     <!--the background div-->
      </div>

      <div class="creative">
     <img src="cree.jpg" align="abstop">
      </div>
CSS</code>```

Any help would be appreciated.

Thanks

答:
By default html page has margin values. Add this to avoid those spaces</p>

```<code>* {
margin: 0;
padding: 0;
}
</code>```

Title: Image has extra space at the top

Body:
I have an image on my website and there is about 50px of extra white space at the top. I have tried padding none and margin none, display block but none of them work. Here is a working jsfiddle of it.
Here's my HTML

     h1 {
     font-size: 100px;
     color: white;
     text-align: center;
     opacity: none;
     font-family: 'Noto Sans', sans-serif;
      }

    p {
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 70px;
    color: black;
    text-align: center;
    }

      .rotate {
       float: left;
      -webkit-transform: rotate(180deg) 2s;
      transform: rotate(180deg) 2s;
      transition: all 2s ease;
      transition-delay: 0.4s;
        }

      .rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
         }

    .container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
    z-index: 150;
     margin-bottom: -80px;
      }

    .container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
       }

    .dropdown {
    float: right;
    overflow: hidden;
     }

    .dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
      }

       .container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
        }

     .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
     }

    .dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
      }

    .dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
     }

    .dropdown:hover .dropdown-content {
    display: block;
         }

       Home
       About
      FAQ
       Games

      <button class="dropbtn"
       onclick="window.location.href='store.html'">Store</button>

        Powerups
        Coins

       We're a top-of-the-line high tech
game company

      –
Driven by passion. Always at our best.

CSS

Any help would be appreciated.

Thanks

Body:
By default html page has margin values. Add this to avoid those spaces

* {
margin: 0;
padding: 0;
}


问:
MySQL syntax error, underscore
Executing this query

```<code>INSERT INTO classes(  '_fkUserID',  'date',  'time' )
VALUES (

'1',  '2017-07-04',  '8:15'
)
</code>```

gives me the following error

```<code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''_fkUserID', 'date', 'time') VALUES ('1', '2017-07-04', '8:15')' at line 1
</code>```

I'm assuming the error has something to do with parsing the underscore, but I can't manage to find a way around it.

答:
Change

```<code>classes('_fkUserID', 'date', 'time')
</code>```

To

```<code>classes(`_fkUserID`,  `date`,  `time`)
</code>```

Single quotes makes the fields as strings

You don't necessarily need to add the backticks on the column names unless they are Reserved Words to the MySql. In your sql statement, date and time are reserved words, so you must use the backticks on it, which means that it would also work as:

```<code>classes(_fkUserID, `date`,  `time`)
</code>```

Backticks are Identifier Quote Characters which means that its purpose is to make MySql understand that it should identify whatever is within it as an identifier, in your case a column name.

Title: MySQL syntax error, underscore

Body:
Executing this query

INSERT INTO classes(  '_fkUserID',  'date',  'time' )
VALUES (

'1',  '2017-07-04',  '8:15'
)

gives me the following error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''_fkUserID', 'date', 'time') VALUES ('1', '2017-07-04', '8:15')' at line 1

I'm assuming the error has something to do with parsing the underscore, but I can't manage to find a way around it.

Body:
Change

classes('_fkUserID', 'date', 'time')

To

classes(`_fkUserID`,  `date`,  `time`)

Single quotes makes the fields as strings

You don't necessarily need to add the backticks on the column names unless they are Reserved Words to the MySql. In your sql statement, date and time are reserved words, so you must use the backticks on it, which means that it would also work as:

classes(_fkUserID, `date`,  `time`)

Backticks are Identifier Quote Characters which means that its purpose is to make MySql understand that it should identify whatever is within it as an identifier, in your case a column name.


答:
It is actually:</p>

```<code>INSERT INTO classes(_fkUserID,date,time)
VALUES (

'1',  '2017-07-04',  '8:15'
)
</code>```

Title: MySQL syntax error, underscore

Body:
It is actually:

INSERT INTO classes(_fkUserID,date,time)
VALUES (

'1',  '2017-07-04',  '8:15'
)


问:
uninitialized constant AWS::S3::NoSuchBucket
I am using Rails 3 with the following code...

```<code>config.gem "aws-s3", :version => ">= 0.6.2", :lib => "aws/s3"
config.gem 'right_aws', :version => '2.0.0'
</code>```

model.rb

```<code>has_attached_file :video,
                      :storage => :s3,
                      :s3_credentials => "#{::Rails.root.to_s}/config/s3.yml",
                      :path => ":attachment/:id/:style/:basename.:extension"

                    # Paperclip Validations
                    validates_attachment_presence :video
                    validates_attachment_content_type :video, :content_type => ['application/x-shockwave-flash', 'application/x-shockwave-flash', 'application/flv', 'video/x-flv']
</code>```

s3.yml

```<code>development:
  bucket_name: tekbookvideo
  access_key_id: xxxx
  secret_access_key: yyyy
production:
  bucket_name: tekbookvideo
  access_key_id: xxxx
  secret_access_key: yyyy
</code>```

And am getting the uninitialized constant AWS::S3::NoSuchBucket error...

I do not know what to do anymore...

答:
It appears to be a bug in the current version of Paperclip. See:

https://github.com/thoughtbot/paperclip/issues/issue/363

Body:
I am using Rails 3 with the following code...

config.gem "aws-s3", :version => ">= 0.6.2", :lib => "aws/s3"
config.gem 'right_aws', :version => '2.0.0'

model.rb

has_attached_file :video,
                      :storage => :s3,
                      :s3_credentials => "#{::Rails.root.to_s}/config/s3.yml",
                      :path => ":attachment/:id/:style/:basename.:extension"

                    # Paperclip Validations
                    validates_attachment_presence :video
                    validates_attachment_content_type :video, :content_type => ['application/x-shockwave-flash', 'application/x-shockwave-flash', 'application/flv', 'video/x-flv']

s3.yml

development:
  bucket_name: tekbookvideo
  access_key_id: xxxx
  secret_access_key: yyyy
production:
  bucket_name: tekbookvideo
  access_key_id: xxxx
  secret_access_key: yyyy

And am getting the uninitialized constant AWS::S3::NoSuchBucket error...

I do not know what to do anymore...


问:
Random string in PHP not enough characters
I'm trying to make some random string in PHP with 5 letters/numbers.
It's working fine but sometimes I get a shorter string.

```<code>$characterset='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$count=0;
$lenght=strlen($characterset);
$i=5; #number of characters
while($count < $i){
  $num=rand(1,$lenght);
  $letter=substr($characterset, $num, 1);
  $string.=$letter;
  $count++;
}
</code>```

And strlen($string) is sometimes 4  (checked 100 records, 85 was 4 characters)

答:
Personally I'd replace your entire logic with this one line wonder :

```<code>print $characters = substr(
                          str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'),
                          0,5)
                          );
</code>```

(slightly off formatting so it fits on the screeen)

Body:
I'm trying to make some random string in PHP with 5 letters/numbers.
It's working fine but sometimes I get a shorter string.

$characterset='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$count=0;
$lenght=strlen($characterset);
$i=5; #number of characters
while($count < $i){
  $num=rand(1,$lenght);
  $letter=substr($characterset, $num, 1);
  $string.=$letter;
  $count++;
}

And strlen($string) is sometimes 4  (checked 100 records, 85 was 4 characters)

Body:
Personally I'd replace your entire logic with this one line wonder :

print $characters = substr(
                          str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'),
                          0,5)
                          );

(slightly off formatting so it fits on the screeen)


问:
Grails 3.3.0.RC Deployment Issue on Tomcat
When I try to deploy my application after upgrade from 3.2.9 to 3.3.0.RC1 (which works fine in my local environment) I occur following error message.
I tried in tomcat 8.0.20, 8.0.28, and 8.5.16. Does anybody has an idea what possibly went wrong?

Feel free to ask for further information.

```<code>2017-07-05 11:28:52.960  INFO --- [ost-startStop-2] fnx1.ApplicationLoader                   : Starting ApplicationLoade
r on krake08.fzi.de with PID 2015 (/usr/lib/apache-tomcat-8.5.16/webapps/ROOT/WEB-INF/classes started by root in /usr/li
b/apache-tomcat-8.5.16)
2017-07-05 11:28:52.966 DEBUG --- [ost-startStop-2] fnx1.ApplicationLoader                   : Running with Spring Boot
v1.5.4.RELEASE, Spring v4.3.9.RELEASE
2017-07-05 11:28:52.966  INFO --- [ost-startStop-2] fnx1.ApplicationLoader                   : The following profiles ar
e active: production
2017-07-05 11:28:57.013 ERROR --- [ost-startStop-2] o.s.boot.SpringApplication               : Application startup faile
d

java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/FilterRegistrationBean
        at asset.pipeline.AssetPipelineGrailsPlugin$_doWithSpring_closure1.doCall(AssetPipelineGrailsPlugin.groovy:104)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
        at groovy.lang.Closure.call(Closure.java:414)
        at groovy.lang.Closure.call(Closure.java:408)
        at grails.spring.BeanBuilder.invokeBeanDefiningClosure(BeanBuilder.java:759)
        at grails.spring.BeanBuilder.beans(BeanBuilder.java:588)
        at grails.spring.BeanBuilder.invokeMethod(BeanBuilder.java:531)
        at org.grails.plugins.DefaultGrailsPlugin.doWithRuntimeConfiguration(DefaultGrailsPlugin.java:559)
        at org.grails.plugins.AbstractGrailsPluginManager.doRuntimeConfiguration(AbstractGrailsPluginManager.java:167)
        at grails.boot.config.GrailsApplicationPostProcessor.postProcessBeanDefinitionRegistry(GrailsApplicationPostProc
essor.groovy:171)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostPro
cessorRegistrationDelegate.java:118)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplic
ationContext.java:687)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext
.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
        at org.springframework.boot.web.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:151)
        at org.grails.boot.context.web.GrailsAppServletInitializer.createRootApplicationContext(GrailsAppServletInitiali
zer.groovy:57)

...
</code>```

Thanks a lot in advance!

EDIT: I append my build.gradle file. Maybe this helps to solve the problem.

```<code>buildscript {
    ext {
        grailsVersion = project.grailsVersion
    }
    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }

        maven { url "http://dl.bintray.com/grails/plugins" }
        maven { url "http://dl.bintray.com/zyro/maven" } //Websocket
        maven { url "http://dl.bintray.com/jamescookie/plugins" } //Quartz Monitor
        maven { url "http://download.java.net/maven/2/" }
        maven { url "http://repo.spring.io/milestone/" }
        maven { url "http://mvnrepository.com/artifact/" }
        maven { url "https://mvnrepository.com/artifact/org.apache.commons/commons-lang3" } //StringEscapeUtils
    }
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
//        classpath 'com.bertramlabs.plugins:asset-pipeline-gradle:2.5.0'
//        classpath 'org.grails.plugins:asset-pipeline:3.2.1'
        classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.14.2"
        classpath "org.grails.plugins:hibernate4:5.0.0" //hibernate:4.3.10.7
    }
}

//plugins {
//    id "io.spring.dependency-management" version "0.5.2.RELEASE"
//}

version "1.0.0"
group "fnx1"

apply plugin: "org.springframework.boot"
apply plugin: "war"
apply plugin: "asset-pipeline"
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: "org.grails.grails-web"
apply plugin: "org.grails.grails-gsp"

ext {
    grailsVersion = project.grailsVersion
    gradleWrapperVersion = project.gradleWrapperVersion

    set "tomcat.version", "8.5.5"
}

assets {
    minifyJs = true
    minifyCss = true
}

repositories {
    mavenLocal()
    maven { url "https://repo.grails.org/grails/core" }
}

dependencyManagement {
    imports {
        mavenBom "org.grails:grails-bom:$grailsVersion"
    }
    applyMavenExclusions false
}

dependencies {

    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"
    compile "org.grails:grails-core"
    compile "org.springframework.boot:spring-boot-starter-actuator"
    provided "org.springframework.boot:spring-boot-starter-tomcat"
//    compile "org.grails:grails-dependencies"
    compile "org.grails:grails-logging"
    compile "org.grails:grails-plugin-rest"
    compile "org.grails:grails-plugin-databinding"
    compile "org.grails:grails-plugin-i18n"
    compile "org.grails:grails-plugin-services"
    compile "org.grails:grails-plugin-url-mappings"
    compile "org.grails:grails-plugin-interceptors"
    compile "org.grails:grails-web-boot"
    compile "org.grails.plugins:cache"
    compile "org.grails.plugins:scaffolding" //runtime
    compile "org.grails.plugins:hibernate5"
    compile "org.grails.plugins:async"
    compile "org.grails.plugins:scaffolding"
    compile "org.grails.plugins:events"
    compile "org.hibernate:hibernate-ehcache"
    compile "org.hibernate:hibernate-core:5.1.5.Final"
    compile "org.grails.plugins:gsp"
    console "org.grails:grails-console"

    console "org.grails:grails-console"
    profile "org.grails.profiles:web:3.1.0" //new
    compile "javax.xml.soap:saaj-api:1.3.4"
    compile "com.sun.xml.messaging.saaj:saaj-impl:1.3"

//    compile "org.grails.plugins:asset-pipeline:3.2.1" //:3.2.1
    runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.14.2"

    testCompile "org.grails:grails-plugin-testing"
    testCompile "org.grails.plugins:geb"

    // Note: It is recommended to update to a more robust driver (Chrome, Firefox etc.)
    testRuntime 'org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1'
    testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"

    //Own dependencies - Start

//    compile 'org.grails.plugins:spring-security-core:3.1.1'
    compile 'org.grails.plugins:spring-security-core:3.2.0.M1'
//    compile 'org.grails.plugins:spring-security-appinfo:3.0.0'
    compile 'org.grails.plugins:quartz:2.0.12'
//    compile 'org.grails.plugins:quartz-monitor:1.3'
//    compile 'org.grails.plugins:mail:2.0.0.RC6'
    compile 'org.grails.plugins:grails-spring-websocket:2.3.0'

//    compile 'org.grails.plugins:database-migration:2.0.0.RC1'
//    compile 'org.liquibase:liquibase-core:3.3.2'

//    compile 'org.apache.commons:commons-lang3:3.1'
//    compile "org.grails.plugins:cookie-session:3.0.0"

    runtime "org.postgresql:postgresql:9.4-1204-jdbc42"

    //Own dependencies - End
}

task wrapper(type: Wrapper) {
    gradleVersion = gradleWrapperVersion
}
</code>```

答:
The problem is definitely

```<code>at asset.pipeline.AssetPipelineGrailsPlugin$_doWithSpring_closure1.doCall(AssetPipelineGrailsPlugin.groovy:104)
</code>```

the asset pipeline plugin. I'm relatively certain the plugin was updated to resolve this problem.

https://github.com/bertramdev/asset-pipeline/issues/145

Looks like fixed in 2.13.2

Body:
When I try to deploy my application after upgrade from 3.2.9 to 3.3.0.RC1 (which works fine in my local environment) I occur following error message.
I tried in tomcat 8.0.20, 8.0.28, and 8.5.16. Does anybody has an idea what possibly went wrong?

Feel free to ask for further information.

2017-07-05 11:28:52.960  INFO --- [ost-startStop-2] fnx1.ApplicationLoader                   : Starting ApplicationLoade
r on krake08.fzi.de with PID 2015 (/usr/lib/apache-tomcat-8.5.16/webapps/ROOT/WEB-INF/classes started by root in /usr/li
b/apache-tomcat-8.5.16)
2017-07-05 11:28:52.966 DEBUG --- [ost-startStop-2] fnx1.ApplicationLoader                   : Running with Spring Boot
v1.5.4.RELEASE, Spring v4.3.9.RELEASE
2017-07-05 11:28:52.966  INFO --- [ost-startStop-2] fnx1.ApplicationLoader                   : The following profiles ar
e active: production
2017-07-05 11:28:57.013 ERROR --- [ost-startStop-2] o.s.boot.SpringApplication               : Application startup faile
d

java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/FilterRegistrationBean
        at asset.pipeline.AssetPipelineGrailsPlugin$_doWithSpring_closure1.doCall(AssetPipelineGrailsPlugin.groovy:104)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
        at groovy.lang.Closure.call(Closure.java:414)
        at groovy.lang.Closure.call(Closure.java:408)
        at grails.spring.BeanBuilder.invokeBeanDefiningClosure(BeanBuilder.java:759)
        at grails.spring.BeanBuilder.beans(BeanBuilder.java:588)
        at grails.spring.BeanBuilder.invokeMethod(BeanBuilder.java:531)
        at org.grails.plugins.DefaultGrailsPlugin.doWithRuntimeConfiguration(DefaultGrailsPlugin.java:559)
        at org.grails.plugins.AbstractGrailsPluginManager.doRuntimeConfiguration(AbstractGrailsPluginManager.java:167)
        at grails.boot.config.GrailsApplicationPostProcessor.postProcessBeanDefinitionRegistry(GrailsApplicationPostProc
essor.groovy:171)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostPro
cessorRegistrationDelegate.java:118)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplic
ationContext.java:687)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext
.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
        at org.springframework.boot.web.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:151)
        at org.grails.boot.context.web.GrailsAppServletInitializer.createRootApplicationContext(GrailsAppServletInitiali
zer.groovy:57)

...

Thanks a lot in advance!

EDIT: I append my build.gradle file. Maybe this helps to solve the problem.

buildscript {
    ext {
        grailsVersion = project.grailsVersion
    }
    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }

        maven { url "http://dl.bintray.com/grails/plugins" }
        maven { url "http://dl.bintray.com/zyro/maven" } //Websocket
        maven { url "http://dl.bintray.com/jamescookie/plugins" } //Quartz Monitor
        maven { url "http://download.java.net/maven/2/" }
        maven { url "http://repo.spring.io/milestone/" }
        maven { url "http://mvnrepository.com/artifact/" }
        maven { url "https://mvnrepository.com/artifact/org.apache.commons/commons-lang3" } //StringEscapeUtils
    }
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
//        classpath 'com.bertramlabs.plugins:asset-pipeline-gradle:2.5.0'
//        classpath 'org.grails.plugins:asset-pipeline:3.2.1'
        classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.14.2"
        classpath "org.grails.plugins:hibernate4:5.0.0" //hibernate:4.3.10.7
    }
}

//plugins {
//    id "io.spring.dependency-management" version "0.5.2.RELEASE"
//}

version "1.0.0"
group "fnx1"

apply plugin: "org.springframework.boot"
apply plugin: "war"
apply plugin: "asset-pipeline"
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: "org.grails.grails-web"
apply plugin: "org.grails.grails-gsp"

ext {
    grailsVersion = project.grailsVersion
    gradleWrapperVersion = project.gradleWrapperVersion

    set "tomcat.version", "8.5.5"
}

assets {
    minifyJs = true
    minifyCss = true
}

repositories {
    mavenLocal()
    maven { url "https://repo.grails.org/grails/core" }
}

dependencyManagement {
    imports {
        mavenBom "org.grails:grails-bom:$grailsVersion"
    }
    applyMavenExclusions false
}

dependencies {

    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"
    compile "org.grails:grails-core"
    compile "org.springframework.boot:spring-boot-starter-actuator"
    provided "org.springframework.boot:spring-boot-starter-tomcat"
//    compile "org.grails:grails-dependencies"
    compile "org.grails:grails-logging"
    compile "org.grails:grails-plugin-rest"
    compile "org.grails:grails-plugin-databinding"
    compile "org.grails:grails-plugin-i18n"
    compile "org.grails:grails-plugin-services"
    compile "org.grails:grails-plugin-url-mappings"
    compile "org.grails:grails-plugin-interceptors"
    compile "org.grails:grails-web-boot"
    compile "org.grails.plugins:cache"
    compile "org.grails.plugins:scaffolding" //runtime
    compile "org.grails.plugins:hibernate5"
    compile "org.grails.plugins:async"
    compile "org.grails.plugins:scaffolding"
    compile "org.grails.plugins:events"
    compile "org.hibernate:hibernate-ehcache"
    compile "org.hibernate:hibernate-core:5.1.5.Final"
    compile "org.grails.plugins:gsp"
    console "org.grails:grails-console"

    console "org.grails:grails-console"
    profile "org.grails.profiles:web:3.1.0" //new
    compile "javax.xml.soap:saaj-api:1.3.4"
    compile "com.sun.xml.messaging.saaj:saaj-impl:1.3"

//    compile "org.grails.plugins:asset-pipeline:3.2.1" //:3.2.1
    runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.14.2"

    testCompile "org.grails:grails-plugin-testing"
    testCompile "org.grails.plugins:geb"

    // Note: It is recommended to update to a more robust driver (Chrome, Firefox etc.)
    testRuntime 'org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1'
    testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"

    //Own dependencies - Start

//    compile 'org.grails.plugins:spring-security-core:3.1.1'
    compile 'org.grails.plugins:spring-security-core:3.2.0.M1'
//    compile 'org.grails.plugins:spring-security-appinfo:3.0.0'
    compile 'org.grails.plugins:quartz:2.0.12'
//    compile 'org.grails.plugins:quartz-monitor:1.3'
//    compile 'org.grails.plugins:mail:2.0.0.RC6'
    compile 'org.grails.plugins:grails-spring-websocket:2.3.0'

//    compile 'org.grails.plugins:database-migration:2.0.0.RC1'
//    compile 'org.liquibase:liquibase-core:3.3.2'

//    compile 'org.apache.commons:commons-lang3:3.1'
//    compile "org.grails.plugins:cookie-session:3.0.0"

    runtime "org.postgresql:postgresql:9.4-1204-jdbc42"

    //Own dependencies - End
}

task wrapper(type: Wrapper) {
    gradleVersion = gradleWrapperVersion
}

Body:
The problem is definitely

at asset.pipeline.AssetPipelineGrailsPlugin$_doWithSpring_closure1.doCall(AssetPipelineGrailsPlugin.groovy:104)

the asset pipeline plugin. I'm relatively certain the plugin was updated to resolve this problem.

https://github.com/bertramdev/asset-pipeline/issues/145

Looks like fixed in 2.13.2


问:
What's the benefit of Scala (singleton) object vs. typical class level artifacts
I understand one of the main benefits from using object is, they are real objects instead of system wide functionality.  But finally those objects are also system wide accessible.

Beside of being more "pure"  what additional benefit does scala "objects" offer.

I bet there are a number but I can't really figure out which.

答:
objects are independent entities, e.g. they can be used as method arguments, as target for implicit conversions, and case objects in pattern matching...

objects can inherit from classes or traits

an object has its own type

objects can restrict the access of its members, even for the companion class:

.

```<code>object X {
  private[this] val z=1
}

class X {
  import X._
  //won't compile
  println(z)
}
</code>```

Body:
objects are independent entities, e.g. they can be used as method arguments, as target for implicit conversions, and case objects in pattern matching...

objects can inherit from classes or traits

an object has its own type

objects can restrict the access of its members, even for the companion class:

.

object X {
  private[this] val z=1
}

class X {
  import X._
  //won't compile
  println(z)
}