问:
How to send a device management request using NodeRed or any REST client
I am trying to sent a DM firmware update command from a NodeRed Flow.

Function node:

```<code>msg.payload = {"MgmtInitiationRequest": {
"action":"firmware/update",
"devices": [{
"typeId": "myType",
"deviceId": "myDevice"
}]

}}
msg.headers={"Content-Type":"application/json"}
return msg;
</code>```

I send it to a http request node with a POST to

```<code>https://orgid.internetofthings.ibmcloud.com/api/v0002/mgmt/requests
</code>```

Basic Authentication with api keys.  I based it of Initiate a device management request

I get back a 403 which the docs have as:

One or more of the devices does not support the requested action

Anyone see what I'm missing?  It works fine from the IoT Platform UI to the same devicetype/deviceid.

EDIT: Same 403 if I use a Rest client like Postman.

答:
The swagger API documentation is a little bit misleading in that the 'body' parameter is given a name.
But, like the other POST APIs, that name isn't actually included anywhere as part of the payload.

The payload should just look like this:

```<code>{
    "action": "firmware/update",
    "devices": [
        {
            "typeId": "string",
            "deviceId": "string"
        }
    ]
}
</code>```

This page in the documentation provides more detail:
https://console.ng.bluemix.net/docs/services/IoT/devices/device_mgmt/requests.html#firmware-actions-update

Body:
I am trying to sent a DM firmware update command from a NodeRed Flow.

Function node:

msg.payload = {"MgmtInitiationRequest": {
"action":"firmware/update",
"devices": [{
"typeId": "myType",
"deviceId": "myDevice"
}]

}}
msg.headers={"Content-Type":"application/json"}
return msg;

I send it to a http request node with a POST to

https://orgid.internetofthings.ibmcloud.com/api/v0002/mgmt/requests

Basic Authentication with api keys.  I based it of Initiate a device management request

I get back a 403 which the docs have as:

One or more of the devices does not support the requested action

Anyone see what I'm missing?  It works fine from the IoT Platform UI to the same devicetype/deviceid.

EDIT: Same 403 if I use a Rest client like Postman.

Body:
The swagger API documentation is a little bit misleading in that the 'body' parameter is given a name.
But, like the other POST APIs, that name isn't actually included anywhere as part of the payload.

The payload should just look like this:

{
    "action": "firmware/update",
    "devices": [
        {
            "typeId": "string",
            "deviceId": "string"
        }
    ]
}

This page in the documentation provides more detail:
https://console.ng.bluemix.net/docs/services/IoT/devices/device_mgmt/requests.html#firmware-actions-update


来源: stackexchange

问:
Yammer Rest API > Authentication based on server side script (php) without user interaction
My project has the requirement to access the yammer data using the given REST API using server side script(mainly PHP) and not involve a client side login using yammer's OAuth dialog.

I have gone through this document:

https://developer.yammer.com/docs/oauth-2

but this says, we requires user interaction.

What I wanted was can I generate a client_id and client_Secret to further generate access token to make API call out, but in all these processes I only use the authenticated users username and password in my server-side script.

Can anyone suggest a solution or is a client-side interaction required by design?

Thanks in advance!!

答:
The below from Microsoft blogs might help you & added source at the end of answer.

Obtain a Verified Admin token for your application in one of the following 2 ways

a. Create the app with a Verified Admin account and then in the app’s Basic Info page, click “Generate a developer token for this application.” Note that you’ll need to use this app’s info in the JS SDK and any subsequent calls.

b.   Use the process outlined at https://developer.yammer.com/docs/test-token with a Verified Admin account to get an OAuth token for that VA account. Note that you must use the app info used to generate this token in all future steps.

Obtain the current user’s email address in the server-side script.

Using the VA token obtained in step 1 to authenticate, pass the user’s email address to our Get User by Email Address endpoint documented at https://developer.yammer.com/docs/usersby_emailjsonemailuserdomaincom, and then process the response
a.  If the call to the API endpoint returns a 200 OK response, first check the “state” field to make sure the user is “active” and if so, store the “id” field that’s returned and go to step 4
b.  If the call returns a 404 or a state other than “active,” direct the user to finish creating and activating their account however you like.

Once you have the user’s ID, you can pass it to our Impersonation endpoint to obtain a pre-authorized OAuth token for that user. This endpoint is documented at https://developer.yammer.com/docs/impersonation and must use the VA token obtained in step 1 to authorize the call, and the consumer_key of your JS SDK app.

You now have an OAuth token for the current user. When generating the code being passed to the browser, have the client side JS SDK code first call yam.platform.getLoginStatus and if there’s no active session and you have a token from step 4, pass that token to yam.platform.setAuthToken($tokenFromStep4, optional_callback_function_if_desired(response)).  If you don’t have a valid token, direct the user to finish setting up their Yammer account.

Continue making JS SDK calls as you normally would, without needing the user to authenticate.

Source: https://blogs.technet.microsoft.com/askyammer/2016/11/04/preauthorizing-the-yammer-js-sdk/

ContentLicense: CC BY-SA 3.0


问:
Creating a Custom reporter block in Scratch
Quite simple, how do I create a hacked custom reporter block in Scratch?

I know I can make my own custom command block by editing the .json file, but I don't know how to create a custom reporter block. I believe that it is coming to Scratch 3.0, but I want to know how to make one by editing the .json file within the .sb2 file. Because I do not know how to use javascript, I don't know, but I believe in languages like C++, you can define a function that returns a value, like:

int function()
       //Function body
      return 0 //Gives the function a value of 0

Is it possible to do something like this is scratch?

People have asked me why I want to this. Imagine the main with having to calculate the factorial of a variable x every time you required to calculate statistical probabilities! You might as well make a function that assigns the result to a variable result and use that, but I cold only calculate one at once.

Thanks you to anybody that can help

答:
This shouldn't be possible, but sort of is. If you're willing to edit the project JSON, you can (ab)use some of the built-in dropdown menus to add your own custom elements.

There are particular "input specifiers" which are used in the project JSON to specify particular inputs for your custom block. This document contains a list of all of them.

In columns D and E of the table linked above, you can see a large list of the menus available. There is, for instance, a "backdrop" menu, which contains each backdrop name as a dropdown option. Adding "%m.backdrop" to your custom block definition will insert the backdrop dropdown. Then you can create named backdrops to appear as input elements.


问:
When to Denormalize a Database Design
I know that normalization has been extensively discussed on Stack Overflow. I've read many of the previous discussions. I've got some additional questions though.

I'm working on a legacy system with at least 100 tables. The database is has some un-normalized structure, tables that contain a variety of disparate data, and other problems. I've been given the task of trying to improve it. I can't just start again but need to modify the existing schema.

In the past I have always tried to design normalized databases. Now the questions. A senior developer has suggested that in some cases we can't normalize:

With temporal data. For example an invoice is created that links to a product. If a customer asks for a copy of this invoice a year later we must be able to produce an exact copy of the original. What if the product price, name or description have been updated? The senior guy suggested that the price and other product information should be copied to the invoice table. I'm thinking maybe we should have another table such as productPrice that has a date field so we can track changes in price over time. We would need the same thing for the product description and name I guess? Seems complicated. What do you think?

The database is an accounting system. I'm not very familiar with accounting. At the moment some summary data is derived and stored in the database. For example total sales for the year. My senior associate has said that accountants like to check things are correct by comparing this value with data that is actually calculated from invoices etc to give them confidence that the application is working correctly.

He said that at the moment for example we can tell if someone deleted an invoice from last year mistakenly because the totals will not be the same. He also pointed out that it could be quite slow to calculate these totals on the fly. Of course I said that data should not be duplicated and should always be calculated when needed. I suggested that we could use SQL Reporting Services or some other solution that will generate these reports overnight and cache them. Anyway he's not convinced. Any comments on this?

答:
For #1

The invoice should be calculated from the sales and payments.  If you do not have detailed sales data including price/product/discount/shipping/etc start there.

For #2

Writing an accounting system into the db from scratch is a big project.  Make sure you have the accountants give you business rules so you can measure your systems accuracy.  The last thing you want is the CFO step into the DBA meeting and announce the DB is overcharging the customer, even worse you are undercharging and driving the company out of business.

If you have SQL Server give the Adventure Works db a look.  If you hate MS then look at Adventure Works and don't do it that way.

ContentLicense: CC BY-SA 4.0

Title: When to Denormalize a Database Design

ContentLicense: CC BY-SA 2.5


问:
Detect and exclude outliers in a pandas DataFrame
I have a pandas data frame with few columns.

Now I know that certain rows are outliers based on a certain column value.

For instance

column 'Vol' has all values around 12xx and one value is 4000 (outlier).

Now I would like to exclude those rows that have Vol column like this.

So, essentially I need to put a filter on the data frame such that we select all rows where the values of a certain column are within, say, 3 standard deviations from mean.

What is an elegant way to achieve this?

答:
For each of your dataframe column, you could get quantile with:

```<code>q = df["col"].quantile(0.99)
</code>```

and then filter with:

```<code>df[df["col"] < q]
</code>```

If one need to remove lower and upper outliers, combine condition with an AND statement:

```<code>q_low = df["col"].quantile(0.01)
q_hi  = df["col"].quantile(0.99)

df_filtered = df[(df["col"] < q_hi) & (df["col"] > q_low)]
</code>```

Body:
For each of your dataframe column, you could get quantile with:

q = df["col"].quantile(0.99)

and then filter with:

df[df["col"] < q]

If one need to remove lower and upper outliers, combine condition with an AND statement:

q_low = df["col"].quantile(0.01)
q_hi  = df["col"].quantile(0.99)

df_filtered = df[(df["col"] < q_hi) & (df["col"] > q_low)]


问:
Add SQL strings in a Query
I have this code in Delphi 10.2 and runs in android.
The data are in a remote mysql server.

```<code>Query1.SQL.Text := '';
Query1.SQL.Add('SELECT userid, userphoto, username');
Query1.SQL.Add('FROM users');
Query1.SQL.Add('WHERE usermail = ' + #39 + Text1.Text + #39);
Query1.Execute;
</code>```

The problem is the SQL in the Query added like this

```<code>SELECT userid, userphoto, username
FROM users
WHERE usermail = 'THE TEXT
'
</code>```

That SQL gives back an empty field.
Why the last character goes to a new line?
Thanks for your answer.

答:
What kind of component is Text1? Does it accept line feeds? It looks like accessing Text1.Text is returning 'THE TEXT'#10.

Try to check if the last character is #10 (or possibly #13 or the last two characters are #13#10) and remove them.

And do what Bruce McGee says: Use a query with a parameter. We don't need yet another app that is vulnerable to SQL injection attacks.

Title: Add SQL strings in a Query

Body:
I have this code in Delphi 10.2 and runs in android.
The data are in a remote mysql server.

Query1.SQL.Text := '';
Query1.SQL.Add('SELECT userid, userphoto, username');
Query1.SQL.Add('FROM users');
Query1.SQL.Add('WHERE usermail = ' + #39 + Text1.Text + #39);
Query1.Execute;

The problem is the SQL in the Query added like this

SELECT userid, userphoto, username
FROM users
WHERE usermail = 'THE TEXT
'

That SQL gives back an empty field.
Why the last character goes to a new line?
Thanks for your answer.


问:
How to enable multiple TextBoxs at once?
I have multiple TextBoxes set on enabled = false. If user clicks on Button (btnEdit) all the textboxes should get enabled = true.

My Code:

protected void Read(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox && c.ID.StartsWith("txt"))
                ((TextBox)c).Enabled = true;
        }
    }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        Read(pnlDialog);
    }```

pnlDialog is a Panel with all the TextBoxs.

答:
Their can be a problem in your code, I'm not very sure about it.Your code should not be able to function and meed your requirement.
The code

```<code>((TextBox)c).Enabled = true</code>```

you used actually behaves in the following descripted way:

1.It creates a COPY of the object c.

2.It sets the 'Enabled' property of the COPY to true.

This means that it wont set the 'Enabled' propert of the origin(c in this case) to true.

What you shoud do is

```<code>TextBox a = c as TextBox;<br/>a.Enabled=true;<br/></code>```

This should be working.

Again, I'm not very sure about what I said.But you can always have a try.

Body:
I have multiple TextBoxes set on enabled = false. If user clicks on Button (btnEdit) all the textboxes should get enabled = true.

My Code:

protected void Read(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox && c.ID.StartsWith("txt"))
                ((TextBox)c).Enabled = true;
        }
    }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        Read(pnlDialog);
    }

pnlDialog is a Panel with all the TextBoxs.

Body:
Their can be a problem in your code, I'm not very sure about it.Your code should not be able to function and meed your requirement.
The code

((TextBox)c).Enabled = true

you used actually behaves in the following descripted way:

1.It creates a COPY of the object c.

2.It sets the 'Enabled' property of the COPY to true.

This means that it wont set the 'Enabled' propert of the origin(c in this case) to true.

What you shoud do is

TextBox a = c as TextBox;
a.Enabled=true;

This should be working.

Again, I'm not very sure about what I said.But you can always have a try.


问:
How to prevent gradlew from download anything?
I am trying to run gradlew on offline machine. It starts from message

```<code>Downloading https://services.gradle.org/distributions/gradle-2.10-all.zip
</code>```

and then fails with exception.

What it wants and how to satisfy it?

答:
Option 1. If you have possibility go online temporary

Command gradlew means you are trying to use Gradle Wrapper. It is a tool for automated downloading of Gradle distribution.

In order to download Gradle Wrapper you have to execute gradlew command with a proper network connection at least once.
Make sure you have correct network and proxy settings.

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

Only after that you can build a project offline. Example:

```<code>./gradlew build --offline
</code>```

Option 2. Download distribution by hand

Or, alternatively, you could download distribution from official site. Then extract it, add gradle to PATH variable, and run:

```<code>gradle build --offline
</code>```

Body:
I am trying to run gradlew on offline machine. It starts from message

Downloading https://services.gradle.org/distributions/gradle-2.10-all.zip

and then fails with exception.

What it wants and how to satisfy it?

Body:
Option 1. If you have possibility go online temporary

Command gradlew means you are trying to use Gradle Wrapper. It is a tool for automated downloading of Gradle distribution.

In order to download Gradle Wrapper you have to execute gradlew command with a proper network connection at least once.
Make sure you have correct network and proxy settings.

./gradlew build

Only after that you can build a project offline. Example:

./gradlew build --offline

Option 2. Download distribution by hand

Or, alternatively, you could download distribution from official site. Then extract it, add gradle to PATH variable, and run:

gradle build --offline


问:
UserControl not showing after applying style
I'm in the making of a usercontrol library. Therefore I don't have app.xaml file nor mainwindow.xaml.

I imported (copied) a slider style from another WPF project. This resource dictionary is set to page and was working fine before but, as soon as I apply it to my slider then the control is not showing in VisualStudio as well as runtime. No errors are thrown.

```<code><UserControl x:Class="WPF.UserControls.CustomSlider"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WPF.UserControls"
         x:Name="CustomSliderControl"
         mc:Ignorable="d"
         d:DesignHeight="407" d:DesignWidth="127">
<UserControl.Resources>
    <ResourceDictionary Source="/WPFUserControls;component/Styles/BaseSliderStyle.xaml"/>
</UserControl.Resources>
<Grid>
    <Slider x:Name="Hello" Style="{DynamicResource BaseSliderStyle}" Value="{Binding Value, Mode=TwoWay,
RelativeSource={RelativeSource AncestorType={x:Type local:CustomSlider}}}" Minimum="0.0" Maximum="1.0"/>
</Grid>
</code>```

And here is part of the slider style :

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:WPF.UserControls">
<Style x:Key="BaseSliderStyle" TargetType="{x:Type Slider}">
    <Setter Property="Stylus.IsPressAndHoldEnabled" Value="false"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="Foreground" Value="{StaticResource SliderThumb.Static.Foreground}"/>
    <Setter Property="Template" Value="{StaticResource SliderHorizontal}"/>
    <Style.Triggers>
        <Trigger Property="Orientation" Value="Vertical">
            <Setter Property="Template" Value="{StaticResource SliderVertical}"/>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

I may have miss something. Any hint ?

Thanks.

答:
Make sure that you have added a reference to WPFUserControls.dll and try this:

```<code><UserControl ...>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/WPFUserControls;component/Styles/BaseSliderStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    <Grid>
        <Slider x:Name="Hello" Style="{StaticResource BaseSliderStyle}" Value="{Binding Value, Mode=TwoWay,
                    RelativeSource={RelativeSource AncestorType={x:Type local:CustomSlider}}}" Minimum="0.0" Maximum="1.0"/>
    </Grid>
</UserControl>
</code>```

Since I am using the StaticResource markup extension you should get an exception if the "BaseSliderStyle" cannot be found. You can switch back to using DynamicResource when you have confirmed that the style is found and is being applied as expected.

Also note that I am using a merged ResourceDictionary and a pack URI to specify the source: https://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspx.

Please also make sure that that the resource dictionary is actually called "BaseSliderStyle.xaml" and that is located under a folder called "Styles" at the root of the project/assembly called "WPFUserControls".

Body:
I'm in the making of a usercontrol library. Therefore I don't have app.xaml file nor mainwindow.xaml.

I imported (copied) a slider style from another WPF project. This resource dictionary is set to page and was working fine before but, as soon as I apply it to my slider then the control is not showing in VisualStudio as well as runtime. No errors are thrown.

<UserControl x:Class="WPF.UserControls.CustomSlider"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WPF.UserControls"
         x:Name="CustomSliderControl"
         mc:Ignorable="d"
         d:DesignHeight="407" d:DesignWidth="127">
<UserControl.Resources>
    <ResourceDictionary Source="/WPFUserControls;component/Styles/BaseSliderStyle.xaml"/>
</UserControl.Resources>
<Grid>
    <Slider x:Name="Hello" Style="{DynamicResource BaseSliderStyle}" Value="{Binding Value, Mode=TwoWay,
RelativeSource={RelativeSource AncestorType={x:Type local:CustomSlider}}}" Minimum="0.0" Maximum="1.0"/>
</Grid>

And here is part of the slider style :

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:WPF.UserControls">

</Style>

I may have miss something. Any hint ?

Thanks.

Body:
Make sure that you have added a reference to WPFUserControls.dll and try this:

<UserControl ...>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/WPFUserControls;component/Styles/BaseSliderStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    <Grid>
        <Slider x:Name="Hello" Style="{StaticResource BaseSliderStyle}" Value="{Binding Value, Mode=TwoWay,
                    RelativeSource={RelativeSource AncestorType={x:Type local:CustomSlider}}}" Minimum="0.0" Maximum="1.0"/>
    </Grid>
</UserControl>

Since I am using the StaticResource markup extension you should get an exception if the "BaseSliderStyle" cannot be found. You can switch back to using DynamicResource when you have confirmed that the style is found and is being applied as expected.

Also note that I am using a merged ResourceDictionary and a pack URI to specify the source: https://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspx.

Please also make sure that that the resource dictionary is actually called "BaseSliderStyle.xaml" and that is located under a folder called "Styles" at the root of the project/assembly called "WPFUserControls".


问:
What are some good Java web development tools (across the board)
For web development what are some standard/good java tools.  That apply to all aspects of development.

For example, The IDE (Eclipse, RAD, Intellij) is important, but what else is there.

Ant is a good one.
Cygwin, Linux OS possibly.

答:
I've been very happy with NetBeans for years. Used Eclipse too but I decided to stick with one and NetBeans was my favorite.

Don't know what the other guy was talking about when he said Netbeans was more visual. Except for Matisse, which is for Swing apps and I think there's a JavaFaces visual thing but I don't use faces.

I started programming java web apps in notepad (yeah i know) years ago and find it much faster to code in NetBeans. You download it and you're ready to start building websites right after you install it.

OwnerDisplayName: Berlin Brown


问:
RecyclerView, different divider dependently on type of row
So I have a ListView with different types of rows. I would like to disable divider for the first row and have another style of a divider for the second one.

What's the best practice to do that?

I'm adding dividers currently by:

```<code>    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL);
    dividerItemDecoration.setDrawable(getDrawable(R.drawable.divider));
    recyclerView.addItemDecoration(dividerItemDecoration);
</code>```

答:
@Ali I like your solution. However, your code requires divider in a layout. I solved it by hiding regular divider. Thank you for the hint anyway. Here is my class:

```<code>public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

private Drawable divider;

/**
 * Default divider will be used
 */
public DividerItemDecoration(Context context) {
    final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
    divider = styledAttributes.getDrawable(0);
    styledAttributes.recycle();
}

/**
 * Custom divider will be used
 */
public DividerItemDecoration(Context context, int resId) {
    divider = ContextCompat.getDrawable(context, resId);
}

@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
    int left = parent.getPaddingLeft();
    int right = parent.getWidth() - parent.getPaddingRight();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View row = parent.getChildAt(i);
        Boolean noDivider = (Boolean) row.getTag(R.id.noSpaceAfter);

        if (noDivider == null || !noDivider) {
            drawDivider(canvas, row, left, right);
        }
    }
}

private void drawDivider(Canvas canvas, View row, int left, int right) {
    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) row.getLayoutParams();

    int top = row.getBottom() + params.bottomMargin;
    int bottom = top + divider.getIntrinsicHeight();

    divider.setBounds(left, top, right, bottom);
    divider.draw(canvas);
}
</code>```

}

Body:
So I have a ListView with different types of rows. I would like to disable divider for the first row and have another style of a divider for the second one.

What's the best practice to do that?

I'm adding dividers currently by:

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL);
    dividerItemDecoration.setDrawable(getDrawable(R.drawable.divider));
    recyclerView.addItemDecoration(dividerItemDecoration);

Body:
@Ali I like your solution. However, your code requires divider in a layout. I solved it by hiding regular divider. Thank you for the hint anyway. Here is my class:

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

private Drawable divider;

/**
 * Default divider will be used
 */
public DividerItemDecoration(Context context) {
    final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
    divider = styledAttributes.getDrawable(0);
    styledAttributes.recycle();
}

/**
 * Custom divider will be used
 */
public DividerItemDecoration(Context context, int resId) {
    divider = ContextCompat.getDrawable(context, resId);
}

@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
    int left = parent.getPaddingLeft();
    int right = parent.getWidth() - parent.getPaddingRight();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View row = parent.getChildAt(i);
        Boolean noDivider = (Boolean) row.getTag(R.id.noSpaceAfter);

        if (noDivider == null || !noDivider) {
            drawDivider(canvas, row, left, right);
        }
    }
}

private void drawDivider(Canvas canvas, View row, int left, int right) {
    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) row.getLayoutParams();

    int top = row.getBottom() + params.bottomMargin;
    int bottom = top + divider.getIntrinsicHeight();

    divider.setBounds(left, top, right, bottom);
    divider.draw(canvas);
}

}


问:
get a list in object from firebase in android

I want to get the list of color from firebase and the following code is the method to get the color

Model : Product.java

```<code>package fyp.hkust.facet.model;

public class Product {

private String name;
private String brand;
private String desc;
private String image;
private String username;
private String uid;

private String color;

public Product()
{

}

public Product(String name,String brand, String desc, String image,String username,String uid,String color) {
    this.name = name;
    this.brand = brand;
    this.desc = desc;
    this.image = image;
    this.username = username;
    this.uid = uid;
    this.color = color;
}

public String getName() {

    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

}
</code>```

The method that I get from using the above model

```<code>mDatabase.child(product_id).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                Log.i("product dataSnapshot.getValue()", dataSnapshot.getValue().toString());
                final Product product_data = dataSnapshot.getValue(Product.class);
                backUp_product_data = product_data;
                if (product_data.getName() != null)
                    product_name_text.setText(product_data.getName());
                if (product_data.getBrand() != null)
                    brand_name_text.setText(product_data.getBrand());
                if (product_data.getDesc() != null)
                    descTextview.setText(product_data.getDesc());
                if( product_data.getUid() != null)
                    product_owner_id = product_data.getUid();

                if(product_data.getColor() != null)
                {
                    Log.d(TAG + " color" , product_data.getColor().toString());

                }
            }
        }
     @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e(TAG, "Failed to read value.", error.toException());
        }
    });
</code>```

E/UncaughtException: com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.ArrayList to String

I got the above error. How can I get them as a list? Please give me some helps. Thank you very much.

答:
```<code> for (DataSnapshot child : dataSnapshot.getChildren()) {
  YOUR_MODEL model = child.getValue(YOUR_MODEL.class);
                                }
</code>```

this if you return Array Of Objects , no one object

and it will be nice if you show your FCM database

..........................................................
UPDATE

your problem now is in color cause it`s array

in your model you put  color as String and now Color Is array in databse

so you can edit your model and change Field "Color"  to "colorNO" and make it int as in your database

Body:
I want to get the list of color from firebase and the following code is the method to get the color

Model : Product.java

package fyp.hkust.facet.model;

public class Product {

private String name;
private String brand;
private String desc;
private String image;
private String username;
private String uid;

private String color;

public Product()
{

}

public Product(String name,String brand, String desc, String image,String username,String uid,String color) {
    this.name = name;
    this.brand = brand;
    this.desc = desc;
    this.image = image;
    this.username = username;
    this.uid = uid;
    this.color = color;
}

public String getName() {

    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

}

The method that I get from using the above model

mDatabase.child(product_id).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                Log.i("product dataSnapshot.getValue()", dataSnapshot.getValue().toString());
                final Product product_data = dataSnapshot.getValue(Product.class);
                backUp_product_data = product_data;
                if (product_data.getName() != null)
                    product_name_text.setText(product_data.getName());
                if (product_data.getBrand() != null)
                    brand_name_text.setText(product_data.getBrand());
                if (product_data.getDesc() != null)
                    descTextview.setText(product_data.getDesc());
                if( product_data.getUid() != null)
                    product_owner_id = product_data.getUid();

                if(product_data.getColor() != null)
                {
                    Log.d(TAG + " color" , product_data.getColor().toString());

                }
            }
        }
     @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e(TAG, "Failed to read value.", error.toException());
        }
    });

E/UncaughtException: com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.ArrayList to String

I got the above error. How can I get them as a list? Please give me some helps. Thank you very much.

Body:
 for (DataSnapshot child : dataSnapshot.getChildren()) {
  YOUR_MODEL model = child.getValue(YOUR_MODEL.class);
                                }

this if you return Array Of Objects , no one object

and it will be nice if you show your FCM database

..........................................................
UPDATE

your problem now is in color cause it`s array

in your model you put  color as String and now Color Is array in databse

so you can edit your model and change Field "Color"  to "colorNO" and make it int as in your database


问:
PHP PDO. error number '00000' when query is correct
I have the code below:

```<code>$sql3 = "update news set date='$time' where id='2'";
$sql3 = $connect->exec($sql3);
if(!$sql3)
{
    print_r($connect->errorInfo());
    $error = $connect->errorInfo();
    die ("Error: (".$error[0].':'.$error[1].') '.$error[2]);
}
</code>```

When I run the script, sometimes I get error number '00000'. I mean it goes intro the IF. and it is all random. output (sometimes):

```<code>Array ( [0] => 00000 [1] => [2] => )
</code>```

What should I do to fix this problem ?

PS: The script executes correctly every time.

答:
In my experience badly formed queries (syntax errors) and failed queries (for example an INSERT that didn't insert anything) also may WRONGLY return error code 00000. You should go ahead and try to run the complete query on your SQL console and see why it failed. I really don't know why the proper error message isn't returned though. Here's a snippet of the code we use</p>

```<code>    $r = $pdo->prepare($sql);
    if (!$r->execute($input_parameters)) { # query failed
        if ($bLogFailures) {
            error_log('query failed: ERROR['.$pdo->errorCode().':'.print_r($pdo->errorInfo(), true).'] QUERY['.$sql.']');
        }
        return false;
    }
</code>```

Body:
I have the code below:

$sql3 = "update news set date='$time' where id='2'";
$sql3 = $connect->exec($sql3);
if(!$sql3)
{
    print_r($connect->errorInfo());
    $error = $connect->errorInfo();
    die ("Error: (".$error[0].':'.$error[1].') '.$error[2]);
}

When I run the script, sometimes I get error number '00000'. I mean it goes intro the IF. and it is all random. output (sometimes):

Array ( [0] => 00000 [1] => [2] => )

What should I do to fix this problem ?

PS: The script executes correctly every time.

Body:
In my experience badly formed queries (syntax errors) and failed queries (for example an INSERT that didn't insert anything) also may WRONGLY return error code 00000. You should go ahead and try to run the complete query on your SQL console and see why it failed. I really don't know why the proper error message isn't returned though. Here's a snippet of the code we use

    $r = $pdo->prepare($sql);
    if (!$r->execute($input_parameters)) { # query failed
        if ($bLogFailures) {
            error_log('query failed: ERROR['.$pdo->errorCode().':'.print_r($pdo->errorInfo(), true).'] QUERY['.$sql.']');
        }
        return false;
    }


问:
MYSQL update with WHERE SELECT subquery error
I have an issue with getting select sub-queries to work on an UPDATE. I'm trying something like the following:

```<code>UPDATE foo
   SET bar=bar-1
 WHERE baz=
      (
       SELECT baz
       FROM foo
       WHERE fooID='1'
      )
</code>```

Where foo is the table name with primary key fooID. bar and baz are of type INT. When executing this I get the following error:

```<code>Error: A query failed. You can't specify target table 'foo' for update
in FROM clause
</code>```

答:
In some cases you can also take advantage of the MySQL variable. e.g.:</p>

```<code>SET @id1 = (SELECT id FROM foo WHERE name = 'parent');
UPDATE foo SET parent_id = @id1 WHERE name = 'emails';
</code>```

Body:
I have an issue with getting select sub-queries to work on an UPDATE. I'm trying something like the following:

UPDATE foo
   SET bar=bar-1
 WHERE baz=
      (
       SELECT baz
       FROM foo
       WHERE fooID='1'
      )

Where foo is the table name with primary key fooID. bar and baz are of type INT. When executing this I get the following error:

Error: A query failed. You can't specify target table 'foo' for update
in FROM clause

Body:
In some cases you can also take advantage of the MySQL variable. e.g.:

SET @id1 = (SELECT id FROM foo WHERE name = 'parent');
UPDATE foo SET parent_id = @id1 WHERE name = 'emails';


问:
Strange namespace issue on php
I have found this article where I can found this syntax on php:

```<code>use Facades\ {
    App\Zonda
};
</code>```

I can't figure out how it works, Facades should be a namespace but I can't understand how it is related to the rest. I tried to check out documentation but I didn't find anything.

答:
It's new PHP7.* use syntax. You can find more in official documentation.

Group use declarations

Classes, functions and constants being imported from the same
  namespace can now be grouped together in a single use statement.

Title: Strange namespace issue on php

Body:
I have found this article where I can found this syntax on php:

use Facades\ {
    App\Zonda
};

I can't figure out how it works, Facades should be a namespace but I can't understand how it is related to the rest. I tried to check out documentation but I didn't find anything.


问:
Cannot invoke format(Date) on the primitive type void
In the jasper Report I am trying the following

new SimpleDateFormat("dd.MM.yyyy HH:mm").setTimeZone(TimeZone.getTimeZone("UTC")).format( new Date(1483337940000L));

in the text field Expression.

But I am getting the error

Cannot invoke format(Date) on the primitive type void

Is not it  the same as the following code in java?

```<code>1483337940000L is 02.01.2107 07:19

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String test  = sdf.format(new Date(1483337940000L)); // Here I am getting 06:19

String test2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").setTimeZone(TimeZone.getTimeZone("UTC")).format( new Date(1483337940000L)); // Here I am getting the error Cannot invoke format(Date) on the primitive type void
</code>```

答:
The method setTimeZone() comes from the DateFormat class; and doesn't return a value; as it is void!

And when you  write

```<code>sdf.setTimeZone(TimeZone.getTimeZone("UTC")).format(new Date(1483337940000L));
</code>```

you try to invoke format() on the result of setTimeZone().

But as that method doesn't have a result; that must fail!

The real take-away here: don't assume what a method is doing. Yes, some APIs are written to allow for "fluent calls", by returning the object on which methods are called; but not all of them! So, when in doubt: check the javadoc. First.

Body:
In the jasper Report I am trying the following

new SimpleDateFormat("dd.MM.yyyy HH:mm").setTimeZone(TimeZone.getTimeZone("UTC")).format( new Date(1483337940000L));

in the text field Expression.

But I am getting the error

Cannot invoke format(Date) on the primitive type void

Is not it  the same as the following code in java?

1483337940000L is 02.01.2107 07:19

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String test  = sdf.format(new Date(1483337940000L)); // Here I am getting 06:19

String test2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").setTimeZone(TimeZone.getTimeZone("UTC")).format( new Date(1483337940000L)); // Here I am getting the error Cannot invoke format(Date) on the primitive type void

Body:
The method setTimeZone() comes from the DateFormat class; and doesn't return a value; as it is void!

And when you  write

sdf.setTimeZone(TimeZone.getTimeZone("UTC")).format(new Date(1483337940000L));

you try to invoke format() on the result of setTimeZone().

But as that method doesn't have a result; that must fail!

The real take-away here: don't assume what a method is doing. Yes, some APIs are written to allow for "fluent calls", by returning the object on which methods are called; but not all of them! So, when in doubt: check the javadoc. First.


问:
tying a UISearchBar into an action
To let you know from the beginning, I am a newbie at iPhone development, and I have taken an a monstrous task.

First of all, I am writing an application that allows to you to online shop. We have an affiliate account with a known online shopping website, are trying to tie our app into searching that site, and putting the results into a table, with hyperlinks to the site, etc.

But first problems first, one thing at a time:

In Interface Builder, I have a Search Bar, and an outlet connected to the search bar. I also have an IBAction made just to take the text that is entered into the search bar, storing it into a variable, and then searching this website (yes, that's a lot of stuff for an action).

Because I am so new at this process with IB, how do I connect the Search Bar with the IBAction? I know, stupid question.

答:
Assuming you don't have a specific SEARCH button, set your View Controller as the delegate for UITextField and implement your action on

```<code>- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // Code here...
    return YES;
}
</code>```

Don't forget to declare the protocol in your interface file too

```<code>@interface ... : ... <UITextFieldDelegate>
</code>```

Once that's done, everytime the GO/SEARCH key is pressed on the keyboard, it will call the method above.

[EDIT]
Here's the apple Doc for your reference http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

Title: tying a UISearchBar into an action

Body:
Assuming you don't have a specific SEARCH button, set your View Controller as the delegate for UITextField and implement your action on

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // Code here...
    return YES;
}

Don't forget to declare the protocol in your interface file too

@interface ... : ... <UITextFieldDelegate>

Once that's done, everytime the GO/SEARCH key is pressed on the keyboard, it will call the method above.

[EDIT]
Here's the apple Doc for your reference http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html


问:
How to resolve injected instances in Vue.js using TypeScript
According to the official document, it seems that we can use dependency injection feature as long as we stay on object-based structure.

Here's my question. I'm using TypeScript to achieve this goal (class-based). I'm going to use Inversify as an IoC container. My initial idea was something like:

DependencyConfig.ts:

```<code>import { Container } from "inversify";
import "reflect-metadata";
import Warrior from "./interfaces/Warrior";
import { Ninja } from "./models/Warrior";

let container = new Container();

container.bind<Warrior>(Symbol("Warrior")).to(Ninja);

export default container;
</code>```

App.ts:

```<code>import container from "./DependencyConfig";

@Component({
  name: "App",
  provide: container
})
export default class App extends Vue {
}
</code>```

When I checked in my browser's dev console, I was able to see the container has been set to the _provided field. Here's Hello.ts, the child component of App.ts:

Hello.ts:

```<code>@Component({
  name: "Hello",
  inject: [ "container" ]
})
export default class Hello extends Vue {
  created (): void {
    console.log(this);
  }
}
</code>```

As App.ts could access to Hello.ts through vue-router, it didn't register Hello.ts as a child component. I was expecting the injected container should appear on _injected or something similar. However, I couldn't find it. I changed the inject property value from "container" to { "container": Symbol("Container") } but I couldn't still find it.

Service Locator:

It works fine to use a service locator instead of the provide/inject pair:

```<code>// App.ts
@Component({
  name: "App"
})
export default class App extends Vue {
}

// Hello.ts
import container from "./DependencyConfig";

@Component({
  name: "Hello"
})
export default class Hello extends Vue {
  created (): void {
    var ninja = container.get<Ninja>(Symbol("Warrior"));
    console.log(ninja.name);
  }
}
</code>```

However, I want to avoid using the service locator pattern here. Did I miss something while using the provide/inject pair for dependency injection?

答:
I found a solution. If we use vue-class-component and vue-property-decorator, we can achieve this goal – using the provide/inject pair. Here's my code snippet:

```<code>// App.vue
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import SERVICE_IDENTIFIER from "./models/Identifiers";
import container from "./configs/DependencyConfigs";

@Component({
  name: "App",
  // Provides IoC container at the top level of VueComponent
  provide: {
    [SERVICE_IDENTIFIER.CONTAINER]: container
  }
})
export default class App extends Vue {
}
</script>
</code>```

At the top-most Vue component, App.vue, we provide the container instance so that its all child component can consume it. Here's one of its child component, Ninja.vue:

```<code>// Ninja.vue
<script lang="ts">
import Vue from "vue";

// Imports both Component and Inject decorators from vue-property-decorator,
// instead of vue-class-component
import { Component, Inject } from "vue-property-decorator";

import { Container } from "inversify";

import SERVICE_IDENTIFIER from "../models/Identifiers";
import { Ninja as _Ninja } from "../models/Warrior";

@Component({
  name: "Ninja"
})
export default class Ninja extends Vue {
  public warrior: string;
  public weapon: string;

  // IoC container provided from App.ts is injected here
  @Inject(SERVICE_IDENTIFIER.CONTAINER)
  private _container: Container;

  private _ninja: _Ninja;

  created (): void {
    this._ninja = this._container.get<_Ninja>(SERVICE_IDENTIFIER.WARRIOR);
    this.warrior = this._ninja.name;
    this.weapon = this._ninja.weapon.name;
  }
}
</script>
</code>```

The child component uses the @Inject(Symbol) decorator to resolve injected container instance from App.vue.

I wrote a blog post about this in both English and Korean about this.

HTH

Body:
According to the official document, it seems that we can use dependency injection feature as long as we stay on object-based structure.

Here's my question. I'm using TypeScript to achieve this goal (class-based). I'm going to use Inversify as an IoC container. My initial idea was something like:

DependencyConfig.ts:

import { Container } from "inversify";
import "reflect-metadata";
import Warrior from "./interfaces/Warrior";
import { Ninja } from "./models/Warrior";

let container = new Container();

container.bind<Warrior>(Symbol("Warrior")).to(Ninja);

export default container;

App.ts:

import container from "./DependencyConfig";

@Component({
  name: "App",
  provide: container
})
export default class App extends Vue {
}

When I checked in my browser's dev console, I was able to see the container has been set to the _provided field. Here's Hello.ts, the child component of App.ts:

Hello.ts:

@Component({
  name: "Hello",
  inject: [ "container" ]
})
export default class Hello extends Vue {
  created (): void {
    console.log(this);
  }
}

As App.ts could access to Hello.ts through vue-router, it didn't register Hello.ts as a child component. I was expecting the injected container should appear on _injected or something similar. However, I couldn't find it. I changed the inject property value from "container" to { "container": Symbol("Container") } but I couldn't still find it.

Service Locator:

It works fine to use a service locator instead of the provide/inject pair:

// App.ts
@Component({
  name: "App"
})
export default class App extends Vue {
}

// Hello.ts
import container from "./DependencyConfig";

@Component({
  name: "Hello"
})
export default class Hello extends Vue {
  created (): void {
    var ninja = container.get<Ninja>(Symbol("Warrior"));
    console.log(ninja.name);
  }
}

However, I want to avoid using the service locator pattern here. Did I miss something while using the provide/inject pair for dependency injection?

Body:
I found a solution. If we use vue-class-component and vue-property-decorator, we can achieve this goal – using the provide/inject pair. Here's my code snippet:

// App.vue
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import SERVICE_IDENTIFIER from "./models/Identifiers";
import container from "./configs/DependencyConfigs";

@Component({
  name: "App",
  // Provides IoC container at the top level of VueComponent
  provide: {
    [SERVICE_IDENTIFIER.CONTAINER]: container
  }
})
export default class App extends Vue {
}
</script>

At the top-most Vue component, App.vue, we provide the container instance so that its all child component can consume it. Here's one of its child component, Ninja.vue:

// Ninja.vue
<script lang="ts">
import Vue from "vue";

// Imports both Component and Inject decorators from vue-property-decorator,
// instead of vue-class-component
import { Component, Inject } from "vue-property-decorator";

import { Container } from "inversify";

import SERVICE_IDENTIFIER from "../models/Identifiers";
import { Ninja as _Ninja } from "../models/Warrior";

@Component({
  name: "Ninja"
})
export default class Ninja extends Vue {
  public warrior: string;
  public weapon: string;

  // IoC container provided from App.ts is injected here
  @Inject(SERVICE_IDENTIFIER.CONTAINER)
  private _container: Container;

  private _ninja: _Ninja;

  created (): void {
    this._ninja = this._container.get<_Ninja>(SERVICE_IDENTIFIER.WARRIOR);
    this.warrior = this._ninja.name;
    this.weapon = this._ninja.weapon.name;
  }
}
</script>

The child component uses the @Inject(Symbol) decorator to resolve injected container instance from App.vue.

I wrote a blog post about this in both English and Korean about this.

HTH


问:
Dataweave Mulesoft Skip XML tags
I am using dataweave to transform a csv file to xml file. At some places there is no value for a certain xml tag and I am getting an empty tag.

What I want is if there is no value than that tag must not be present in xml at all.

It's a long mapping so I don't want to write the entire mapping in the when otherwise tag but just the mapping for that tag in the when otherwise condition.

Data mapping

```<code>    name: ((payload01.name) when payload01.name != ""
    otherwise {}),
</code>```

Output:
If there is value for name in input

```<code>    <name>Kittu</name>
</code>```

Otherwise

```<code>    <name/>
</code>```

What I want is that in the otherwise condition, no tag should come at all.

All help is appreciated. Thanks.

答:
For adding empty tab in mule this should more appropriate.
name: payload.name default {}

this will produce

if the name don't have a value.

Title: Dataweave Mulesoft Skip XML tags

Body:
I am using dataweave to transform a csv file to xml file. At some places there is no value for a certain xml tag and I am getting an empty tag.

What I want is if there is no value than that tag must not be present in xml at all.

It's a long mapping so I don't want to write the entire mapping in the when otherwise tag but just the mapping for that tag in the when otherwise condition.

Data mapping

    name: ((payload01.name) when payload01.name != ""
    otherwise {}),

Output:
If there is value for name in input

    <name>Kittu</name>

Otherwise

    <name/>

What I want is that in the otherwise condition, no tag should come at all.

All help is appreciated. Thanks.


问:
How to add radio button in highchart legend symbol
I have 3 line series in my highchart , i want to make one series fixed (user) cant disable/hide it by clicking the legend.

And other two i want to work as radio button i.e user can choose among those 2 which one to show , now i was able to make that happen , but now i want a radio button next to those two legend symbols which user can choose from .

legend should be like this.
and the radio button should toggle the series. the working code (without radio button and legend allignment) is :

```<code>drawChart(data1, data2, data3) {
    let chart = Highcharts.chart("container", {
            chart: {
                zoomType: "xy"
            },
            title: {
                text: null
            },
            plotOptions: {
                series: {
                    events: {
                        show: function () {
                            let chart = this.chart,
                                series = chart.series,
                                i = series.length,
                                otherSeries;
                            while (i--) {
                                if (i != 0)
                                    otherSeries = series[i];
                                if (otherSeries != this && otherSeries.visible) {
                                    otherSeries.hide();
                                }
                            }
                        },
                        legendItemClick: function () {
                            if (this.visible) {
                                return false;
                            }
                        }
                    }
                }
            },

            series: [{
                name: "series1",
                data: data1
            }, {
                name: "series2",
                data: data2
            }, {
                name: "series3",
                data: data3,
                visible: false
            }]

        }
</code>```

答:
You need to set the plotOptions and set showCheckbox: true

```<code>plotOptions: {
    line: {
        marker: {   enabled: false  }
    },
    turboThreshold: 0,
    series: {
        cursor: 'pointer',
        showCheckbox: true,
        events: {
            checkboxClick: function (event) {
                if (event.checked) {
                    this.show();
                    this.legendSymbol.show();
                } else {
                    this.hide();
                    this.legendSymbol.hide();
                }
            },
            legendItemClick: function() {
                return false;
            }
        }
    }
},
</code>```

By default the checkboxes are placed right next to series label but we can override it according to our need,
Here is a fiddle that might help !!! It's just a pointer, You can customize according to your need.

Body:
I have 3 line series in my highchart , i want to make one series fixed (user) cant disable/hide it by clicking the legend.

And other two i want to work as radio button i.e user can choose among those 2 which one to show , now i was able to make that happen , but now i want a radio button next to those two legend symbols which user can choose from .

legend should be like this.
and the radio button should toggle the series. the working code (without radio button and legend allignment) is :

drawChart(data1, data2, data3) {
    let chart = Highcharts.chart("container", {
            chart: {
                zoomType: "xy"
            },
            title: {
                text: null
            },
            plotOptions: {
                series: {
                    events: {
                        show: function () {
                            let chart = this.chart,
                                series = chart.series,
                                i = series.length,
                                otherSeries;
                            while (i--) {
                                if (i != 0)
                                    otherSeries = series[i];
                                if (otherSeries != this && otherSeries.visible) {
                                    otherSeries.hide();
                                }
                            }
                        },
                        legendItemClick: function () {
                            if (this.visible) {
                                return false;
                            }
                        }
                    }
                }
            },

            series: [{
                name: "series1",
                data: data1
            }, {
                name: "series2",
                data: data2
            }, {
                name: "series3",
                data: data3,
                visible: false
            }]

        }

Body:
You need to set the plotOptions and set showCheckbox: true

plotOptions: {
    line: {
        marker: {   enabled: false  }
    },
    turboThreshold: 0,
    series: {
        cursor: 'pointer',
        showCheckbox: true,
        events: {
            checkboxClick: function (event) {
                if (event.checked) {
                    this.show();
                    this.legendSymbol.show();
                } else {
                    this.hide();
                    this.legendSymbol.hide();
                }
            },
            legendItemClick: function() {
                return false;
            }
        }
    }
},

By default the checkboxes are placed right next to series label but we can override it according to our need,
Here is a fiddle that might help !!! It's just a pointer, You can customize according to your need.


问:
Is my masking correct
What does it mean by

```<code>if ((readParameter - > type(0) & 0xff) == 0xff) {}
</code>```

I know when we dO '&'with oxff then it returns the LSB. But what does it mean by evaluating it with again == 0xff  ?

I feel it something like this(for instance) :

```<code> if ((00000000 00000000 00000000 11011001 & 00000000 00000000 00000000 11111111) == 00000000 00000000 00000000 11111111)
   {
     //IF THEY ARE EQUAL IT ENTERS IN THE LOOP ? IN THIS CASE THEY ARE  NOT EQUAL
   }
</code>```

Please correct me
if i am wrong ?

答: The result of the filtering operation ( & 0xff ) is compared to the mask itself, to check if the last 8 bits of the parameter were all equals to 1

Title: Is my masking correct

Body:
What does it mean by

if ((readParameter - > type(0) & 0xff) == 0xff) {}

I know when we dO '&'with oxff then it returns the LSB. But what does it mean by evaluating it with again == 0xff  ?

I feel it something like this(for instance) :

 if ((00000000 00000000 00000000 11011001 & 00000000 00000000 00000000 11111111) == 00000000 00000000 00000000 11111111)
   {
     //IF THEY ARE EQUAL IT ENTERS IN THE LOOP ? IN THIS CASE THEY ARE  NOT EQUAL
   }

Please correct me
if i am wrong ?


问:
How to detect if web app running standalone on Chrome mobile
Chrome mobile has recently added the ability to add to home screen, similar to iOS. This is cool but it doesn't support it as well as iOS - it doesn't support window.navigator.standalone so you can't detect whether you are running as a standalone app.

The reference says:

How can I detect if the app is running as an installed app?

You can’t, directly.

Notice it says "directly". My question is can we do it indirectly? Is there some tricky way to make an educated guess?

答:
An old question but significantly better solutions available today for Chrome Android.

One of the ways(cleanest IMO). You may add Web App Manifest with a 'start_url' key with a value that adds a query string parameter to your usual homepage.

ex:- if homepage url is https://www.example.com.
in Web App Manifest set

```<code>    "start_url": "https://www.example.com/?user_mode=app"
</code>```

Google's guide about Web app manifest:https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/

Body:
An old question but significantly better solutions available today for Chrome Android.

One of the ways(cleanest IMO). You may add Web App Manifest with a 'start_url' key with a value that adds a query string parameter to your usual homepage.

ex:- if homepage url is https://www.example.com.
in Web App Manifest set

    "start_url": "https://www.example.com/?user_mode=app"

Google's guide about Web app manifest:https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/


问:
how to get the date from string in C#
I have a string like

```<code> string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");
</code>```

want the output only 2017-03-10

答:
DateTime firstdate = DateTime.ParseExact(startdatestring,
                                       "yyyy-MM-dd hh:mm:ss",
                                       CultureInfo.InvariantCulture);

it's yyyy-MM-dd instead of yyyy/MM/dd

;)

Title: how to get the date from string in C#

Body:
I have a string like

 string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");

want the output only 2017-03-10


问:
I don't understand why is this step necessary to count the number of chars in text document
```<code>lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"
</code>```

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

```<code>no_of_chars = lines.length
</code>```

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

答:
It might be cleaner to do it the other way round, i.e. read the whole file as a single string via IO.read and split the lines afterwards using String#lines:

```<code>text = IO.read('document.txt')
no_of_chars = text.length
lines_count = text.lines.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"
</code>```

Note that String#length will count any character, including punctuation, spaces and newline characters.

Body:
lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

no_of_chars = lines.length

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

Body:
It might be cleaner to do it the other way round, i.e. read the whole file as a single string via IO.read and split the lines afterwards using String#lines:

text = IO.read('document.txt')
no_of_chars = text.length
lines_count = text.lines.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"

Note that String#length will count any character, including punctuation, spaces and newline characters.


问:
fetching data and show in view page

when i execute while loop in view page this below error show
  Message: mysql_fetch_array() expects parameter 1 to be resource, array given

my model

```<code>function get_row($id) {
    $this->db->select("*");
    $this->db->from('pending_list');
    $this->db->where('id',$id);
    $query = $this->db->get();
    return $query->result_array();
}
</code>```

my controller

```<code>public function pass_print() {
    $id = $this->uri->segment(3);

    $data['h'] = $this->admin_model->get_row($id);
    $this->load->view('header');
    $this->load->view('sidebar');
    $this->load->view('print_pass',$data);
    $this->load->view('footer');
}
</code>```

my view

```<code><?php while($rows= mysql_fetch_array($h)){?>
                                        <div class="form-group">
                                            <label for="inputEmail3" class="col-sm-3 control-label">
                                                Visitors Name</label>
                                            <div class="col-sm-9">
                                                <input type="text" class="form-control" id="inputEmail3" value="<?php $rows['visitor_name']?>" name="visitor" placeholder="Visitors Name">
                                            </div>
                                        </div>
<?php}?>
</code>```

答:
View part is wrong. It' should be

```<code><?php
foreach ($h as $item) {
    ?>
    <div class="form-group">
        <label for="inputEmail3" class="col-sm-3 control-label">
            Visitors Name
        </label>
        <div class="col-sm-9">
            <input type="text" class="form-control" id="inputEmail3"
            value="<?php echo $item['visitor_name']?>" name="visitor" placeholder="Visitors Name">
        </div>
    </div>
    <?php
}
?>
</code>```

if you pass the data to view $this->load->view('print_pass',$data); with this then the array name $data['h'] you have mentioned can only call in VIEW. In your case its h

Doubt on your code is

in controller you calling $data['h'] = $this->admin_model->get_row($id); But model code you have added is have function select(). Make sure you're calling correct model method/function

Title: fetching data and show in view page

Body:
when i execute while loop in view page this below error show
  Message: mysql_fetch_array() expects parameter 1 to be resource, array given

my model

function get_row($id) {
    $this->db->select("*");
    $this->db->from('pending_list');
    $this->db->where('id',$id);
    $query = $this->db->get();
    return $query->result_array();
}

my controller

public function pass_print() {
    $id = $this->uri->segment(3);

    $data['h'] = $this->admin_model->get_row($id);
    $this->load->view('header');
    $this->load->view('sidebar');
    $this->load->view('print_pass',$data);
    $this->load->view('footer');
}

my view

<?php while($rows= mysql_fetch_array($h)){?>

                                                Visitors Name

                                                <input type="text" class="form-control" id="inputEmail3" value="<?php $rows['visitor_name']?>" name="visitor" placeholder="Visitors Name">

<?php}?>

Body:
View part is wrong. It' should be

<?php
foreach ($h as $item) {
    ?>
    <div class="form-group">
        <label for="inputEmail3" class="col-sm-3 control-label">
            Visitors Name
        </label>
        <div class="col-sm-9">
            <input type="text" class="form-control" id="inputEmail3"
            value="<?php echo $item['visitor_name']?>" name="visitor" placeholder="Visitors Name">
        </div>
    </div>
    <?php
}
?>

if you pass the data to view $this->load->view('print_pass',$data); with this then the array name $data['h'] you have mentioned can only call in VIEW. In your case its h

Doubt on your code is

in controller you calling $data['h'] = $this->admin_model->get_row($id); But model code you have added is have function select(). Make sure you're calling correct model method/function


问:
VS 2010: After installing WinPhone dev tools, can't choose solution platform
After installing VS2010, I can no longer choose the solution platform in the toolbar (x86/x64/AnyCPU/etc), even for non-Windows Phone projects. I can choose the platform manually by choosing "Configuration Manager" and doing it that way, but that's a bit annoying. In its place there's a greyed out "Windows Phone 7 Emulator" dropdown. Any ideas? Here's what my toolbar looks like right now:

Solution

Matt Lacey's answer pointed me in the right direction. Go to customize, then choose the toolbars radio button, "Standard" in the combo box next to it, then (under the build category), add the solution platform and remove the deployment device. Sucks they do this automatically for all project types, but whatever.

答: You can customize the toolbars however you want. Simply right click on the tool bar and select 'Customize...'. You can select what is displayed and where in the toolbars.</p>


问:
How to download information?
Currently, I have the following that downloads all files under an AWS (Amazon Web Services) S3 bucket.</p>

答:
Limitation:  boto3 list_object() and list_object_v2() will return maximum 1000 keys. To continue get object, you need to make use of "ContinuationToken" parameter.  boto3.s3.resource.objects.all()  will generate an iterator, currently there is no known limit.

However, you must know this :

Downloading from S3 to your local system from the internet WILL cost you, i.e. 0.09/GB. If you need frequently process on such files, maybe you should run your download inside EC2 or use lambda to do the post-processing.

same region S3 data to EC2 download is free. you can run test massive download proof (e.g. say 100GB+  ) without worry about the bill.  You just pay EC2 instance.

Downloading performance/continuity of session from s3 to your local intranet , are subject to your local internet connectivity setup. This can be restriction in your own firewall policies, your router, ISP, etc

Title: How to download information?


问:
comparing the content of two HashMaps with set<> value
I have these two objects.

```<code>public Map<String, Set<RuleConditionBl>> countryToNonSplittedRules1 = new HashMap<>;
public Map<String, Set<RuleConditionBl>> countryToNonSplittedRules2 = new HashMap<>;
</code>```

I have a test that compares these two

and even though their content is the same, i get false for

countryToNonSplittedRules1.equals(countryToNonSplittedRules2);

here is an example:

I read this post, so i'm not sure why doesn't this return true

```<code>public class RuleConditionBl {

public int weight;
public boolean isAll;
public List<String> countries;
public UserFlag userFlag;

@JsonIgnore
private Range<LocalDate> datesRange;

public String fromDate;
public String toDate;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        RuleConditionBl that = (RuleConditionBl) o;

        if (weight != that.weight) return false;
        if (isAll != that.isAll) return false;
        if (countries != null ? !countries.equals(that.countries) : that.countries != null) return false;
        if (userFlag != that.userFlag) return false;
        return datesRange != null ? datesRange.equals(that.datesRange) : that.datesRange == null;
    }

    @Override
    public int hashCode() {
//        int result = weight;
        int result = 0;
        result = 31 * result + (isAll ? 1 : 0);
        result = 31 * result + (countries != null ? countries.hashCode() : 0);
        result = 31 * result + (userFlag != null ? userFlag.hashCode() : 0);
        result = 31 * result + (datesRange != null ? datesRange.hashCode() : 0);
        return result;
    }

{
</code>```

答:
I have looked a bit at your solution.

Your implementation is correct(ish).

First of all, Range<LocalDate> datesRange should not work if I am not mistaken.
Range is not generic, so it cannot be parameterized with arguments.(Please correct me if im wrong).

I change Range<LocalDate> datesRange to List<LocalDate> datesRange.

So besides that, your code is correct. I think your problem is the key values when you put your objects into countryToNonSplittedRules1 and countryToNonSplittedRules2. The key values has to be the same, otherwise you cannot compare the two maps.

```<code>Map<String, Set<RuleConditionBl>> countryToNonSplittedRules1 = new HashMap<>();
Map<String, Set<RuleConditionBl>> countryToNonSplittedRules2 = new HashMap<>();

Set<RuleConditionBl> s1 = new LinkedHashSet<>();
Set<RuleConditionBl> s2 = new LinkedHashSet<>();

//Objects for s1
RuleConditionBl r1 = new RuleConditionBl();
r1.weight = 710;
r1.userFlag = null;
r1.isAll = false;

RuleConditionBl r3 = new RuleConditionBl();
r3.weight = 700;
r3.userFlag = null;
r3.isAll = false;

s1.add(r1);
s1.add(r3);

countryToNonSplittedRules1.put("r1", s1);

//Objects for s2
RuleConditionBl r2 = new RuleConditionBl();
r2.weight = 700;
r2.userFlag = null;
r2.isAll = false;

RuleConditionBl r4 = new RuleConditionBl();
r4.weight = 710;
r4.userFlag = null;
r4.isAll = false;

s2.add(r2);
s2.add(r4);

countryToNonSplittedRules2.put("r1", s2);

System.out.println(countryToNonSplittedRules1.equals(countryToNonSplittedRules2));
</code>```

Output:

```<code>true
</code>```

The order of the elements in Set does matter. According to the documentation:

Compares the specified object with this set for equality. Returns true
  if the given object is also a set, the two sets have the same size,
  and every member of the given set is contained in this set. This
  ensures that the equals method works properly across different
  implementations of the Set interface.

Body:
I have these two objects.

public Map<String, Set<RuleConditionBl>> countryToNonSplittedRules1 = new HashMap<>;
public Map<String, Set<RuleConditionBl>> countryToNonSplittedRules2 = new HashMap<>;

I have a test that compares these two

and even though their content is the same, i get false for

countryToNonSplittedRules1.equals(countryToNonSplittedRules2);

here is an example:

I read this post, so i'm not sure why doesn't this return true

public class RuleConditionBl {

public int weight;
public boolean isAll;
public List<String> countries;
public UserFlag userFlag;

@JsonIgnore
private Range<LocalDate> datesRange;

public String fromDate;
public String toDate;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        RuleConditionBl that = (RuleConditionBl) o;

        if (weight != that.weight) return false;
        if (isAll != that.isAll) return false;
        if (countries != null ? !countries.equals(that.countries) : that.countries != null) return false;
        if (userFlag != that.userFlag) return false;
        return datesRange != null ? datesRange.equals(that.datesRange) : that.datesRange == null;
    }

    @Override
    public int hashCode() {
//        int result = weight;
        int result = 0;
        result = 31 * result + (isAll ? 1 : 0);
        result = 31 * result + (countries != null ? countries.hashCode() : 0);
        result = 31 * result + (userFlag != null ? userFlag.hashCode() : 0);
        result = 31 * result + (datesRange != null ? datesRange.hashCode() : 0);
        return result;
    }

{

Body:
I have looked a bit at your solution.

Your implementation is correct(ish).

First of all, Range<LocalDate> datesRange should not work if I am not mistaken.
Range is not generic, so it cannot be parameterized with arguments.(Please correct me if im wrong).

I change Range<LocalDate> datesRange to List<LocalDate> datesRange.

So besides that, your code is correct. I think your problem is the key values when you put your objects into countryToNonSplittedRules1 and countryToNonSplittedRules2. The key values has to be the same, otherwise you cannot compare the two maps.

Map<String, Set<RuleConditionBl>> countryToNonSplittedRules1 = new HashMap<>();
Map<String, Set<RuleConditionBl>> countryToNonSplittedRules2 = new HashMap<>();

Set<RuleConditionBl> s1 = new LinkedHashSet<>();
Set<RuleConditionBl> s2 = new LinkedHashSet<>();

//Objects for s1
RuleConditionBl r1 = new RuleConditionBl();
r1.weight = 710;
r1.userFlag = null;
r1.isAll = false;

RuleConditionBl r3 = new RuleConditionBl();
r3.weight = 700;
r3.userFlag = null;
r3.isAll = false;

s1.add(r1);
s1.add(r3);

countryToNonSplittedRules1.put("r1", s1);

//Objects for s2
RuleConditionBl r2 = new RuleConditionBl();
r2.weight = 700;
r2.userFlag = null;
r2.isAll = false;

RuleConditionBl r4 = new RuleConditionBl();
r4.weight = 710;
r4.userFlag = null;
r4.isAll = false;

s2.add(r2);
s2.add(r4);

countryToNonSplittedRules2.put("r1", s2);

System.out.println(countryToNonSplittedRules1.equals(countryToNonSplittedRules2));

Output:

true

The order of the elements in Set does matter. According to the documentation:

Compares the specified object with this set for equality. Returns true
  if the given object is also a set, the two sets have the same size,
  and every member of the given set is contained in this set. This
  ensures that the equals method works properly across different
  implementations of the Set interface.


问:
spirit x3 cannot propagate attributes of type optional<vector>
A simple parser as on Coliru. The parser -(+x3::alpha) should be able to propagate an attribute of type boost::optional<std::string> as Qi does. But it does not compile.

```<code>std::string const input = "abc";
boost::optional<std::string> attr;
if(x3::parse(boost::begin(input),boost::end(input),
    -(+x3::alpha),
    attr)) {
    std::cout<<"match!"<<std::endl;
}
else {
    std::cout<<"NOT match!"<<std::endl;
}
</code>```

答:
I don't think the normative claim "should be able [...] as Qi does" cuts wood. X3 is not an evolution of Qi, for very good reasons (such as this).

An oft recurring pattern is that type hints are required in more complicated propagation scenarios. The ugly verbose way could be like this:

```<code>    -(x3::rule<struct _, std::string> {} = +x3::alpha),
</code>```

Live On Coliru

Or you can use the hack I described previously:

```<code>namespace {
    template <typename T>
    struct as_type {
        template <typename Expr>
            auto operator[](Expr&& expr) const {
                return x3::rule<struct _, T>{"as"} = x3::as_parser(std::forward<Expr>(expr));
            }
    };

    template <typename T> static const as_type<T> as = {};
}
</code>```

Live On Coliru

Body:
A simple parser as on Coliru. The parser -(+x3::alpha) should be able to propagate an attribute of type boost::optional<std::string> as Qi does. But it does not compile.

std::string const input = "abc";
boost::optional<std::string> attr;
if(x3::parse(boost::begin(input),boost::end(input),
    -(+x3::alpha),
    attr)) {
    std::cout<<"match!"<<std::endl;
}
else {
    std::cout<<"NOT match!"<<std::endl;
}

Body:
I don't think the normative claim "should be able [...] as Qi does" cuts wood. X3 is not an evolution of Qi, for very good reasons (such as this).

An oft recurring pattern is that type hints are required in more complicated propagation scenarios. The ugly verbose way could be like this:

    -(x3::rule<struct _, std::string> {} = +x3::alpha),

Live On Coliru

Or you can use the hack I described previously:

namespace {
    template <typename T>
    struct as_type {
        template <typename Expr>
            auto operator[](Expr&& expr) const {
                return x3::rule<struct _, T>{"as"} = x3::as_parser(std::forward<Expr>(expr));
            }
    };

    template <typename T> static const as_type<T> as = {};
}

Live On Coliru


问:
String companion object in scala
Given a type which has a "converter", I would like to have automatic conversion on method call using this type's companion object. That is, given the following definition,

```<code>case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit val StringConverter = new Converter[String] {
  def perform = Converted("String")
}
</code>```

make the following code to work:

```<code>implicit def toConverter(a: String.type): Converted =
  implicitly[Converter[String]].perform // Error: `Found String.type, required AnyRef`

def f(needsConverted: Converted) = ???

f(String) // <- That's what I would like to be able to write.
</code>```

But this fails and both attempts for conversion fail. Note that I cannot change f because it is provided by a third-party library and there are many of them.

Can I make f(String) compile using implicits?

If not possible for Strings, what about classes which do have a companion object, can I do this generically like:

```<code>object TheClass

case class TheClass()

implicit val TheClassConverter = new Converter[TheClass] {
  def perform = Converted("TheClass")
}

implicit def toConverter[A: Converter](a: A.type): Converted =
  implicitly[Converter[A]].perform // Error: `Not found value A`

implicit def toConverter(a: TheClass.type): Converted =
  implicitly[Converter[TheClass]].perform // This works but is not generic

f(TheClass) // This works.
</code>```

Can I make the first toConverter to compile ?

答:
Can I make f(String) compile using implicits?

No. You can define a value called String, of course, but it won't be related to the type String.

```<code>implicit toConverter[A: Converter](a: A.type): Converted =
    implicitly[Converter[A]].perform
</code>```

A in A.type must be a value; it is not related to the type parameter A.

In fact, so far as Scala's type system is concerned, there is no relationship between a class/trait and its companion object. So you can't do what you want generically.

Of course, if you don't insist on using () instead of [], it becomes trivial:

```<code>def f1[A: Converter] = f(implicitly[Converter[A]].perform)

f1[String]
f1[TheClass]
</code>```

Title: String companion object in scala

Body:
Given a type which has a "converter", I would like to have automatic conversion on method call using this type's companion object. That is, given the following definition,

case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit val StringConverter = new Converter[String] {
  def perform = Converted("String")
}

make the following code to work:

implicit def toConverter(a: String.type): Converted =
  implicitly[Converter[String]].perform // Error: `Found String.type, required AnyRef`

def f(needsConverted: Converted) = ???

f(String) // <- That's what I would like to be able to write.

But this fails and both attempts for conversion fail. Note that I cannot change f because it is provided by a third-party library and there are many of them.

Can I make f(String) compile using implicits?

If not possible for Strings, what about classes which do have a companion object, can I do this generically like:

object TheClass

case class TheClass()

implicit val TheClassConverter = new Converter[TheClass] {
  def perform = Converted("TheClass")
}

implicit def toConverter[A: Converter](a: A.type): Converted =
  implicitly[Converter[A]].perform // Error: `Not found value A`

implicit def toConverter(a: TheClass.type): Converted =
  implicitly[Converter[TheClass]].perform // This works but is not generic

f(TheClass) // This works.

Can I make the first toConverter to compile ?

Body:
Can I make f(String) compile using implicits?

No. You can define a value called String, of course, but it won't be related to the type String.

implicit toConverter[A: Converter](a: A.type): Converted =
    implicitly[Converter[A]].perform

A in A.type must be a value; it is not related to the type parameter A.

In fact, so far as Scala's type system is concerned, there is no relationship between a class/trait and its companion object. So you can't do what you want generically.

Of course, if you don't insist on using () instead of [], it becomes trivial:

def f1[A: Converter] = f(implicitly[Converter[A]].perform)

f1[String]
f1[TheClass]


问:
C++ Line into Vector
Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.

Anyways, I have a text file:

```<code>6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10
</code>```

6 is the Number of "floats" in the second line (the 3.0,2.5 etc...)
3.0,2.5,-1.5 are all a series of floats.
6 and 10 are just 2 integers.

I have a Vector

```<code>std::vector<double> numbers;
</code>```

All i need to do, is get the Second line put into numbers.
So right now I have

```<code>ifstream myfile (filename.c_str());
</code>```

I can simply just do a myfile>> to get the first value (6)
but how would I go about putting the second line in my vector? Remember I ONLY know how big line 2 is, by reading in the first line (the 6 in this case).

Also the last 2 numbers aren't supposed to be in this vector, but two seperate values.
Which i can just do myfile >> a >> b.

Sorry again for sooo many questions. but I've literally been looking everywhere and asking probably the wrong questions.

答:
Do you have copy_n() in your arsenal?

```<code>template<class In, class Size, class Out>
Out copy_n(In first, Size n, Out result)
{
    while( n-- ) *result++ = *first++;
    return result;
}
</code>```

Put it somewhere where you can easily #include it in other translation units. It's useful. Use it like so to copy your n floating-point values:

```<code>copy_n(std::istream_iterator<double>(std::cin),
       n,
       std::back_inserter(v));
</code>```

Title: C++ Line into Vector

Body:
Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.

Anyways, I have a text file:

6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10

6 is the Number of "floats" in the second line (the 3.0,2.5 etc...)
3.0,2.5,-1.5 are all a series of floats.
6 and 10 are just 2 integers.

I have a Vector

std::vector<double> numbers;

All i need to do, is get the Second line put into numbers.
So right now I have

ifstream myfile (filename.c_str());

I can simply just do a myfile>> to get the first value (6)
but how would I go about putting the second line in my vector? Remember I ONLY know how big line 2 is, by reading in the first line (the 6 in this case).

Also the last 2 numbers aren't supposed to be in this vector, but two seperate values.
Which i can just do myfile >> a >> b.

Sorry again for sooo many questions. but I've literally been looking everywhere and asking probably the wrong questions.

Body:
Do you have copy_n() in your arsenal?

template<class In, class Size, class Out>
Out copy_n(In first, Size n, Out result)
{
    while( n-- ) *result++ = *first++;
    return result;
}

Put it somewhere where you can easily #include it in other translation units. It's useful. Use it like so to copy your n floating-point values:

copy_n(std::istream_iterator<double>(std::cin),
       n,
       std::back_inserter(v));


问:
open a window(wpf) on the foreground from a page(wpf)
I am working at a WPF desktop application, in this application I open a wpf page which contains a listbox of contacts on a frame.

When I double-click on a contact, a window opens to modify it. The problem is that the window is opened in the back and I want it on the foreground , I used this code

```<code>private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
   if (listBox.SelectedItem != null)
   {
       modify_contact window = new modify_contact(list[listBox.SelectedIndex]);
       window.Owner=this;
       window.Show();
    }
}
</code>```

It didn't work because it's and not a window
So what can I do to make my opened on the foreground ?

答:
You can always create a Window and set it's Content like this

```<code>private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
   modify_contact window = new modify_contact(list[listBox.SelectedIndex]);
   Window windowHost = new Window
   {
      Title = "I'm the title",
      Content = window
   };
   windowHost.ShowDialog();
}
</code>```

Body:
I am working at a WPF desktop application, in this application I open a wpf page which contains a listbox of contacts on a frame.

When I double-click on a contact, a window opens to modify it. The problem is that the window is opened in the back and I want it on the foreground , I used this code

private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
   if (listBox.SelectedItem != null)
   {
       modify_contact window = new modify_contact(list[listBox.SelectedIndex]);
       window.Owner=this;
       window.Show();
    }
}

It didn't work because it's and not a window
So what can I do to make my opened on the foreground ?

Body:
You can always create a Window and set it's Content like this

private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
   modify_contact window = new modify_contact(list[listBox.SelectedIndex]);
   Window windowHost = new Window
   {
      Title = "I'm the title",
      Content = window
   };
   windowHost.ShowDialog();
}


问:
Check if column value is in other columns in pandas
I have the following dataframe in pandas

```<code>  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge
</code>```

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

答:
You can use eq, for drop column pop if neech check by rows:

```<code>mask = df.eq(df.pop('target'), axis=0)
print (mask)
       A      B      C
0  False   True  False
1  False  False  False
2  False  False   True
</code>```

And then if need check at least one True add any:

```<code>mask = df.eq(df.pop('target'), axis=0).any(axis=1)
print (mask)
0     True
1    False
2     True
dtype: bool

df['new'] = df.eq(df.pop('target'), axis=0).any(axis=1)
print (df)
        A     B       C    new
0  bridge   cat   brush   True
1     dog   cat    shoe  False
2     cat  shoe  bridge   True
</code>```

But if need check all values in column use isin:

```<code>mask = df.isin(df.pop('target').values.tolist())
print (mask)
       A      B      C
0   True   True   True
1  False   True  False
2   True  False   True
</code>```

And if want check if all values are True add all:

```<code>df['new'] = df.isin(df.pop('target').values.tolist()).all(axis=1)
print (df)
        A     B       C    new
0  bridge   cat   brush   True
1     dog   cat    shoe  False
2     cat  shoe  bridge  False
</code>```

Body:
I have the following dataframe in pandas

  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

Body:
You can use eq, for drop column pop if neech check by rows:

mask = df.eq(df.pop('target'), axis=0)
print (mask)
       A      B      C
0  False   True  False
1  False  False  False
2  False  False   True

And then if need check at least one True add any:

mask = df.eq(df.pop('target'), axis=0).any(axis=1)
print (mask)
0     True
1    False
2     True
dtype: bool

df['new'] = df.eq(df.pop('target'), axis=0).any(axis=1)
print (df)
        A     B       C    new
0  bridge   cat   brush   True
1     dog   cat    shoe  False
2     cat  shoe  bridge   True

But if need check all values in column use isin:

mask = df.isin(df.pop('target').values.tolist())
print (mask)
       A      B      C
0   True   True   True
1  False   True  False
2   True  False   True

And if want check if all values are True add all:

df['new'] = df.isin(df.pop('target').values.tolist()).all(axis=1)
print (df)
        A     B       C    new
0  bridge   cat   brush   True
1     dog   cat    shoe  False
2     cat  shoe  bridge  False


问:
How to resolve keybinding-conflicts in atom.io
I installed the atom.io plugins git-plus and asciidoc-preview.

Unfortunately both claim the keybinding Ctrl + Shift + A. There is no warning shown in the keybinding-settings.

How to solve this Problem? Should I manually add the *.cson files and add another keybinding? Or is there a way to do it directly in atim.io?

答:
Atom version used: 1.15.0

go to settings: ⌘,

go to Keybindings tab

type your command, it'll show all the keybindings associated with your comand

save the keybinding by clicking on the copy button. It'll save it to your clipboard.
a

type ⌘+shift+p and enter keymap. Click on Application: Open your keymap

go to bottom of the file. Paste the keybinding ⌘+s

Done! You should now be able to use your command which atom sorts with higher preference.