问:
sql site or book with exercise queries more complicated than www3.schools.com
Hi
is there any online resource for practicing SQL queries more complicated ?
basically I had a db dev until now and I kind of forgot. I want to switch jobs and freshen up a little.
They should more complicated than 2 joins or something, as my level is medium or senior hopefully :)
Thank you</p>

答:
It may be a bit dry, but if you're mid to senior level why not just look at the transact-sql reference on MSDN: http://msdn.microsoft.com/en-us/library/bb510741.aspx

Take a look at what's possible with the product, both the supporting examples and documentation are detailed and insightful. Many of the examples use the AdventureWorks sample database which you can download from codeplex


来源: stackexchange

问:
Call a controller method in a view
I've got an asp.net core application in Visual studio.
In a auto-created view (Events/index.cshtml) I want to call this method from the EventsController.cs

```<code>public Boolean IsInRole(string Role)
{
    Boolean roleMembership = false;

    if (HttpContext.Session.GetInt32("ID") != null)
    {
        if (HttpContext.Session.GetString("Role") == Role)
        {
            roleMembership = true;
        }
    }

    return roleMembership;
}
</code>```

My idea was to call this method at the top of the view with

```<code>@if(IsInRole("Admin")) {
    show some content
}
</code>```

How can I achieve this task?

答:
Since this is a generic method not specific to any controller, move it into a separate class.

Then you can reference that class's namespace in your view with a @using directive (almost exactly like you would in a .cs file), and then call the method.

ContentLicense: CC BY-SA 3.0

Title: Call a controller method in a view

Body:
I've got an asp.net core application in Visual studio.
In a auto-created view (Events/index.cshtml) I want to call this method from the EventsController.cs

public Boolean IsInRole(string Role)
{
    Boolean roleMembership = false;

    if (HttpContext.Session.GetInt32("ID") != null)
    {
        if (HttpContext.Session.GetString("Role") == Role)
        {
            roleMembership = true;
        }
    }

    return roleMembership;
}

My idea was to call this method at the top of the view with

@if(IsInRole("Admin")) {
    show some content
}

How can I achieve this task?


问:
Start reading a line after n characters
I am making a program that take the data from internet, more specifically this url: https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt

I want to calculate the standings based on the result, but I'm struggling with reading the file since I haven't figured out how to get the result in the middle of the line. I noticed there is a certain pattern in the text such as the results are always written after 27 characters, beginning with a white space but I don't know how to implement that into my code in order to extract the results and I also wonder if there were any better way to achieve this (I tried using delimiter but it didn't work).
Therefore, any help or advice would be very appreciated.

答:
You can get the result with a matcher, see code below. You just need read the file line by line

```<code>public static void main(String[] args) {
        String mydata = "Arsenal FC               4-3  Leicester City";
        Pattern pattern = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}");
        Matcher matcher = pattern.matcher(mydata);
        String result = "";
        if (matcher.find()) {
            result = matcher.group();
            mydata = mydata.replace(result, "#");
        }
        String[] dataSplit = mydata.split("#");

        HashMap<String, String> match = new HashMap<>();

        match.put("local", dataSplit[0].trim());
        match.put("visitor", dataSplit[1].trim());
        match.put("result", result);

        System.out.println(match.get("local"));
        System.out.println(match.get("result"));
        System.out.println(match.get("visitor"));
}
</code>```

Output:

Arsenal FC
4-3
Leicester City

When you have the result you can replace it for a # for example, then split that line by # and you get both teams. From here is easy to create a map or a json with both teams and the match result

Title: Start reading a line after n characters

Body:
You can get the result with a matcher, see code below. You just need read the file line by line

public static void main(String[] args) {
        String mydata = "Arsenal FC               4-3  Leicester City";
        Pattern pattern = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}");
        Matcher matcher = pattern.matcher(mydata);
        String result = "";
        if (matcher.find()) {
            result = matcher.group();
            mydata = mydata.replace(result, "#");
        }
        String[] dataSplit = mydata.split("#");

        HashMap<String, String> match = new HashMap<>();

        match.put("local", dataSplit[0].trim());
        match.put("visitor", dataSplit[1].trim());
        match.put("result", result);

        System.out.println(match.get("local"));
        System.out.println(match.get("result"));
        System.out.println(match.get("visitor"));
}

Output:

Arsenal FC
4-3
Leicester City

When you have the result you can replace it for a # for example, then split that line by # and you get both teams. From here is easy to create a map or a json with both teams and the match result


问:
Autolayout : Need constraints for y position or height
I am trying to satisfying the constraint form a long time but getting above error i.e. is "Need constraints for y position or height" for Yellow View and Green View. Basically I have 2 UILabel (dynamic height) within UIView and UIImageView of 4:3 ratio within a Cell.

And my applied constraint is

I am also including sample project here with above issue.

答:
Just one Constraints required

Provide SubHeading label height >= (Greater than equal to ) Constraints

Because of you have applied aspect ratio of UIImageView  of 4:3
so it required to fixed other items height and Y position before it apply a ratio to it.
By giving height to subheading Autolayout is able to calculate approx value min required in image ratio

Hope it is helpful to you


问:
How do I install a specific version of a git commit library in Linux?
How to install a specific version of git commit in Linux? When any program requests for the library it should take from the installation.

Eg:
The following version of wiringPi is required by one of my c++ program.

```<code>git://git.drogon.net/wiringPi
Version: 5edd177112c99416f68ba3e8c6c4db6ed942e796
</code>```

答:
Add a checkout statement after you clone?

Eg:

```<code>git clone git://git.drogon.net/wiringPi
git checkout 5edd177112c99416f68ba3e8c6c4db6ed942e796
</code>```

Then you type the build and installation commands - if you want everything to use it, it probably needs to go in the default location. For the package you're looking at the documentation says it's:

```<code>./build
</code>```

If you already have a version from a package manager (like apt you should remove that first - the README.md from the package you linked explains how to do this)

Body:
How to install a specific version of git commit in Linux? When any program requests for the library it should take from the installation.

Eg:
The following version of wiringPi is required by one of my c++ program.

git://git.drogon.net/wiringPi
Version: 5edd177112c99416f68ba3e8c6c4db6ed942e796

Body:
Add a checkout statement after you clone?

Eg:

git clone git://git.drogon.net/wiringPi
git checkout 5edd177112c99416f68ba3e8c6c4db6ed942e796

Then you type the build and installation commands - if you want everything to use it, it probably needs to go in the default location. For the package you're looking at the documentation says it's:

./build

If you already have a version from a package manager (like apt you should remove that first - the README.md from the package you linked explains how to do this)


问:
How to find all children from another table?
I have two tables

CATEGORY

```<code>id   category     parent_id
1    Electronic
2    Furniture
3    Phone        1
4    LCD          1
5    Watch        1
6    Desk         2
</code>```

ORDER

```<code>id customer product      category_id
1  John     Smartphone   3
2  Marry    Montior      4
3  King     Wood-Desk    6
</code>```

I want to find all of electronic result by child_id.

Like this..

```<code>SELECT product FROM order WHERE category_id = (category.id = 1)
</code>```

RESULT

```<code>product
Smartphone
Monitor
</code>```

Is there any expression like this in MySQL?

答:
You have to use INNER JOIN

```<code>SELECT order.product
FROM order
INNER JOIN category
ON order.category_id = category.id
WHERE category.parent_id = 1
</code>```

The ON keyword shows what columns will be compare between these tables. When you make a JOIN you need to put the table name before the column name separated with "." because it is possible to exist a column with the same name in both tables.

Body:
I have two tables

CATEGORY

id   category     parent_id
1    Electronic
2    Furniture
3    Phone        1
4    LCD          1
5    Watch        1
6    Desk         2

ORDER

id customer product      category_id
1  John     Smartphone   3
2  Marry    Montior      4
3  King     Wood-Desk    6

I want to find all of electronic result by child_id.

Like this..

SELECT product FROM order WHERE category_id = (category.id = 1)

RESULT

product
Smartphone
Monitor

Is there any expression like this in MySQL?

Body:
You have to use INNER JOIN

SELECT order.product
FROM order
INNER JOIN category
ON order.category_id = category.id
WHERE category.parent_id = 1

The ON keyword shows what columns will be compare between these tables. When you make a JOIN you need to put the table name before the column name separated with "." because it is possible to exist a column with the same name in both tables.


问:
Html text colours heatmap lots of font tags (slow)
I'm currently writing an application that returns an array or [word, value] tuples. For example:

```<code>var data =
[['Hello', 1]
['world', 1]
['how', 5]
['are', 9]
['you', 16]
['?', 1]]
</code>```

I want to display the text word by word as a heatmap according to it's value. There can be many words/sentences that appear hot in a large text corpus leading to many font tags:

```<code><font color="#{value}">{word}</font>
</code>```

Example:

```<code><font color="#111">hello</font>
<font color="#111">world</font>
<font color="#555">how</font>
<font color="#999">are</font>
<font color="#FFF">you</font>
<font color="#111">?</font>
</code>```

All of the tags create a huge DOM and this can cause the browser to become very slow. This can be seen when scrolling or interacting with the text.

Are there any alternatives that offer better performance? I need the text to be selectable so images won't suffice.

答:
I have created two tests in JS Fiddle to approximate what your question was describing, one using classes and the other programmatically assigning an inline colour to the text:

Inline based array of values:
http://jsfiddle.net/h6kd5zu4/

```<code>["Lorem", 0],
["ipsum", 1],
["dolor", 2],
...

let colourList = [
  ["000"],
  ["111"],
  ["222"],
  ...

let theColor = colourList[randomWords[i][1]];
let listItem = "<p style='color:#" + theColor + "'>" + randomWords[i][0] + "</p>";
</code>```

Class based array of values:
http://jsfiddle.net/cjgwuk2q/

```<code>["Lorem","zero"],
["ipsum","one"],
["dolor","two"],
...

let listItem = "<p class="+ randomWords[i][1] +">" + randomWords[i][0] + "</p>";

<p class="zero">Lorem</p>

.zero {
  color: #000;
}
</code>```

Results

For an array 10000 items long the difference is fairly tiny:

Inline colours: 34ms

CSS classes: 20ms

You could get some savings by pre-assigning each item with a CSS class but it's very minimal.

Considering that this is a list of 10000 items and it's loading in around 30ms, how many items are you talking about and also how are you actually adding the items to the DOM?

I have created a third test which writes each item to the DOM rather than building a 'virtual' set of items first and then appending the whole lot in one go. I am wondering if you are rewriting the DOM on each addition, if so this takes considerably longer at around 5 seconds just for 2000 items:

http://jsfiddle.net/k6mnefLb/

Possible solutions

If the above hasn't brought any help to your situation you could try one of the following:

Build the view backend so there isn't as much heavy DOM work on the client side

Split the list into blocks of results, either lazyload the results as the user scrolls/interacts or put them into a multiple pages/paginated sections

Body:
I'm currently writing an application that returns an array or [word, value] tuples. For example:

var data =
[['Hello', 1]
['world', 1]
['how', 5]
['are', 9]
['you', 16]
['?', 1]]

I want to display the text word by word as a heatmap according to it's value. There can be many words/sentences that appear hot in a large text corpus leading to many font tags:

{word}

Example:

hello
world
how
are
you
?

All of the tags create a huge DOM and this can cause the browser to become very slow. This can be seen when scrolling or interacting with the text.

Are there any alternatives that offer better performance? I need the text to be selectable so images won't suffice.

Body:
I have created two tests in JS Fiddle to approximate what your question was describing, one using classes and the other programmatically assigning an inline colour to the text:

Inline based array of values:
http://jsfiddle.net/h6kd5zu4/

["Lorem", 0],
["ipsum", 1],
["dolor", 2],
...

let colourList = [
  ["000"],
  ["111"],
  ["222"],
  ...

let theColor = colourList[randomWords[i][1]];
let listItem = "<p style='color:#" + theColor + "'>" + randomWords[i][0] + "</p>";

Class based array of values:
http://jsfiddle.net/cjgwuk2q/

["Lorem","zero"],
["ipsum","one"],
["dolor","two"],
...

let listItem = "<p class="+ randomWords[i][1] +">" + randomWords[i][0] + "</p>";

<p class="zero">Lorem</p>

.zero {
  color: #000;
}

Results

For an array 10000 items long the difference is fairly tiny:

Inline colours: 34ms

CSS classes: 20ms

You could get some savings by pre-assigning each item with a CSS class but it's very minimal.

Considering that this is a list of 10000 items and it's loading in around 30ms, how many items are you talking about and also how are you actually adding the items to the DOM?

I have created a third test which writes each item to the DOM rather than building a 'virtual' set of items first and then appending the whole lot in one go. I am wondering if you are rewriting the DOM on each addition, if so this takes considerably longer at around 5 seconds just for 2000 items:

http://jsfiddle.net/k6mnefLb/

Possible solutions

If the above hasn't brought any help to your situation you could try one of the following:

Build the view backend so there isn't as much heavy DOM work on the client side

Split the list into blocks of results, either lazyload the results as the user scrolls/interacts or put them into a multiple pages/paginated sections


问:
jquery to display comments and clickable link in asp.net datalist
I am a new coder trying to experiment with jquery for my first time. I'm trying to setup a simple datalist that might be used to display comments for an item. I want a clickable link (per datalist row) to drop down a panel (per datalist row) that has comment text. so the user looks at row 1, clicks it's link to read comments, and the comments panel drops down. they scroll down and do the same for the next item.

so far i have the below code as a small test page, but it's not working. nothing happens basically. I'm hoping someone can help me out because i'm very new and just teaching myself this stuff from what I see in tutorial videos and such. I tried the clientID thing because it seems i need that to deal with the auto-generated ID's .NET will assign panels as it's rendered, but i'm not sure if i'm doing it right.

greatly appreciate your time and effort.

head section

```<code><script src="jquery-1.4.4.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function() {
       $('Panel1text').hide();
    });

    $("#<%=HyperLink1.ClientID%>").click(function() {
        $("<%=Panel1text.ClientID%>").show();
    });
</script>
</code>```

body section

```<code>    <asp:DataList ID="DataList1" runat="server" DataKeyField="cid"
        DataSourceID="SqlDataSource1" Width="645px">
        <ItemTemplate>
            cid:
            <asp:Label ID="cidLabel" runat="server" Text='<%# Eval("cid") %>' />
            <br />
            cuser:
            <asp:Label ID="cuserLabel" runat="server" Text='<%# Eval("cuser") %>' />
            <br />
            blogid:
            <asp:Label ID="blogidLabel" runat="server" Text='<%# Eval("blogid") %>' />
            <br />
            <br />
            <asp:HyperLink ID="HyperLink1" runat="server">show text</asp:HyperLink>
            <br />
            <asp:Panel ID="Panel1text" runat="server">
                <asp:Label ID="textLabel" runat="server" Text='<%# Eval("text") %>' />
            </asp:Panel>
            <br />
        </ItemTemplate>
    </asp:DataList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT * FROM [ocomments]"></asp:SqlDataSource>
</code>```

答:
It looks to me like you are going to have multiple elements with the id of 'HyperLink1' and 'Panel1text'. I would recommend using classes instead. Add a "class='link'" to the link element and a "class='panel'" to the panel element. Use the following CSS to initially hide the panels:

```<code>.panel { display: none; }
</code>```

Then use the following jQuery to show the element:

```<code>$(document).ready(function(){

   $(".link").click(function(evt){
      evt.preventDefault(); // prevents the click from leaving the page

      $(this).next().show(); // show the panel

   });

});
</code>```

You may need to fiddle with the '.next().show()' selector a bit. Not certain how ASP.NET is going to render out the elements.

Bob

ContentLicense: CC BY-SA 2.5

Body:
I am a new coder trying to experiment with jquery for my first time. I'm trying to setup a simple datalist that might be used to display comments for an item. I want a clickable link (per datalist row) to drop down a panel (per datalist row) that has comment text. so the user looks at row 1, clicks it's link to read comments, and the comments panel drops down. they scroll down and do the same for the next item.

so far i have the below code as a small test page, but it's not working. nothing happens basically. I'm hoping someone can help me out because i'm very new and just teaching myself this stuff from what I see in tutorial videos and such. I tried the clientID thing because it seems i need that to deal with the auto-generated ID's .NET will assign panels as it's rendered, but i'm not sure if i'm doing it right.

greatly appreciate your time and effort.

head section

body section

    <asp:DataList ID="DataList1" runat="server" DataKeyField="cid"
        DataSourceID="SqlDataSource1" Width="645px">
        <ItemTemplate>
            cid:
            <asp:Label ID="cidLabel" runat="server" Text='<%# Eval("cid") %>' />

            cuser:
            <asp:Label ID="cuserLabel" runat="server" Text='<%# Eval("cuser") %>' />

            blogid:
            <asp:Label ID="blogidLabel" runat="server" Text='<%# Eval("blogid") %>' />

            <asp:HyperLink ID="HyperLink1" runat="server">show text</asp:HyperLink>

            <asp:Panel ID="Panel1text" runat="server">
                <asp:Label ID="textLabel" runat="server" Text='<%# Eval("text") %>' />
            </asp:Panel>

        </ItemTemplate>
    </asp:DataList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT * FROM [ocomments]"></asp:SqlDataSource>

Body:
It looks to me like you are going to have multiple elements with the id of 'HyperLink1' and 'Panel1text'. I would recommend using classes instead. Add a "class='link'" to the link element and a "class='panel'" to the panel element. Use the following CSS to initially hide the panels:

.panel { display: none; }

Then use the following jQuery to show the element:

$(document).ready(function(){

   $(".link").click(function(evt){
      evt.preventDefault(); // prevents the click from leaving the page

      $(this).next().show(); // show the panel

   });

});

You may need to fiddle with the '.next().show()' selector a bit. Not certain how ASP.NET is going to render out the elements.

Bob


问:
Injecting Context in MVP Presenter Android
I am using MVP Architecture along with Dagger2. I want to get Context in my Presenter using constructor injection.

My Activity :

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appintroduction);
        activityComponent().inject(this);
        ButterKnife.bind(this);
        skipall.bringToFront();
     }
</code>```

My Presenter:

```<code>@ConfigPersistent

    public class AppIntroPresenter extends BasePresenter<AppIntroMvpView> {

        private final DataManager mDataManager;
        private final Context ctx1;

        @Inject
        public AppIntroPresenter(DataManager dataManager,Context context) {
            mDataManager = dataManager;
            ctx1=context;

        }

        public void openCamView(Context ctx) {

            ctx.startActivity(new Intent(ctx, CameraActivity.class));
        }
    }
</code>```

My Application Component :

```<code>@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

    void inject(SyncService syncService);

    @ApplicationContext Context context();
    Application application();
    RibotsService ribotsService();
    PreferencesHelper preferencesHelper();
    DatabaseHelper databaseHelper();
    DataManager dataManager();
    RxEventBus eventBus();
    ClassService classService();
    AnsweredQuestionService answeredQuestionService();
}
</code>```

My Activity Component:

```<code>@PerActivity
@Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {

    void inject(MainActivity mainActivity);
    void inject(CameraActivity cameraActivity);
    void inject(AppIntroActivity appIntroActivity);

}
</code>```

My Application Module:

```<code>@Module
public class ApplicationModule {
    protected final Application mApplication;

    public ApplicationModule(Application application) {
        mApplication = application;
    }

    @Provides
    Application provideApplication() {
        return mApplication;
    }

    @Provides
    @ApplicationContext
    Context provideContext() {
        return mApplication;
    }

    @Provides
    @Singleton
    RibotsService provideRibotsService() {
        return RibotsService.Creator.newRibotsService();
    }

    @Provides
    @Singleton
    ClassService provideClassService() {
        return ClassService.Creator.newClassService();
    }

    @Provides
    @Singleton
    AnsweredQuestionService provideAnsweredQuestionService() {
        return AnsweredQuestionService.Creator.newAnsweredQuestionService();
    }

}
</code>```

My Activity Module:

```<code>@Module
public class ActivityModule {

    private Activity mActivity;

    public ActivityModule(Activity activity) {
        mActivity = activity;
    }

    @Provides
    Activity provideActivity() {
        return mActivity;
    }

}
</code>```

After running the code, i get error:

```<code>Error:(17, 8) error: [uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity)] android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter.<init>(…, context)
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity.mAppIntroPresenter
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity is injected at
uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(appIntroActivity)
</code>```

I know when i add context to constructor injection in My Presenter i get this error, but i am not able to figure out why? If i remove the context from constructor :

```<code>@Inject
        public AppIntroPresenter(DataManager dataManager,Context context) {
            mDataManager = dataManager;
            ctx1=context;

        }
</code>```

Then everything works fine. But i need the context from injection. Please help me with this?

答: Since your constructor has members, you need to create a module and create there an instance annotated with @Provides and @Singleton, same as ApplicationModule.

Body:
I am using MVP Architecture along with Dagger2. I want to get Context in my Presenter using constructor injection.

My Activity :

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appintroduction);
        activityComponent().inject(this);
        ButterKnife.bind(this);
        skipall.bringToFront();
     }

My Presenter:

@ConfigPersistent

    public class AppIntroPresenter extends BasePresenter<AppIntroMvpView> {

        private final DataManager mDataManager;
        private final Context ctx1;

        @Inject
        public AppIntroPresenter(DataManager dataManager,Context context) {
            mDataManager = dataManager;
            ctx1=context;

        }

        public void openCamView(Context ctx) {

            ctx.startActivity(new Intent(ctx, CameraActivity.class));
        }
    }

My Application Component :

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

    void inject(SyncService syncService);

    @ApplicationContext Context context();
    Application application();
    RibotsService ribotsService();
    PreferencesHelper preferencesHelper();
    DatabaseHelper databaseHelper();
    DataManager dataManager();
    RxEventBus eventBus();
    ClassService classService();
    AnsweredQuestionService answeredQuestionService();
}

My Activity Component:

@PerActivity
@Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {

    void inject(MainActivity mainActivity);
    void inject(CameraActivity cameraActivity);
    void inject(AppIntroActivity appIntroActivity);

}

My Application Module:

@Module
public class ApplicationModule {
    protected final Application mApplication;

    public ApplicationModule(Application application) {
        mApplication = application;
    }

    @Provides
    Application provideApplication() {
        return mApplication;
    }

    @Provides
    @ApplicationContext
    Context provideContext() {
        return mApplication;
    }

    @Provides
    @Singleton
    RibotsService provideRibotsService() {
        return RibotsService.Creator.newRibotsService();
    }

    @Provides
    @Singleton
    ClassService provideClassService() {
        return ClassService.Creator.newClassService();
    }

    @Provides
    @Singleton
    AnsweredQuestionService provideAnsweredQuestionService() {
        return AnsweredQuestionService.Creator.newAnsweredQuestionService();
    }

}

My Activity Module:

@Module
public class ActivityModule {

    private Activity mActivity;

    public ActivityModule(Activity activity) {
        mActivity = activity;
    }

    @Provides
    Activity provideActivity() {
        return mActivity;
    }

}

After running the code, i get error:

Error:(17, 8) error: [uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity)] android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter.<init>(…, context)
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity.mAppIntroPresenter
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity is injected at
uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(appIntroActivity)

I know when i add context to constructor injection in My Presenter i get this error, but i am not able to figure out why? If i remove the context from constructor :

@Inject
        public AppIntroPresenter(DataManager dataManager,Context context) {
            mDataManager = dataManager;
            ctx1=context;

        }

Then everything works fine. But i need the context from injection. Please help me with this?


问:
Spark Streaming: Application health
I have a Kafka based Spark Streaming application that runs every 5 mins. Looking at the statistics after 5 days of run, there are a few observations:

The Processing time gradually increases from 30 secs to 50 secs. The snapshot is shown below which highlights the processing time chart:

A good number of Garbage collection logs are appearing as shown below:

Questions:

Is there a good explanation why the Processing Time has increased substantially, even when number of events are more or less same (during the last trough) ?

I am getting almost 70 GC logs at the end of each processing cycle. It is normal?

Is the a better strategy to ensure the processing time to remain with in acceptable delays?

答:
It really depends on the application. The way I'd approach when debugging this issue is the following:

Under Storage tab see whether the stored sizes are not growing. If there's a growth this can indicate some kind of cached resources leak. Check what's the value of spark.cleaner.ttl, but better make sure you uncache all the resources when they are not needed anymore.

Inspect DAG visualization of running jobs, and see whether the lineage is not growing. If this is the case, make sure to perform checkpointing to cut the lineage.

Reduce the number of retained batches in UI (spark.streaming.ui.retainedBatches parameter).

Even the number of events is the same, please see whether the amount of data processed by tasks doesn't grow with time (Stages tab -> Input column). This could point to an application level issue.

I've had relatively complex Spark Streaming applications (Spark v1.6, v2.1.1, v2.2.0) running for days without any degradation in performance, so there must be some solvable issue.

Title: Spark Streaming: Application health


问:
React native picker looks good in andriod but awful in ios
I use a react native picker for three different things the user has to fill in to report his/her time to the company. It all looks good on Android with a small field that you click then the options popup but in ios it becomes this huge field where you cycle throu the options. I thought this was a common problem bu cant seem to find how people do to make it look similar to the android way.

anyone have any idea or perhaps doen this before?

答:
Maybe, you can assign a different style depending of the platform ( Android - IOS):</p>

```<code>    import { Platform, Text, TouchableOpacity } from 'react-native';

    function SubmitBtn ({ onPress }) {
        return (
          <TouchableOpacity style={Platform.OS === 'ios' ? styles.iosSubmitBtn : styles.androidSubmitBtn} onPress={onPress}>
              <Text style={styles.submitBtnText}>Submit</Text>
          </TouchableOpacity>
        )
    }

const styles = StyleSheet.create({
    iosSubmitBtn: {
        backgroundColor: lightPurp,
        marginTop: 50,
        padding: 10,
        borderRadius: 7,
        height: 45,
        marginLeft: 20,
        marginRight: 20,
    },

    androidSubmitBtn: {
        backgroundColor: lightPurp,
        marginTop: 50,
        padding: 10,
        paddingLeft: 30,
        paddingRight: 30,
        height: 45,
        borderRadius: 2,
        marginLeft: 20,
        marginRight: 20,
        justifyContent: 'center',
        alignItems: 'center',
    },

    submitBtnText: {
        color: white,
        fontSize: 22,
        textAlign: 'center',
    },
});
</code>```

Body:
Maybe, you can assign a different style depending of the platform ( Android - IOS):

    import { Platform, Text, TouchableOpacity } from 'react-native';

    function SubmitBtn ({ onPress }) {
        return (
          <TouchableOpacity style={Platform.OS === 'ios' ? styles.iosSubmitBtn : styles.androidSubmitBtn} onPress={onPress}>
              <Text style={styles.submitBtnText}>Submit</Text>
          </TouchableOpacity>
        )
    }

const styles = StyleSheet.create({
    iosSubmitBtn: {
        backgroundColor: lightPurp,
        marginTop: 50,
        padding: 10,
        borderRadius: 7,
        height: 45,
        marginLeft: 20,
        marginRight: 20,
    },

    androidSubmitBtn: {
        backgroundColor: lightPurp,
        marginTop: 50,
        padding: 10,
        paddingLeft: 30,
        paddingRight: 30,
        height: 45,
        borderRadius: 2,
        marginLeft: 20,
        marginRight: 20,
        justifyContent: 'center',
        alignItems: 'center',
    },

    submitBtnText: {
        color: white,
        fontSize: 22,
        textAlign: 'center',
    },
});


问:
AWS ECS - Rails Container is not able to connect linked container mysql via mysqld.sock
I have setup application on AWS ECS , with repository, task and cluster management.
My Dockerfile is

```<code>FROM ruby:2.4.1
ENV LANG C.UTF-8

RUN apt-get update && \
    apt-get install -y nodejs \
                       vim \
                       mysql-client --no-install-recommends && rm -rf /var/lib/apt/lists/*

WORKDIR /tmp
ADD ./Gemfile Gemfile
ADD ./Gemfile.lock Gemfile.lock
RUN bundle install

ENV APP_ROOT /workspace
RUN mkdir -p $APP_ROOT
WORKDIR $APP_ROOT
COPY . $APP_ROOT

EXPOSE  3000
CMD ["rails", "server", "-b", "0.0.0.0", "-e", "production"]
</code>```

This is a repository which I have set up on the AWS ECS repository.

In the task destination I have set up two containers rail-app and mysql, which are linked to each other

From the rails-app, I am trying to connect RDS mysql instance, but as its throwing following error, I have added mysql container to support the connection which I think is not required as well

When I run the application with added task in the cluster service . Both containers runs fine, But on the rails-app container I got this error.

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)

When I run rails c production under docker exec -it containerid bash it runs fine and connects db properly. Here I can test active records as well

Please provide me a solution in task destination to share volume of mysql to rails application.

答:
I am answering my own question here,

I have assigned env variables on the container section of task. Which were not loaded properly on the environment. When I have used figaro with application.yml It has started using variables as per the environment.

Mysql was not able to get the host from environment

Body:
I have setup application on AWS ECS , with repository, task and cluster management.
My Dockerfile is

FROM ruby:2.4.1
ENV LANG C.UTF-8

RUN apt-get update && \
    apt-get install -y nodejs \
                       vim \
                       mysql-client --no-install-recommends && rm -rf /var/lib/apt/lists/*

WORKDIR /tmp
ADD ./Gemfile Gemfile
ADD ./Gemfile.lock Gemfile.lock
RUN bundle install

ENV APP_ROOT /workspace
RUN mkdir -p $APP_ROOT
WORKDIR $APP_ROOT
COPY . $APP_ROOT

EXPOSE  3000
CMD ["rails", "server", "-b", "0.0.0.0", "-e", "production"]

This is a repository which I have set up on the AWS ECS repository.

In the task destination I have set up two containers rail-app and mysql, which are linked to each other

From the rails-app, I am trying to connect RDS mysql instance, but as its throwing following error, I have added mysql container to support the connection which I think is not required as well

When I run the application with added task in the cluster service . Both containers runs fine, But on the rails-app container I got this error.

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)

When I run rails c production under docker exec -it containerid bash it runs fine and connects db properly. Here I can test active records as well

Please provide me a solution in task destination to share volume of mysql to rails application.


问:
How can I test a plug that calls an action_fallback controller?
Hello I am currently trying to get this test pass

```<code>  test "authentication plug should return 401 when not authenticated", %{conn: conn} do
    conn = Map.put(conn, :params, %{})
    conn =  ChaacServerWeb.Plugs.Authentication.call(conn, nil)
    assert json_response(conn, 401)["errors"] != %{}
  end
</code>```

Here is my plug

```<code>  def call(conn, _) do
     token = List.first(get_req_header(conn, "authorization"))
     case Accounts.validate_token(conn.params["user_id"], token) do
     {:ok, valid_token} -> conn
     err ->
       conn
       |> halt()
       |> ChaacServerWeb.FallbackController.call(err)
     end
  end
</code>```

I get this error

```<code>1) test authentication plug should return 401 when not authenticated (ChaacServerWeb.AuthenticationTest)                                                                               test/chaac_server_web/plugs/authentication_test.exs:26
** (RuntimeError) cannot render template :"401" because conn.params["_format"] is not set.
Please set `plug :accepts, ~w(html json ...)` in your pipeline.
code: conn =  ChaacServerWeb.Plugs.Authentication.call(conn, nil)
stacktrace:
 (phoenix) lib/phoenix/controller.ex:689: Phoenix.Controller.render/3
 test/chaac_server_web/plugs/authentication_test.exs:28: (test)
</code>```

I understand I need to call plug :accepts, [:json] somehow in my test setup but how do I do that? Thanks

(EDIT) My router has plug :accepts, [:json] in my pipeline

答:
You can use put_req_header:

```<code>setup %{conn: conn} do
    {:ok, conn: put_req_header(conn, "accept", "application/json")}
end
</code>```

Body:
Hello I am currently trying to get this test pass

  test "authentication plug should return 401 when not authenticated", %{conn: conn} do
    conn = Map.put(conn, :params, %{})
    conn =  ChaacServerWeb.Plugs.Authentication.call(conn, nil)
    assert json_response(conn, 401)["errors"] != %{}
  end

Here is my plug

  def call(conn, _) do
     token = List.first(get_req_header(conn, "authorization"))
     case Accounts.validate_token(conn.params["user_id"], token) do
     {:ok, valid_token} -> conn
     err ->
       conn
       |> halt()
       |> ChaacServerWeb.FallbackController.call(err)
     end
  end

I get this error

1) test authentication plug should return 401 when not authenticated (ChaacServerWeb.AuthenticationTest)                                                                               test/chaac_server_web/plugs/authentication_test.exs:26
** (RuntimeError) cannot render template :"401" because conn.params["_format"] is not set.
Please set `plug :accepts, ~w(html json ...)` in your pipeline.
code: conn =  ChaacServerWeb.Plugs.Authentication.call(conn, nil)
stacktrace:
 (phoenix) lib/phoenix/controller.ex:689: Phoenix.Controller.render/3
 test/chaac_server_web/plugs/authentication_test.exs:28: (test)

I understand I need to call plug :accepts, [:json] somehow in my test setup but how do I do that? Thanks

(EDIT) My router has plug :accepts, [:json] in my pipeline

Body:
You can use put_req_header:

setup %{conn: conn} do
    {:ok, conn: put_req_header(conn, "accept", "application/json")}
end


问:
Vue.js + TypeScript project doesn't render template inside .vue file
I'm trying to set up a Vue TS based project. You can view a structure of it inside this repo:

https://github.com/AndrewBogdanovTSS/typed-vue-test

I'm using latest versions of all dependencies that are required to render TS inside .vue files. Once I'm running a project my TS constructor seems to be running without any issues (I see console statements are working normally) but the problem is that template data isn't getting to the browser's DOM. Moreover, the default div with id app is getting removed so the only thing that is left inside of my DOM is a reference to build.js file.
I don't have any errors occurring on the first run, but once I do any change inside of the .vue file I'm getting:

```<code>TypeError: Cannot read property 'extend' of undefined
</code>```

答:
I've figured out what was wrong with my code, I forgot to use @Component decorator in front of my ts class inside App.vue file. Without it, TS code has been executing but it wasn't connected to the Vue instance, that's why nothing was displaying on the screen.
I went and created a new repo that I plan to support as my base template for Vue-TS type projects.
https://github.com/AndrewBogdanovTSS/typed-vue

feel free to suggest improvements/ideas

Body:
I'm trying to set up a Vue TS based project. You can view a structure of it inside this repo:

https://github.com/AndrewBogdanovTSS/typed-vue-test

I'm using latest versions of all dependencies that are required to render TS inside .vue files. Once I'm running a project my TS constructor seems to be running without any issues (I see console statements are working normally) but the problem is that template data isn't getting to the browser's DOM. Moreover, the default div with id app is getting removed so the only thing that is left inside of my DOM is a reference to build.js file.
I don't have any errors occurring on the first run, but once I do any change inside of the .vue file I'm getting:

TypeError: Cannot read property 'extend' of undefined


问:
Slick slider change speed after change
What i want achieve is to change autoplay speed when the first animation will be loaded.

I found that slick has afterChange function but I don't know how to use it.

My code:

```<code>  $(".home-slider-t").slick({
      dots: false,
      arrows: true,
      infinite: false,
      speed: 2500,
      slidesToShow: 1,
      autoplay: true,
      fade: true,
      autoplaySpeed: 6000
  });
</code>```

I want to set autoplay speed to 15 000ms after first change. (infinite true)

答:
Please note: If you provide a demo of your problem in jsfiddle help us to help you better because this is a plugin. anyways lets see what options we have:

First initialize the plugin

```<code>$(".home-slider-t").slick({
  dots: false,
  arrows: true,
  infinite: false,
  speed: 2500,
  slidesToShow: 1,
  autoplay: true,
  fade: true,
  autoplaySpeed: 6000,
});
</code>```

and then use slick plugin events and methods:

```<code>$(".home-slider-t").on('afterChange', function(event, slick, currentSlide, nextSlide){
    $(".home-slider-t").slick('slickSetOption', 'autoplaySpeed', '15000');
});
</code>```

p.s: Hope this code help to get idea of using methods and events of this plugin.
i couldn't check the code because you didn't provide any jsfiddle but seems its fine.

Title: Slick slider change speed after change

Body:
What i want achieve is to change autoplay speed when the first animation will be loaded.

I found that slick has afterChange function but I don't know how to use it.

My code:

  $(".home-slider-t").slick({
      dots: false,
      arrows: true,
      infinite: false,
      speed: 2500,
      slidesToShow: 1,
      autoplay: true,
      fade: true,
      autoplaySpeed: 6000
  });

I want to set autoplay speed to 15 000ms after first change. (infinite true)

Body:
Please note: If you provide a demo of your problem in jsfiddle help us to help you better because this is a plugin. anyways lets see what options we have:

First initialize the plugin

$(".home-slider-t").slick({
  dots: false,
  arrows: true,
  infinite: false,
  speed: 2500,
  slidesToShow: 1,
  autoplay: true,
  fade: true,
  autoplaySpeed: 6000,
});

and then use slick plugin events and methods:

$(".home-slider-t").on('afterChange', function(event, slick, currentSlide, nextSlide){
    $(".home-slider-t").slick('slickSetOption', 'autoplaySpeed', '15000');
});

p.s: Hope this code help to get idea of using methods and events of this plugin.
i couldn't check the code because you didn't provide any jsfiddle but seems its fine.


问:
'http': a namespace with this name does not exist C++ rest SDK

I'm working on a project which is using C++ RESTAPI. Im follwing Casablanca tutorial. According to that tutorial I added Casablanca to my C++ console aplication project using NuGet package manager. I am using Visual Studio 2015 Enterprise Edition. I am getting errors when I try to build my solution that 'http': a namespace with this name does not exist

'web': a namespace with this name does not exist

'web': is not a class or namespace name

'http': a namespace with this name does not exist

'web': is not a class or namespace name

'client': a namespace with this name does not exist

'concurrency': is not a class or namespace name

'streams': a namespace with this name does not exist.
enter image description here
'make_shared': is not a member of 'std'

```<code>enter code here
// RESTProject.cpp : Defines the entry point for the console application.
//
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <fstream>
#include <iostream>
#include "stdafx.h"

using namespace std;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
using namespace std;

int main()
{
    auto filestream = std::make_shared<concurrency::streams::ostream>();
    pplx::task<void> requesttask =concurrency::streams::fstream::open_ostream(U("result.html")).then([=](concurrency::streams::ostream outfile)
    {
        *filestream = outfile;

        // Create http_client to send the request.
        http_client client(U("http://www.bing.com/"));

        // Build request URI and start the request.
        uri_builder builder(U("/search"));
        builder.append_query(U("q"), U("cpprestsdk github"));
        return client.request(methods::GET, builder.to_string());
    });
    return 0;
}
</code>```

答:
I had to add stdio.h include
to resolve the issue</p>

Body:
I'm working on a project which is using C++ RESTAPI. Im follwing Casablanca tutorial. According to that tutorial I added Casablanca to my C++ console aplication project using NuGet package manager. I am using Visual Studio 2015 Enterprise Edition. I am getting errors when I try to build my solution that 'http': a namespace with this name does not exist

'web': a namespace with this name does not exist

'web': is not a class or namespace name

'http': a namespace with this name does not exist

'web': is not a class or namespace name

'client': a namespace with this name does not exist

'concurrency': is not a class or namespace name

'streams': a namespace with this name does not exist.
enter image description here
'make_shared': is not a member of 'std'

enter code here
// RESTProject.cpp : Defines the entry point for the console application.
//
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <fstream>
#include <iostream>
#include "stdafx.h"

using namespace std;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
using namespace std;

int main()
{
    auto filestream = std::make_shared<concurrency::streams::ostream>();
    pplx::task<void> requesttask =concurrency::streams::fstream::open_ostream(U("result.html")).then([=](concurrency::streams::ostream outfile)
    {
        *filestream = outfile;

        // Create http_client to send the request.
        http_client client(U("http://www.bing.com/"));

        // Build request URI and start the request.
        uri_builder builder(U("/search"));
        builder.append_query(U("q"), U("cpprestsdk github"));
        return client.request(methods::GET, builder.to_string());
    });
    return 0;
}


问:
mysql escaping single and double quotes
I have a script that i am writing to move certain fields to a new db like

```<code>$results = mysql_query ( "SELECT body, title  FROM $source_db.Post" );
while ($row = mysql_fetch_array($results)) {
if(mysql_num_rows($users_result) > 0){
    $insert = "INSERT INTO wp_posts (`body`,`title`) VALUES ('{$row['body']}', '{$row['row']}')";
    mysql_query($insert);
    }
}
</code>```

but as you can see the query will break everytime due to the single and double quotes, is there a solution to this problem like herdok or something

```<code>INSERT INTO wp_posts (`body`,`title`)
            VALUES
                ('Here are the final returns from today's ...<br /><br />he stayed home...<br />
<div class="entry-content">
<div class="entry-body">', 'something')
</code>```

答: The sanest approach is to use bound parameters. Bobby Tables has examples. </p>

Title: mysql escaping single and double quotes

Body:
I have a script that i am writing to move certain fields to a new db like

$results = mysql_query ( "SELECT body, title  FROM $source_db.Post" );
while ($row = mysql_fetch_array($results)) {
if(mysql_num_rows($users_result) > 0){
    $insert = "INSERT INTO wp_posts (`body`,`title`) VALUES ('{$row['body']}', '{$row['row']}')";
    mysql_query($insert);
    }
}

but as you can see the query will break everytime due to the single and double quotes, is there a solution to this problem like herdok or something

INSERT INTO wp_posts (`body`,`title`)
            VALUES
                ('Here are the final returns from today's ...

he stayed home...

', 'something')


问:
Laravel foreach Looping Returns Weird Result
I have a problem with when I 'm looping through a result set with a relation inside that I am foreach-ing as well.

This is the code currently:

```<code><?php

$deadlines = App\Deadlines::where('beginDatum', '<=', date("Y-m-d"))
    ->where('eindDatum', '>=', date("Y-m-d"))
    ->first();

$totalActivities = App\UserActivity::where('userid', Auth::id())
    ->where('deadline', '=', $deadlines->id)
    ->count();

if($totalActivities > 0) {
    $activiteiten = \App\User::find(Auth::id());
    foreach ($activiteiten->useractivities as $user_activity) {
        if ($deadlines->id == $user_activity->deadline) {
            print_r("<div class='col-md-4'><input type='text' value='$user_activity->datum' class='form-control'></div>");
            foreach ($user_activity->activity as $activity) {
                print_r("<div class='col-md-7'><input type='text' value='$activity->activiteit' class='form-control'></div>");
            }
            print_r("<div class='col-md-1'><input type='submit' class='btn btn-primary' value='Edit'></div>");
        }
    }
} else {
?>

<br/>U heeft nog geen activiteiten toegevoegd!

<?php
}
</code>```

But it has some strange behaviour when there is a duplicate 'activityid' in the 'user_activity' table. For example...

```<code>|--------------------------------------|
|  date     |  userid     | activityid |
|--------------------------------------|
| 2017-12-28| 1           | 1          |
| 2017-11-30| 1           | 1          |
|--------------------------------------|
</code>```

It has two of the same activityid's so the name of the activity is the same, but I don't know why it only shows the date of duplicate activities. When there is only one entry of an activityid it shows just fine:
https://gyazo.com/11cc6828f97e7a191bf40c8b74448e83

答:
You should be making use of Laravel Eloquent many-to-many relationships for this kind of query.

Assuming you're using Laravel 5.5, this documentation entry will help:

https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

Basically, in your model definitions, you should be setting up the relationships. For example, in the Deadline model's definition, you would have something like the following:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Deadline extends Model
{
    /**
     * The activities associated with this deadline
     */
    public function activities()
    {
        return $this->belongsToMany('App\UserActivity');
    }
}
</code>```

If you have this set up for all of your related Models, then you can do things like this:

```<code>$user = App\User::findOrFail(Auth::id());
$today = date("Y-m-d");

$activities = $user->activities->whereHas('deadlines', function ($query) {
    $query->where('beginDatum', '<=', $today)->where('eindDatum', '>=', $today;
})->get();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with when I 'm looping through a result set with a relation inside that I am foreach-ing as well.

This is the code currently:

<?php

$deadlines = App\Deadlines::where('beginDatum', '<=', date("Y-m-d"))
    ->where('eindDatum', '>=', date("Y-m-d"))
    ->first();

$totalActivities = App\UserActivity::where('userid', Auth::id())
    ->where('deadline', '=', $deadlines->id)
    ->count();

if($totalActivities > 0) {
    $activiteiten = \App\User::find(Auth::id());
    foreach ($activiteiten->useractivities as $user_activity) {
        if ($deadlines->id == $user_activity->deadline) {
            print_r("
<input type='text' value='$user_activity->datum' class='form-control'>
");
            foreach ($user_activity->activity as $activity) {
                print_r("
<input type='text' value='$activity->activiteit' class='form-control'>
");
            }
            print_r("
<input type='submit' class='btn btn-primary' value='Edit'>
");
        }
    }
} else {
?>

U heeft nog geen activiteiten toegevoegd!

<?php
}

But it has some strange behaviour when there is a duplicate 'activityid' in the 'user_activity' table. For example...

|--------------------------------------|
|  date     |  userid     | activityid |
|--------------------------------------|
| 2017-12-28| 1           | 1          |
| 2017-11-30| 1           | 1          |
|--------------------------------------|

It has two of the same activityid's so the name of the activity is the same, but I don't know why it only shows the date of duplicate activities. When there is only one entry of an activityid it shows just fine:
https://gyazo.com/11cc6828f97e7a191bf40c8b74448e83

Body:
You should be making use of Laravel Eloquent many-to-many relationships for this kind of query.

Assuming you're using Laravel 5.5, this documentation entry will help:

https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

Basically, in your model definitions, you should be setting up the relationships. For example, in the Deadline model's definition, you would have something like the following:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Deadline extends Model
{
    /**
     * The activities associated with this deadline
     */
    public function activities()
    {
        return $this->belongsToMany('App\UserActivity');
    }
}

If you have this set up for all of your related Models, then you can do things like this:

$user = App\User::findOrFail(Auth::id());
$today = date("Y-m-d");

$activities = $user->activities->whereHas('deadlines', function ($query) {
    $query->where('beginDatum', '<=', $today)->where('eindDatum', '>=', $today;
})->get();


问:
Render plotly.js graph without GUI freezing (Web Worker?)
I'm working on an dashboard where users can build their own visualizations (with plotly.js).
Sometimes the complexity of these visualizations are resulting in a long rendering time which leads to a freezing Browser UI.

I've already created web-workers for other tasks in my dashboard. Maybe there is a way of rendering plotly.js graphs in a web-worker and return them to the main thread?

I know that there is no DOM/Canvas ability in web-workers. But maybe there is trick or you know a better way to prevent GUI freezing? Maybe outsourcing rendering to server with phantomjs (I've never used it so it is just a guess that it could work with pjs).

答:
A possible solution for your problem could be the OffscreenCanvas API: https://developer.mozilla.org/de/docs/Web/API/OffscreenCanvas

You can access this API from a worker and maybe also use it directly with the library you mentioned.

But as browser support is really bad and (at least in Firefox, I don't know how it currently is with other browsers, https://bugzilla.mozilla.org/show_bug.cgi?id=801176) 2d canvas context is not supported (but if you use a library which uses WebGL that wouldn't be an issue).

As an alternative, you could use a pure javascript polyfill (it's a re-implementation) of canvas which works in WebWorkers:
https://www.npmjs.com/package/canvas-webworker
It's worth mentioning that this way no hardware acceleration is appliable.

In combination, a good solution could be created.


问:
Make some sub-directories using one rule in makefile
I am trying to make some sub directories in a makefile. I know how to do it using a rule for each sub-directory. I am looking for the syntax that will do it using one rule for all subdirectories (either using a loop or using SUBDIRs list).

For example:

```<code>$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/rm/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/utility/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/lzo/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)
</code>```

答:
This should do the job (GNU make):

```<code>define DIR_RULE
$$(dst_dir)/%.o : $$(M2M_GENERIC_DIR)/$(1)/%.c
    $$(TRACE_CC)
    $$(Q)$$(GCC) -c $$(CFLAGS) $$< -o $$@
    $$(Q)$$(GCC) -c $$(CFLAGS) -MM -MT $$@ -MF $$(subst .o,.d,$$@) $$< -o $$(subst .o,.d,$$@)
endef
SUBDIRS = rm/src utility/src fota/src fota/src/lzo
$(foreach d,$(SUBDIRS),$(eval $(call DIR_RULE,$(d))))
</code>```

For a slightly more detailed explanation, see for instance this other question (and answer).

Body:
I am trying to make some sub directories in a makefile. I know how to do it using a rule for each sub-directory. I am looking for the syntax that will do it using one rule for all subdirectories (either using a loop or using SUBDIRs list).

For example:

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/rm/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/utility/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

$(dst_dir)/%.o : $(M2M_GENERIC_DIR)/fota/src/lzo/%.c
    $(TRACE_CC)
    $(Q)$(GCC) -c $(CFLAGS) $< -o $@
    $(Q)$(GCC) -c $(CFLAGS) -MM -MT $@ -MF $(subst .o,.d,$@) $< -o $(subst .o,.d,$@)

Body:
This should do the job (GNU make):

define DIR_RULE
$$(dst_dir)/%.o : $$(M2M_GENERIC_DIR)/$(1)/%.c
    $$(TRACE_CC)
    $$(Q)$$(GCC) -c $$(CFLAGS) $$< -o $$@
    $$(Q)$$(GCC) -c $$(CFLAGS) -MM -MT $$@ -MF $$(subst .o,.d,$$@) $$< -o $$(subst .o,.d,$$@)
endef
SUBDIRS = rm/src utility/src fota/src fota/src/lzo
$(foreach d,$(SUBDIRS),$(eval $(call DIR_RULE,$(d))))

For a slightly more detailed explanation, see for instance this other question (and answer).


问:
Is using a cached "this" faster than "this" when accessing methods of the same object?
if I access this.something multiple times from another method, would it be faster to cache "this" and access something() or should I just use this.something() over and over?</p>

```<code><script type="text/javascript">
var Foo = (function() {
    return {
        something: function() {
            // Do something
        },
        stuff: function(obj) {
            this.something(obj);
            // ...
            this.something(obj);

            /* OR should I cache this? */
            var $that = this;
            $that.something(obj);
            // ...
            $that.something(obj);
        }
    };
}());
</script>
</code>```

答:
Update: Check CMS' comment below for the real truth (but I don't think it changes anything regarding performance).

Approximate truth:

No, it won't make any difference. Upon execution of the function, an activation object is created and put at the beginning of the scope chain of the function (more specifically, its execution context).

The activation object has the properties this, arguments, one property for each parameter passed and for each variable declared in the function.

Hence, this and $that live in the same scope and you gain nothing from it. You only get an improvement, when you reference an object/value locally that is in a higher scope.

```<code>  +-------------------+     +-------------+
  | Execution Context |  +->| Scope Chain |
  | ----------------- |  |  | ----------- |
  | Scope chain  +----+--+  | 0    |  +---+----------+
  +-------------------+     | 1    |  +---+-...      |
                            +-------------+          |
                                                     |
                                                     |
                                                     |
                            +--------------------+   |
                            |  Activation Object |<--+
                            | ------------------ |
                            | this     |  foo    |  (if called with foo.method())
                            | arguments|[someObj]|
                            | obj      | someObj |
                            | $that    |  foo    | (undefined until assignment)
                            +--------------------+
</code>```

Graphic stolen from High Performance JavaScript. It's an interesting book to read.

Body:
Update: Check CMS' comment below for the real truth (but I don't think it changes anything regarding performance).

Approximate truth:

No, it won't make any difference. Upon execution of the function, an activation object is created and put at the beginning of the scope chain of the function (more specifically, its execution context).

The activation object has the properties this, arguments, one property for each parameter passed and for each variable declared in the function.

Hence, this and $that live in the same scope and you gain nothing from it. You only get an improvement, when you reference an object/value locally that is in a higher scope.

  +-------------------+     +-------------+
  | Execution Context |  +->| Scope Chain |
  | ----------------- |  |  | ----------- |
  | Scope chain  +----+--+  | 0    |  +---+----------+
  +-------------------+     | 1    |  +---+-...      |
                            +-------------+          |
                                                     |
                                                     |
                                                     |
                            +--------------------+   |
                            |  Activation Object |<--+
                            | ------------------ |
                            | this     |  foo    |  (if called with foo.method())
                            | arguments|[someObj]|
                            | obj      | someObj |
                            | $that    |  foo    | (undefined until assignment)
                            +--------------------+

Graphic stolen from High Performance JavaScript. It's an interesting book to read.


问:
Globally installed keyboard hook prevents keyboard input to other applications
I am setting a global hook for keyboard. When I give keyboard inputs to other applications, the application does not receive the input and it hangs. When the console is stopped, the application recovers and the keyboard inputs are posted together.

DLL source:

```<code>#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
#define DLLEXPORT __declspec(dllexport)

DLLEXPORT bool installhook();
DLLEXPORT void unhook();
DLLEXPORT string TestLoaded();
DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam );

static HHOOK kb_hook;
string test = "not loaded";
HINSTANCE hDLL;

DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam )
{
    if(code == HC_ACTION)   // if there is an incoming action and a key was pressed
    {
        switch(wParam)
        {
        case VK_SPACE:
            printf("Space was pressed\n"); //tried without this also
            MessageBoxA(NULL, "Hi", "Space", MB_OK);
            break;
        }
    }
    return CallNextHookEx(NULL, code, wParam, lParam);
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    test = "loaded";
    switch(ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hDLL = hModule;
        break;
    }
    printf("test str = %s \n", test.c_str());
    return TRUE;
}

bool installhook()
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, hDLL, NULL);
    if(!kb_hook)
    {
        return false;
    }
    return true;
}

void unhook()
{
    if(kb_hook)
    {
        UnhookWindowsHookEx(kb_hook);
    }
}

string TestLoaded()
{
    return test;
}
</code>```

Console applicatioon source:

```<code>#include <iostream>
#include <Windows.h>
#include <string>
#define DLLIMPORT __declspec(dllimport)
using namespace std;

DLLIMPORT void unhook();
DLLIMPORT bool installhook();
DLLIMPORT string TestLoaded();

int main()
{
    cout << TestLoaded() <<endl;
    installhook();
    for(int i = 1; i<=10 ; i++)
    {
        //Do some keyboard activities in this 10 secs
        Sleep(1000);
        cout << i<<endl;
    }

    unhook();
    cin.get();
    return 1;
}
</code>```

My suspicion was that since the dll will be loaded into each process in the process's own address space and console would not be present in other applications, it gets void and crashed. So I removed the console outputs and replaced with messagebox. Then also no difference.

What could be the problem?

Update:

I tried to do a local hook to a specific thread before trying it global. But I get Parameter is incorrect error 87 at setwindowshookex. Below are the updated code:

dll:

```<code>bool installhook(DWORD ThreadId) //exporting this function
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, NULL, ThreadId); //tried with the dll module's handle also instead of NULL
    if(!kb_hook)
    {
        printf("SetWindowsHookEx failed : %d\n", GetLastError());
        return false;
    }
    return true;
}
</code>```

Console application source:

```<code>DWORD myThread()
{
    cout<< "Thread started\n";
    char str[250];
    cin>>str;
    return 0;
}

int main()
{
    cout << TestLoaded() <<endl;
    DWORD myThreadID;
    HANDLE myHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)myThread, NULL, 0, &myThreadID);
    installhook(myThreadID);
    for(int i = 0; i<100 ; i++)
    {
        Sleep(100);
        if(i%10 == 0)
        {
            cout << i<<endl;
        }
    }
    unhook();
}
</code>```

答:
Try to use WH_KEYBOARD_LL. You can set global hook even without dll declaring hook function in you process. Plus, you should detect space action using PKBDLLHOOKSTRUCT struct</p>

```<code>LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam )
{
   if ( code == HC_ACTION )
   {
       switch ( wParam )
       {
          case WM_KEYDOWN:
          {
              // Get hook struct
              PKBDLLHOOKSTRUCT p = ( PKBDLLHOOKSTRUCT ) lParam;
              if ( p->vkCode == VK_SPACE)
              {
                MessageBoxA( NULL, "Hi", "Space", MB_OK );
              }
          }
       break;
       }
   }
   return CallNextHookEx( NULL, code, wParam, lParam );
 }

 ....
 // Somewhere in code
 kb_hook = SetWindowsHookEx( WH_KEYBOARD_LL, KeyboardProc, NULL, NULL );
</code>```

Body:
I am setting a global hook for keyboard. When I give keyboard inputs to other applications, the application does not receive the input and it hangs. When the console is stopped, the application recovers and the keyboard inputs are posted together.

DLL source:

#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
#define DLLEXPORT __declspec(dllexport)

DLLEXPORT bool installhook();
DLLEXPORT void unhook();
DLLEXPORT string TestLoaded();
DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam );

static HHOOK kb_hook;
string test = "not loaded";
HINSTANCE hDLL;

DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam )
{
    if(code == HC_ACTION)   // if there is an incoming action and a key was pressed
    {
        switch(wParam)
        {
        case VK_SPACE:
            printf("Space was pressed\n"); //tried without this also
            MessageBoxA(NULL, "Hi", "Space", MB_OK);
            break;
        }
    }
    return CallNextHookEx(NULL, code, wParam, lParam);
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    test = "loaded";
    switch(ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hDLL = hModule;
        break;
    }
    printf("test str = %s \n", test.c_str());
    return TRUE;
}

bool installhook()
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, hDLL, NULL);
    if(!kb_hook)
    {
        return false;
    }
    return true;
}

void unhook()
{
    if(kb_hook)
    {
        UnhookWindowsHookEx(kb_hook);
    }
}

string TestLoaded()
{
    return test;
}

Console applicatioon source:

#include <iostream>
#include <Windows.h>
#include <string>
#define DLLIMPORT __declspec(dllimport)
using namespace std;

DLLIMPORT void unhook();
DLLIMPORT bool installhook();
DLLIMPORT string TestLoaded();

int main()
{
    cout << TestLoaded() <<endl;
    installhook();
    for(int i = 1; i<=10 ; i++)
    {
        //Do some keyboard activities in this 10 secs
        Sleep(1000);
        cout << i<<endl;
    }

    unhook();
    cin.get();
    return 1;
}

My suspicion was that since the dll will be loaded into each process in the process's own address space and console would not be present in other applications, it gets void and crashed. So I removed the console outputs and replaced with messagebox. Then also no difference.

What could be the problem?

Update:

I tried to do a local hook to a specific thread before trying it global. But I get Parameter is incorrect error 87 at setwindowshookex. Below are the updated code:

dll:

bool installhook(DWORD ThreadId) //exporting this function
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, NULL, ThreadId); //tried with the dll module's handle also instead of NULL
    if(!kb_hook)
    {
        printf("SetWindowsHookEx failed : %d\n", GetLastError());
        return false;
    }
    return true;
}

Console application source:

DWORD myThread()
{
    cout<< "Thread started\n";
    char str[250];
    cin>>str;
    return 0;
}

int main()
{
    cout << TestLoaded() <<endl;
    DWORD myThreadID;
    HANDLE myHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)myThread, NULL, 0, &myThreadID);
    installhook(myThreadID);
    for(int i = 0; i<100 ; i++)
    {
        Sleep(100);
        if(i%10 == 0)
        {
            cout << i<<endl;
        }
    }
    unhook();
}

Body:
Try to use WH_KEYBOARD_LL. You can set global hook even without dll declaring hook function in you process. Plus, you should detect space action using PKBDLLHOOKSTRUCT struct

LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam )
{
   if ( code == HC_ACTION )
   {
       switch ( wParam )
       {
          case WM_KEYDOWN:
          {
              // Get hook struct
              PKBDLLHOOKSTRUCT p = ( PKBDLLHOOKSTRUCT ) lParam;
              if ( p->vkCode == VK_SPACE)
              {
                MessageBoxA( NULL, "Hi", "Space", MB_OK );
              }
          }
       break;
       }
   }
   return CallNextHookEx( NULL, code, wParam, lParam );
 }

 ....
 // Somewhere in code
 kb_hook = SetWindowsHookEx( WH_KEYBOARD_LL, KeyboardProc, NULL, NULL );


问:
Errors while performing caret tuning in R
I am building a predictive model with caret/R and I am running into the following problems:

When trying to execute the training/tuning, I get this error:

Error in if (tmps < .Machine$double.eps^0.5) 0 else tmpm/tmps :
    missing value where TRUE/FALSE needed

After some research it appears that this error occurs when there missing values in the data, which is not the case in this example (I confirmed that the data set has no NAs).  However, I also read somewhere that the missing values may be introduced during the  re-sampling routine in caret, which I suspect is what's happening.

In an attempt to solve problem 1, I tried "pre-processing" the data during the re-sampling in caret by removing zero-variance and near-zero-variance predictors, and automatically inputting missing values using a carets knn automatic imputing method preProcess(c('zv','nzv','knnImpute')), , but now I get the following error:

Error: Matrices or data frames are required for preprocessing

Needless to say I checked and confirmed that the input data set are indeed matrices, so I dont understand why I get this second error.

The code follows:

```<code>x.train <- predict(dummyVars(class ~ ., data = train.transformed),train.transformed)
y.train <- as.matrix(select(train.transformed,class))
vbmp.grid <- expand.grid(estimateTheta = c(TRUE,FALSE))
adaptive_trctrl <- trainControl(method = 'adaptive_cv',
                   number = 10,
                   repeats = 3,
                   search = 'random',
                   adaptive = list(min = 5, alpha = 0.05,
                                   method = "gls", complete = TRUE),
                   allowParallel = TRUE)
fit.vbmp.01 <- train(
                 x = (x.train),
                 y = (y.train),
                 method = 'vbmpRadial',
                 trControl = adaptive_trctrl,
                 preProcess(c('zv','nzv','knnImpute')),
                 tuneGrid = vbmp.grid)
</code>```

The only difference between the code for problem (1) and (2) is that in (1), the pre-processing line in the train statement is commented out.

In summary,

-There are no missing values in the data

-Both x.train and y.train are definitely matrices

-I tried using a standard 'repeatedcv' method in instead of 'adaptive_cv' in trainControl with the same exact outcome

-Forgot to mention that the outcome class has 3 levels

Anyone has any suggestions as to what may be going wrong?

As always, thanks in advance

reyemarr

答:
I had the same problem with my data, after some digging i found that I had some Inf (infinite) values in one of the columns.

After taking them out (df <- df %>% filter(!is.infinite(variable))) the computation ran without error.

Body:
I am building a predictive model with caret/R and I am running into the following problems:

When trying to execute the training/tuning, I get this error:

Error in if (tmps < .Machine$double.eps^0.5) 0 else tmpm/tmps :
    missing value where TRUE/FALSE needed

After some research it appears that this error occurs when there missing values in the data, which is not the case in this example (I confirmed that the data set has no NAs).  However, I also read somewhere that the missing values may be introduced during the  re-sampling routine in caret, which I suspect is what's happening.

In an attempt to solve problem 1, I tried "pre-processing" the data during the re-sampling in caret by removing zero-variance and near-zero-variance predictors, and automatically inputting missing values using a carets knn automatic imputing method preProcess(c('zv','nzv','knnImpute')), , but now I get the following error:

Error: Matrices or data frames are required for preprocessing

Needless to say I checked and confirmed that the input data set are indeed matrices, so I dont understand why I get this second error.

The code follows:

x.train <- predict(dummyVars(class ~ ., data = train.transformed),train.transformed)
y.train <- as.matrix(select(train.transformed,class))
vbmp.grid <- expand.grid(estimateTheta = c(TRUE,FALSE))
adaptive_trctrl <- trainControl(method = 'adaptive_cv',
                   number = 10,
                   repeats = 3,
                   search = 'random',
                   adaptive = list(min = 5, alpha = 0.05,
                                   method = "gls", complete = TRUE),
                   allowParallel = TRUE)
fit.vbmp.01 <- train(
                 x = (x.train),
                 y = (y.train),
                 method = 'vbmpRadial',
                 trControl = adaptive_trctrl,
                 preProcess(c('zv','nzv','knnImpute')),
                 tuneGrid = vbmp.grid)

The only difference between the code for problem (1) and (2) is that in (1), the pre-processing line in the train statement is commented out.

In summary,

-There are no missing values in the data

-Both x.train and y.train are definitely matrices

-I tried using a standard 'repeatedcv' method in instead of 'adaptive_cv' in trainControl with the same exact outcome

-Forgot to mention that the outcome class has 3 levels

Anyone has any suggestions as to what may be going wrong?

As always, thanks in advance

reyemarr


问:
SonataAdmin: Prevent Admin From Deleting His Own Account
I am using sonatadmin for a symfony 2 project. Sometimes admin user may accidently delete his own account. how to prevent admin user to delete his own account? Thanks!</p>

答:
I am using SonataUserBundle along with FOSUserBundle and I ended up with the following solution.

config.yml:

```<code>parameters:
    sonata.user.admin.user.controller: AppBundle:CRUD\CRUD
</code>```

AppBundle\Controller\CRUD\CRUDController:

```<code><?php

namespace AppBundle\Controller\CRUD;

use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CRUDController extends Controller
{
    public function deleteAction($id)
    {
        $request = $this->getRequest();
        $id      = $request->get($this->admin->getIdParameter());
        $object  = $this->admin->getObject($id);

        if (!$object) {
            throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
        }

        $currentUserId = $this->getUser()->getId(); // ID of the current user
        if ($currentUserId == $id) {
            $this->addFlash(
                'sonata_flash_error',
                'You cannot delete your own account.'
            );

            return $this->redirectTo($object);
        }

        return parent::deleteAction($id);
    }

    public function batchActionDelete(ProxyQueryInterface $query)
    {
        $request       = $this->getRequest();
        $currentUserId = $this->getUser()->getId(); // ID of the current user
        $selectedUsers = $query->execute();

        foreach ($selectedUsers as $selectedUser) {
            if ($selectedUser->getId() == $currentUserId) {
                $this->addFlash(
                    'sonata_flash_error',
                    'You cannot delete your own account.'
                );

                return new RedirectResponse(
                    $this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters()))
                );
            }
        }

        return parent::batchActionDelete($query);
    }
}
</code>```

References:

M Khalid Junaid's answer

https://sonata-project.org/bundles/admin/3-x/doc/cookbook/recipe_custom_action.html (Sonata documentation)

https://sonata-project.org/bundles/user/2-0/doc/reference/advanced_configuration.html
(advanced configuration)

Body:
I am using SonataUserBundle along with FOSUserBundle and I ended up with the following solution.

config.yml:

parameters:
    sonata.user.admin.user.controller: AppBundle:CRUD\CRUD

AppBundle\Controller\CRUD\CRUDController:

<?php

namespace AppBundle\Controller\CRUD;

use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CRUDController extends Controller
{
    public function deleteAction($id)
    {
        $request = $this->getRequest();
        $id      = $request->get($this->admin->getIdParameter());
        $object  = $this->admin->getObject($id);

        if (!$object) {
            throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
        }

        $currentUserId = $this->getUser()->getId(); // ID of the current user
        if ($currentUserId == $id) {
            $this->addFlash(
                'sonata_flash_error',
                'You cannot delete your own account.'
            );

            return $this->redirectTo($object);
        }

        return parent::deleteAction($id);
    }

    public function batchActionDelete(ProxyQueryInterface $query)
    {
        $request       = $this->getRequest();
        $currentUserId = $this->getUser()->getId(); // ID of the current user
        $selectedUsers = $query->execute();

        foreach ($selectedUsers as $selectedUser) {
            if ($selectedUser->getId() == $currentUserId) {
                $this->addFlash(
                    'sonata_flash_error',
                    'You cannot delete your own account.'
                );

                return new RedirectResponse(
                    $this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters()))
                );
            }
        }

        return parent::batchActionDelete($query);
    }
}

References:

M Khalid Junaid's answer

https://sonata-project.org/bundles/admin/3-x/doc/cookbook/recipe_custom_action.html (Sonata documentation)

https://sonata-project.org/bundles/user/2-0/doc/reference/advanced_configuration.html
(advanced configuration)


问:
XSLT: Change attribute value everywhere
I have XML files of unknown/different structure. I have to change the value of an attribute.

 This is just an example and the structure can be anything:

```<code><root>
    <SomeElement endTime='12:00:00' />
    <subLevel>
        <OtherElement endTime='14:00:00' />
    </subLevel>
</root>
</code>```

I need to change the endTime attribute everywhere it occurs. The output should be

```<code><root>
    <SomeElement endTime='11:59:59' />
    <subLevel>
        <OtherElement endTime='13:59:59' />
    </subLevel>
</root>
</code>```

I could do this if I knew the exact position of the attribute but how to do it if I just don't know the structure of the XML file and need to change it for every element in the file? Is that even possible?

答:
Add to the identity transformation,

XSLT v3.0 only

```<code><xsl:mode on-no-match="shallow-copy"/>
</code>```

XSLT v1.0-x.x

```<code>  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</code>```

an override for @endTime which will replace the existing values with one a second earlier:

```<code>  <xsl:param name="datePart">2017-12-04T</xsl:param>
  <xsl:template match="@endTime">
    <xsl:attribute name="endTime">
      <xsl:value-of select="substring-after(xs:dateTime(concat($datePart,.))
                            - xs:dayTimeDuration('PT1S'),$datePart)"/>
    </xsl:attribute>
  </xsl:template>
</code>```

by temporarily prepending a date so that the built-in dateTime calculation functions can be used.

Full XSLT

(Datetime calculations require XSLT 2.0 or higher)

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xsl:output indent="yes"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:param name="datePart">2017-12-04T</xsl:param>
  <xsl:template match="@endTime">
    <xsl:attribute name="endTime">
      <xsl:value-of select="substring-after(xs:dateTime(concat($datePart,.))
                            - xs:dayTimeDuration('PT1S'),$datePart)"/>
    </xsl:attribute>
  </xsl:template>

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

applied to your XML input:

```<code><root>
    <SomeElement endTime='12:00:00' />
    <subLevel>
        <OtherElement endTime='14:00:00' />
    </subLevel>
</root>
</code>```

provides your requested XML output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
    <SomeElement endTime="11:59:59"/>
    <subLevel>
        <OtherElement endTime="13:59:59"/>
    </subLevel>
</root>
</code>```

as requested.

Title: XSLT: Change attribute value everywhere

Body:
I have XML files of unknown/different structure. I have to change the value of an attribute.

 This is just an example and the structure can be anything:

<root>
    <SomeElement endTime='12:00:00' />
    <subLevel>
        <OtherElement endTime='14:00:00' />
    </subLevel>
</root>

I need to change the endTime attribute everywhere it occurs. The output should be

<root>
    <SomeElement endTime='11:59:59' />
    <subLevel>
        <OtherElement endTime='13:59:59' />
    </subLevel>
</root>

I could do this if I knew the exact position of the attribute but how to do it if I just don't know the structure of the XML file and need to change it for every element in the file? Is that even possible?

Body:
Add to the identity transformation,

XSLT v3.0 only

<xsl:mode on-no-match="shallow-copy"/>

XSLT v1.0-x.x

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

an override for @endTime which will replace the existing values with one a second earlier:

  <xsl:param name="datePart">2017-12-04T</xsl:param>
  <xsl:template match="@endTime">
    <xsl:attribute name="endTime">
      <xsl:value-of select="substring-after(xs:dateTime(concat($datePart,.))
                            - xs:dayTimeDuration('PT1S'),$datePart)"/>
    </xsl:attribute>
  </xsl:template>

by temporarily prepending a date so that the built-in dateTime calculation functions can be used.

Full XSLT

(Datetime calculations require XSLT 2.0 or higher)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xsl:output indent="yes"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:param name="datePart">2017-12-04T</xsl:param>
  <xsl:template match="@endTime">
    <xsl:attribute name="endTime">
      <xsl:value-of select="substring-after(xs:dateTime(concat($datePart,.))
                            - xs:dayTimeDuration('PT1S'),$datePart)"/>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

applied to your XML input:

<root>
    <SomeElement endTime='12:00:00' />
    <subLevel>
        <OtherElement endTime='14:00:00' />
    </subLevel>
</root>

provides your requested XML output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <SomeElement endTime="11:59:59"/>
    <subLevel>
        <OtherElement endTime="13:59:59"/>
    </subLevel>
</root>

as requested.


问:
Getting values of specific tr in table repeated through angular JS using filters
I am calling an API which will return a JSON object. Based on some conditions I am getting values from this JSON object and displaying them in a table which can be repeated using angular JS. Now I need to get data of each table but I don't know how as some data is filtered.

Below is the table:

```<code>    <table class="table">
            <thead>
            <tr>
                <th>Relation
                </th>
                <th>Date Of Birth
                </th>
                <th >In Hospital
                </th>
                <th >AMB & PM
                </th>
                <th > Total
                </th>
            </tr>
        </thead>

        <tr ng-repeat="member in CalculatorResponse">
            <td>
               {{member.Relation}}
            </td>
            <td>{{member.dateOfBirth}}
            </td>
            <td>
                <span ng-repeat=" InHosp in member.InHospital | filter:{strClassName: class.className}">
                  {{InHosp.intClassValue}}
                </span>

            </td>
            <td >
                <span ng-repeat=" OutHosp in member.OutHospital | filter:{OptionType: Option_Select.type}">
                     <span ng-model="AMBPMVal" ng-repeat=" Benefits in OutHosp.Benefits | filter:{intExcess: CoBenefitsSelect.type}">
                          {{Benefits.intAMBPM}}
                    </span>
                </span>
            </td>
           <td> Total value (unable to calculate it) {{InHosp.intClassValue}} + {{Benefits.intAMBPM}}
        </td>
    </tr>
</table>

<input type="button" value="Generate"  ng-click="Generate()"/>
</code>```

So the main problem is that I am trying to get all values of the table when generate button is clicked, but I cannot get the filtered values;

I did this but it is not working:

```<code><span ng-repeat=" OutHosp in (filteredHosp = (member.OutHospital | filter:{OptionType: Option_Select.type}))">
    <span ng-repeat=" Benefits in (filteredBenefits = (OutHosp.Benefits | filter:{intExcess: CoBenefitsSelect.type}))"> {{Benefits.intAMBPM}}  </span>
    <%--{{filteredBenefits[0].intAMBPM}}--%> </span> <%--{{filteredHosp[0].Benefits}}--%>
</code>```

--> filtered benefits and filteredHosp can be only accessed in the commented region, if you put them outside the 2 spans you will get nothing.

I am also trying also to calculate the total of In Hospital and AMB&M but I cannot as I don't know how to get their values after filter.

Any suggestion?

答: They are not available, not because of filter but because they are outside the scope of ng-repeat. You can either do your calculations inside ng-repeat or iterate through your list and do calculations in your controller.</p>

Body:
I am calling an API which will return a JSON object. Based on some conditions I am getting values from this JSON object and displaying them in a table which can be repeated using angular JS. Now I need to get data of each table but I don't know how as some data is filtered.

Below is the table:

                Relation

                Date Of Birth

                In Hospital

                AMB & PM

                 Total

               {{member.Relation}}

            {{member.dateOfBirth}}

                  {{InHosp.intClassValue}}

                          {{Benefits.intAMBPM}}

            Total value (unable to calculate it) {{InHosp.intClassValue}} + {{Benefits.intAMBPM}}

<input type="button" value="Generate"  ng-click="Generate()"/>

So the main problem is that I am trying to get all values of the table when generate button is clicked, but I cannot get the filtered values;

I did this but it is not working:

     {{Benefits.intAMBPM}}
    <%--{{filteredBenefits[0].intAMBPM}}--%>  <%--{{filteredHosp[0].Benefits}}--%>

--> filtered benefits and filteredHosp can be only accessed in the commented region, if you put them outside the 2 spans you will get nothing.

I am also trying also to calculate the total of In Hospital and AMB&M but I cannot as I don't know how to get their values after filter.

Any suggestion?


答:
mysql_real_escape_string is made for just this.

PHP: mysql_real_escape_string

```<code>$insert = "INSERT INTO wp_posts ('body','title') VALUES ('".mysql_real_escape_string($row['body'])."', '".mysql_real_escape_string($row['row'])."')";
</code>```

Title: mysql escaping single and double quotes

Body:
mysql_real_escape_string is made for just this.

PHP: mysql_real_escape_string

$insert = "INSERT INTO wp_posts ('body','title') VALUES ('".mysql_real_escape_string($row['body'])."', '".mysql_real_escape_string($row['row'])."')";


问:
Date.strptime throwing invalid date for "%Y%W" format
My date = 1st January, 2015.
I did
date_formatted = date.strftime('%Y%W') which returned "201500"

Then when am trying to do Date.strptime(date_formatted, '%Y%W') it's throwing an invalid date error even though the original string was returned from strptime's counterpart srftime.

答: Found the solution. Time.strptime(date_formatted, '%Y%W') is what will work here.


问:
execute powershell commands from ruby
I was trying to execute a powershell command from ruby code.
Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Qlik Sense Client'" |Select-Object -Property version

It gives me the version of the product perefectly. But the same thing when i try to execute from ruby like(entire command in backticks) :
find = powershell.exe  Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name=''"|Select-Object -Property version

The command breaks, it cant interpret the quotes, pipes etc in ruby. I tried to escape those quotes but it still it breaks. I dont know how to escape that pipe as well.
Kindly help me here or refer me to something relevant. Many thanks.

答:
Here an example of how I shell to external apps, should also work with Powershell. Copy the working command from your console between the {} without extra delimiters. The %Q also makes it possible to do interpolation of variables in case your command is not always the same, it works the same way as between the " delimiter.

All the output is captured by the " 2>&1" and enumerated line by line in the block after while.

In case more than one line is captured you need to check which line the result you are after is displayed and return the result.

```<code>def powershell
  command = %Q{your command just like you execute it in a console}
  IO.popen(command+" 2>&1") do |pipe|
    pipe.sync = true
    while lijn = pipe.gets
      # do whatever you need with the output of the command
      # return the result
    end
  end
end
</code>```

Use the %q{} alternative if you don't need the interpolation since that also could give problems. Use the Ruby comamnd in the same console as where you get your powershell results. Ensure you can run powershell from there (must be in the path).

But as I understand this will get you the name and version of the installed products on your pc.

Why not use just Ruby ? It's way more faster than the VERY slow Wmi queries.

```<code>require 'win32/registry'

Win32::Registry::HKEY_LOCAL_MACHINE.open(
  'Software\Microsoft\Windows\CurrentVersion\Uninstall'
) do |reg|
  reg.each_key do |key|
    k = reg.open(key)
    puts key
    puts k["DisplayName"]    rescue "?"
    puts k["DisplayVersion"] rescue "?"
    puts
  end
end
</code>```

Title: execute powershell commands from ruby

Body:
Here an example of how I shell to external apps, should also work with Powershell. Copy the working command from your console between the {} without extra delimiters. The %Q also makes it possible to do interpolation of variables in case your command is not always the same, it works the same way as between the " delimiter.

All the output is captured by the " 2>&1" and enumerated line by line in the block after while.

In case more than one line is captured you need to check which line the result you are after is displayed and return the result.

def powershell
  command = %Q{your command just like you execute it in a console}
  IO.popen(command+" 2>&1") do |pipe|
    pipe.sync = true
    while lijn = pipe.gets
      # do whatever you need with the output of the command
      # return the result
    end
  end
end

Use the %q{} alternative if you don't need the interpolation since that also could give problems. Use the Ruby comamnd in the same console as where you get your powershell results. Ensure you can run powershell from there (must be in the path).

But as I understand this will get you the name and version of the installed products on your pc.

Why not use just Ruby ? It's way more faster than the VERY slow Wmi queries.

require 'win32/registry'

Win32::Registry::HKEY_LOCAL_MACHINE.open(
  'Software\Microsoft\Windows\CurrentVersion\Uninstall'
) do |reg|
  reg.each_key do |key|
    k = reg.open(key)
    puts key
    puts k["DisplayName"]    rescue "?"
    puts k["DisplayVersion"] rescue "?"
    puts
  end
end


问:
How to package front-end for deploy to nginx
I create a client only project using:

```<code>jhipster --skip-server --db mysql --auth jwt
</code>```

successfully.

Now I want to generate a package (either dev or prod) which I want to deploy to nginx.

Following official guide I issued:

```<code>yarn webpack:build:dev
yarn webpack:build:prod
</code>```

on Windows powershell, however I got the error:

error Command "webpack:build:dev" not found

  error Command "webpack:build:prod" not found

How to generate a package manually?

答: Commands are wrong, check the scripts section in your project's package.json, it should be yarn webpack:prod

Body:
I create a client only project using:

jhipster --skip-server --db mysql --auth jwt

successfully.

Now I want to generate a package (either dev or prod) which I want to deploy to nginx.

Following official guide I issued:

yarn webpack:build:dev
yarn webpack:build:prod

on Windows powershell, however I got the error:

error Command "webpack:build:dev" not found

  error Command "webpack:build:prod" not found

How to generate a package manually?