问:
Converting jquery based component to angular 2/4 component?
I'm in the process of learning angular and im making a test application for that.
I found a very nice "user card" design based on jquery and google material color pallete and i'd like to migrate it and create a component from it.

The cards can be found here- https://github.com/marlenesco/material-cards

I was wondering - what is the cleaest process of doing so? What should i include and where? Where should i add the javascript associated with that project

答:
It doesn't look like jQuery is doing an awful lot in the codepen, so you can probably forget it altogether. Rather than using jQuery selectors, you could probably get away with using @ViewChild and ElementRef in order to get the DOM elements for manipulation.

My first step would be to make a Card component, so all your JS (TS?) is relative to just one instance.

In parts of the JS where classes are being added and removed, you could use [ngClass] directly in the template, and base their conditions on values you set in your component TS.

Lastly, instances such as:

```<code>window.setTimeout(function() {
    icon
      .removeClass('fa-arrow-left')
      .removeClass('fa-spin-fast')
      .addClass('fa-bars');

  }, 800);
</code>```

Can be handled with Observable.timer(800).subscribe(() => { // do stuff... (like update your ngClass conditions) }.

Of course, there are many different approaches to convert this, but that would be a decent start.

I haven't got time just now, but if you're still stuck this evening, I may have time to have a go at a clean conversion solution.

Happy Coding!

Body:
It doesn't look like jQuery is doing an awful lot in the codepen, so you can probably forget it altogether. Rather than using jQuery selectors, you could probably get away with using @ViewChild and ElementRef in order to get the DOM elements for manipulation.

My first step would be to make a Card component, so all your JS (TS?) is relative to just one instance.

In parts of the JS where classes are being added and removed, you could use [ngClass] directly in the template, and base their conditions on values you set in your component TS.

Lastly, instances such as:

window.setTimeout(function() {
    icon
      .removeClass('fa-arrow-left')
      .removeClass('fa-spin-fast')
      .addClass('fa-bars');

  }, 800);

Can be handled with Observable.timer(800).subscribe(() => { // do stuff... (like update your ngClass conditions) }.

Of course, there are many different approaches to convert this, but that would be a decent start.

I haven't got time just now, but if you're still stuck this evening, I may have time to have a go at a clean conversion solution.

Happy Coding!


来源: stackexchange

问:
Create one-way relationship without foreign key
I've got a problem with relationships I'm trying to form between some models.

I have a Node which has many NodeTasks. This is modelled so that NodeTask belongs_to :node, which works as expected.

I would also like to add a reference to an arbitrary NodeTask on Node - let's say first_node_task, as an optional attribute. This is where I'm having trouble.

I was able to hack it together so that node.first_node_task could be set and worked as expected with the following migration:

```<code>add_reference :nodes, :first_node_task, { type: :uuid, foreign_key: { to_table: :node_tasks } }
</code>```

And model:

```<code>class Node
  belongs_to :first_node_task, class_name: 'NodeTask', foreign_key: 'first_node_task_id', optional: true
end
</code>```

However, I found that I could no longer delete those Nodes, because of the reference to NodeTask. There was some weird reverse relationship going on with the foreign key constraint: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table "nodes" violates foreign key constraint "fk_rails_696709283b" on table "node_tasks"

How can I model my references so that Node can have a first_node_task set, which is a reference to an arbitrary NodeTask, without affecting the related NodeTask?

答:
Try to add dependent: :nullify to

```<code>class Node
    belongs_to :first_node_task, class_name: 'NodeTask', foreign_key: 'first_node_task_id', optional: true, dependent: :nullify
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got a problem with relationships I'm trying to form between some models.

I have a Node which has many NodeTasks. This is modelled so that NodeTask belongs_to :node, which works as expected.

I would also like to add a reference to an arbitrary NodeTask on Node - let's say first_node_task, as an optional attribute. This is where I'm having trouble.

I was able to hack it together so that node.first_node_task could be set and worked as expected with the following migration:

add_reference :nodes, :first_node_task, { type: :uuid, foreign_key: { to_table: :node_tasks } }

And model:

class Node
  belongs_to :first_node_task, class_name: 'NodeTask', foreign_key: 'first_node_task_id', optional: true
end

However, I found that I could no longer delete those Nodes, because of the reference to NodeTask. There was some weird reverse relationship going on with the foreign key constraint: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table "nodes" violates foreign key constraint "fk_rails_696709283b" on table "node_tasks"

How can I model my references so that Node can have a first_node_task set, which is a reference to an arbitrary NodeTask, without affecting the related NodeTask?

Body:
Try to add dependent: :nullify to

class Node
    belongs_to :first_node_task, class_name: 'NodeTask', foreign_key: 'first_node_task_id', optional: true, dependent: :nullify
end


问:
How to Save an HTML page layout into PDF
I am using core PHP having version 5.1.6 in procedural style

How can i save an HTML page into PDF containing exact layout information?

The major with me at currently that, whenever i am trying to save a_pahe.html to pdf by clicking "Save as PDF" link/button, it saves the HTML page but have lost all the layouts that i have needed.

My exact layout of an HTML page is

And the Generated PDF output is as like this

答:
Use the dompdf library: GitHub link

Dompdf is an HTML to PDF converter.
Just download and install it (read the documentation),
then pass your HTML in to dompdf and stream the output:

```<code>// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml(file_get_contents('exemple.html'));

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();
</code>```

Body:
Use the dompdf library: GitHub link

Dompdf is an HTML to PDF converter.
Just download and install it (read the documentation),
then pass your HTML in to dompdf and stream the output:

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml(file_get_contents('exemple.html'));

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();


问:
How to add text file in my project so that it is not visible to user..?
Sir,

I am developing an application in which i am to save some information in text file. During execution, I wish to read/write data from/to the file(.txt file). I dont want the file to be visible to user. Or if it is visible then it must be in programfile folder of the system and user could not delete the data of the file. What should i do? I tried to add the file in Resource file but could not read and write the file. PLease help me to read/write OR provide some other way to implement the same(described above).

Thanks in advance....

答:
I am not sure if this might help you.
You may make the text file as an Embedded resource and get the same via

```<code>Assembly assm = Assembly.GetExecutingAssembly();
StreamReader aread = new StreamReader(assm.GetManifestResourceStream("Namespace.TextFile1.txt"));
</code>```

So this is not accessible to the user nor available in the deployed location

ContentLicense: CC BY-SA 2.5

Body:
I am not sure if this might help you.
You may make the text file as an Embedded resource and get the same via

Assembly assm = Assembly.GetExecutingAssembly();
StreamReader aread = new StreamReader(assm.GetManifestResourceStream("Namespace.TextFile1.txt"));

So this is not accessible to the user nor available in the deployed location


问:
Remove spaces between links from html table if links removed
I have below table in my jsp with links coming dynamically on page load using java arraylist

```<code><%ArrayList<String> display  = ArrayList<String>)session.getAttribute("links");       %>
<table border="0" width="100%" style ="">
    <tr></tr>
    <td width="20%"></td>
    <table border="0" width ="50%" id="LinkDisplay">
        <div id="LinkDisplay">
            <%if(display!=null){
            for(int p=0;p<display.size();p++){%>
            <tr><td width="42%"> </td><td><a href="javascript:removeLink('<%=display.get(p)%>')"><%=display.get(p)%></a><br></td><td> </td></tr>
            <% } }%>
        </div>
    </table>
    <td></td>
    <tr></tr>
</table>
</code>```

When I click on link, it remove and hide the link calling removeLink javascript function

```<code>$('#LinkDisplay a').click(function() {
    var $this = $(this);
    $this.remove();
}
</code>```

But when link remove, it leaves the spaces between links. How to remove that space, when link clicked. I tried to hide even tried to remove the empty td element (without link text) but it does not help..
Page with all the links look as below :-

after clicking on links it leaves the spaces as below :-

Also if there are more than 10 links I want to add scroll bars, can we do that on table.
If table is not the right way to do all this, is there any other easy way?

答:
You should remove the complete
, .closest() can be used to traverse up to
 then remove it.

```<code>$('#LinkDisplay a').click(function () {
    var $this = $(this);
    $this.closest('tr').remove();
});
</code>```

Body:
I have below table in my jsp with links coming dynamically on page load using java arraylist

<%ArrayList<String> display  = ArrayList<String>)session.getAttribute("links");       %>

            <%if(display!=null){
            for(int p=0;p<display.size();p++){%>

 	<a href="javascript:removeLink('<%=display.get(p)%>')"><%=display.get(p)%>

            <% } }%>

When I click on link, it remove and hide the link calling removeLink javascript function

$('#LinkDisplay a').click(function() {
    var $this = $(this);
    $this.remove();
}

But when link remove, it leaves the spaces between links. How to remove that space, when link clicked. I tried to hide even tried to remove the empty td element (without link text) but it does not help..
Page with all the links look as below :-

after clicking on links it leaves the spaces as below :-

Also if there are more than 10 links I want to add scroll bars, can we do that on table.
If table is not the right way to do all this, is there any other easy way?

Body:
You should remove the complete <TR>, .closest() can be used to traverse up to <TR> then remove it.

$('#LinkDisplay a').click(function () {
    var $this = $(this);
    $this.closest('tr').remove();
});


问:
Auto-insert soft hyphen in Jekyll Markdown, assuming a specific language?
I'd like to use justified text for my Jekyll-based website, but there are currently some unpleasant gaps in text at various widths. By inserting the soft hyphen character, , into my Markdown, I managed to make it look much better.

However, it is an unpleasant process, and it defeats most of the point of using Markdown. Software packages such as Microsoft Word are capable of inserting hyphens at logical points, presumably based on a dictionary of acceptable break points.

Where can I get a dictionary of that sort?

How can I make Jekyll automatically perform this process when processing Markdown text?

I only care about supporting English at this point.

答:
However, it is an unpleasant process, and it defeats most of the point
  of using Markdown.

This does not have anything to do with Markdown. This is an HTML issue.

HTML does not hyphenate, unless you use CSS hyphenation. This has poor browser support and is language dependent (use hyphenate-resources for this).

I would accept the spotty browser support of this CSS feature (accept its graceful degredation/progressive enhancement). If that is unacceptable for you, you can use a javascript library, like hyphenator.js, to insert the  characters into your content.

Body:
However, it is an unpleasant process, and it defeats most of the point
  of using Markdown.

This does not have anything to do with Markdown. This is an HTML issue.

HTML does not hyphenate, unless you use CSS hyphenation. This has poor browser support and is language dependent (use hyphenate-resources for this).

I would accept the spotty browser support of this CSS feature (accept its graceful degredation/progressive enhancement). If that is unacceptable for you, you can use a javascript library, like hyphenator.js, to insert the &shy; characters into your content.


问:
How to keep page header sticky when soft keyboard shows?
I have a very simple page with a header and several textboxes in my UWP app:

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <TextBlock Grid.Row="0" Text="Page Title!" />

    <ScrollViewer Grid.Row="1" VerticalScrollMode="Auto">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <TextBox Grid.Row="0" Margin="20" />
            <TextBox Grid.Row="1" Margin="20" />
            <TextBox Grid.Row="2" Margin="20" />
            <TextBox Grid.Row="3" Margin="20" />
            <TextBox Grid.Row="4" Margin="20" />
        </Grid>
    </ScrollViewer>
</Grid>
</code>```

In Windows 10 mobile, when the bottom textbox get focus and soft keyboard appears, the full content of the page is scrolling up and I don't want this. I want the header to remain visible and the scrollviewer scrolls to the textbox to keep in view.
How can I achive this?
Thanks in advance.

答:
You can use the CommandBar and add the TextBlock into CommandBar.Content, then the header will remain visible in the page. The page xaml code should look like this,

```<code><Page.TopAppBar>
    <CommandBar Background="Transparent" OverflowButtonVisibility="Collapsed">
        <CommandBar.Content>
            <TextBlock  Text="Page Title!" Margin="20" />
        </CommandBar.Content>
    </CommandBar>
</Page.TopAppBar>
<Grid>
    <ScrollViewer  VerticalScrollMode="Auto">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <TextBox Grid.Row="0" Margin="20" />
            <TextBox Grid.Row="1" Margin="20" />
            <TextBox Grid.Row="2" Margin="20" />
            <TextBox Grid.Row="3" Margin="20" />
            <TextBox Grid.Row="4" Margin="20" />
        </Grid>
    </ScrollViewer>
</Grid>
</code>```

Body:
I have a very simple page with a header and several textboxes in my UWP app:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <TextBlock Grid.Row="0" Text="Page Title!" />

    <ScrollViewer Grid.Row="1" VerticalScrollMode="Auto">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <TextBox Grid.Row="0" Margin="20" />
            <TextBox Grid.Row="1" Margin="20" />
            <TextBox Grid.Row="2" Margin="20" />
            <TextBox Grid.Row="3" Margin="20" />
            <TextBox Grid.Row="4" Margin="20" />
        </Grid>
    </ScrollViewer>
</Grid>

In Windows 10 mobile, when the bottom textbox get focus and soft keyboard appears, the full content of the page is scrolling up and I don't want this. I want the header to remain visible and the scrollviewer scrolls to the textbox to keep in view.
How can I achive this?
Thanks in advance.

Body:
You can use the CommandBar and add the TextBlock into CommandBar.Content, then the header will remain visible in the page. The page xaml code should look like this,

<Page.TopAppBar>
    <CommandBar Background="Transparent" OverflowButtonVisibility="Collapsed">
        <CommandBar.Content>
            <TextBlock  Text="Page Title!" Margin="20" />
        </CommandBar.Content>
    </CommandBar>
</Page.TopAppBar>
<Grid>
    <ScrollViewer  VerticalScrollMode="Auto">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <TextBox Grid.Row="0" Margin="20" />
            <TextBox Grid.Row="1" Margin="20" />
            <TextBox Grid.Row="2" Margin="20" />
            <TextBox Grid.Row="3" Margin="20" />
            <TextBox Grid.Row="4" Margin="20" />
        </Grid>
    </ScrollViewer>
</Grid>


问:
SQL MAX COUNT & MIN COUNT
I am trying these two SQL statements on the following two tables:

```<code>SELECT TOP 1
    Country
FROM (
    SELECT
        customer.country,
        count(*) as Appointments
    FROM
       customer.country
    GROUP BY
        country
    ORDER BY
        count(*)
) AS AppointmentCount
</code>```

The SQL above is supposed to give the country with maximum appointments through COUNT (For the MIN I was going to use ORDER BY DESC)

tables' image

Unfortunately the above SQL is giving the following error but I cannot find a way to fix it:

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near '1 Country FROM ( SELECT customer.country, count(*)' at line 1

Any help on how I can gix the above SQL statement? Any help would be much appreciated. Thanks in advance.

答:
It's a minor problem. You need to fix the FROM clause. I.e. customer.country is not a table. This will be right:

```<code>FROM
   customer
</code>```

Also, the TOP is not really compatible with the subquery. Luckily, you don't need the subquery:

```<code>SELECT
     TOP 1  customer.country
FROM
   customer
GROUP BY
    country
ORDER BY
    count(*)
</code>```

Title: SQL MAX COUNT & MIN COUNT

Body:
I am trying these two SQL statements on the following two tables:

SELECT TOP 1
    Country
FROM (
    SELECT
        customer.country,
        count(*) as Appointments
    FROM
       customer.country
    GROUP BY
        country
    ORDER BY
        count(*)
) AS AppointmentCount

The SQL above is supposed to give the country with maximum appointments through COUNT (For the MIN I was going to use ORDER BY DESC)

tables' image

Unfortunately the above SQL is giving the following error but I cannot find a way to fix it:

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near '1 Country FROM ( SELECT customer.country, count(*)' at line 1

Any help on how I can gix the above SQL statement? Any help would be much appreciated. Thanks in advance.

Body:
It's a minor problem. You need to fix the FROM clause. I.e. customer.country is not a table. This will be right:

FROM
   customer

Also, the TOP is not really compatible with the subquery. Luckily, you don't need the subquery:

SELECT
     TOP 1  customer.country
FROM
   customer
GROUP BY
    country
ORDER BY
    count(*)


问:
How to identify request (by ID) through middleware chain in Express.
I am developping a RESTful server in node.js, using Express as framework, and Winston, for the moment, as logger module.
This server will handle a big amount of simultaneous request, and it would be very useful to me to be able to track the log entries for each specific request, using something like a 'request ID'. The straight solution is just to add this ID as another piece of logging information each time I want to make a log entry, but it will mean to pass the 'request ID' to each method used by the server.

I would like to know if there is any node.js/javascript module or technique that would allow me to do this in an easier way, without carrying around the request ID for each specific request.

答:
I was struggling search for a solution for this problem.
The thing I didn't like it about solutions suggested here was that they imply to share the req object among all the functions along the project.
I found out a solution mixing your approach (creating an uuid per request) and with a library (continuation-local-storage) that allows sharing namespaces among modules.

You can find the explanation in this other answer: https://stackoverflow.com/a/47261545/5710581

If you want more info, I wrote down all these ideas and all the code in a post, in order to explain everything in one place:
Express.js: Logging info with global unique request ID – Node.js


问:
"Oops" error while installing SQL Server 2017 developer edition on Windows 10
I'm trying to install SQL Server 2017 Developer edition with "Basic" installation type but it gives below error message:

Oops...

Unable to install SQL Server (setup.exe).

Build version it is trying to install is 14.1710.3866.2

I've already tried running the installer several time but I got the very same error screen every time. Also tried launching the installer with administrative privileges but no luck.

Does anyone has any idea about this mysterious error message and how to overcome it? It doesn't point me to any log file which I can look into to get some idea about why it is happening on my machine. I downloaded the setup from official MS website here.

Update: With help from @TheGameiswar I was able to locate the log files for the installation attempts. Only relevant things which I could find from a file named Detail_Rules.txt was as below:

(01) 2017-11-17 14:37:43 Slp: Neither the localized version nor the
ENU help .chm file exist in the media. This could mean that there is
no appropriate help file to display on the UI. Error message: The help
.chm file
'C:\SQLServer2017Media\RulesEng\1033_ENU_LP\x64\1033\help\s11ch_setup.chm'
is missing from the media..

I'm not sure if it is the root cause of the error.

答:
Neither the localized version nor the ENU help .chm file exist in the media. This could mean that there is no appropriate help file to display on the UI. Error message: The help .chm file 'C:\SQLServer2017Media\RulesEng\1033_ENU_LP\x64\1033\help\s11ch_setup.chm' is missing from the media

As per my understanding,this issue arises when setup files are not downloaded completely..

You may have to download entire setup first and install it later as shown in screenshot below


问:
array in array in array and also one
I need to write a factorial using an array but the problem is only Show 120 five times and what i want is  1, 2, 6, 24, 120 showing in the textBox

```<code>int factProg = 1;
public void factArray(int[] arr)
{
    for (int i = 0; i < arr.Length; i++)
    {
        factProg = factProg * arr[i];
    }
}

int[] arr = {1,2,3,4,5};

for (int i = 0; i < arr.Length; i++)
{
    factArray(arr);
    textBox1.Text += Convert.ToString(factProg);
    textBox1.Text += Environment.NewLine;
}
</code>```

答:
Please find the code below

```<code>public static void FactorialJohn(int[] arr)
            {

                List<int> Resarr = new List<int>();
                arr.ToList().ForEach(x => Resarr.Add(Enumerable.Range(1, x).Aggregate((a, b) => a * b)));

                foreach (var item in Resarr)
                {
                    Console.WriteLine(item);
                }
            }
</code>```

The above code gets you factorial of every element in the array.

Title: array in array in array and also one

Body:
I need to write a factorial using an array but the problem is only Show 120 five times and what i want is  1, 2, 6, 24, 120 showing in the textBox

int factProg = 1;
public void factArray(int[] arr)
{
    for (int i = 0; i < arr.Length; i++)
    {
        factProg = factProg * arr[i];
    }
}

int[] arr = {1,2,3,4,5};

for (int i = 0; i < arr.Length; i++)
{
    factArray(arr);
    textBox1.Text += Convert.ToString(factProg);
    textBox1.Text += Environment.NewLine;
}

Body:
Please find the code below

public static void FactorialJohn(int[] arr)
            {

                List<int> Resarr = new List<int>();
                arr.ToList().ForEach(x => Resarr.Add(Enumerable.Range(1, x).Aggregate((a, b) => a * b)));

                foreach (var item in Resarr)
                {
                    Console.WriteLine(item);
                }
            }

The above code gets you factorial of every element in the array.


问:
Django models: Why the name clash?
Firstly, I know how to fix the problem, I'm just trying to understand why it's occuring. The error message:

users.profile: Reverse query name for field 'address' clashes with related field 'Address.profile'. Add a related_name a
  rgument to the definition for 'address'.

And the code:

```<code>class Address(models.Model):
    country = fields.CountryField(default='CA')
    province = fields.CAProvinceField()
    city = models.CharField(max_length=80)
    postal_code = models.CharField(max_length=6)
    street1 = models.CharField(max_length=80)
    street2 = models.CharField(max_length=80, blank=True, null=True)
    street3 = models.CharField(max_length=80, blank=True, null=True)

class Profile(Address):
    user = models.ForeignKey(User, unique=True, related_name='profile')
    primary_phone = models.CharField(max_length=20)
    address = models.ForeignKey(Address, unique=True)
</code>```

If I understand correctly, this line:

```<code>address = models.ForeignKey(Address, unique=True)
</code>```

Will cause an attribute to be added to the Address class with the name profile. What's creating the other "profile" name?

What if I don't need a reverse name? Is there a way to disable it? Addresses are used for a dozen things, so most of the reverse relationships will be blank anyway.

Is there a way to copy the address fields into the model rather than having a separate table for addresses? Without Python inheritance (this doesn't make sense, and if an Model has 2 addresses, it doesn't work).

答:
in the django docs it says:

If you'd prefer Django didn't create a backwards relation, set related_name to '+'. For example, this will ensure that the User model won't get a backwards relation to this model:

```<code>user = models.ForeignKey(User, related_name='+')
</code>```

but I never tried it myself....

Title: Django models: Why the name clash?

Body:
Firstly, I know how to fix the problem, I'm just trying to understand why it's occuring. The error message:

users.profile: Reverse query name for field 'address' clashes with related field 'Address.profile'. Add a related_name a
  rgument to the definition for 'address'.

And the code:

class Address(models.Model):
    country = fields.CountryField(default='CA')
    province = fields.CAProvinceField()
    city = models.CharField(max_length=80)
    postal_code = models.CharField(max_length=6)
    street1 = models.CharField(max_length=80)
    street2 = models.CharField(max_length=80, blank=True, null=True)
    street3 = models.CharField(max_length=80, blank=True, null=True)

class Profile(Address):
    user = models.ForeignKey(User, unique=True, related_name='profile')
    primary_phone = models.CharField(max_length=20)
    address = models.ForeignKey(Address, unique=True)

If I understand correctly, this line:

address = models.ForeignKey(Address, unique=True)

Will cause an attribute to be added to the Address class with the name profile. What's creating the other "profile" name?

What if I don't need a reverse name? Is there a way to disable it? Addresses are used for a dozen things, so most of the reverse relationships will be blank anyway.

Is there a way to copy the address fields into the model rather than having a separate table for addresses? Without Python inheritance (this doesn't make sense, and if an Model has 2 addresses, it doesn't work).

Body:
in the django docs it says:

If you'd prefer Django didn't create a backwards relation, set related_name to '+'. For example, this will ensure that the User model won't get a backwards relation to this model:

user = models.ForeignKey(User, related_name='+')

but I never tried it myself....


问:
How to get field values from unicode[u'a', u'd'] in odoo10
I want to get string form unicode. For this my code is here:

```<code>@api.multi

    def _select_service_product(self):

        r = []

        for order in self.order_line:

            res = order.product_id.type_service

            r.append(res)

            self.services_infor = r

            l = self.services_infor

            print "test,,,", res, self.services_infor, l
</code>```

services_infor = fields.Char(compute='_select_service_product')

Now terminal showes:

test,,, d [False, u'a', u'd'] [False, u'a', u'd']

From here i want values a, b

答:
```<code>x = u"['a', 'b']"
# either you c an explicitly convert the unicode chars
print str(x)
output : "['a', 'b']"
#use eval function to make the unicode list to original
print eval(x)
output: ['a','b']
</code>```

Body:
I want to get string form unicode. For this my code is here:

@api.multi

    def _select_service_product(self):

        r = []

        for order in self.order_line:

            res = order.product_id.type_service

            r.append(res)

            self.services_infor = r

            l = self.services_infor

            print "test,,,", res, self.services_infor, l

services_infor = fields.Char(compute='_select_service_product')

Now terminal showes:

test,,, d [False, u'a', u'd'] [False, u'a', u'd']

From here i want values a, b


问:
BXSlider event when video starts playing
I am using BXSlider to display various videos.  I am trying to fade out an overlay when the first video starts playing.

I have tried hooking into onSliderLoad but that trigger before the video has started playing.

Anyone know if there is a way I can detect when the video has actually started playing?

答:
Listen for the playing event.

Demo

var vid = document.getElementById('vid');

vid.addEventListener('playing', function(e) {
  console.log('Video has started');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id='vid' src='http://media6000.dropshots.com/photos/1381926/20170326/005611.mp4' width='320' height='180' controls autoplay></video></code>```

Body:
Listen for the playing event.

Demo

var vid = document.getElementById('vid');

vid.addEventListener('playing', function(e) {
  console.log('Video has started');
});

<video id='vid' src='http://media6000.dropshots.com/photos/1381926/20170326/005611.mp4' width='320' height='180' controls autoplay></video>


问:
How to set split value in XSL 1.0
I need to set split values in different  parameters.My response like below.

```<code>  `<Response >
     <Result>100002 0 Testing 1500.00 YES</Result>
  </Response>`
</code>```

What i need is to get above split value in different result like below .[please note i have hard coded "select="100002" " values]

```<code>          ` <xsl:element name="ns1:Response">
              <xsl:value-of select="100002">
           </xsl:element>`

     `<xsl:element name="ns1:amount">
              <xsl:value-of select="0 ">
           </xsl:element>`

    `<xsl:element name="ns1:name">
              <xsl:value-of select="Testing  ">
           </xsl:element>`

   `<xsl:element name="ns1:Amount">
              <xsl:value-of select="1500.00">
           </xsl:element>`

 `<xsl:element name="ns1:Other">
              <xsl:value-of select="Yes">
           </xsl:element>`
</code>```

答:
There are plenty topics to a split function already. E.g.: Split implementation

This should help you out.
WithRefering to that you should just need a result template looking like this:

```<code><xsl:template match="result">
    <xsl:call-template name="splitfunction">
        <xsl:with-param name="string" select="."/>
        <xsl:with-param name="seperator" select=" "/>
    </xsl:call:template>
</xsl:template>
</code>```

Title: How to set split value in XSL 1.0

Body:
I need to set split values in different  parameters.My response like below.

  `<Response >
     <Result>100002 0 Testing 1500.00 YES</Result>
  </Response>`

What i need is to get above split value in different result like below .[please note i have hard coded "select="100002" " values]

          ` <xsl:element name="ns1:Response">
              <xsl:value-of select="100002">
           </xsl:element>`

     `<xsl:element name="ns1:amount">
              <xsl:value-of select="0 ">
           </xsl:element>`

    `<xsl:element name="ns1:name">
              <xsl:value-of select="Testing  ">
           </xsl:element>`

   `<xsl:element name="ns1:Amount">
              <xsl:value-of select="1500.00">
           </xsl:element>`

 `<xsl:element name="ns1:Other">
              <xsl:value-of select="Yes">
           </xsl:element>`

Body:
There are plenty topics to a split function already. E.g.: Split implementation

This should help you out.
WithRefering to that you should just need a result template looking like this:

<xsl:template match="result">
    <xsl:call-template name="splitfunction">
        <xsl:with-param name="string" select="."/>
        <xsl:with-param name="seperator" select=" "/>
    </xsl:call:template>
</xsl:template>


问:
SSRS bar chart with multiple categories
I have built some quite ssrs charts, but is it possible to create below bar chart n SSRS.

![click on the link below to show the bar chart][1]

but when am creating this in ssrs , am getting report as below.

I am getting the report in ssrs as below, but not like the above one:

![][2]

答:
If you want to include the heading as they are in your first image, you will need to be clever with your dataset.

Personally I would probably take the approach of including dummy chart values to get your Category heading without a corresponding bar in the chart, such as:

```<code>Group          Order  Category       Value
31 to 60 Days  1      31 to 60 Days  0
31 to 60 Days  2      Today          14
31 to 60 Days  3      1 Month Ago    12
31 to 60 Days  4      2 Month Ago    44
Up to 30 Days  1      Up to 30 Days  0
Up to 30 Days  2      Today          11
Up to 30 Days  3      1 Month Ago    8
Up to 30 Days  4      2 Month Ago    21
</code>```

From which you can:

Group your Categories using the Group value

Display each Category in its correct order by sorting on the Order column

Actually display your chart values using the Value column, which will show nothing for your group headings

How you get your data into that format will depend on your data source, but should be fairly trivial if you are using a SQL source.

Title: SSRS bar chart with multiple categories

Body:
If you want to include the heading as they are in your first image, you will need to be clever with your dataset.

Personally I would probably take the approach of including dummy chart values to get your Category heading without a corresponding bar in the chart, such as:

Group          Order  Category       Value
31 to 60 Days  1      31 to 60 Days  0
31 to 60 Days  2      Today          14
31 to 60 Days  3      1 Month Ago    12
31 to 60 Days  4      2 Month Ago    44
Up to 30 Days  1      Up to 30 Days  0
Up to 30 Days  2      Today          11
Up to 30 Days  3      1 Month Ago    8
Up to 30 Days  4      2 Month Ago    21

From which you can:

Group your Categories using the Group value

Display each Category in its correct order by sorting on the Order column

Actually display your chart values using the Value column, which will show nothing for your group headings

How you get your data into that format will depend on your data source, but should be fairly trivial if you are using a SQL source.


问:
How to convert int with more zero digits to string in python?
While i was participating in an online python competition i got stuck in a small operation,
the thing is that,
i need to convert an integer 0000 to a string. but by using str(0000) will give only '0' as the output similarly i need to convert numbers like 0001,0003,0000,00045,0003.</p>

```<code>I am expecting str(0000)='0000'
</code>```

答: In the example by Jonathan, 0045 becomes 37 because 0045 is considered as octal by the interpreter. 4*8+5=37. Usually in cases like this, we will not start with leading zeroes. we will start with 45. Hence the answer will be consistent. leading zeroes in string form provide a way for the interpreter to understand octal representation. Hope this helps. </p>

Body:
While i was participating in an online python competition i got stuck in a small operation,
the thing is that,
i need to convert an integer 0000 to a string. but by using str(0000) will give only '0' as the output similarly i need to convert numbers like 0001,0003,0000,00045,0003.

I am expecting str(0000)='0000'


问:
C# 4.0 optional out/ref arguments
Does C# 4.0 allow optional out or ref arguments?

答:
No, but you can use a delegate (e.g. Action) as an alternative.

Inspired in part by Robin R's answer when facing a situation where I thought I wanted an optional out parameter, I instead used an Action delegate. I've borrowed his example code to modify for use of Action<int> in order to show the differences and similarities:

```<code>public string foo(string value, Action<int> outResult = null)
{
    // .. do something

    outResult?.Invoke(100);

    return value;
}

public void bar ()
{
    string str = "bar";

    string result;
    int optional = 0;

    // example: call without the optional out parameter
    result = foo (str);
    Console.WriteLine ("Output was {0} with no optional value used", result);

    // example: call it with optional parameter
    result = foo (str, x => optional = x);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);

    // example: call it with named optional parameter
    foo (str, outResult: x => optional = x);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
}
</code>```

This has the advantage that the optional variable appears in the source as a normal int (the compiler wraps it in a closure class, rather than us wrapping it explicitly in a user-defined class).

The variable needs explicit initialisation because the compiler cannot assume that the Action will be called before the function call exits.

It's not suitable for all use cases, but worked well for my real use case (a function that provides data for a unit test, and where a new unit test needed access to some internal state not present in the return value).

Title: C# 4.0 optional out/ref arguments

Body:
No, but you can use a delegate (e.g. Action) as an alternative.

Inspired in part by Robin R's answer when facing a situation where I thought I wanted an optional out parameter, I instead used an Action delegate. I've borrowed his example code to modify for use of Action<int> in order to show the differences and similarities:

public string foo(string value, Action<int> outResult = null)
{
    // .. do something

    outResult?.Invoke(100);

    return value;
}

public void bar ()
{
    string str = "bar";

    string result;
    int optional = 0;

    // example: call without the optional out parameter
    result = foo (str);
    Console.WriteLine ("Output was {0} with no optional value used", result);

    // example: call it with optional parameter
    result = foo (str, x => optional = x);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);

    // example: call it with named optional parameter
    foo (str, outResult: x => optional = x);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
}

This has the advantage that the optional variable appears in the source as a normal int (the compiler wraps it in a closure class, rather than us wrapping it explicitly in a user-defined class).

The variable needs explicit initialisation because the compiler cannot assume that the Action will be called before the function call exits.

It's not suitable for all use cases, but worked well for my real use case (a function that provides data for a unit test, and where a new unit test needed access to some internal state not present in the return value).


问:
Call to undefined method DOMNodeList::getElementsByTagName()
I would like to parse an html table using PHP's DOMDocument, so I use a foreach for every table:   foreach($_POST['comparison'] as $value) {   } in which  i nested the code below. So from the comparison table i want to take each row ($value), the value contains an html table (
 ...
). Here is the table i want to parse:

```<code><table>
    <tbody>
        <tr>
            <td >.....</td>
            <td>....</td>
        </tr>
        <tr>
            <td>....</td>
            <td>.....</td>
        </tr>
    </tbody>
</table>
</code>```

The second code goes like this, i create a foreach for the rows, then an index ($i) for every row and inside every row another foreach with a new index ($j) for the columns, so the purpose is to echo each column of every row like this (first column-first row, second column-first row, first column-second row, second column-second row...

```<code>          foreach($_POST['comparison'] as $value) {

    echo  "<div id='primary' class='content-area'>";

               var_dump($value);  // check the type in the variable value
      $dom = new DOMDocument;

    $dom->loadHTML($value);
    $dom->preserveWhiteSpace = false;

    $tables = $dom->getElementsByTagName('table');

     foreach ($tables->getElementsByTagName('tr') as $element1) {
            for ($i = 0; $i < $element1->length; $i++) {

             echo   $element1->item($i)->nodeValue . "\n";

               foreach ($element1->getElementsByTagName('td') as $element2) {

                  for ($j = 0; $j < $element2->length; $j++) {

               echo $element2->item($j)->nodeValue . "\n";  }

           /* $value_spec[] = $element2->nodeValue + "<br>";  */
        }
     }
  }

    echo " </div><!-- content-area -->";

 }

}
</code>```

I followed the instructions for the error "Call to undefined method DOMNodeList::getElementsByTagName()", which is to add item() to have access to every cell of the table but the error remains. I would appreciate if someone could help.

答:
Try this,</p>

```<code><?php

$dom = new domDocument;
$dom->loadHTML($value);
$dom->preserveWhiteSpace = false;

$tables = $dom->getElementsByTagName('table');
$tr = $dom->getElementsByTagName('tr');

foreach ($tr as $element1) {
    for ($i = 0; $i < count($element1); $i++) {
        echo $element1->nodeValue . "\n";
        foreach ($element1->getElementsByTagName('td') as $element2) {
            for ($j = 0; $j < count($element2); $j++) {
                echo $element2->nodeValue . "\n";
            }
        }
    }
}
</code>```

Body:
I would like to parse an html table using PHP's DOMDocument, so I use a foreach for every table:   foreach($_POST['comparison'] as $value) {   } in which  i nested the code below. So from the comparison table i want to take each row ($value), the value contains an html table (
 ...
). Here is the table i want to parse:

            .....
            ....

            ....
            .....

The second code goes like this, i create a foreach for the rows, then an index ($i) for every row and inside every row another foreach with a new index ($j) for the columns, so the purpose is to echo each column of every row like this (first column-first row, second column-first row, first column-second row, second column-second row...

          foreach($_POST['comparison'] as $value) {

    echo  "
";

               var_dump($value);  // check the type in the variable value
      $dom = new DOMDocument;

    $dom->loadHTML($value);
    $dom->preserveWhiteSpace = false;

    $tables = $dom->getElementsByTagName('table');

     foreach ($tables->getElementsByTagName('tr') as $element1) {
            for ($i = 0; $i < $element1->length; $i++) {

             echo   $element1->item($i)->nodeValue . "\n";

               foreach ($element1->getElementsByTagName('td') as $element2) {

                  for ($j = 0; $j < $element2->length; $j++) {

               echo $element2->item($j)->nodeValue . "\n";  }

           /* $value_spec[] = $element2->nodeValue + "
";  */
        }
     }
  }

    echo "
";

 }

}

I followed the instructions for the error "Call to undefined method DOMNodeList::getElementsByTagName()", which is to add item() to have access to every cell of the table but the error remains. I would appreciate if someone could help.

Body:
Try this,

<?php

$dom = new domDocument;
$dom->loadHTML($value);
$dom->preserveWhiteSpace = false;

$tables = $dom->getElementsByTagName('table');
$tr = $dom->getElementsByTagName('tr');

foreach ($tr as $element1) {
    for ($i = 0; $i < count($element1); $i++) {
        echo $element1->nodeValue . "\n";
        foreach ($element1->getElementsByTagName('td') as $element2) {
            for ($j = 0; $j < count($element2); $j++) {
                echo $element2->nodeValue . "\n";
            }
        }
    }
}


问:
How to change menu sandwich to 'X' on mobile screen
I am not a bootstrap or css or front end guy. I been trying to look for help online for two days no luck, I have the following navbar:

```<code><nav class="navbar navbar-default navbar-captum navbar-static-top">
    <div class="container">
        <div class="navbar-header">

            <!-- Collapsed Hamburger -->
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#app-navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar top-bar"</span>
                <span class="icon-bar middle-bar"></span>
                <span class="icon-bar bottom-bar"></span>
            </button>

            <!-- Branding Image -->
            <a class="navbar-brand" href="{{ url('/') }}">
                {{--<span class="company-name">{{ config('app.name', 'Laravel') }}</span>/--}}
                <img src="{{asset('/public/images/logo-captum.png')}}" class="logo">
            </a>
        </div>

        <div class="collapse navbar-collapse" id="app-navbar-collapse">

            <!-- User Profile Navbar -->
            <ul class="nav navbar-nav navbar-right navbar-user-profile">

                <!-- Authentication Links -->
                @if (!session()->has('status'))
                    <li><a href="{{ route('login') }}" class="btn btn-default btn-login">Logga in</a></li>

                @else
                    <li>
                        <a href="//captum.provideit.se/kundservice/" target="_blank">
                            <i class="icon-custom icon-custom-message pull-left"></i>
                            Kontakta kundservice
                        </a>
                    </li>

                    <li>
                        <a href="{{ route('profile') }}">
                            <i class="icon-custom icon-custom-lock pull-left"></i>
                            {{ $customer['firstName'].str_repeat(' ',1).$customer['lastName'] }}
                        </a>
                    </li>
                    <li>
                        <a href="{{ route('logout') }}"
                           class="btn btn-default btn-login" style="margin-left: 5px;"
                           onclick="event.preventDefault();document.getElementById('logout-form').submit();">
                            Logga ut
                        </a>

                        <form id="logout-form" action="{{ route('logout') }}" method="POST"
                              style="display: none;">
                            {{ csrf_field() }}
                        </form>
                    </li>
                @endif
            </ul>

        </div>

    </div>
</nav>
</code>```

So when I shrink to phone screen I get a sandwich menu like this

Is there any way to make this menu on mobile look like this :Basically convert sandwich to 'X' and make it menu full screen centered items.

Would be very appreciated if I could get any help

答:
I don't think that anyone can help you with your particular problem here if you don't provide CSS, at least for the button in question.

However, I would suggest using Jonathan Suh's ready-made "hamburger" solution. You only need to include a single CSS file, choose an animation and write a simple JavaScript to toggle the is-active class.

$('.hamburger').click(function(){
 $(this).toggleClass("is-active");
  // Toggle your menu here
  // $('#menu').toggleClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  outline: none;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/0.9.1/hamburgers.min.css" rel="stylesheet"/>

<button class="hamburger hamburger--collapse" type="button">

</button>```

Body:
I am not a bootstrap or css or front end guy. I been trying to look for help online for two days no luck, I have the following navbar:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#app-navbar-collapse">
                Toggle Navigation
                <span class="icon-bar top-bar"

            </button>

                {{--{{ config('app.name', 'Laravel') }}/--}}

                @if (!session()->has('status'))

Logga in

                @else

                            Kontakta kundservice

                            {{ $customer['firstName'].str_repeat(' ',1).$customer['lastName'] }}

                            Logga ut

                        <form id="logout-form" action="{{ route('logout') }}" method="POST"
                              style="display: none;">
                            {{ csrf_field() }}
                        </form>

                @endif

So when I shrink to phone screen I get a sandwich menu like this

Is there any way to make this menu on mobile look like this :Basically convert sandwich to 'X' and make it menu full screen centered items.

Would be very appreciated if I could get any help

Body:
I don't think that anyone can help you with your particular problem here if you don't provide CSS, at least for the button in question.

However, I would suggest using Jonathan Suh's ready-made "hamburger" solution. You only need to include a single CSS file, choose an animation and write a simple JavaScript to toggle the is-active class.

$('.hamburger').click(function(){
 $(this).toggleClass("is-active");
  // Toggle your menu here
  // $('#menu').toggleClass('active');
});

button {
  outline: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/0.9.1/hamburgers.min.css" rel="stylesheet"/>

<button class="hamburger hamburger--collapse" type="button">
  <span class="hamburger-box">
    <span class="hamburger-inner"></span>
  </span>
</button>


问:
Spring Data - querying with optionals withoud if-else
I'm trying to expose simple REST-API for data querying with two optional params available:

```<code>GET myServ/greeting?message=X&type=Y
</code>```

Unfortunately I'm stucked with proper spring-data configuration to enable proper querying. Below methods should

GET myServ/greeting - return every greeting

GET myServ/greeting?message=X - return every greeting with message=X

GET myServ/greeting?type=Y - return every greeting with type=Y

GET myServ/greeting?message=X&type=Y - return every greeting with message=X AND type=Y

Simple as it can be - but I don't want to write any if-else code in my controller! Is there any out-of-box configuration enabled which will result in below behavior? I tried different mix of standard JpaReposotory methods and ExampleMatchers but still I cannot make it work.

My model:

```<code>package my.model;

import lombok.*;
import javax.persistence.*;

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@ToString
public class Greeting {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String message;
    private String type;
}
</code>```

repository:

```<code>package my.repository;

import my.model.Greeting;
import org.springframework.data.jpa.repository.JpaRepository;

public interface GreetingRepository extends JpaRepository<Greeting, Long>{
}
</code>```

web-controller:

```<code>package my.web;

import my.model.Greeting;
import my.repository.GreetingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class GreetingController {

    @Autowired
    private GreetingRepository repository;

    @RequestMapping(value = "/greeting", method = GET)
    public List<Greeting> get(
            @RequestParam(value = "message", required = false) String message,
            @RequestParam(value = "type", required = false) String type ){

        return HOW_TO_DO_IT??;
    }
}
</code>```

答:
If the entity is that simple use Query By Example. Your repository needs to extend addtionaly QueryByExampleExecutor<Greeting>. This will add the method findAll(Example<S> example) to your repository.
Then you call it like:

```<code>Example<Greeting> example = Example.of(new Greeting("someMessage", "aType"));
repo.findAll(example);
</code>```

Other options are the Criteria API and QueryDSL. All three options are mentioned here.

Body:
I'm trying to expose simple REST-API for data querying with two optional params available:

GET myServ/greeting?message=X&type=Y

Unfortunately I'm stucked with proper spring-data configuration to enable proper querying. Below methods should

GET myServ/greeting - return every greeting

GET myServ/greeting?message=X - return every greeting with message=X

GET myServ/greeting?type=Y - return every greeting with type=Y

GET myServ/greeting?message=X&type=Y - return every greeting with message=X AND type=Y

Simple as it can be - but I don't want to write any if-else code in my controller! Is there any out-of-box configuration enabled which will result in below behavior? I tried different mix of standard JpaReposotory methods and ExampleMatchers but still I cannot make it work.

My model:

package my.model;

import lombok.*;
import javax.persistence.*;

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@ToString
public class Greeting {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String message;
    private String type;
}

repository:

package my.repository;

import my.model.Greeting;
import org.springframework.data.jpa.repository.JpaRepository;

public interface GreetingRepository extends JpaRepository<Greeting, Long>{
}

web-controller:

package my.web;

import my.model.Greeting;
import my.repository.GreetingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class GreetingController {

    @Autowired
    private GreetingRepository repository;

    @RequestMapping(value = "/greeting", method = GET)
    public List<Greeting> get(
            @RequestParam(value = "message", required = false) String message,
            @RequestParam(value = "type", required = false) String type ){

        return HOW_TO_DO_IT??;
    }
}

Body:
If the entity is that simple use Query By Example. Your repository needs to extend addtionaly QueryByExampleExecutor<Greeting>. This will add the method findAll(Example<S> example) to your repository.
Then you call it like:

Example<Greeting> example = Example.of(new Greeting("someMessage", "aType"));
repo.findAll(example);

Other options are the Criteria API and QueryDSL. All three options are mentioned here.


问:
Odoo auto-fill fields when created from other form
Any idea how I can fill in some fields on the product page when I quick create this from a Sales Order. These fields are based on the Sales Order (name and customer). Do I need to pass them with context?

Thanks

答:
Yes, it can be done with context. In your sale.order.line XML views, you have a Many2one field named product_id (it points to product.product model).

You have to specify the default value you want for each product.product field, extracting the value for the fields of the current view (sale.order.line):

```<code><xpath expr="//field[@name='product_id']" position="attributes">
    <attribute name="context">{'default_field_1': field_1, 'default_field_2': field_2}</attribute>
</xpath>
</code>```

Where default_field_1 and default_field_2 are fields of the product.product model, and field_1 and field_2 are fields of sale.order.line model.

Example:

```<code><xpath expr="//field[@name='product_id']" position="attributes">
    <attribute name="context">{'default_name': name}</attribute>
</xpath>
</code>```

In the above case, when you create a new product (clicking on the create option of the dropdown of the Many2one field product_id) from sale.order.line tree or form view, the product.product form would be opened with the name field automatically filled in with the name of the current sale order line.

Body:
Yes, it can be done with context. In your sale.order.line XML views, you have a Many2one field named product_id (it points to product.product model).

You have to specify the default value you want for each product.product field, extracting the value for the fields of the current view (sale.order.line):

<xpath expr="//field[@name='product_id']" position="attributes">
    <attribute name="context">{'default_field_1': field_1, 'default_field_2': field_2}</attribute>
</xpath>

Where default_field_1 and default_field_2 are fields of the product.product model, and field_1 and field_2 are fields of sale.order.line model.

Example:

<xpath expr="//field[@name='product_id']" position="attributes">
    <attribute name="context">{'default_name': name}</attribute>
</xpath>

In the above case, when you create a new product (clicking on the create option of the dropdown of the Many2one field product_id) from sale.order.line tree or form view, the product.product form would be opened with the name field automatically filled in with the name of the current sale order line.


问:
aws ec2 describe-images state filter ignored when combined with name
I want to use AWS CLI to return all my AMIs whose name starts with some string and whose state is "available", but the state filter seems to be ignored if I run

```<code>aws ec2 describe-images --owners self --filter Name=state,Values=available,Name=name,Values="Prod*"
</code>```

This returns all AMIs that match by name, regardless of their state. Same if I separate the two filter arguments, like this:

```<code>aws ec2 describe-images --owners self --filter Name=state,Values=available --filter Name=name,Values="Prod*"
</code>```

If I filter only by state it works as expected, e.g. this returns only available AMIs:

```<code>aws ec2 describe-images --owners self --filter Name=state,Values=available
</code>```

How do I get the two filters to work together (as an AND)?

答:
This is how to describe multiple filters that AND the filter requirements.</p>

```<code>aws ec2 describe-images --owners self --filter "Name=state,Values=available" "Name=name,Values=Prod*"
</code>```

Body:
I want to use AWS CLI to return all my AMIs whose name starts with some string and whose state is "available", but the state filter seems to be ignored if I run

aws ec2 describe-images --owners self --filter Name=state,Values=available,Name=name,Values="Prod*"

This returns all AMIs that match by name, regardless of their state. Same if I separate the two filter arguments, like this:

aws ec2 describe-images --owners self --filter Name=state,Values=available --filter Name=name,Values="Prod*"

If I filter only by state it works as expected, e.g. this returns only available AMIs:

aws ec2 describe-images --owners self --filter Name=state,Values=available

How do I get the two filters to work together (as an AND)?

Body:
This is how to describe multiple filters that AND the filter requirements.

aws ec2 describe-images --owners self --filter "Name=state,Values=available" "Name=name,Values=Prod*"


问:
Return value from CAPL function to C# function
I'm calling a CAPL function from a C# function and I'm expected to get in C# the value that the CAPL function returns but it always return the same value that has nothing to do with the one I'm assigning inside the CAPL function.
Is there something I need to add in my CAPL function so it can pass the correct value to the C# function I'm calling it from?
This is how I'm calling the CAPL function from C# and assigning the return value to a variable:

```<code>int var = (int)this.SendRawDiagnosticF.Call(id, bytestosend[0], bytestosend[1], bytestosend[2], bytestosend[3], bytestosend[4], bytestosend[5], bytestosend[6], bytestosend[7]);
</code>```

This is the way the CAPL function looks:

```<code>int ReturnRXIDMessage(long ID, long DLC, long a, long b, long c, long d, long e, long f, long g, long h)
{
  long o = 0;
  if (messageID == ID + 0x40)
  {
    o = messageID;
  }
  return (o);
}
</code>```

答:
I'm not exactly sure what you are doing, but to call the CAPL function from .NET you need to call the function directly via CaplFunctions.MyCaplFile.MyFunction(param);
The rest depends on your setup. If you are using vTESTstudio you just need to export the function with the export keyword.
If you are using the old .NET test feature set, you need to reference the CAPL file in your test node. If you are using Visual Studio you might need to reference the generated type library too.

Body:
I'm calling a CAPL function from a C# function and I'm expected to get in C# the value that the CAPL function returns but it always return the same value that has nothing to do with the one I'm assigning inside the CAPL function.
Is there something I need to add in my CAPL function so it can pass the correct value to the C# function I'm calling it from?
This is how I'm calling the CAPL function from C# and assigning the return value to a variable:

int var = (int)this.SendRawDiagnosticF.Call(id, bytestosend[0], bytestosend[1], bytestosend[2], bytestosend[3], bytestosend[4], bytestosend[5], bytestosend[6], bytestosend[7]);

This is the way the CAPL function looks:

int ReturnRXIDMessage(long ID, long DLC, long a, long b, long c, long d, long e, long f, long g, long h)
{
  long o = 0;
  if (messageID == ID + 0x40)
  {
    o = messageID;
  }
  return (o);
}


问:
OOP Inheritance: Modifying Array in Base Class from Derived Class
I have this code:

```<code>class Base{
public:
 int A[3]={1,2,3};
 void out(){
    for (int i=0;i<3;++i) cout << A[i] << " ";
    cout << endl;
 }
};

class Derived: public Base{
public:
 void modify(){
    A[2] = 5;
}
 };

int main(){
  Base base;
  Derived derived;
  base.out();
  derived.modify();
  base.out();
  return 0;
}

OUTPUT: 1 2 3
        1 2 3
</code>```

What I'm trying to do is to modify A[2] and print the array with the changed value through function in Base class.
But the problem is after I modify it in my Derived class and print the array with the function in my Base class, it's still the old array from the Base function.

答:
This is because base and derived are completely different copies of objects, so modifying in one doesn't reflect on the other. So you have to use derived.out(); to get the modified array. But uncommenting either of the comments down here works if you want to modify through base class object.</p>

```<code>int main()
{
  Base base;
  Derived derived;
  base.out();
  derived.modify();
  derived.out();
  //base.A[2]=5;
  //base=derived;
  base.out();
  return 0;
}
</code>```

Body:
I have this code:

class Base{
public:
 int A[3]={1,2,3};
 void out(){
    for (int i=0;i<3;++i) cout << A[i] << " ";
    cout << endl;
 }
};

class Derived: public Base{
public:
 void modify(){
    A[2] = 5;
}
 };

int main(){
  Base base;
  Derived derived;
  base.out();
  derived.modify();
  base.out();
  return 0;
}

OUTPUT: 1 2 3
        1 2 3

What I'm trying to do is to modify A[2] and print the array with the changed value through function in Base class.
But the problem is after I modify it in my Derived class and print the array with the function in my Base class, it's still the old array from the Base function.

Body:
This is because base and derived are completely different copies of objects, so modifying in one doesn't reflect on the other. So you have to use derived.out(); to get the modified array. But uncommenting either of the comments down here works if you want to modify through base class object.

int main()
{
  Base base;
  Derived derived;
  base.out();
  derived.modify();
  derived.out();
  //base.A[2]=5;
  //base=derived;
  base.out();
  return 0;
}


问:
How to return proper error response for content-type text/csv?
I have a servlet where in general I return text/csv as response. So a plain comma separated string.

BUT: in case of exceptions, I'd want to show just some error text as response.  But instead Spring generates a custom ResponseEntity object, then tries to convert this response to csv which obviously fails.

Is it possible to replace the requested format to format=json, and then just return the default Spring error response?

```<code>@RestController
public class CsvServlet {

    @RequestMapping(value = "/test", produces = "text/csv")
    @ResponseBody
    public String errorCsv(HttpServletRequest request) {
        return "some, plain, text";
    }
}
</code>```

Usage: localhost:8080/test?format=csv

When having spring.security.enabled=true, this will first validate the basic auth credentials. If they fail, spring will automatically redirect to /error servlet.

Thereby BasicErrorController.error() method comes in, catching the error and generating a ResponseEntity with error attributes like timestamp, exception, path, etc.

Problem: now an Object of type ResponseEntity is returned. This is fine as long as the format parameter is either ?format=json/xml. As the response can then be properly converted.

But in my special case, where I request ?format=csv, the conversation will fail, leading to:

Response could not be created:
  org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
  find acceptable representation

This is partially true, moreover misleading because the user should directly see that the authentication credentials have been invalid. Because in general I'm accepting csv, but Spring and the mappers don't know how to convert a ResponseEntity to a plain format like csv.

Question: how can I preserve the original exception? So that I could just return a plain text error message. It would also be fine if I could return a application/json response in this case!

答: Try to use a void @ExceptionHandler, and write error message directly in HttpResponse

Body:
I have a servlet where in general I return text/csv as response. So a plain comma separated string.

BUT: in case of exceptions, I'd want to show just some error text as response.  But instead Spring generates a custom ResponseEntity object, then tries to convert this response to csv which obviously fails.

Is it possible to replace the requested format to format=json, and then just return the default Spring error response?

@RestController
public class CsvServlet {

    @RequestMapping(value = "/test", produces = "text/csv")
    @ResponseBody
    public String errorCsv(HttpServletRequest request) {
        return "some, plain, text";
    }
}

Usage: localhost:8080/test?format=csv

When having spring.security.enabled=true, this will first validate the basic auth credentials. If they fail, spring will automatically redirect to /error servlet.

Thereby BasicErrorController.error() method comes in, catching the error and generating a ResponseEntity with error attributes like timestamp, exception, path, etc.

Problem: now an Object of type ResponseEntity is returned. This is fine as long as the format parameter is either ?format=json/xml. As the response can then be properly converted.

But in my special case, where I request ?format=csv, the conversation will fail, leading to:

Response could not be created:
  org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
  find acceptable representation

This is partially true, moreover misleading because the user should directly see that the authentication credentials have been invalid. Because in general I'm accepting csv, but Spring and the mappers don't know how to convert a ResponseEntity to a plain format like csv.

Question: how can I preserve the original exception? So that I could just return a plain text error message. It would also be fine if I could return a application/json response in this case!


问:
How to add text file in my project so that it is not visible to user..?
Sir,

I am developing an application in which i am to save some information in text file. During execution, I wish to read/write data from/to the file(.txt file). I dont want the file to be visible to user. Or if it is visible then it must be in programfile folder of the system and user could not delete the data of the file. What should i do? I tried to add the file in Resource file but could not read and write the file. PLease help me to read/write OR provide some other way to implement the same(described above).

Thanks in advance....

答:
Don't use ProgramFiles (installation) folder:
1. File will be visible for user
2. If user won't have admin rights your app will fail on modifying the file.
Windows System folder is also question of rights. I'd advice to use system registry or appdata folder: you can get it Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData). You'll be able to write to that location without admin rights. You should create some special subfolder there (not needed, but would be convinient).
Or in registry case:
writing to registry:

```<code>string myEncrStringToSave;
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Your_Cpecial_Key");
key.SetValue("Software\\Your_Cpecial_Key", myEncrStringToSave);
key.Close();
</code>```

reading from registry:

```<code>Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Your_Cpecial_Key");
object value = key.GetValue("Software\\Your_Cpecial_Key");
if (value!=null)
   string myEncryptedString = value.ToString();
key.Close();
</code>```

Your_Cpecial_Key here is some identifier (like in hashtable) that allows you to get access to your data.

Body:
Don't use ProgramFiles (installation) folder:
1. File will be visible for user
2. If user won't have admin rights your app will fail on modifying the file.
Windows System folder is also question of rights. I'd advice to use system registry or appdata folder: you can get it Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData). You'll be able to write to that location without admin rights. You should create some special subfolder there (not needed, but would be convinient).
Or in registry case:
writing to registry:

string myEncrStringToSave;
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Your_Cpecial_Key");
key.SetValue("Software\\Your_Cpecial_Key", myEncrStringToSave);
key.Close();

reading from registry:

Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Your_Cpecial_Key");
object value = key.GetValue("Software\\Your_Cpecial_Key");
if (value!=null)
   string myEncryptedString = value.ToString();
key.Close();

Your_Cpecial_Key here is some identifier (like in hashtable) that allows you to get access to your data.


问:
Remove spaces between links from html table if links removed
I have below table in my jsp with links coming dynamically on page load using java arraylist

```<code><%ArrayList<String> display  = ArrayList<String>)session.getAttribute("links");       %>
<table border="0" width="100%" style ="">
    <tr></tr>
    <td width="20%"></td>
    <table border="0" width ="50%" id="LinkDisplay">
        <div id="LinkDisplay">
            <%if(display!=null){
            for(int p=0;p<display.size();p++){%>
            <tr><td width="42%"> </td><td><a href="javascript:removeLink('<%=display.get(p)%>')"><%=display.get(p)%></a><br></td><td> </td></tr>
            <% } }%>
        </div>
    </table>
    <td></td>
    <tr></tr>
</table>
</code>```

When I click on link, it remove and hide the link calling removeLink javascript function

```<code>$('#LinkDisplay a').click(function() {
    var $this = $(this);
    $this.remove();
}
</code>```

But when link remove, it leaves the spaces between links. How to remove that space, when link clicked. I tried to hide even tried to remove the empty td element (without link text) but it does not help..
Page with all the links look as below :-

after clicking on links it leaves the spaces as below :-

Also if there are more than 10 links I want to add scroll bars, can we do that on table.
If table is not the right way to do all this, is there any other easy way?

答:
You are only removing the a element, you need to remove the whole tr:

```<code>$('#LinkDisplay a').click(function() {
    var $this = $(this);
    $this.parent().parent().remove();
}
</code>```

Or even better $this.parent("#LinkDisplay tr").remove();.

Note:

You can't use the same id="LinkDisplay" for more than one element, you used it for table and div here.

Your HTML is invalid you can't have a div as immediate child of a table, it needs to be fixed.

And yes you can do this without a table, just use a div for each link, they will be displayed as block by default and use margin with your div instead of a td with   as content, this way you can better manage the layout.

Body:
I have below table in my jsp with links coming dynamically on page load using java arraylist

<%ArrayList<String> display  = ArrayList<String>)session.getAttribute("links");       %>

            <%if(display!=null){
            for(int p=0;p<display.size();p++){%>

 	<a href="javascript:removeLink('<%=display.get(p)%>')"><%=display.get(p)%>

            <% } }%>

When I click on link, it remove and hide the link calling removeLink javascript function

$('#LinkDisplay a').click(function() {
    var $this = $(this);
    $this.remove();
}

But when link remove, it leaves the spaces between links. How to remove that space, when link clicked. I tried to hide even tried to remove the empty td element (without link text) but it does not help..
Page with all the links look as below :-

after clicking on links it leaves the spaces as below :-

Also if there are more than 10 links I want to add scroll bars, can we do that on table.
If table is not the right way to do all this, is there any other easy way?

Body:
You are only removing the a element, you need to remove the whole tr:

$('#LinkDisplay a').click(function() {
    var $this = $(this);
    $this.parent().parent().remove();
}

Or even better $this.parent("#LinkDisplay tr").remove();.

Note:

You can't use the same id="LinkDisplay" for more than one element, you used it for table and div here.

Your HTML is invalid you can't have a div as immediate child of a table, it needs to be fixed.

And yes you can do this without a table, just use a div for each link, they will be displayed as block by default and use margin with your div instead of a td with &nbsp; as content, this way you can better manage the layout.


问:
python variable memory size - error
I am new in python programming : and I am trying to solve this problem : http://codeforces.com/contest/791/problem/A
- but, when I tried to solve it in my editor it gives me : problem in statement:
"x *= 3", and the interpreter error is :
line 6, in main
    x *= 3
MemoryError</p>

```<code>def main():
    x = input("inter first number : ")
    z = input("inter second number : ")
    result = 0
    while x <= z:
        x *= 3
        z *= 2
        result += 1
    print(result)

if __name__ == '__main__':
    main()
</code>```

答:
input type is str: you must convert inputs to numerical values, int or float prior to applying numerical operations (*=)on them::

```<code>def main():
    x = int(input("inter first number : "))  # alternatively: float(input("inter first number : "))
    z = int(input("inter second number : ")) # same alternative
    result = 0
    while x <= z:
        x *= 3
        z *= 2
        result += 1
    print(result)

if __name__ == '__main__':
    main()
</code>```

As @juanpa.arrivillaga pointed out in the comments, the reason for
  MemoryError is that x and y are strings, multiplication on
  strings does '10'*3 == '101010' and you probably create an infinite
  loop, creating larger and larger strings, until you run out of memory.

Title: python variable memory size - error

Body:
I am new in python programming : and I am trying to solve this problem : http://codeforces.com/contest/791/problem/A
- but, when I tried to solve it in my editor it gives me : problem in statement:
"x *= 3", and the interpreter error is :
line 6, in main
    x *= 3
MemoryError

def main():
    x = input("inter first number : ")
    z = input("inter second number : ")
    result = 0
    while x <= z:
        x *= 3
        z *= 2
        result += 1
    print(result)

if __name__ == '__main__':
    main()

Body:
input type is str: you must convert inputs to numerical values, int or float prior to applying numerical operations (*=)on them::

def main():
    x = int(input("inter first number : "))  # alternatively: float(input("inter first number : "))
    z = int(input("inter second number : ")) # same alternative
    result = 0
    while x <= z:
        x *= 3
        z *= 2
        result += 1
    print(result)

if __name__ == '__main__':
    main()

As @juanpa.arrivillaga pointed out in the comments, the reason for
  MemoryError is that x and y are strings, multiplication on
  strings does '10'*3 == '101010' and you probably create an infinite
  loop, creating larger and larger strings, until you run out of memory.


问:
Store Dropdown values in cookie [ASP]
I'm fairly new to this, so please help me out.

I am trying to store the values of 2 dropdown lists in a cookie, then have those values as the default values when the page loads again.

```<code>        protected void ddlSelectedIndexChange(Object sender, EventArgs e) {

        HttpCookie cookie = new HttpCookie("ddlValues");
        cookie.Values["ddlCatalogType"] = ddlCatalogType.SelectedValue;
        cookie.Values["ddlSource"] = ddlSource.SelectedValue;
        cookie.Expires = DateTime.Now.AddYears(50);
        Response.Cookies.Add(cookie);
    }
</code>```

From here, where do I go? I am lost past this point, and not even sure if the above code is 100% correct.

答:
Add below snippet in Page_Load of the page you desired.

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Cookies["ddlValues"] != null)
            {
                if (Request.Cookies["ddlValues"]["ddlCatalogType"] != null)
                {
                    string catalog = Request.Cookies["ddlValues"]["ddlCatalogType"];
                    ddlCatalogType.SelectedIndex = ddlCatalogType.Items.IndexOf(ddlCatalogType.Items.FindByText(catalog));
                }

                if (Request.Cookies["ddlValues"]["ddlSource"] != null)
                {
                    string source = Request.Cookies["ddlValues"]["ddlSource"];
                    ddlSource.SelectedIndex = ddlSource.Items.IndexOf(ddlSource.Items.FindByText(source));
                }
            }
        }
    }
</code>```

For your code, I suggest to check cookie already exist or not.

```<code>protected void ddlSelectedIndexChange(Object sender, EventArgs e)
{
    if (Request.Cookies["ddlValues"] == null)
    {
        HttpCookie cookie = new HttpCookie("ddlValues");
        cookie.Values["ddlCatalogType"] = ddlCatalogType.SelectedValue;
        cookie.Values["ddlSource"] = ddlSource.SelectedValue;
        cookie.Expires = DateTime.Now.AddYears(50);
        Response.Cookies.Add(cookie);
    }
}
</code>```

Title: Store Dropdown values in cookie [ASP]

Body:
I'm fairly new to this, so please help me out.

I am trying to store the values of 2 dropdown lists in a cookie, then have those values as the default values when the page loads again.

        protected void ddlSelectedIndexChange(Object sender, EventArgs e) {

        HttpCookie cookie = new HttpCookie("ddlValues");
        cookie.Values["ddlCatalogType"] = ddlCatalogType.SelectedValue;
        cookie.Values["ddlSource"] = ddlSource.SelectedValue;
        cookie.Expires = DateTime.Now.AddYears(50);
        Response.Cookies.Add(cookie);
    }

From here, where do I go? I am lost past this point, and not even sure if the above code is 100% correct.

Body:
Add below snippet in Page_Load of the page you desired.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Cookies["ddlValues"] != null)
            {
                if (Request.Cookies["ddlValues"]["ddlCatalogType"] != null)
                {
                    string catalog = Request.Cookies["ddlValues"]["ddlCatalogType"];
                    ddlCatalogType.SelectedIndex = ddlCatalogType.Items.IndexOf(ddlCatalogType.Items.FindByText(catalog));
                }

                if (Request.Cookies["ddlValues"]["ddlSource"] != null)
                {
                    string source = Request.Cookies["ddlValues"]["ddlSource"];
                    ddlSource.SelectedIndex = ddlSource.Items.IndexOf(ddlSource.Items.FindByText(source));
                }
            }
        }
    }

For your code, I suggest to check cookie already exist or not.

protected void ddlSelectedIndexChange(Object sender, EventArgs e)
{
    if (Request.Cookies["ddlValues"] == null)
    {
        HttpCookie cookie = new HttpCookie("ddlValues");
        cookie.Values["ddlCatalogType"] = ddlCatalogType.SelectedValue;
        cookie.Values["ddlSource"] = ddlSource.SelectedValue;
        cookie.Expires = DateTime.Now.AddYears(50);
        Response.Cookies.Add(cookie);
    }
}


问:
HTML5 Layout DIV sizings
I'm working on amending a HTML5 template. The default setup of the Bootstrap parameters were:

col-sm-12 col-md-4 col-lg-4

col-sm-12 col-md-8 col-lg-8

This meant that the latin text took up 20% of screen width and pics 80%, but I want it the other way round... Text taking up 80% width, photo 20%.

Can someone please advise what the bootstrap parameters need to be for this for responsive to work? I've tried loads of options but can't get it right!

Is this possible or do I need to revise CSS?

Thanks

Full code below:

```<code><section id="ourteam" class="wow fadeInUp">
<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-4 col-lg-4">
      <h2>Meet our Team</h2>
      <div class="ourteamd">
        <p>Lorem ipsum dolor sit eros. Pellentesque nec vulpe eros.</p>
      </div>
    </div>
    <div class="col-sm-12 col-md-8 col-lg-8">
      <div class="responsive">
        <div>
          <div class="third-effect">
            <img src="http://www.placehold.it/384x444" class="img-responsive" alt="Our Team">
            <div class="mask">
                <a href="#">Facebook</a>
                <a href="#" class="twitter">Twitter</a>
            </div>
          </div>
</code>```

答:
Try with below code.</p>

```<code><div class="row">
<div class="col-sm-12 col-md-8 col-lg-8">
  <h2>Meet our Team</h2>
  <div class="ourteamd">
    <p>Lorem ipsum dolor sit eros. Pellentesque nec vulpe eros.</p>
  </div>
</div>
<div class="col-sm-12 col-md-4 col-lg-4">
    <div class="responsive">
        <div class="third-effect">
            <img src="http://www.placehold.it/384x444" class="img-responsive" alt="Our Team">
            <div class="mask">
                <a href="#">Facebook</a>
                <a href="#" class="twitter">Twitter</a>
            </div>
        </div>
    </div>
</div>
</code>```

<p>  </p>

Title: HTML5 Layout DIV sizings

Body:
I'm working on amending a HTML5 template. The default setup of the Bootstrap parameters were:

col-sm-12 col-md-4 col-lg-4

col-sm-12 col-md-8 col-lg-8

This meant that the latin text took up 20% of screen width and pics 80%, but I want it the other way round... Text taking up 80% width, photo 20%.

Can someone please advise what the bootstrap parameters need to be for this for responsive to work? I've tried loads of options but can't get it right!

Is this possible or do I need to revise CSS?

Thanks

Full code below:

Meet our Team

Lorem ipsum dolor sit eros. Pellentesque nec vulpe eros.

                Facebook
                Twitter

Body:
Try with below code.

<div class="row">
<div class="col-sm-12 col-md-8 col-lg-8">
  <h2>Meet our Team</h2>
  <div class="ourteamd">
    <p>Lorem ipsum dolor sit eros. Pellentesque nec vulpe eros.</p>
  </div>
</div>
<div class="col-sm-12 col-md-4 col-lg-4">
    <div class="responsive">
        <div class="third-effect">
            <img src="http://www.placehold.it/384x444" class="img-responsive" alt="Our Team">
            <div class="mask">
                <a href="#">Facebook</a>
                <a href="#" class="twitter">Twitter</a>
            </div>
        </div>
    </div>
</div>


问:
yii2 controller JS
How to add JS inside controller. It says some error when I tried to do it. Here's my line:

```<code>    $script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
    var \$form = $(this);
    $.post(
    \$form.attr('action'), //serialize the form
    \$form.serialize(),
    )
    .done(function(result){
       if (result == 1)
       {
        $(\$form).trigger('reset');
        $.pjax.reload({container: '#w0', timeout: false});
    } else {
        $('#message').html(result);
    }
}).fail(function()
{
    console.log('server error');
});
    return false;
});
JS;
$this->registerJs($script);
</code>```

How can I use javascript properly inside controller. Thank you.

Here's error:

答:
You can add JS inside your controller by this way:

```<code>$this->view->registerJs($js);
</code>```

Also, you can register js anywhere:

```<code>Yii::$app->controller->view->registerJs($js);
</code>```

Title: yii2 controller JS

Body:
How to add JS inside controller. It says some error when I tried to do it. Here's my line:

    $script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
    var \$form = $(this);
    $.post(
    \$form.attr('action'), //serialize the form
    \$form.serialize(),
    )
    .done(function(result){
       if (result == 1)
       {
        $(\$form).trigger('reset');
        $.pjax.reload({container: '#w0', timeout: false});
    } else {
        $('#message').html(result);
    }
}).fail(function()
{
    console.log('server error');
});
    return false;
});
JS;
$this->registerJs($script);

How can I use javascript properly inside controller. Thank you.

Here's error:

Body:
You can add JS inside your controller by this way:

$this->view->registerJs($js);

Also, you can register js anywhere:

Yii::$app->controller->view->registerJs($js);


问:
I18n of XSD validation error messages in Java
I perform XSD XML validation using the following classes:

```<code>import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
</code>```

The problem is that XSD error messages returned by validator are always in English language. Is it possible to call locale-aware validation with JAXP API?

答: Apparently there's no way to achieve what I want.</p>

Body:
I perform XSD XML validation using the following classes:

import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

The problem is that XSD error messages returned by validator are always in English language. Is it possible to call locale-aware validation with JAXP API?


问:
ApplicationDbContext for static classes
This is what I've got:

```<code>//PUT: api/teams/id/member/id
[Route ("api/Detail/detial_id/Option/option_id")]
public IHttpActionResult PutTeams(int team_id, int member_id)
{
   var team = db.Teams.Find(team_id);
   var member= db.Members.Find(member_id);
}
</code>```

I can't write this piece of code:

```<code>public System.Data.Entity.DbSet<cb_api.Models.Member> Teams{ get; set; }
</code>```

in context.cs since Member is  a static class but I need it in order to used in PutTeam.

Any suggestions?

答:
The entity classes cannot be a static class. These classes should be instantiable. Why do you want it to be a static class?. The teams are stored in the database and whenever you want to fetch it from the database, you need DBSet properties having Entity types passed. So the Teams property with Member class type cannot be a static class.

To convert them to JSON
Create a Static class called GenericHelper.cs

```<code>public static class GenericHelper
{
    public static string ToJson(this IList<Member> teams)
    {
         //convert these objects and return json string using JSONConvert.SerializeObject
    }
}
</code>```

Title: ApplicationDbContext for static classes

Body:
This is what I've got:

//PUT: api/teams/id/member/id
[Route ("api/Detail/detial_id/Option/option_id")]
public IHttpActionResult PutTeams(int team_id, int member_id)
{
   var team = db.Teams.Find(team_id);
   var member= db.Members.Find(member_id);
}

I can't write this piece of code:

public System.Data.Entity.DbSet<cb_api.Models.Member> Teams{ get; set; }

in context.cs since Member is  a static class but I need it in order to used in PutTeam.

Any suggestions?

Body:
The entity classes cannot be a static class. These classes should be instantiable. Why do you want it to be a static class?. The teams are stored in the database and whenever you want to fetch it from the database, you need DBSet properties having Entity types passed. So the Teams property with Member class type cannot be a static class.

To convert them to JSON
Create a Static class called GenericHelper.cs

public static class GenericHelper
{
    public static string ToJson(this IList<Member> teams)
    {
         //convert these objects and return json string using JSONConvert.SerializeObject
    }
}


问:
Instagram ads engagement is only for business api?
I am doing a project for my company and I am stuck. I have to make this cost-effective.

In this link there are some methods to get comments and do comment but it gives me error: "(#10) Application does not have permission for this action" and when I try to query them with standard API it says that media_id is not valid(I got the media id with oembed code btw I am not putting there effective story id).

My question is:

Do I have any solution for getting and doing comments to ads other than switching to Business API? If I don't how should I progress with this? Should I just send my app to review with instagram_manage_comments?

Thanks

答:
Ad comments are on Ad media - and Instagram ads are only created via facebook ad account.

You have to use facebook ad graph API. You can check detail info at this answer: Instagram dark posts, using api to read info and do operations

The link you gave in the question is correct starting point to fetch ad media and comments. However you don't need Instagram accounts to be converted to "business account" to be linked with FB page(more context for that here). But you do need to connect with FB ad account for ads media.


问:
higcharts highstock issue with flag position
I am using Highstock flags in my charts, while using squirepin flag shapre with template, flag is overlapping the series, but if I use it without templates it works fine.

```<code>series: [{
    name: 'USD to EUR',
    data: data,
    id: 'dataseries',
    tooltip: {
        valueDecimals: 4
    }
}, {
    type: 'flags',
    data: [{
        x: Date.UTC(year, 1, 22),
        title: '<span><b>Name</b>:John Doe </span><br><span> Age:20</span><br><span>Gender:Male</span>',
        text: 'Shape: "squarepin"'
    }],
    onSeries: 'dataseries',
    shape: 'squarepin'
}]
</code>```

Here is my fiddle with issue,

Expected output:

It should be above the series.

答:
Add y attribute to series like

```<code>series: [{
        name: 'USD to EUR',
        data: data,
        id: 'dataseries',
        tooltip: {
            valueDecimals: 4
        }
    }, {
        type: 'flags',
        data: [{
            x: Date.UTC(year, 1, 22),
            title: '<span><b>Name</b>:John Doe </span><br><span> Age:20</span><br><span>Gender:Male</span>',
            text: 'Shape: "squarepin"'
        }, {
            x: Date.UTC(year, 3, 28),
            title: 'A',
            text: 'Shape: "squarepin"'
        }],
        onSeries: 'dataseries',
        shape: 'squarepin',
        y:-70  //place required value
    }]
</code>```

Fiddle demo

Body:
I am using Highstock flags in my charts, while using squirepin flag shapre with template, flag is overlapping the series, but if I use it without templates it works fine.

series: [{
    name: 'USD to EUR',
    data: data,
    id: 'dataseries',
    tooltip: {
        valueDecimals: 4
    }
}, {
    type: 'flags',
    data: [{
        x: Date.UTC(year, 1, 22),
        title: 'Name:John Doe
 Age:20
Gender:Male',
        text: 'Shape: "squarepin"'
    }],
    onSeries: 'dataseries',
    shape: 'squarepin'
}]

Here is my fiddle with issue,

Expected output:

It should be above the series.

Body:
Add y attribute to series like

series: [{
        name: 'USD to EUR',
        data: data,
        id: 'dataseries',
        tooltip: {
            valueDecimals: 4
        }
    }, {
        type: 'flags',
        data: [{
            x: Date.UTC(year, 1, 22),
            title: '<span><b>Name</b>:John Doe </span><br><span> Age:20</span><br><span>Gender:Male</span>',
            text: 'Shape: "squarepin"'
        }, {
            x: Date.UTC(year, 3, 28),
            title: 'A',
            text: 'Shape: "squarepin"'
        }],
        onSeries: 'dataseries',
        shape: 'squarepin',
        y:-70  //place required value
    }]

Fiddle demo


问:
Docker: " login attempt to https://hub.docker.com/v2/ failed with status: 404 Not Found" in Fedora 25
I have Docker CE installed in Fedora 25.

When I try to login into docker hub using below command I am getting error.

```<code>$ docker login --username xxx --password yyy https://hub.docker.com/
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: login attempt to
https://hub.docker.com/v2/ failed with status: 404 Not Found

$ docker --version
 Docker version 17.07.0-ce, build 8784753

$ docker-machine --version
 docker-machine version 0.12.2, build 9371605
</code>```

Notice that the same command works fine in Ubuntu 16.04
Only difference I can think of is ubuntu have docker and fedora have docker-ce.

Not sure why I get this error only on Fedora. I get this this error when Fedora is installed on virtual box VM.

答:
as discussed in Couldn't login to docker hub
it's possible the registry only implements V1 (or has not been configured to use the V2 specification, in which case the daemon has to be configured to support legacy registries

you can verify that with the "docker info" command :

```<code>docker info
...
Server Version: 17.09.0-ce
Operating System: Ubuntu 16.04.3 LTS
...
Registry: https://index.docker.io/v1/
</code>```

consequently, it fails...

```<code>docker login --username my_login --password my_password
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have Docker CE installed in Fedora 25.

When I try to login into docker hub using below command I am getting error.

$ docker login --username xxx --password yyy https://hub.docker.com/
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: login attempt to
https://hub.docker.com/v2/ failed with status: 404 Not Found

$ docker --version
 Docker version 17.07.0-ce, build 8784753

$ docker-machine --version
 docker-machine version 0.12.2, build 9371605

Notice that the same command works fine in Ubuntu 16.04
Only difference I can think of is ubuntu have docker and fedora have docker-ce.

Not sure why I get this error only on Fedora. I get this this error when Fedora is installed on virtual box VM.

Body:
as discussed in Couldn't login to docker hub
it's possible the registry only implements V1 (or has not been configured to use the V2 specification, in which case the daemon has to be configured to support legacy registries

you can verify that with the "docker info" command :

docker info
...
Server Version: 17.09.0-ce
Operating System: Ubuntu 16.04.3 LTS
...
Registry: https://index.docker.io/v1/

consequently, it fails...

docker login --username my_login --password my_password
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password