问:
jQuery alert when row with specific attribute is clicked
I have html table like below:

```<code><table id='messagelist'>

  <tr id="rcmrowMTM" class="message selected" aria-selected="true">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject" tabindex="0"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Today 08:27</span><span class="subject"><span id="msgicnrcmrowMTM" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=13&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowMTM" class="unflagged" title="Not Flagged"></span></span><span class="attachment"><span class="attachment" title="With attachment"></span></span>
    </td>
  </tr>

  <tr id="rcmrowNw" class="message">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Sun 12:22</span><span class="subject"><span id="msgicnrcmrowNw" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=7&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowNw" class="unflagged" title="Not Flagged"></span></span><span class="attachment"> </span></td>
  </tr>

</table>
</code>```

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

```<code>$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});
</code>```

any help is appreciated. Thanks in advance.

JSFiddle

答:
The best would be to combine the search for the "With attachment" in same event handler that adds the class.

Alternatively you can add a new click event listener to all rows... and check if the selected class exists

```<code>$('#messagelist').on('click', 'tr', function() {

    var $row = $(this);

   // slight delay while class is added
   setTimeout(function(){
      if($row.hasClass('selected') && $row.find("span[title|='With attachment']").length){
          alert('with attachment');
      }
   },50);
});
</code>```

Body:
I have html table like below:

    test@example.com
      Today 08:27test

    test@example.com
      Sun 12:22test

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});

any help is appreciated. Thanks in advance.

JSFiddle

Body:
The best would be to combine the search for the "With attachment" in same event handler that adds the class.

Alternatively you can add a new click event listener to all rows... and check if the selected class exists

$('#messagelist').on('click', 'tr', function() {

    var $row = $(this);

   // slight delay while class is added
   setTimeout(function(){
      if($row.hasClass('selected') && $row.find("span[title|='With attachment']").length){
          alert('with attachment');
      }
   },50);
});


来源: stackexchange

问:
How to store username and password details from my app to my database and how to connect my app with my database?
I am trying to build an Android app but I stuck at my login page.
I don't know how to store a user's information into my database and how to match when the user tries to login again ?</p>

答:
You can refer to the sqlite database tutorials to store the data into the database. If you are storing the data in the database that is in the server, then also see the tutorials on connecting to the server database using any volley or retrofit etc.

Always its better dont store password in the text format, hash it with the hashing algorithm like SHA256, MD5 etc and then store it.

In the sqlite tutorial you will get the method to retreive the data back from the database and from there once the login button is clicked match the hashes of the data and allow to login.

https://www.tutorialspoint.com/android/android_sqlite_database.htm

ContentLicense: CC BY-SA 3.0


问:
I am new to MVC or you can say new to OOPS. Can anyone tell me what is the meaning of both the lines?
.Where(m=> m.Depatment.Name =="")

.Where(m => m.JobTitle.Name == "Administrator")

答:
Where(m=> m.Depatment.Name =="")

this line means it will take only which department is blank or string.Empty;

```<code>.Where(m => m.JobTitle.Name == "Administrator")
</code>```

this line is similar to the first one only change is model property in the first one you have taken department and in this you have taken JobTitle
basically this line means it will take only which jobTitle have a name is Administrator

Body:
Where(m=> m.Depatment.Name =="")

this line means it will take only which department is blank or string.Empty;

.Where(m => m.JobTitle.Name == "Administrator")

this line is similar to the first one only change is model property in the first one you have taken department and in this you have taken JobTitle
basically this line means it will take only which jobTitle have a name is Administrator


问:
mysql DELETE multiple tables
is it possible to delete from multiple tables?

i have 3 tables all related by an id, so where the id is the same delete the relevant information.

many thanks

答:
You need to specify ON DELETE CASCADE rule for your tables. Have a look at MySQL docs on foreign keys. Cascading rules are exactly what you need to force data integrity.

With those rules properly specified when you delete the parent row all children rows will be automatically deleted by RDBMS.

ContentLicense: CC BY-SA 2.5

Title: mysql DELETE multiple tables


问:
Update table with another table values
There are two MySQL tables, the update is working in local test mode against H2, also the query is fine with the MySQL command line. But it fails when Play tries to use the query in an evolution file.

Play: 2.5.6
Scala: 2.11.8

Query:

```<code>UPDATE table1 t1,table2 t2
SET t1.user_id = t2.id
WHERE t1.buyer_id = t2.buyer_id;
</code>```

Error:

```<code>[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[error] p.a.d.e.DefaultEvolutionsApi - Syntax error in SQL statement "UPDATE table1 t1,[*]table2 t2
SET t1.user_id = t2.id
WHERE t1.buyer_id = t2.buyer_id;"; expected "SET"; SQL statement:
UPDATE table1 t1,table2 t2
SET t1.user_id = t2.id
WHERE t1.buyer_id = t2.buyer_id[42001-191] [ERROR:42001, SQLSTATE:42001]
</code>```

答:
```<code>update table1 join table 2 on table1.id = table2.id
set table1.name = table2.customername,
    table1.mobilenum = table2.phonenum ;
</code>```

Title: Update table with another table values

Body:
There are two MySQL tables, the update is working in local test mode against H2, also the query is fine with the MySQL command line. But it fails when Play tries to use the query in an evolution file.

Play: 2.5.6
Scala: 2.11.8

Query:

UPDATE table1 t1,table2 t2
SET t1.user_id = t2.id
WHERE t1.buyer_id = t2.buyer_id;

Error:

[info] c.z.h.HikariDataSource - HikariCP pool db is starting.
[error] p.a.d.e.DefaultEvolutionsApi - Syntax error in SQL statement "UPDATE table1 t1,[*]table2 t2
SET t1.user_id = t2.id
WHERE t1.buyer_id = t2.buyer_id;"; expected "SET"; SQL statement:
UPDATE table1 t1,table2 t2
SET t1.user_id = t2.id
WHERE t1.buyer_id = t2.buyer_id[42001-191] [ERROR:42001, SQLSTATE:42001]


问:
Android EditText inputType="none" doesn't work, becomes "textMultiLine"
Tested with Android 1.6(4) and 2.3.3(10).

I've made a minimalistic test application to demonstrate this, all it does is load the xml with:

```<code>setContentView(R.layout.main);
</code>```

and the xml is:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="none"
    android:ems="10" >

</EditText>
</code>```

The problem:

when setting inputType="none" the actual input type during execution becomes textMultiLine(0x00020001), I've checked it with a debugger.

On the other hand if I use inputType="text" it works as expected.

Is this a bug in Android?

答:
Setting InputType="none" xml doesn't work, but if you're using databinding then you can use the binding syntax to set Input type.

import the type..

<data>
      <import type="android.text.InputType" />
</data>

then bind the value

<EditText
   android:id="@+id/edit_text"
   android:inputType="@{InputType.TYPE_NULL}" />

Body:
Tested with Android 1.6(4) and 2.3.3(10).

I've made a minimalistic test application to demonstrate this, all it does is load the xml with:

setContentView(R.layout.main);

and the xml is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="none"
    android:ems="10" >

</EditText>

The problem:

when setting inputType="none" the actual input type during execution becomes textMultiLine(0x00020001), I've checked it with a debugger.

On the other hand if I use inputType="text" it works as expected.

Is this a bug in Android?


问:
python command line programming examples, recipes
There has been a need for python command line utilities at work lately and I have no experience in writing cli's. Regardless, I must still pop them out.

My biggest hurdle is the structure of these programs. Also, the method in getting and verifying input from the user. I have been ending up with very looong while loops and I just dont think that is the most efficient approach.

Could someone provide links to open source cli programs that I may pick to gain a bit of an understanding? Or, books, tutorials, etc that I could get my hands on. I have dug around but have had little success (my google skills must be lacking).

答: Pretty much any python script can be a "command line program". What specific question do you have?</p>


问:
Assert in Selenium C#
Is there a Assert class present in Selenium C# just like we have in Coded UI test.

Or I should use the Microsoft.VisualStudio.TestTools.UnitTesting.Assert class to perform asserts in Selenium?

答:
According to https://msdn.microsoft.com/en-us/library/ms182532.aspx</p>

```<code>[TestClass]
public class UnitTest1
{
    private IWebDriver driver;
    [TestInitialize]
    public void Setup()
    {
        driver = new ChromeDriver();
        driver.Url = "Your URL";
    }

    [TestMethod]
    public void TestMethod1()
    {
        //Your first test method
        var element = driver.FindElement(By.Id("ID"));
        Assert.IsTrue(element.Displayed);
        Assert.AreEqual(element.Text.ToLower(), "Expected text".ToLower());
    }

    [TestMethod]
    public void TestMethod2()
    {
        //Your second test method
    }

    [TestCleanup]
    public void TearDown()
    {
        driver.Quit();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Assert in Selenium C#

Body:
According to https://msdn.microsoft.com/en-us/library/ms182532.aspx

[TestClass]
public class UnitTest1
{
    private IWebDriver driver;
    [TestInitialize]
    public void Setup()
    {
        driver = new ChromeDriver();
        driver.Url = "Your URL";
    }

    [TestMethod]
    public void TestMethod1()
    {
        //Your first test method
        var element = driver.FindElement(By.Id("ID"));
        Assert.IsTrue(element.Displayed);
        Assert.AreEqual(element.Text.ToLower(), "Expected text".ToLower());
    }

    [TestMethod]
    public void TestMethod2()
    {
        //Your second test method
    }

    [TestCleanup]
    public void TearDown()
    {
        driver.Quit();
    }
}


问:
Can't customise color of material-ui RaisedButton
I'm trying to change the color of the material-ui RaisedButton using inline style customisation using backgroundColor: '#fb933c', but it's still showing the default color.</p>

答:
You can use build-in backgroundColor property.

```<code><RaisedButton
   backgroundColor="#fb933c"
/>
</code>```

Body:
You can use build-in backgroundColor property.

<RaisedButton
   backgroundColor="#fb933c"
/>


问:
how to get table data in json using linq and entityframework
i have table with these fields sms,id,updtd_date. im trying get it in json but date value getting in different format. how to get updt_time field in string in json

o/p

```<code>/Date(1497309538000)/
</code>```

req op

```<code>13-06-2017 04:48
</code>```

code

```<code> public ActionResult getSMS()
        {
            using (DBEntities dc = new DBEntities())
            {
                var data = dc.sms.OrderByDescending(a => a.id).ToList();
                return Json(new { data = data }, JsonRequestBehavior.AllowGet);
            }
        }
</code>```

答:
You can serialize your date manually: </p>

```<code>public ActionResult getSMS()
{
    using (DBEntities dc = new DBEntities())
    {
        var data = dc.sms.OrderByDescending(a => a.id);
        return Json(data.Select(d => new { d.sms, d.id, updtd_date = d.ToString("dd-MM-yyyy HH:mm") }).ToList(), JsonRequestBehavior.AllowGet);

    }
}
</code>```

Body:
i have table with these fields sms,id,updtd_date. im trying get it in json but date value getting in different format. how to get updt_time field in string in json

o/p

/Date(1497309538000)/

req op

13-06-2017 04:48

code

 public ActionResult getSMS()
        {
            using (DBEntities dc = new DBEntities())
            {
                var data = dc.sms.OrderByDescending(a => a.id).ToList();
                return Json(new { data = data }, JsonRequestBehavior.AllowGet);
            }
        }

Body:
You can serialize your date manually:

public ActionResult getSMS()
{
    using (DBEntities dc = new DBEntities())
    {
        var data = dc.sms.OrderByDescending(a => a.id);
        return Json(data.Select(d => new { d.sms, d.id, updtd_date = d.ToString("dd-MM-yyyy HH:mm") }).ToList(), JsonRequestBehavior.AllowGet);

    }
}


问:
How to make a dict of multiple lists in python?
I want to make a list of dicts that have the following structure,

```<code>[{'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, {'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, ...]
</code>```

However at the moment i only have a csv file consisting of the website text.

Below i have attempted to somehow create lists of the same length as my website text file, then zip them and create a dict from that. I have been unable to find information on here when it comes to creating a dict from more that 2 lists.

```<code>with open('attorneys text.csv') as data_file:
    attorneys = list(line for line in data_file)

website = []
business = []
classes = []
for l in range(len(attorneys)):
    website.append("Website text")

for k in range(len(attorneys)):
    business.append("Business")

for i in range(len(attorneys)):
    classes.append("Attorney")

data = dict(zip((business, classes, website, attorneys)))
</code>```

I am well aware of the ugliness of the try as well...

答:
This is what i would do:

```<code>data = []

with open('attorneys text.csv') as data_file:
  for line in data_file
    row = { "Business": "Attorney", "Website text": line}
    data.append(row)
</code>```

I don t know if i understood well what you want to do

Body:
I want to make a list of dicts that have the following structure,

[{'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, {'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, ...]

However at the moment i only have a csv file consisting of the website text.

Below i have attempted to somehow create lists of the same length as my website text file, then zip them and create a dict from that. I have been unable to find information on here when it comes to creating a dict from more that 2 lists.

with open('attorneys text.csv') as data_file:
    attorneys = list(line for line in data_file)

website = []
business = []
classes = []
for l in range(len(attorneys)):
    website.append("Website text")

for k in range(len(attorneys)):
    business.append("Business")

for i in range(len(attorneys)):
    classes.append("Attorney")

data = dict(zip((business, classes, website, attorneys)))

I am well aware of the ugliness of the try as well...

Body:
This is what i would do:

data = []

with open('attorneys text.csv') as data_file:
  for line in data_file
    row = { "Business": "Attorney", "Website text": line}
    data.append(row)

I don t know if i understood well what you want to do


问:
VSTO Outlook Add-in Move folders up and down
i have an outlook add-in in which a folder is selected.Now what i want is, i want to move the folder up and down using C#. Is there someone that can help me in this case. You help is greatly appreciated.</p>

答: To my knowledge you can not. Non-default folders are sorted alphabetically. </p>


问:
Implementing Attatched Objects: Unclear Documentation Example
I try to understand the documentation section Providing Attached Objects for Data Annotations, or specifically it's example.

If I get the steps right it works like this:

Create a Type (MessageBoardAttatchedType) which holds the signals and properties of that shall be accessible through the attached property

Create a static method that returns an instance of the affore mentioned type in the type, that shall be used as the attached property (MessageBoard)

Provide the information, that this attached type exists by invoking the macro QML_DECLARE_TYPEINFO(..., QML_HAS_ATTACHED_PROPERTIES)

The following questions arrise for me:

(Minor one): In the documentation we have this code:

```<code>static MessageBoard *qmlAttachedProperties(QObject *object)
{
    return new MessageBoardAttachedType(object);
}
</code>```

The return type is MessageBoard, but we return a MessageBoardAttachedType. How is that made possible? MessageBoardAttachedType does not inherrit MessageBoard - is that some magic of the macro in 3.?

And the main question:

Here we learn, that attached properties may(?) be available just in very specific Items - e.g. just in the delegate root for the XView attached properties.

In the example it is not mentioned, that I can access the attatched property from a Message-object. How is that determined? By returning null from the

```<code>*qmlAttachedProperties(...)
</code>```

if the passed *object does not please me (is not a Message e.g.)?

答:
Returning a null pointer from qmlAttachedProperties will crash the QML engine.
You should always return an instance of an object in qmlAttachedProperties.

You could however display a warning when the object being attached doesn't fit your requirements, either in the qmlAttachedProperties function or in the constructor of the attached type.

For example that's how it's done for the StackView attached type and multiple others.

The qmlAttachedProperties of StackView returns an object inconditionnaly :

```<code>QQuickStackViewAttached *QQuickStackView::qmlAttachedProperties(QObject *object)
{
    return new QQuickStackViewAttached(object);
}
</code>```

The constructor of the StackView attached type outputs a warning if the attached object is not an QQuickItem (checking with qobject_cast), and does its magic only if it is.

```<code>QQuickStackViewAttached::QQuickStackViewAttached(QObject *parent)
    : QObject(*(new QQuickStackViewAttachedPrivate), parent)
{
    Q_D(QQuickStackViewAttached);
    QQuickItem *item = qobject_cast<QQuickItem *>(parent);
    if (item) {
        connect(item, &QQuickItem::visibleChanged, this, &QQuickStackViewAttached::visibleChanged);
        QQuickItemPrivate::get(item)->addItemChangeListener(d, QQuickItemPrivate::Parent);
        d->itemParentChanged(item, item->parentItem());
    } else if (parent) {
        qmlWarning(parent) << "StackView must be attached to an Item";
    }
}
</code>```

Body:
I try to understand the documentation section Providing Attached Objects for Data Annotations, or specifically it's example.

If I get the steps right it works like this:

Create a Type (MessageBoardAttatchedType) which holds the signals and properties of that shall be accessible through the attached property

Create a static method that returns an instance of the affore mentioned type in the type, that shall be used as the attached property (MessageBoard)

Provide the information, that this attached type exists by invoking the macro QML_DECLARE_TYPEINFO(..., QML_HAS_ATTACHED_PROPERTIES)

The following questions arrise for me:

(Minor one): In the documentation we have this code:

static MessageBoard *qmlAttachedProperties(QObject *object)
{
    return new MessageBoardAttachedType(object);
}

The return type is MessageBoard, but we return a MessageBoardAttachedType. How is that made possible? MessageBoardAttachedType does not inherrit MessageBoard - is that some magic of the macro in 3.?

And the main question:

Here we learn, that attached properties may(?) be available just in very specific Items - e.g. just in the delegate root for the XView attached properties.

In the example it is not mentioned, that I can access the attatched property from a Message-object. How is that determined? By returning null from the

*qmlAttachedProperties(...)

if the passed *object does not please me (is not a Message e.g.)?

Body:
Returning a null pointer from qmlAttachedProperties will crash the QML engine.
You should always return an instance of an object in qmlAttachedProperties.

You could however display a warning when the object being attached doesn't fit your requirements, either in the qmlAttachedProperties function or in the constructor of the attached type.

For example that's how it's done for the StackView attached type and multiple others.

The qmlAttachedProperties of StackView returns an object inconditionnaly :

QQuickStackViewAttached *QQuickStackView::qmlAttachedProperties(QObject *object)
{
    return new QQuickStackViewAttached(object);
}

The constructor of the StackView attached type outputs a warning if the attached object is not an QQuickItem (checking with qobject_cast), and does its magic only if it is.

QQuickStackViewAttached::QQuickStackViewAttached(QObject *parent)
    : QObject(*(new QQuickStackViewAttachedPrivate), parent)
{
    Q_D(QQuickStackViewAttached);
    QQuickItem *item = qobject_cast<QQuickItem *>(parent);
    if (item) {
        connect(item, &QQuickItem::visibleChanged, this, &QQuickStackViewAttached::visibleChanged);
        QQuickItemPrivate::get(item)->addItemChangeListener(d, QQuickItemPrivate::Parent);
        d->itemParentChanged(item, item->parentItem());
    } else if (parent) {
        qmlWarning(parent) << "StackView must be attached to an Item";
    }
}


问:
upload several files at once
i'm building a website with very simple cms.
I built a form already with an input type="file" already to upload pictures, but the client wants to upload several files at once. So i've looking for and I found the Uploadify, but also found some bugs and i want to try something else.
Any help??

Thanks in advance ;)

答:
Have a look at plupload.

This is a plugin that uses many different technologies to upload multiple files to server like HTML5, GEARS, FLASH, HTML4, SILVERLIGHT and select the one that best fits in the user browser.

It also feature a jquery UI plugin for your upload queue.

Title: upload several files at once


问:
Using parameters as user Defined Variables?
We run our tests in non gui mode and pass in various parameters like Server, port, threads etc. We'd also like to run our test in GUI mode, and be able to change these parameters in the GUI.

What I wanted to do, was use 2x User Defined variable objects, and have one with static data we can edit, and another with parameters. That way the actual test plan doesn't change, but we can set variables as parameters, and just disable the static data one. Or disable the parameterized one when we want to run with static data.

But this doesn't seem to work - no errors nothing.

答:
Actually i am using a function named as regular expression for getting value.
here i have to use variable under variable because there is lots of value with same boundary, so i have selected one paragraph as ${ABC} and fetching value from this paragraph ${XYLEM}. both the variable created as regular expression.tried with ${__V(ABC${XYLEM})};

```<code>${__setProperty{Search_Investment_Banking,$Investment_Banking}};
</code>```

Body:
Actually i am using a function named as regular expression for getting value.
here i have to use variable under variable because there is lots of value with same boundary, so i have selected one paragraph as ${ABC} and fetching value from this paragraph ${XYLEM}. both the variable created as regular expression.tried with ${__V(ABC${XYLEM})};

${__setProperty{Search_Investment_Banking,$Investment_Banking}};


问:
Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)
I am developing a web page using JavaScript and HTML, everything was working
good when I have received this list of errors from my HTML page:

The resource from “https://raw.githubusercontent.com/dataarts/dat.gui/master/build/dat.gui.min.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/CanvasRenderer.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/Projector.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
```

These errors appeared after an automatic browser update (Mozilla Firefox), may
be something has been changed in the set up. Do you know any way to solve this
problem?

答:
For Wordpress

In my case i just missed the slash "/" after get_template_directory_uri() so resulted / generated path was wrong:

My Wrong code :

```<code>wp_enqueue_script( 'retina-js', get_template_directory_uri().'js/retina.min.js' );
</code>```

My Corrected Code :

```<code>wp_enqueue_script( 'retina-js', get_template_directory_uri().'/js/retina.min.js' );
</code>```

Body:
I am developing a web page using JavaScript and HTML, everything was working
good when I have received this list of errors from my HTML page:

The resource from “https://raw.githubusercontent.com/dataarts/dat.gui/master/build/dat.gui.min.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/CanvasRenderer.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/Projector.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

These errors appeared after an automatic browser update (Mozilla Firefox), may
be something has been changed in the set up. Do you know any way to solve this
problem?

Body:
For Wordpress

In my case i just missed the slash "/" after get_template_directory_uri() so resulted / generated path was wrong:

My Wrong code :

wp_enqueue_script( 'retina-js', get_template_directory_uri().'js/retina.min.js' );

My Corrected Code :

wp_enqueue_script( 'retina-js', get_template_directory_uri().'/js/retina.min.js' );


问:
xsl value of as xsl element name
I have the following structure

```<code><Rowsets>
<Rowset>
    <Row>
        <ID>123</ID>
        <PropertyID>property 1</PropertyID>
        <PropertyValue>value 1</PropertyValue>
    </Row>
    <Row>
        <ID>123</ID>
        <PropertyID>property 2</PropertyID>
        <PropertyValue>value 2</PropertyValue>
    </Row>
    <Row>
        <ID>456</ID>
        <PropertyID>property 1</PropertyID>
        <PropertyValue>value 11</PropertyValue>
    </Row>
    <Row>
        <ID>456</ID>
        <PropertyID>property 2</PropertyID>
        <PropertyValue>value 22</PropertyValue>
    </Row>
</Rowset>
</code>```

I want to group the properties together with the ID, as in the following structure

```<code><SEGMENTS>
<SET>
    <ID>123</ID>
    <property 1>value 1</property 1>
    <property 2>value 2</property 2>
</SET>
<SET>
    <ID>456</ID>
    <property 1>value 11</property 1>
    <property 2>value 22</property 2>
</SET>
</code>```

I do this with this XSLT form

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="ID-sets" match="Row" use="ID" />
<xsl:template match="Rowsets/Rowset">
    <SEGMENTS>
        <xsl:for-each select="Row[count(. | key('ID-sets', ID)[1]) = 1]">
            <xsl:sort select="ID" />
            <SET>
                <ID>
                    <xsl:value-of select="ID" />
                </ID>

                <xsl:for-each select="key('ID-sets', ID)">
                    <xsl:sort select="PropertyID" />
                    <xsl:element name="PropertyID">
                        <xsl:value-of select="PropertyValue"/>
                    </xsl:element>
                </xsl:for-each>
            </SET>
        </xsl:for-each>
    </SEGMENTS>
</xsl:template>
</code>```

I'm almost there, but the one thing that won't work is the element name.
After some reseach I found that I need to use this:
xsl:element name="{PropertyID}"

Except, it doesn't work. Notepad++ gives the warning that it's unable to apply transformation on current source.
Without the {} tags it works, but then it's just static and not the variable PropertyID.

It's probably a little thing, but I can't find it.
I'm limited to xslt 1.0 if that matters.

答:
Spaces are not allowed in element names.
An alternative is

```<code><Property id="{PropertyID}">
</code>```

Thanks to Tim C for the answer.

Title: xsl value of as xsl element name

Body:
I have the following structure

<Rowsets>
<Rowset>
    <Row>
        <ID>123</ID>
        <PropertyID>property 1</PropertyID>
        <PropertyValue>value 1</PropertyValue>
    </Row>
    <Row>
        <ID>123</ID>
        <PropertyID>property 2</PropertyID>
        <PropertyValue>value 2</PropertyValue>
    </Row>
    <Row>
        <ID>456</ID>
        <PropertyID>property 1</PropertyID>
        <PropertyValue>value 11</PropertyValue>
    </Row>
    <Row>
        <ID>456</ID>
        <PropertyID>property 2</PropertyID>
        <PropertyValue>value 22</PropertyValue>
    </Row>
</Rowset>

I want to group the properties together with the ID, as in the following structure

<SEGMENTS>
<SET>
    <ID>123</ID>
    <property 1>value 1</property 1>
    <property 2>value 2</property 2>
</SET>
<SET>
    <ID>456</ID>
    <property 1>value 11</property 1>
    <property 2>value 22</property 2>
</SET>

I do this with this XSLT form

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="ID-sets" match="Row" use="ID" />
<xsl:template match="Rowsets/Rowset">
    <SEGMENTS>
        <xsl:for-each select="Row[count(. | key('ID-sets', ID)[1]) = 1]">
            <xsl:sort select="ID" />
            <SET>
                <ID>
                    <xsl:value-of select="ID" />
                </ID>

                <xsl:for-each select="key('ID-sets', ID)">
                    <xsl:sort select="PropertyID" />
                    <xsl:element name="PropertyID">
                        <xsl:value-of select="PropertyValue"/>
                    </xsl:element>
                </xsl:for-each>
            </SET>
        </xsl:for-each>
    </SEGMENTS>
</xsl:template>

I'm almost there, but the one thing that won't work is the element name.
After some reseach I found that I need to use this:
xsl:element name="{PropertyID}"

Except, it doesn't work. Notepad++ gives the warning that it's unable to apply transformation on current source.
Without the {} tags it works, but then it's just static and not the variable PropertyID.

It's probably a little thing, but I can't find it.
I'm limited to xslt 1.0 if that matters.

Body:
Spaces are not allowed in element names.
An alternative is

<Property id="{PropertyID}">

Thanks to Tim C for the answer.


问:
How to call WCF Service that requires Headers from Silverlight
WCF 3.5 SP1 Services / Called from Silverlight 4

In the situation where vendor has created a WCF API, both as svc services, as well as a custom proxy client.

Both aspects of this API sit on top of a core four-layer abstraction.

First there is are two abstract MessageContract classes: WcfRequest and WcfResponse.

The abstract WcfRequest type contains properties decorated with the MessageHeader attribute, and contain things such as a custom authentication identifier and timezone.

Then there is the second layer of the onion where each method is divided into two classes: GetSomethingRequest and a GetSomethingResponse, both of which inherit from WcfRequest and WcfReponse, respectively.

Next comes the implementation layer, where the WcfRequest and WcfResponse based types bubble up and get invoked by a custom WcfClient type, which controls all the ChannelFactory construction, establishes the binding, and most importantly, sets the identifier header in the WcfRequest type based on a previously set value in memory (like a session key).

Lastly comes the view to the ouside world, where you request POCO types via id values.

Now, the API is written in such a way that if I use the vendor supplied proxy, things will work as expected - authentication occurs and this identifier is set, and then I can call a method call without a problem.

If you've made it this far, thanks for sticking with me.

Now, the problem occurs when I want to write a Silverlight client, using either "Add Service Reference" or SLSvcUtil, none of the proxy client types generated have these header properties from the WcfRequest header to set, and are not defined in the message prototype as parameters to pass in.

To set these headers, I've looked at the WCFExtras project on Codeplex and tried to use the ClientSoapHeaderHelper routines, but that doesn't work for Silverlight (No extension capability).

I've tried to look into the OperationContext - to see if I could set the header there, but that's null - at least if I inspect it in the client proxy method.

Are you a person that knows how to manually (hack) these headers into place?

Thanks for any assistance...but totally understand if this gets no hits.

答:
I ran in to the problem of custom headers a while ago... I basically needed to write headers a little differently than the internal classes wanted to (it was an apache service).

Here is the way I got around this (three classes).

Inside the operation context i create a new instance of my HeaderSerializer class. This class is based on HeaderSerializerBase (my class too) which is based on XmlObjectSerializer. HeaderSerializerBase uses WriteRaw to basically write any string in to the header that you like (in my case it was stored in the app, but you could build this dynamically no problems).

HTH :)

```<code>using (OperationContextScope ocs = new OperationContextScope(client.InnerChannel))
            {

                var ser = new HeaderSerializer();
                OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("SecurityHeader",
                                                                                "http://somesite.com/schema",
                                                                                authHeader, ser));

                var req = new GetPredefinedSearchResultsRequest()
                              {
                                  Someproperty = somevalue
                              };

                client.GetPredefinedSearchResultsAsync(req);
            }

            public class HeaderSerializer : HeaderSerializerBase
            {
                public EPGHeaderSerializer()
                {
                    base.autheHeaderString = XamlingCore.Infrastructure.Resource.ResourceLoader.LoadStringResource("Assembly.Data", "RawHeaderData.txt");
                }
            }

            public class HeaderSerializerBase : XmlObjectSerializer
            {
                protected string autheHeaderString;

                public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
                {
                    throw new NotImplementedException();
                }

                public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
                {
                    writer.WriteRaw(autheHeaderString.ToCharArray(), 0, autheHeaderString.Length);
                }

                public override void WriteEndObject(XmlDictionaryWriter writer)
                {
                    throw new NotImplementedException();
                }

                public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
                {
                    throw new NotImplementedException();
                }

                public override bool IsStartObject(XmlDictionaryReader reader)
                {
                    throw new NotImplementedException();
                }
            }
</code>```

Body:
I ran in to the problem of custom headers a while ago... I basically needed to write headers a little differently than the internal classes wanted to (it was an apache service).

Here is the way I got around this (three classes).

Inside the operation context i create a new instance of my HeaderSerializer class. This class is based on HeaderSerializerBase (my class too) which is based on XmlObjectSerializer. HeaderSerializerBase uses WriteRaw to basically write any string in to the header that you like (in my case it was stored in the app, but you could build this dynamically no problems).

HTH :)

using (OperationContextScope ocs = new OperationContextScope(client.InnerChannel))
            {

                var ser = new HeaderSerializer();
                OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("SecurityHeader",
                                                                                "http://somesite.com/schema",
                                                                                authHeader, ser));

                var req = new GetPredefinedSearchResultsRequest()
                              {
                                  Someproperty = somevalue
                              };

                client.GetPredefinedSearchResultsAsync(req);
            }

            public class HeaderSerializer : HeaderSerializerBase
            {
                public EPGHeaderSerializer()
                {
                    base.autheHeaderString = XamlingCore.Infrastructure.Resource.ResourceLoader.LoadStringResource("Assembly.Data", "RawHeaderData.txt");
                }
            }

            public class HeaderSerializerBase : XmlObjectSerializer
            {
                protected string autheHeaderString;

                public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
                {
                    throw new NotImplementedException();
                }

                public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
                {
                    writer.WriteRaw(autheHeaderString.ToCharArray(), 0, autheHeaderString.Length);
                }

                public override void WriteEndObject(XmlDictionaryWriter writer)
                {
                    throw new NotImplementedException();
                }

                public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
                {
                    throw new NotImplementedException();
                }

                public override bool IsStartObject(XmlDictionaryReader reader)
                {
                    throw new NotImplementedException();
                }
            }


问:
Colorbar tick labels as log outputs
I am playing around with histogram2d and I am trying incorporate a color bar logarithmic values.

Here is my current code:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list('mycmap', ['black', 'maroon',
                                                'crimson', 'orange', 'white'])

fig = plt.figure()
ax = fig.add_subplot(111)
H = ax.hist2d(gas_pos[:,0]/0.7, gas_pos[:,1]/0.7, cmap=cmap,
            norm=matplotlib.colors.LogNorm(), bins=350, weights=np.log(gas_Temp))

ax.tick_params(axis=u'both', which=u'both',length=0)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

cb = fig.colorbar(H[3], ax=ax, shrink=0.8, pad=0.01,
                orientation="horizontal", label=r'$\log T\ [\mathrm{K}]$')
cb.ax.set_xticklabels([1,2,3,4])
cb.update_ticks()

empty = Rectangle((0,0 ), 0, 0, alpha=0.0)
redshift = fig.legend([empty], [r'$z = 127$'],
        loc='upper right', frameon=False, handlelength=0, handletextpad=0)
redshift.get_texts()[0].set_color('white')
#fig.add_artist(redshift)

plt.show()
</code>```

The weights are values not passed through np.log() and are currently being normalized through LogNorm().

What I am trying to get is to have the colorbar tic labels to be the logarithmic values of what is currently there eg. 10**4 --> 4, 10**6 --> 6, etc.

I have tried changing the formatting and also passing through the logarithmic values of np.log(gas_Temp), but nothing is really working.

答:
The idiomatic thing to do is use a LogFormatterExponent to do the formatting of your colorbar. That's exactly what you need: to display 10**x values as x, or in other words, to display y values as log10(x).

Proof using dummy data:

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib.ticker import LogFormatterExponent # <-- one new import here

# generate dummy data
histdata = 10**(np.random.rand(200,200)*4 + 1)  # 10^1 -> 10^5

# plot
fig = plt.figure()
ax = fig.add_subplot(111)

ax.tick_params(axis=u'both', which=u'both',length=0)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

im = plt.imshow(histdata,cmap='viridis',norm=LogNorm())
cb = fig.colorbar(im, ax=ax, shrink=0.8, pad=0.01,
                  orientation="horizontal", label=r'$\log T\ [\mathrm{K}]$')

# v-- one new line here
cb.formatter = LogFormatterExponent(base=10) # 10 is the default
cb.update_ticks()
</code>```

Compare the result of your original (left) with the modified version (right):

Title: Colorbar tick labels as log outputs

Body:
I am playing around with histogram2d and I am trying incorporate a color bar logarithmic values.

Here is my current code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list('mycmap', ['black', 'maroon',
                                                'crimson', 'orange', 'white'])

fig = plt.figure()
ax = fig.add_subplot(111)
H = ax.hist2d(gas_pos[:,0]/0.7, gas_pos[:,1]/0.7, cmap=cmap,
            norm=matplotlib.colors.LogNorm(), bins=350, weights=np.log(gas_Temp))

ax.tick_params(axis=u'both', which=u'both',length=0)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

cb = fig.colorbar(H[3], ax=ax, shrink=0.8, pad=0.01,
                orientation="horizontal", label=r'$\log T\ [\mathrm{K}]$')
cb.ax.set_xticklabels([1,2,3,4])
cb.update_ticks()

empty = Rectangle((0,0 ), 0, 0, alpha=0.0)
redshift = fig.legend([empty], [r'$z = 127$'],
        loc='upper right', frameon=False, handlelength=0, handletextpad=0)
redshift.get_texts()[0].set_color('white')
#fig.add_artist(redshift)

plt.show()

The weights are values not passed through np.log() and are currently being normalized through LogNorm().

What I am trying to get is to have the colorbar tic labels to be the logarithmic values of what is currently there eg. 10**4 --> 4, 10**6 --> 6, etc.

I have tried changing the formatting and also passing through the logarithmic values of np.log(gas_Temp), but nothing is really working.

Body:
The idiomatic thing to do is use a LogFormatterExponent to do the formatting of your colorbar. That's exactly what you need: to display 10**x values as x, or in other words, to display y values as log10(x).

Proof using dummy data:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib.ticker import LogFormatterExponent # <-- one new import here

# generate dummy data
histdata = 10**(np.random.rand(200,200)*4 + 1)  # 10^1 -> 10^5

# plot
fig = plt.figure()
ax = fig.add_subplot(111)

ax.tick_params(axis=u'both', which=u'both',length=0)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

im = plt.imshow(histdata,cmap='viridis',norm=LogNorm())
cb = fig.colorbar(im, ax=ax, shrink=0.8, pad=0.01,
                  orientation="horizontal", label=r'$\log T\ [\mathrm{K}]$')

# v-- one new line here
cb.formatter = LogFormatterExponent(base=10) # 10 is the default
cb.update_ticks()

Compare the result of your original (left) with the modified version (right):


问:
jQuery equivalent in vanilla js
Building JS calculator as per freecodecamp front end track. My problem is that I have an idea how this can be implemented by using jQuery, but having problems with turning it into pure javascript .

Codepen: https://codepen.io/ekilja01/pen/MoXROe

jQuery:

```<code> $("#clear,#clearall").click(function(){
      number = "";
      totalNumber.text("0");
      if ($(this).attr("id") === "clearall") {
          newNumber = "";
      }
  }
</code>```

I'm trying this, but it doesn't work

```<code>["clear", "clearAll"].forEach.call(function(e){
        e.addEventListener("click", function(){
            totalNumber.textContent = "0";
        });
    });
</code>```

js:

```<code>document.addEventListener("DOMContentLoaded", function (event) {
    console.log("DOM OK");

    // Declare variables for number, new number and operators

    var number = "";
    var newNumber = "";
    var operator = "";

    // Declare variable total number to display total on the calculator's display

    var totalNumber = document.getElementById("total");
    totalNumber.textContent = "0";

    // Testing if number displayed is longer than 6 digits and if it is - Err to be displayed
    var testNumLength = function(number) {
        if (number.length > 6) {
            number = "";
            totalNumber.textContent = "Err";
        }
    }

    document.getElementById("numbers").addEventListener("click", function(e){
        number += e.target.textContent;
        totalNumber.textContent = number;
        testNumLength(number);
    })

    var clear = document.getElementById("clear");
    var clearAll = document.getElementById("clearall");

})

   ["clear", "clearAll"].forEach.call(function(e){
        e.addEventListener("click", function(){
            totalNumber.textContent = "0";
        });
    });
</code>```

答:
This code has some wrong assumptions about how forEah works

```<code>["clear", "clearAll"].forEach.call(function(e){
    e.addEventListener("click", function(){
        totalNumber.textContent = "0";
    });
});
</code>```

Every array has forEachmethod inherited from Array.prototype so you don't need to use forEach.call

["clear", "clearAll"] is an array of strings (not DOM elements) so you need to either construct an array of DOM elements or get those elements by id inside forEach method.

Pick one of the following options

Select elements by id and iterate

```<code>var clear = document.getElementById("clear");
    var clearAll = document.getElementById("clearall");

})

   [clear, clearAll].forEach(function(e){
        e.addEventListener("click", function(){
            totalNumber.textContent = "0";
        });
    });
</code>```

or iterate over NodeList you get from querySelectorAll

```<code>[].forEach.call(document.querySelectorAll('#clear, #clearAll'), function(el) {
 ...
})
</code>```

or iterate over ids and get element by id

```<code>['clear', 'clearAll'].forEach(function(id) {
  document.getElementById(id).addEventListener('click', ...)
})
</code>```

Title: jQuery equivalent in vanilla js

Body:
Building JS calculator as per freecodecamp front end track. My problem is that I have an idea how this can be implemented by using jQuery, but having problems with turning it into pure javascript .

Codepen: https://codepen.io/ekilja01/pen/MoXROe

jQuery:

 $("#clear,#clearall").click(function(){
      number = "";
      totalNumber.text("0");
      if ($(this).attr("id") === "clearall") {
          newNumber = "";
      }
  }

I'm trying this, but it doesn't work

["clear", "clearAll"].forEach.call(function(e){
        e.addEventListener("click", function(){
            totalNumber.textContent = "0";
        });
    });

js:

document.addEventListener("DOMContentLoaded", function (event) {
    console.log("DOM OK");

    // Declare variables for number, new number and operators

    var number = "";
    var newNumber = "";
    var operator = "";

    // Declare variable total number to display total on the calculator's display

    var totalNumber = document.getElementById("total");
    totalNumber.textContent = "0";

    // Testing if number displayed is longer than 6 digits and if it is - Err to be displayed
    var testNumLength = function(number) {
        if (number.length > 6) {
            number = "";
            totalNumber.textContent = "Err";
        }
    }

    document.getElementById("numbers").addEventListener("click", function(e){
        number += e.target.textContent;
        totalNumber.textContent = number;
        testNumLength(number);
    })

    var clear = document.getElementById("clear");
    var clearAll = document.getElementById("clearall");

})

   ["clear", "clearAll"].forEach.call(function(e){
        e.addEventListener("click", function(){
            totalNumber.textContent = "0";
        });
    });

Body:
This code has some wrong assumptions about how forEah works

["clear", "clearAll"].forEach.call(function(e){
    e.addEventListener("click", function(){
        totalNumber.textContent = "0";
    });
});

Every array has forEachmethod inherited from Array.prototype so you don't need to use forEach.call

["clear", "clearAll"] is an array of strings (not DOM elements) so you need to either construct an array of DOM elements or get those elements by id inside forEach method.

Pick one of the following options

Select elements by id and iterate

var clear = document.getElementById("clear");
    var clearAll = document.getElementById("clearall");

})

   [clear, clearAll].forEach(function(e){
        e.addEventListener("click", function(){
            totalNumber.textContent = "0";
        });
    });

or iterate over NodeList you get from querySelectorAll

[].forEach.call(document.querySelectorAll('#clear, #clearAll'), function(el) {
 ...
})

or iterate over ids and get element by id

['clear', 'clearAll'].forEach(function(id) {
  document.getElementById(id).addEventListener('click', ...)
})


问:
How to download multiple PDFs with curl in Terminal.app
In terminal.app I entered this line

curl -o http://print.nap.edu/pdf/0309065577/pdf_image/[1-319].pdf

And it in Terminal it says:

curl: no URL specified!

How is this possible? I'm just trying to download a bunch of successively numbered PDF files from a web server. If I leave off the -o it just downloads a bunch of gibberish into the Terminal window but not as a file. Am I doing anything wrong here?

答:
Try

```<code>curl -o file_#1.pdf 'http://foo.bar/abc/[1-319].pdf'
</code>```

note two things: (1) the placeholder #1 in the (2) output file name

Body:
Try

curl -o file_#1.pdf 'http://foo.bar/abc/[1-319].pdf'

note two things: (1) the placeholder #1 in the (2) output file name


问:
Generic Methods, how to call a parent method without specifying a type
I have this parent class

```<code>public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}
</code>```

and this child

```<code>public class Child : Parent
{
    public string Name { get; set; }
}
</code>```

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

答:
This would be the extension method approach:</p>

```<code>public static class ExtensionMethods
{
    public static T Find<T>(this T source, string id) where T : class, new()
    {
        return new T();
    }
}

public class Child
{
    public void FindChild()
    {
        this.Find("");
    }
}
</code>```

Body:
I have this parent class

public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}

and this child

public class Child : Parent
{
    public string Name { get; set; }
}

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

Body:
This would be the extension method approach:

public static class ExtensionMethods
{
    public static T Find<T>(this T source, string id) where T : class, new()
    {
        return new T();
    }
}

public class Child
{
    public void FindChild()
    {
        this.Find("");
    }
}


问:
keras LSTM model input and output dimensions mismatch
```<code>model = Sequential()

    model.add(Embedding(630, 210))
    model.add(LSTM(1024, dropout = 0.2, return_sequences = True))
    model.add(LSTM(1024, dropout = 0.2, return_sequences = True))
    model.add(Dense(210, activation = 'softmax'))

    model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

    filepath = 'ner_2-{epoch:02d}-{loss:.5f}.hdf5'
    checkpoint = ModelCheckpoint(filepath, monitor = 'loss', verbose = 1, save_best_only = True, mode = 'min')
    callback_list = [checkpoint]

    model.fit(X, y , epochs = 20, batch_size = 1024, callbacks = callback_list)
</code>```

X: the input vector is of the shape (204564, 630, 1)

y: the target vector is of the shape (204564, 210, 1)

i.e. for every 630 inputs 210 outputs have to be predicted but the code throws the following error on compilation

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-57-05a6affb6217> in <module>()
     50 callback_list = [checkpoint]
     51
---> 52 model.fit(X, y , epochs = 20, batch_size = 1024, callbacks = callback_list)
     53 print('successful')

ValueError: Error when checking model input: expected embedding_8_input to have 2 dimensions, but got array with shape (204564, 630, 1)
</code>```

Please someone explain why this error is occurring and how to solve this

答:
The message says:

Your first layer expects an input with 2 dimensions: (BatchSize, SomeOtherDimension). But your input has 3 dimensions (BatchSize=204564,SomeOtherDimension=630, 1).

Well... remove the 1 from your input, or reshape it inside the model:

Solution 1 - Removing it from the input:

```<code>X = X.reshape((204564,630))
</code>```

Solution 2 - Adding a reshape layer:

```<code>model = Sequential()
model.add(Reshape((630,),input_shape=(630,1)))
model.add(Embedding.....)
</code>```

Body:
model = Sequential()

    model.add(Embedding(630, 210))
    model.add(LSTM(1024, dropout = 0.2, return_sequences = True))
    model.add(LSTM(1024, dropout = 0.2, return_sequences = True))
    model.add(Dense(210, activation = 'softmax'))

    model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

    filepath = 'ner_2-{epoch:02d}-{loss:.5f}.hdf5'
    checkpoint = ModelCheckpoint(filepath, monitor = 'loss', verbose = 1, save_best_only = True, mode = 'min')
    callback_list = [checkpoint]

    model.fit(X, y , epochs = 20, batch_size = 1024, callbacks = callback_list)

X: the input vector is of the shape (204564, 630, 1)

y: the target vector is of the shape (204564, 210, 1)

i.e. for every 630 inputs 210 outputs have to be predicted but the code throws the following error on compilation

ValueError                                Traceback (most recent call last)
<ipython-input-57-05a6affb6217> in <module>()
     50 callback_list = [checkpoint]
     51
---> 52 model.fit(X, y , epochs = 20, batch_size = 1024, callbacks = callback_list)
     53 print('successful')

ValueError: Error when checking model input: expected embedding_8_input to have 2 dimensions, but got array with shape (204564, 630, 1)

Please someone explain why this error is occurring and how to solve this

Body:
The message says:

Your first layer expects an input with 2 dimensions: (BatchSize, SomeOtherDimension). But your input has 3 dimensions (BatchSize=204564,SomeOtherDimension=630, 1).

Well... remove the 1 from your input, or reshape it inside the model:

Solution 1 - Removing it from the input:

X = X.reshape((204564,630))

Solution 2 - Adding a reshape layer:

model = Sequential()
model.add(Reshape((630,),input_shape=(630,1)))
model.add(Embedding.....)


问:
iOS : activityType doesn't work on UIactivityViewController
hi this is my code I have implement UIactivityViewCotroller but when I click I don't see mail and Facebook app

```<code>@IBAction func activityView(_ sender: UIButton) {
    let text = "This is some text that I want to share."
    let textToShare = [ text ]
    let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook, UIActivityType.mail ]
    self.present(activityViewController, animated: true, completion: nil)
}
</code>```

but I don't see those app
what should I do?

答:
Replace the function as follows

```<code>@IBAction func activityView(_ sender: UIButton) {
    let text = "This is some text that I want to share."
    let textToShare = [ text ]
    let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop ]
    self.present(activityViewController, animated: true, completion: nil)
}
</code>```

Activity Controllers excludedActivityTypes means you are excluding those sharing options to list in activityController

Body:
hi this is my code I have implement UIactivityViewCotroller but when I click I don't see mail and Facebook app

@IBAction func activityView(_ sender: UIButton) {
    let text = "This is some text that I want to share."
    let textToShare = [ text ]
    let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook, UIActivityType.mail ]
    self.present(activityViewController, animated: true, completion: nil)
}

but I don't see those app
what should I do?

Body:
Replace the function as follows

@IBAction func activityView(_ sender: UIButton) {
    let text = "This is some text that I want to share."
    let textToShare = [ text ]
    let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop ]
    self.present(activityViewController, animated: true, completion: nil)
}

Activity Controllers excludedActivityTypes means you are excluding those sharing options to list in activityController


问:
Pattern Matching - Regex
User input Format:

[fieldname1] comparator [fieldvalue1,fieldvalue2,value3],[fieldname2]
  comparator [fieldvalue1,value2,..],..

Need to parse this into:

1.[fieldname1] comparator [fieldvalue1,fieldvalue2,value3]

2.[fieldname2] comparator [fieldvalue1,value2,..] and so on

(ie)each field along with its comparator and value has to be separated.
whereas comparator will be any one of the below:

<=|>=|=|is|<|>|startswith|Starts with|Beginswith|Begins with|Ends
  with|Endswith|

contains

Regex used by me :

([(.)+?](\s)(<=|>=|=|is|<|>|startswith|Starts
  with|Beginswith|Begins with|Ends
  with|Endswith|contains)(\s)[(.)+?](\,)*)

Example:
[company] contains [abc,efg],[email] contains [cdf,test]
above is parsed properly no issues.

Problem:
When field name or field value contains symbol "[" or "]" the parsing goes wrong .

example :
[company] contains [ab[]c,efg],[email] contains [siva,test]

Above is valid but since [] is used as delimiter it stops parsing till [company] contains [ab[] but i want it to parse properly as above eg,

1.[company] contains [ab[]c,efg]

2.[email] contains [siva,test]

Thanks.

答:
So basically you need to split the string at each , that is between ] and [.

If you use google's guava, you can use the Splitter and split on a regex with positve lookbefore ] and positive lookbehind [

```<code>String s = "[fieldname1] comparator [fieldvalue1,fieldvalue2,value3],[fieldname2] comparator [fieldvalue1,value2]";
Pattern stringPattern = Pattern.compile("(?<=\\]),(?=\\[)");
Iterable<String> split = Splitter.on(stringPattern).omitEmptyStrings().split(s);
split.forEach(System.out::println);
</code>```

Title: Pattern Matching - Regex

Body:
So basically you need to split the string at each , that is between ] and [.

If you use google's guava, you can use the Splitter and split on a regex with positve lookbefore ] and positive lookbehind [

String s = "[fieldname1] comparator [fieldvalue1,fieldvalue2,value3],[fieldname2] comparator [fieldvalue1,value2]";
Pattern stringPattern = Pattern.compile("(?<=\\]),(?=\\[)");
Iterable<String> split = Splitter.on(stringPattern).omitEmptyStrings().split(s);
split.forEach(System.out::println);


问:
Passing Controller a FormCollection and an IList<T>
I have a form which contains a whole heap of data entry fields that will be completed by the user including some elements where the user can dictate how many of the same items they will enter. This is as is being used in Phil Haack's blog entry Model Binding To A List.

I am successfully using JQuery to create the extra form elements, correctly indexed, etc. My issue is the best way to actually read these within my Controller. The Controller in the article only expects one object, IList<Product> whereas my Controller already expects a FormCollection form and now I am trying to also send it an IList<Itmes> as well.

Should I be adding this to the parameters expected by the Controller or accessing via form["items"] or something else?

View

```<code><form action="/MyItems/Add" method="post">
   <input type="text" name="Title" value="" />

   <input type="hidden" name="myItem.Index" value="0" />
   <input id="item[0].Amount" name="item[0].Amount" type="text" value="" />
   <input id="item[0].Name" name="item[0].Name" type="text" value="" />

   <input type="hidden" name="myItem.Index" value="1" />
   <input id="item[1].Amount" name="item[1].Amount" type="text" value="" />
   <input id="item[1].Name" name="item[1].Name" type="text" value="" />
</form>
</code>```

Controller

```<code>public ActionResult Add(FormCollection form)
{
    string Title = form["Title"];
    List<Item> Items = form["items"].ToList();
}
</code>```

DTO

```<code>public class Item()
{
    int Amount {get; set; };
    string Name {get; set; };
}
</code>```

答:
I have decided to work with exclusively with the FormCollection rather than muddying the waters with some data being passed through using FormCollection and other data being mapped to a List by the framework. The below code takes the items and hydrates the DTO manually. This works nicely and allows me to do some other things within my code that were not possible mapping directly to a List.

```<code>List<Item> itemList = new List<Item>();
int i = 0;

while ( form["item[" + i + "].Amount"] != null)
{
    itemList.Add(new Item()
        {
            Amount = Convert.ToInt32(form[String.Format("item[{0}].Amount",i )]),
            Name = form[String.Format("item[{0}].Name",i )]
        });
}
</code>```

OwnerDisplayName: dave

Body:
I have a form which contains a whole heap of data entry fields that will be completed by the user including some elements where the user can dictate how many of the same items they will enter. This is as is being used in Phil Haack's blog entry Model Binding To A List.

I am successfully using JQuery to create the extra form elements, correctly indexed, etc. My issue is the best way to actually read these within my Controller. The Controller in the article only expects one object, IList<Product> whereas my Controller already expects a FormCollection form and now I am trying to also send it an IList<Itmes> as well.

Should I be adding this to the parameters expected by the Controller or accessing via form["items"] or something else?

View

<form action="/MyItems/Add" method="post">
   <input type="text" name="Title" value="" />

   <input type="hidden" name="myItem.Index" value="0" />
   <input id="item[0].Amount" name="item[0].Amount" type="text" value="" />
   <input id="item[0].Name" name="item[0].Name" type="text" value="" />

   <input type="hidden" name="myItem.Index" value="1" />
   <input id="item[1].Amount" name="item[1].Amount" type="text" value="" />
   <input id="item[1].Name" name="item[1].Name" type="text" value="" />
</form>

Controller

public ActionResult Add(FormCollection form)
{
    string Title = form["Title"];
    List<Item> Items = form["items"].ToList();
}

DTO

public class Item()
{
    int Amount {get; set; };
    string Name {get; set; };
}

LastEditorDisplayName: dave

Body:
I have decided to work with exclusively with the FormCollection rather than muddying the waters with some data being passed through using FormCollection and other data being mapped to a List by the framework. The below code takes the items and hydrates the DTO manually. This works nicely and allows me to do some other things within my code that were not possible mapping directly to a List.

List<Item> itemList = new List<Item>();
int i = 0;

while ( form["item[" + i + "].Amount"] != null)
{
    itemList.Add(new Item()
        {
            Amount = Convert.ToInt32(form[String.Format("item[{0}].Amount",i )]),
            Name = form[String.Format("item[{0}].Name",i )]
        });
}


问:
mysql DELETE multiple tables
is it possible to delete from multiple tables?

i have 3 tables all related by an id, so where the id is the same delete the relevant information.

many thanks

答: In InnoDB you can have a foreign key by setting it up as foreign keys to cascade.  Please see here: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html</p>

Title: mysql DELETE multiple tables


问:
Making message appear in the middle of screen
I recently started to play round with Bootstrap and I created my logo to go on the top left of the page, and then the nav bar to go on the same line but on the right hand side, and then I wanted to say in the middle of the screen: "Welcome blablah"

However, the welcome bit appears on the top part of the screen, rather then the middle, so it's overlapping the logo for some reason.

Not sure why this is doing this, guessing some bad coding etc.

body {
  font-family: 'Open Sans', sans-serif, Arial;
  font-size: 16px;
  color: #6D6D6D;
  background-color: #F5F5F5;
  font-weight: 300;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'Montserrat', sans-serif, Arial;
  padding-bottom: 5px;
  color: #373432;
  line-height: 1em;
  font-weight: normal;
}

a {
  text-decoration: none;
  outline: none;
}

.parallax {
  background-image: url("../Images/back1.jpg");
  min-height: 1000px;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  width: 100%;
}

.logo {
  float: left;
  padding-top: 50px;
  padding-left: 40px;
}

.logo h1 {
  text-transform: uppercase;
  font-weight: 900;
  font-size: 60px;
  letter-spacing: -5px;
  line-height: 50px;
  color: white;
}

.navbar-nav>li>a {
  line-height: 6px;
}

.navbar {
  float: right;
  padding-top: 53px;
  padding-right: 60px;
  font-size: 13px;
  text-transform: uppercase;
}

.navbar-default {
  background-color: transparent;
  border-top: 0px solid rgba(0, 0, 0, 0.5);
  border-bottom: 0px solid rgba(0, 0, 0, 0.5);
  border-left: 0px solid rgba(0, 0, 0, 0.5);
  border-right: 0px solid rgba(0, 0, 0, 0.5);
}

.navbar-default .navbar-nav>li>a {
  color: #ffffff;
}

.navbar-default .navbar-nav>li>a:hover,
.navbar-default .navbar-nav>li>a:focus {
  background-color: #F8BD23;
  text-decoration: none;
  color: #ffffff;
  -webkit-transition: background-color 200ms linear;
  -moz-transition: background-color 200ms linear;
  -o-transition: background-color 200ms linear;
  -ms-transition: background-color 200ms linear;
  transition: background-color 200ms linear;
}

.navbar-nav>li {
  padding-left: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="parallax">
  <div class="logo"><img src="http://placehold.it/50x50"></div>
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button aria-controls="navbar" aria-expanded="false" class="navbar-toggle collapsed" data-target="#navbar" data-toggle="collapse" type="button"><span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span></button>
      </div>
      <div class="navbar-collapse collapse" id="navbar">
        <ul class="nav navbar-nav">
          <li>
            Home
          </li>
          <li>
            a
          </li>
          <li>
            b
          </li>
          <li>
            c Us
          </li>
          <li>
            d
          </li>
          <li>
            e
          </li>
          <li>
            f
          </li>
          <li class="dropdown">
            Classes
            <ul class="dropdown-menu">
              <li>
                a
              </li>
              <li>
                b
              </li>
              <li>
                c
              </li>
              <li>
                d
              </li>
              <li>
                We
              </li>
              <li>
                r
              </li>
              <li>
                a
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <!--/.nav-collapse -->
    </div>
    <!--/.container-fluid -->
  </nav>
  <div class="container">
    <div class="HomeMes">
      <h1>WELCOME</h1>
    </div>
  </div>
</div></code>```

The way I could "fix" it is do margin-top: 200px; on the HomeMes class but I know this is bad coding, so I'm trying to find the right way of doing it. If anyone could let me know what I have done wrong that would be excellent. Thanks.

So it should look like this :

```<code>Logo                                            Navbar

                    Welcome message
</code>```

答:
There you go sir, change your container class to this :

```<code>.container {
  width:100%;
  height:100%;
  display:flex;
  justify-content:center;
  flex-direction: column;
  align-items: center;
}
</code>```

Tested it in chrome and it works, but for some reason it doesn't work in code snippet preview. Hope this helps you. Display:flex helps a lot when trying to horizontally+vertically align elements!

Body:
I recently started to play round with Bootstrap and I created my logo to go on the top left of the page, and then the nav bar to go on the same line but on the right hand side, and then I wanted to say in the middle of the screen: "Welcome blablah"

However, the welcome bit appears on the top part of the screen, rather then the middle, so it's overlapping the logo for some reason.

Not sure why this is doing this, guessing some bad coding etc.

body {
  font-family: 'Open Sans', sans-serif, Arial;
  font-size: 16px;
  color: #6D6D6D;
  background-color: #F5F5F5;
  font-weight: 300;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'Montserrat', sans-serif, Arial;
  padding-bottom: 5px;
  color: #373432;
  line-height: 1em;
  font-weight: normal;
}

a {
  text-decoration: none;
  outline: none;
}

.parallax {
  background-image: url("../Images/back1.jpg");
  min-height: 1000px;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  width: 100%;
}

.logo {
  float: left;
  padding-top: 50px;
  padding-left: 40px;
}

.logo h1 {
  text-transform: uppercase;
  font-weight: 900;
  font-size: 60px;
  letter-spacing: -5px;
  line-height: 50px;
  color: white;
}

.navbar-nav>li>a {
  line-height: 6px;
}

.navbar {
  float: right;
  padding-top: 53px;
  padding-right: 60px;
  font-size: 13px;
  text-transform: uppercase;
}

.navbar-default {
  background-color: transparent;
  border-top: 0px solid rgba(0, 0, 0, 0.5);
  border-bottom: 0px solid rgba(0, 0, 0, 0.5);
  border-left: 0px solid rgba(0, 0, 0, 0.5);
  border-right: 0px solid rgba(0, 0, 0, 0.5);
}

.navbar-default .navbar-nav>li>a {
  color: #ffffff;
}

.navbar-default .navbar-nav>li>a:hover,
.navbar-default .navbar-nav>li>a:focus {
  background-color: #F8BD23;
  text-decoration: none;
  color: #ffffff;
  -webkit-transition: background-color 200ms linear;
  -moz-transition: background-color 200ms linear;
  -o-transition: background-color 200ms linear;
  -ms-transition: background-color 200ms linear;
  transition: background-color 200ms linear;
}

.navbar-nav>li {
  padding-left: 30px;
}

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

        <button aria-controls="navbar" aria-expanded="false" class="navbar-toggle collapsed" data-target="#navbar" data-toggle="collapse" type="button">Toggle navigation   </button>

            Home

            a

            b

            c Us

            d

            e

            f

            Classes

                a

                b

                c

                d

                We

                r

                a

WELCOME

The way I could "fix" it is do margin-top: 200px; on the HomeMes class but I know this is bad coding, so I'm trying to find the right way of doing it. If anyone could let me know what I have done wrong that would be excellent. Thanks.

So it should look like this :

Logo                                            Navbar

                    Welcome message

Body:
There you go sir, change your container class to this :

.container {
  width:100%;
  height:100%;
  display:flex;
  justify-content:center;
  flex-direction: column;
  align-items: center;
}

Tested it in chrome and it works, but for some reason it doesn't work in code snippet preview. Hope this helps you. Display:flex helps a lot when trying to horizontally+vertically align elements!


问:
Add index position Value of an array of array using Linq
We can do sum using arr.Sum() function. But if it is an array of arrays. How will we add all values.
suppose data is
Array/List is  [[1,2,3],[3,4,5],[5,4,3]]
how will you get s1 , sum of all first index value, s2 , sum of second index value and so on using LINQ.

答:
A possible LINQ based approach (which will handle variable number of columns in each row):

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    public class Program
    {
        private static IEnumerable<int> GetTotalsPerColumn(int[][] inputData)
        {
            var data = inputData.SelectMany(z =>
            {
                return z.Select((item, index) => new { item, index });
            })
                .GroupBy(z => z.index)
                .OrderBy(z => z.Key)
                .Select(y => y.Select(z => z.item).Sum()
            );

            return data;
        }

        static void Main(string[] args)
        {
            var inputData = new[] {
                      new[] { 1, 2, 3, 5},
                      new[] { 3, 4, 5, 6},
                      new[] { 5, 4, 3},
                    };

            var values = GetTotalsPerColumn(inputData);

            foreach (var value in values)
            {
                Console.WriteLine(value);
            }

            Console.ReadLine();
        }
    }
}
</code>```

If you are happy to avoid LINQ, this is another approach you could consider.
GetTotalsPerColumn populates a Dictionary where the key is the column number, and the value is the sum.

```<code>using System;
using System.Collections.Generic;

namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            var inputData = new[] {
                  new[] { 1, 2, 3, 5},
                  new[] { 3, 4, 5, 6},
                  new[] { 5, 4, 3},
                };

            var values = GetTotalsPerColumn(inputData);

            foreach (var value in values)
            {
                Console.WriteLine(value.Key + " - " + value.Value);
            }

            Console.ReadLine();
        }

        private static Dictionary<int, int> GetTotalsPerColumn(int[][] inputData)
        {
            var values = new Dictionary<int, int>();

            foreach (var line in inputData)
            {
                for (int i = 0; i < line.Length; i++)
                {
                    int tempValue;

                    values.TryGetValue(i, out tempValue);
                    tempValue += line[i];
                    values[i] = tempValue;
                }
            }
            return values;
        }
    }
}
</code>```

Body:
A possible LINQ based approach (which will handle variable number of columns in each row):

using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    public class Program
    {
        private static IEnumerable<int> GetTotalsPerColumn(int[][] inputData)
        {
            var data = inputData.SelectMany(z =>
            {
                return z.Select((item, index) => new { item, index });
            })
                .GroupBy(z => z.index)
                .OrderBy(z => z.Key)
                .Select(y => y.Select(z => z.item).Sum()
            );

            return data;
        }

        static void Main(string[] args)
        {
            var inputData = new[] {
                      new[] { 1, 2, 3, 5},
                      new[] { 3, 4, 5, 6},
                      new[] { 5, 4, 3},
                    };

            var values = GetTotalsPerColumn(inputData);

            foreach (var value in values)
            {
                Console.WriteLine(value);
            }

            Console.ReadLine();
        }
    }
}

If you are happy to avoid LINQ, this is another approach you could consider.
GetTotalsPerColumn populates a Dictionary where the key is the column number, and the value is the sum.

using System;
using System.Collections.Generic;

namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            var inputData = new[] {
                  new[] { 1, 2, 3, 5},
                  new[] { 3, 4, 5, 6},
                  new[] { 5, 4, 3},
                };

            var values = GetTotalsPerColumn(inputData);

            foreach (var value in values)
            {
                Console.WriteLine(value.Key + " - " + value.Value);
            }

            Console.ReadLine();
        }

        private static Dictionary<int, int> GetTotalsPerColumn(int[][] inputData)
        {
            var values = new Dictionary<int, int>();

            foreach (var line in inputData)
            {
                for (int i = 0; i < line.Length; i++)
                {
                    int tempValue;

                    values.TryGetValue(i, out tempValue);
                    tempValue += line[i];
                    values[i] = tempValue;
                }
            }
            return values;
        }
    }
}


问:
Splitting database data into class and subclass
Say now I have a table in a database, with these fields:

properties

```<code>id
num_bedrooms
num_bathrooms
num_garages
latitude
longitude
street_1
street_2
street_3
suburb
city
region
country
</code>```

Now I would like to CRUD to it from my ASP .Net Core Web API using EF Core. So I create a model for it, but I would like to create a separate class for the address:

```<code>public class Address
{
    [Column("latitude")]
    public double Latitude { get; set; }

    [Column("longitude")]
    public double Longitude { get; set; }

    [Column("street_1")]
    public string Street1 { get; set; }

    [Column("street_2")]
    public string Street2 { get; set; }

    [Column("street_3")]
    public string Street3 { get; set; }

    [Column("suburb")]
    public string Suburb { get; set; }

    [Column("city")]
    public string City { get; set; }

    [Column("region")]
    public string Region { get; set; }

    [Column("country")]
    public string Country { get; set; }
}

public class Property
{
    [Column("num_bedrooms")]
    public int NumBedrooms { get; set; }

    [Column("num_bathrooms")]
    public int NumBathrooms { get; set; }

    [Column("num_garages")]
    public int NumGarages { get; set; }

    public Address StreetAddress { get; set; }
}
</code>```

Is it possible to do something like that? When I try to execute a read against the database in my API controller like this:

```<code>public DbSet<InspectionsData.Models.Property> Properties { get; set; }

// GET: api/Properties
Authorize]
[HttpGet]
public async Task<IActionResult> GetProperty()
{
    return Ok(_context.Properties);
}
</code>```

I get this error:

"The entity type 'Address' requires a primary key to be defined."

Now, I can add an "Id" to the Address class, but it wouldnt really map to anything in the database... Am I doing this right?

答:
Your class Address doesn't have primary key.
You should add property

```<code>[Key]
public int Id {get;set;}
</code>```

or to set already exist property as primary key with [Key]

As I can see also for class Property you will have same message.

Body:
Say now I have a table in a database, with these fields:

properties

id
num_bedrooms
num_bathrooms
num_garages
latitude
longitude
street_1
street_2
street_3
suburb
city
region
country

Now I would like to CRUD to it from my ASP .Net Core Web API using EF Core. So I create a model for it, but I would like to create a separate class for the address:

public class Address
{
    [Column("latitude")]
    public double Latitude { get; set; }

    [Column("longitude")]
    public double Longitude { get; set; }

    [Column("street_1")]
    public string Street1 { get; set; }

    [Column("street_2")]
    public string Street2 { get; set; }

    [Column("street_3")]
    public string Street3 { get; set; }

    [Column("suburb")]
    public string Suburb { get; set; }

    [Column("city")]
    public string City { get; set; }

    [Column("region")]
    public string Region { get; set; }

    [Column("country")]
    public string Country { get; set; }
}

public class Property
{
    [Column("num_bedrooms")]
    public int NumBedrooms { get; set; }

    [Column("num_bathrooms")]
    public int NumBathrooms { get; set; }

    [Column("num_garages")]
    public int NumGarages { get; set; }

    public Address StreetAddress { get; set; }
}

Is it possible to do something like that? When I try to execute a read against the database in my API controller like this:

public DbSet<InspectionsData.Models.Property> Properties { get; set; }

// GET: api/Properties
Authorize]
[HttpGet]
public async Task<IActionResult> GetProperty()
{
    return Ok(_context.Properties);
}

I get this error:

"The entity type 'Address' requires a primary key to be defined."

Now, I can add an "Id" to the Address class, but it wouldnt really map to anything in the database... Am I doing this right?

Body:
Your class Address doesn't have primary key.
You should add property

[Key]
public int Id {get;set;}

or to set already exist property as primary key with [Key]

As I can see also for class Property you will have same message.


问:
upload several files at once
i'm building a website with very simple cms.
I built a form already with an input type="file" already to upload pictures, but the client wants to upload several files at once. So i've looking for and I found the Uploadify, but also found some bugs and i want to try something else.
Any help??

Thanks in advance ;)

答: If they can only use a browser that supports HTML5, I would suggest using the new multiple upload feature.  I would also implement drag-and-drop uploads like gmail has.</p>

Title: upload several files at once


问:
Android Adjusting System Brightness from a Service
I'm relatively new to Android development.  I've been able to adjust screen brightness of my own app by doing things like this:

```<code>WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 0;
getWindow().setAttributes(layout);
</code>```

What I really need to do though is change the screen brightness on a system level.  I'd like to do this from a Service or Intent Service.  The issue I'm running into is that

```<code>getWindow()
</code>```

fails when you call it from a Service.  I think this may be possible through the use of ViewOverlays or something but everything I've tried so far has failed.  Does anyone have an idea?

I need a solution where my app starts a service in the background and then that service adjusts the screen brightness as you use the device in other apps or on the home screen.

答:
You can try this :

```<code>android.provider.Settings.System.putInt(getContentResolver(),
                android.provider.Settings.System.SCREEN_BRIGHTNESS,
                value);
</code>```

add this to manifest

```<code><uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</code>```

and check for run-time permission like this

```<code>   ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_SETTINGS}, 1);
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            switch (requestCode) {
                case 1: {
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        //permission accepted

                    } else {
                        // permission denied,
                    }
                    return;
                }

            }
        }
</code>```

Body:
I'm relatively new to Android development.  I've been able to adjust screen brightness of my own app by doing things like this:

WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 0;
getWindow().setAttributes(layout);

What I really need to do though is change the screen brightness on a system level.  I'd like to do this from a Service or Intent Service.  The issue I'm running into is that

getWindow()

fails when you call it from a Service.  I think this may be possible through the use of ViewOverlays or something but everything I've tried so far has failed.  Does anyone have an idea?

I need a solution where my app starts a service in the background and then that service adjusts the screen brightness as you use the device in other apps or on the home screen.

Body:
You can try this :

android.provider.Settings.System.putInt(getContentResolver(),
                android.provider.Settings.System.SCREEN_BRIGHTNESS,
                value);

add this to manifest

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

and check for run-time permission like this

   ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_SETTINGS}, 1);
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            switch (requestCode) {
                case 1: {
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        //permission accepted

                    } else {
                        // permission denied,
                    }
                    return;
                }

            }
        }


问:
R - recycle NA values for previous non-NA value
I have a data frame called input that looks like the following:

```<code>structure(list(sequence = c("LdBPK_010012800.1", "MAQNDKIAPQDQDSF",
"AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD", "NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ",
"KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG", "APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR",
"LdBPK_020009000.1", "MAQNDKIAPQDQDSF", "AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD",
"NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ", "KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG",
"APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR"), score = c(1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486, 1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486), epitope = structure(c(1L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L), .Label = c("", "Epitope", "Non-Epitope"), class = "factor"),
    positioning = c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE), accessions = c("LdBPK_010012800.1",
    NA, NA, NA, NA, NA, NA, NA, NA, NA, "LdBPK_020009000.1",
    NA, NA, NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA, -20L
), .Names = c("sequence", "score", "epitope", "positioning",
"accessions"), class = "data.frame")
</code>```

(actually my original data frame has over 1 million rows, so this is just a small portion of it)

I want to recycle the non-NA values under input$accessions (starting with  LdBPK_010012800.1) until I found the next non-NA value (considering the present example, LdBPK_020009000.1). Then I would recycle the NA values below LdBPK_020009000.1 until I encounter the next non-NA value, and so on.

After this operation, my new data frame should look like this:

```<code>structure(list(sequence = c("LdBPK_010012800.1", "MAQNDKIAPQDQDSF",
"AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD", "NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ",
"KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG", "APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR",
"LdBPK_020009000.1", "MAQNDKIAPQDQDSF", "AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD",
"NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ", "KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG",
"APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR"), score = c(1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486, 1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486), epitope = structure(c(1L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L), .Label = c("", "Epitope", "Non-Epitope"), class = "factor"),
    positioning = c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE), accessions = c("LdBPK_010012800.1",
    "LdBPK_010012800.1", "LdBPK_010012800.1", "LdBPK_010012800.1",
    "LdBPK_010012800.1", "LdBPK_010012800.1", "LdBPK_010012800.1",
    "LdBPK_010012800.1", "LdBPK_010012800.1", "LdBPK_010012800.1",
    "LdBPK_020009000.1", "LdBPK_020009000.1", "LdBPK_020009000.1",
    "LdBPK_020009000.1", "LdBPK_020009000.1", "LdBPK_020009000.1",
    "LdBPK_020009000.1", "LdBPK_020009000.1", "LdBPK_020009000.1",
    "LdBPK_020009000.1")), row.names = c(NA, -20L), .Names = c("sequence",
"score", "epitope", "positioning", "accessions"), class = "data.frame")
</code>```

I am doing this because my ultimate goal is to use dplyr to group by accessions and get the sum of each group under score

答:
We can use fill

```<code>library(tidyverse)
df1 %>%
    fill(accessions)
</code>```

Body:
I have a data frame called input that looks like the following:

structure(list(sequence = c("LdBPK_010012800.1", "MAQNDKIAPQDQDSF",
"AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD", "NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ",
"KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG", "APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR",
"LdBPK_020009000.1", "MAQNDKIAPQDQDSF", "AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD",
"NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ", "KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG",
"APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR"), score = c(1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486, 1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486), epitope = structure(c(1L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L), .Label = c("", "Epitope", "Non-Epitope"), class = "factor"),
    positioning = c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE), accessions = c("LdBPK_010012800.1",
    NA, NA, NA, NA, NA, NA, NA, NA, NA, "LdBPK_020009000.1",
    NA, NA, NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA, -20L
), .Names = c("sequence", "score", "epitope", "positioning",
"accessions"), class = "data.frame")

(actually my original data frame has over 1 million rows, so this is just a small portion of it)

I want to recycle the non-NA values under input$accessions (starting with  LdBPK_010012800.1) until I found the next non-NA value (considering the present example, LdBPK_020009000.1). Then I would recycle the NA values below LdBPK_020009000.1 until I encounter the next non-NA value, and so on.

After this operation, my new data frame should look like this:

structure(list(sequence = c("LdBPK_010012800.1", "MAQNDKIAPQDQDSF",
"AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD", "NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ",
"KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG", "APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR",
"LdBPK_020009000.1", "MAQNDKIAPQDQDSF", "AQNDKIAPQDQDSFL", "QNDKIAPQDQDSFLD",
"NDKIAPQDQDSFLDD", "DKIAPQDQDSFLDDQ", "KIAPQDQDSFLDDQP", "IAPQDQDSFLDDQPG",
"APQDQDSFLDDQPGV", "PQDQDSFLDDQPGVR"), score = c(1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486, 1, 17007, 12388,
15984, 23405, 31897, 26826, 35239, 35361, 36486), epitope = structure(c(1L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L), .Label = c("", "Epitope", "Non-Epitope"), class = "factor"),
    positioning = c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE), accessions = c("LdBPK_010012800.1",
    "LdBPK_010012800.1", "LdBPK_010012800.1", "LdBPK_010012800.1",
    "LdBPK_010012800.1", "LdBPK_010012800.1", "LdBPK_010012800.1",
    "LdBPK_010012800.1", "LdBPK_010012800.1", "LdBPK_010012800.1",
    "LdBPK_020009000.1", "LdBPK_020009000.1", "LdBPK_020009000.1",
    "LdBPK_020009000.1", "LdBPK_020009000.1", "LdBPK_020009000.1",
    "LdBPK_020009000.1", "LdBPK_020009000.1", "LdBPK_020009000.1",
    "LdBPK_020009000.1")), row.names = c(NA, -20L), .Names = c("sequence",
"score", "epitope", "positioning", "accessions"), class = "data.frame")

I am doing this because my ultimate goal is to use dplyr to group by accessions and get the sum of each group under score

Body:
We can use fill

library(tidyverse)
df1 %>%
    fill(accessions)


问:
Where does notification observers fit in the VIPER pattern?
I am changing my project to VIPER pattern.

I got a lot of observers for my main view. I don't find where should I place my observers in VIPER .

Because i don't want to place my observer in view .
Previously I had separate class for observers and when there use to be notification , I use to update to main view.

But in new VIPER i don't know where is best place.

Should I make new VIPER-N  ? N for notification observations .

答:
Guys if you are confused .
Then put the observers in interactor.

p.s : don't get confused
and then transfer the data received in integrator to presenter to view .

:) :)

Happy viper.