问:
CSS position relative vs absolute
I have the following page (see code snippet below). I would like to position each of the items, so that when it is a full web page, the elements are i their desired positions, but as soon as it is viewed on narrow aspect ratio (e.g. mobile phone), then the items need to fold under each other.

I can get a full web page working, using position: absolute;. I can position the items where I want. But the problem is then on a mobile devise, the items overlap each other. So I figure I need to use position: relative;.

position: relative; allows the items to fold beneath each other on a narrow browser. However, I cannot seem to position the items where I want.

In the below example, I would like to position the items as follows:

```<code>                                    logo
                                    title
    text                                                    screen-print-one
    google apple web                                        screen-print-two

                                             Terms of Service  some@email.com
</code>```

body {
 font-family: "proxima-nova" ,"Helvetica", sans-serif;
}

/* logo */

.wz-logo {
 text-align: center;
 padding: 20px 20px 0px 20px;
}

/* title */

.wz-title {
 font-size: 120%;
 color: #B2D137;
 text-align: center;
 padding: 0 20px 40px 30px;
}

/* text */
.text-description {
 padding-left: 10%;
 padding-bottom: 20px;
 padding-top: 20px;
 width: 500px;
}

/* screen-prints */

.screen-prints {
    position: relative;
 float: right;
 padding-right: 10%;
}

.screen-print1 {
  position: relative;
  top: 100px;
  left: 0;
  z-index: 2;

}

.screen-print2 {
  position: relative;
   top: -430px;
   left: -120px;
 z-index: 1;
}

/* store */

.store-container {
  display: flex;
  justify-content: left;
  align-items: center;
  padding-left: 10%;
}

.store-container .apple, .img-container .google, .img-container .web {

 padding: 10px;
 padding-left: 20px;
}

.store-container .google {
 padding-top: 0px;
 padding-left: 0px;
 padding-right: 0px;
 margin-top: 10px;
}

.store-container .apple {
 padding-top: 8px;
 padding-left: 0px;
 padding-right: 0px;
}

.store-container .web {
 padding-top: 15px;
}

/* footer */

footer .terms, footer .contact {
 display:inline-block;
 padding-bottom: 30px;
 padding-right: 10px;
 padding-left: 10px;
}

footer .contact {
 padding-right: 40px !important;
}

footer a {
 color: white;
 text-decoration: none;
 font-size: 14px;
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

footer {
 position:absolute;
 bottom:0;
 right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body class="background-image">

 <div class="wz-logo">
  logo
 </div>

 <div class="wz-title">
  title
 </div>

 <div class="text-description">
  text
 </div>

   <div class="screen-prints">
  <div class="screen-print1">screen-print-one
  </div>
  <div class="screen-print2">screen-print-two
  </div>
 </div>

 <div class="store-container">
  <div class="google">
   google
  </div>

  <div class="apple">
   apple
  </div>

  <div class="web">
   web
  </div>
 </div>

 <footer>

  <div class="terms">
   Terms of Service
  </div>

  <div class="contact">
   some@email.com
  </div>

 </footer>

</body></code>```

If anyone can assist with how I can position the items, I would appreciate the help. (As you can see my main problem is trying to position the screen-print-one & screen-print-two).

Thanks

答:
hmm there are a bunch of problems with your html logic. too many divs and not wrapped logically . but i made what i could with it

see below. or jsFiddle

.wz-logo,.wz-title {
 width:100%;
 float:left;
 text-align:center;
}

.left_text {
 float:left;width:50%;
}
.left_text .store-container  div{
 display:inline
}
.screen-prints {
 float:right;
 width:50%;
 text-align:right;
}
footer {
 float:left;
 width:100%;
 text-align:right
}
footer div {
 display:inline
}
@media only screen and (max-width: 460px) {

 .left_text,.screen-prints,footer {
  width:100%;
  text-align:center;
 }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body class="background-image">

 <div class="wz-logo">
  logo
 </div>

 <div class="wz-title">
  title
 </div>
<div class="left_text">

 <div class="text-description">
  text
 </div>
  <div class="store-container">
  <div class="google">
   google
  </div>

  <div class="apple">
   apple
  </div>

  <div class="web">
   web
  </div>
 </div>
 </div>
   <div class="screen-prints">
  <div class="screen-print1">screen-print-one
  </div>
  <div class="screen-print2">screen-print-two
  </div>
 </div>

 <footer>

  <div class="terms">
   Terms of Service
  </div>

  <div class="contact">
   some@email.com
  </div>

 </footer>

</body></code>```

i suggest you use bootstrap for responsiveness . it's much easier to use

Title: CSS position relative vs absolute

Body:
I have the following page (see code snippet below). I would like to position each of the items, so that when it is a full web page, the elements are i their desired positions, but as soon as it is viewed on narrow aspect ratio (e.g. mobile phone), then the items need to fold under each other.

I can get a full web page working, using position: absolute;. I can position the items where I want. But the problem is then on a mobile devise, the items overlap each other. So I figure I need to use position: relative;.

position: relative; allows the items to fold beneath each other on a narrow browser. However, I cannot seem to position the items where I want.

In the below example, I would like to position the items as follows:

                                    logo
                                    title
    text                                                    screen-print-one
    google apple web                                        screen-print-two

                                             Terms of Service  some@email.com

body {
 font-family: "proxima-nova" ,"Helvetica", sans-serif;
}

/* logo */

.wz-logo {
 text-align: center;
 padding: 20px 20px 0px 20px;
}

/* title */

.wz-title {
 font-size: 120%;
 color: #B2D137;
 text-align: center;
 padding: 0 20px 40px 30px;
}

/* text */
.text-description {
 padding-left: 10%;
 padding-bottom: 20px;
 padding-top: 20px;
 width: 500px;
}

/* screen-prints */

.screen-prints {
    position: relative;
 float: right;
 padding-right: 10%;
}

.screen-print1 {
  position: relative;
  top: 100px;
  left: 0;
  z-index: 2;

}

.screen-print2 {
  position: relative;
   top: -430px;
   left: -120px;
 z-index: 1;
}

/* store */

.store-container {
  display: flex;
  justify-content: left;
  align-items: center;
  padding-left: 10%;
}

.store-container .apple, .img-container .google, .img-container .web {

 padding: 10px;
 padding-left: 20px;
}

.store-container .google {
 padding-top: 0px;
 padding-left: 0px;
 padding-right: 0px;
 margin-top: 10px;
}

.store-container .apple {
 padding-top: 8px;
 padding-left: 0px;
 padding-right: 0px;
}

.store-container .web {
 padding-top: 15px;
}

/* footer */

footer .terms, footer .contact {
 display:inline-block;
 padding-bottom: 30px;
 padding-right: 10px;
 padding-left: 10px;
}

footer .contact {
 padding-right: 40px !important;
}

footer a {
 color: white;
 text-decoration: none;
 font-size: 14px;
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

footer {
 position:absolute;
 bottom:0;
 right: 0;
}

  logo

  title

  text

screen-print-one

screen-print-two

   google

   apple

   web

   Terms of Service

   some@email.com

If anyone can assist with how I can position the items, I would appreciate the help. (As you can see my main problem is trying to position the screen-print-one & screen-print-two).

Thanks

Body:
hmm there are a bunch of problems with your html logic. too many divs and not wrapped logically . but i made what i could with it

see below. or jsFiddle

.wz-logo,.wz-title {
 width:100%;
 float:left;
 text-align:center;
}

.left_text {
 float:left;width:50%;
}
.left_text .store-container  div{
 display:inline
}
.screen-prints {
 float:right;
 width:50%;
 text-align:right;
}
footer {
 float:left;
 width:100%;
 text-align:right
}
footer div {
 display:inline
}
@media only screen and (max-width: 460px) {

 .left_text,.screen-prints,footer {
  width:100%;
  text-align:center;
 }

}

<body class="background-image">

 <div class="wz-logo">
  logo
 </div>

 <div class="wz-title">
  title
 </div>
<div class="left_text">

 <div class="text-description">
  text
 </div>
  <div class="store-container">
  <div class="google">
   <a href="path to app on play store">google</a>
  </div>

  <div class="apple">
   <a href="path to app on apple store">apple</a>
  </div>

  <div class="web">
   <a href="path to website">web</a>
  </div>
 </div>
 </div>
   <div class="screen-prints">
  <div class="screen-print1">screen-print-one
  </div>
  <div class="screen-print2">screen-print-two
  </div>
 </div>

 <footer>

  <div class="terms">
   <a href="terms.html">Terms of Service</a>
  </div>

  <div class="contact">
   <a href="mailto:some@email.com" target="_top">some@email.com</a>
  </div>

 </footer>

</body>

i suggest you use bootstrap for responsiveness . it's much easier to use


来源: stackexchange

问:
ASP.net Web forms - Page Routing Naming Conflict
I'm rebuilding an old project from asp 4.0 to a 4.52 (moving to bootstrap).
This is a Web Forms website not MVC.
My original version was made with VS2012 and now it's with VS 2015 which chagned a bit for example adding by default the RouteConfig class.

In V4.0 my url formation used to be as follows:

domain.com/nike-shoes

domain.com/nike-shoes/nike-air-pegasus-21-1001

In my new site it does not work because of the "/nike-shoes" duplicity.

Calling "domain.com/nike-shoes/nike-air-pegasus-21" will simply call "domain.com/nike-shoes"

Here is the "new" code:

```<code>Sub Application_Start(sender As Object, e As EventArgs)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
    RegisterRoutes(RouteTable.Routes)
End Sub

Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.MapPageRoute("Nike-Shoes", "nike-shoes", "~/nike-shoes.aspx")
    routes.MapPageRoute("Nike-Shoe", "nike-shoes/{shoe-id}", "~/display-shoe.aspx")
End Sub
</code>```

The old code RegisterRoutes Sub was the same but the Application_Start was different (there was no RouteConfig):`

```<code>Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub
</code>```

Previous version also needed re-routing from /page.aspx to /page which now is by default. Since I do not want to do redirects keeping current url formation is extremely important.

THANKS a lot!

答:
I think you need to have different names for every route name, something like:</p>

```<code>Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.MapPageRoute("Nike-Shoes", "nike-shoes", "~/nike-shoes.aspx")
    routes.MapPageRoute("Nike-Shoes-2", "nike-shoes/{shoe-id}", "~/display-shoe.aspx")
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm rebuilding an old project from asp 4.0 to a 4.52 (moving to bootstrap).
This is a Web Forms website not MVC.
My original version was made with VS2012 and now it's with VS 2015 which chagned a bit for example adding by default the RouteConfig class.

In V4.0 my url formation used to be as follows:

domain.com/nike-shoes

domain.com/nike-shoes/nike-air-pegasus-21-1001

In my new site it does not work because of the "/nike-shoes" duplicity.

Calling "domain.com/nike-shoes/nike-air-pegasus-21" will simply call "domain.com/nike-shoes"

Here is the "new" code:

Sub Application_Start(sender As Object, e As EventArgs)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
    RegisterRoutes(RouteTable.Routes)
End Sub

Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.MapPageRoute("Nike-Shoes", "nike-shoes", "~/nike-shoes.aspx")
    routes.MapPageRoute("Nike-Shoe", "nike-shoes/{shoe-id}", "~/display-shoe.aspx")
End Sub

The old code RegisterRoutes Sub was the same but the Application_Start was different (there was no RouteConfig):`

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub

Previous version also needed re-routing from /page.aspx to /page which now is by default. Since I do not want to do redirects keeping current url formation is extremely important.

THANKS a lot!

Body:
I think you need to have different names for every route name, something like:

Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.MapPageRoute("Nike-Shoes", "nike-shoes", "~/nike-shoes.aspx")
    routes.MapPageRoute("Nike-Shoes-2", "nike-shoes/{shoe-id}", "~/display-shoe.aspx")
End Sub


问:
Is it good practice to unit test properties?
I'm still getting to grips with the whole TDD concept. Should I be writing tests for properties? Should one only write tests on properties containing sufficient logic? Any thoughts or examples on this would be great.</p>

答:
Simple rule of thumb I use when doing TDD: always write tests that fail.

If a test fails at first it's a good test for TDD. It means something is not yet implemented, or not implemented as it should be. Then you can change code to make it pass. A test that succeeds at first is a bad test. You don't even know if it succeeded because you made some mistake writing the test, or because what you are testing is already working.

If you are able to produce a test failure using properties, then write tests for those properties. Typically you should begin by writing a test testing a setter or a getter before implementing it. A not implemented setter or getter can look trivial but makes test fail. And why would you write any line of code even a setter or getter if it's not driven by a test failure ?

Other kinds of tests, like tests as documentation showing how to use an API are also very useful, and good agile practice, but that is not TDD. TDD is about trying actively to break the code until you can't any more. Then you run functional tests and if you pushed unit tests hard enough, and if there is not some integration or system problem going into the way, all should be fine.

ContentLicense: CC BY-SA 2.5


问:
Does rest supports arraylist of objects?
I am having a class BookMain which is returning an arraylist of objects. I am using REST service to get the output, but I am getting an error.

This is my BookMain class:

```<code>@GET
@Path("/get")
@Produces(MediaType.APPLICATION_XML)
public ArrayList<Object> addObjects() {

    Book book = new Book();
    book.setName("The Book");
    book.setAuthor("Author");

    BookStore bookstore = new BookStore();
    bookstore.setName("The Bookstore");
    bookstore.setLocation("UK");

    ArrayList<Object> list = new ArrayList<Object>();
    list.add(book);
    list.add(bookstore);

    return list;
}
</code>```

This is the error which I am getting:

```<code>11 Jul, 2013 3:36:52 PM com.sun.jersey.spi.container.ContainerResponse write
SEVERE: A message body writer for Java class java.util.ArrayList, and Java type java.util.ArrayList<java.lang.Object>, and MIME media type application/xml was not found 11 Jul, 2013 3:36:52 PM com.sun.jersey.spi.container.
ContainerResponse write SEVERE: The registered message body writers
compatible with the MIME media type are:application/xml ->
com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$App
com.sun.jersey.core.impl.provider.entity.DocumentProvider
com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App
com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$App
</code>```

Can anyone provide me a solution for it ?

答:
You can simply use JSONArray to display the result.
Create a JSONArray object and pass the list to the JSONArray() constructor.
Then return the JSONArray object in string format.
Change the return type of your method to String and the flollowing code would work.

Blockquote

JSONArray a=new JSONArray(list);
return a.toString();

Body:
I am having a class BookMain which is returning an arraylist of objects. I am using REST service to get the output, but I am getting an error.

This is my BookMain class:

@GET
@Path("/get")
@Produces(MediaType.APPLICATION_XML)
public ArrayList<Object> addObjects() {

    Book book = new Book();
    book.setName("The Book");
    book.setAuthor("Author");

    BookStore bookstore = new BookStore();
    bookstore.setName("The Bookstore");
    bookstore.setLocation("UK");

    ArrayList<Object> list = new ArrayList<Object>();
    list.add(book);
    list.add(bookstore);

    return list;
}

This is the error which I am getting:

11 Jul, 2013 3:36:52 PM com.sun.jersey.spi.container.ContainerResponse write
SEVERE: A message body writer for Java class java.util.ArrayList, and Java type java.util.ArrayList<java.lang.Object>, and MIME media type application/xml was not found 11 Jul, 2013 3:36:52 PM com.sun.jersey.spi.container.
ContainerResponse write SEVERE: The registered message body writers
compatible with the MIME media type are:application/xml ->
com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$App
com.sun.jersey.core.impl.provider.entity.DocumentProvider
com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App
com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$App

Can anyone provide me a solution for it ?


问:
How to add shadow in dropdown spinner in Android
I am using a Spinner drop down in my Form. But when I drop down my spinner, the color of it is matching to background color. How can I add shadow to my dropdown spinner in Android </p>

答:
Ok, I got the answer, this worked for me</p>

```<code>android:popupBackground="@android:drawable/dialog_holo_light_frame"
</code>```

Body:
Ok, I got the answer, this worked for me

android:popupBackground="@android:drawable/dialog_holo_light_frame"


问:
angular 2 window.open() callback
I opened new window in angular 2 using window.open(MyURL,title,options).
I need a callback when this popup window is closed.
New in angular 2.

Thanks in advance.

答:
You can use the onbeforeunload event

```<code>let myWindow = window.open(MyURL, title, options);
myWindow.onbeforeunload = () => {
  //Do something
}
</code>```

Title: angular 2 window.open() callback

Body:
You can use the onbeforeunload event

let myWindow = window.open(MyURL, title, options);
myWindow.onbeforeunload = () => {
  //Do something
}


问:
Azure Data Factory Test Framework
Are there any automatic testing mechanism available for azure data factory pipelines? Does the azure data factory visual studio project come with any test suite of its own? Any help highly appreciated

Thanks

答:
Not that I'm aware of, but happy to be told otherwise.

I suggest you post this on Microsoft's user voice page as a feedback idea. Then people searching will come here, go to that link and vote to get something developed.

https://feedback.azure.com/forums/270578-data-factory/filters/my_feedback?query=Unit%20Testing%20for%20ADF%20Projects

Hope this helps.

Title: Azure Data Factory Test Framework


问:
How to calculate the area of a polygon on the earth's surface using python?
The title basically says it all. I need to calculate the area inside a polygon on the Earth's surface using Python. Calculating area enclosed by arbitrary polygon on Earth's surface says something about it, but remains vague on the technical details:

If you want to do this with a more
  "GIS" flavor, then you need to select
  an unit-of-measure for your area and
  find an appropriate projection that
  preserves area (not all do). Since you
  are talking about calculating an
  arbitrary polygon, I would use
  something like a Lambert Azimuthal
  Equal Area projection. Set the
  origin/center of the projection to be
  the center of your polygon, project
  the polygon to the new coordinate
  system, then calculate the area using
  standard planar techniques.

So, how do I do this in Python?

答:
Or simply use a library: https://github.com/scisco/area

```<code>from area import area
>>> obj = {'type':'Polygon','coordinates':[[[-180,-90],[-180,90],[180,90],[180,-90],[-180,-90]]]}
>>> area(obj)
511207893395811.06
</code>```

...returns the area in square meters.

Body:
Or simply use a library: https://github.com/scisco/area

from area import area
>>> obj = {'type':'Polygon','coordinates':[[[-180,-90],[-180,90],[180,90],[180,-90],[-180,-90]]]}
>>> area(obj)
511207893395811.06

...returns the area in square meters.


问:
Can i get Unique value of each fingerprint while using TouchID in ios?
I wanted to get unique value of each fingerprint while using TouchID. I'm doing that in swift3.1. Can anyone help me for this?</p>

答: You can't get any unique information about fingerprint while using touchID. Apple doesn't expose that details as of now.</p>


问:
Repository Pattern - Validating Object and Return Message
I'm working on a website, and just trying to get my head around the general structure. I have a database in the background that I'm accessing using the "Repository Pattern". I have the below code in my UserRepository class:

```<code>public bool IsValid(User user)
{
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    Message = "Email address already in use";
    return false;
  }

  return true;
}
</code>```

And that is implemented here

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(User user)
{
  if (ModelState.IsValid)
  {
    var context = new Context("DatabaseContext");
    var userRepo = new UserRepository(context);

    if (userRepo.IsValid(user))
    {
      userRepo.Add(user);
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }
  }

  return View(user);
}
</code>```

My problem is I don't think I'm going around the "message" bit correctly, but I can't find anything online to help me out (specifically around repository). I think I should be changing the return type of IsValid to something like a result (as I've seen with dialog boxes), but again, I'm not sure.

Any help would be much appreciated.

Thanks.

答:
Although the solution provided by above user is good but I don't think you are doing this in right way. This kind of validating email address solution has some cons.

Suppose If email is available(not valid because this is not validity) then you have to return view with error.And what if all input email address is available then the end user will get this error multiple time but the whole view will be rendered in every request and this is not good practice.Always try to use remote validation in this kind of scenario.

Use Remoteattribute on your model properties (email) and try to return availability message dynamically in view through JsonResult.I am giving you this demo example feel free to implement in your code.

```<code>[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public JsonResult IsEmailAvailable(string emailAddress)
{
    if (!_context.Users.Any(c => c.EmailAddress == emailAddress))
    {
         return Json(true, JsonRequestBehavior.AllowGet);
    }
    return Json("Email address already taken" , JsonRequestBehavior.AllowGet);
}
</code>```

The OutputCacheAttribute attribute is required in order to prevent ASP.NET MVC from caching the results of the validation methods.

And decorate your model Email property like this:

```<code>//inside you model.
    [Required]
    [Remote("IsEmailAvailable", "YourControllerName")]
    [RegularExpression(@"Your email address validation regex here", ErrorMessage = "Email address is not valid .")]
    [Editable(true)]
    public string Email{ get; set; }
</code>```

And add this snippet in the Web.config file to allow the use of the Remote attribute:

```<code><appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
</code>```

And remove following code from register action method.

```<code>if (userRepo.IsValid(user))
    {
      userRepo.Add(user); //write this only inside code cause you will always get valid email now.
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }
</code>```

I hope this will work. For more information please read this article. https://msdn.microsoft.com/en-us/library/gg508808(vs.98).aspx

Body:
I'm working on a website, and just trying to get my head around the general structure. I have a database in the background that I'm accessing using the "Repository Pattern". I have the below code in my UserRepository class:

public bool IsValid(User user)
{
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    Message = "Email address already in use";
    return false;
  }

  return true;
}

And that is implemented here

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(User user)
{
  if (ModelState.IsValid)
  {
    var context = new Context("DatabaseContext");
    var userRepo = new UserRepository(context);

    if (userRepo.IsValid(user))
    {
      userRepo.Add(user);
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }
  }

  return View(user);
}

My problem is I don't think I'm going around the "message" bit correctly, but I can't find anything online to help me out (specifically around repository). I think I should be changing the return type of IsValid to something like a result (as I've seen with dialog boxes), but again, I'm not sure.

Any help would be much appreciated.

Thanks.

Body:
Although the solution provided by above user is good but I don't think you are doing this in right way. This kind of validating email address solution has some cons.

Suppose If email is available(not valid because this is not validity) then you have to return view with error.And what if all input email address is available then the end user will get this error multiple time but the whole view will be rendered in every request and this is not good practice.Always try to use remote validation in this kind of scenario.

Use Remoteattribute on your model properties (email) and try to return availability message dynamically in view through JsonResult.I am giving you this demo example feel free to implement in your code.

[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public JsonResult IsEmailAvailable(string emailAddress)
{
    if (!_context.Users.Any(c => c.EmailAddress == emailAddress))
    {
         return Json(true, JsonRequestBehavior.AllowGet);
    }
    return Json("Email address already taken" , JsonRequestBehavior.AllowGet);
}

The OutputCacheAttribute attribute is required in order to prevent ASP.NET MVC from caching the results of the validation methods.

And decorate your model Email property like this:

//inside you model.
    [Required]
    [Remote("IsEmailAvailable", "YourControllerName")]
    [RegularExpression(@"Your email address validation regex here", ErrorMessage = "Email address is not valid .")]
    [Editable(true)]
    public string Email{ get; set; }

And add this snippet in the Web.config file to allow the use of the Remote attribute:

<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

And remove following code from register action method.

if (userRepo.IsValid(user))
    {
      userRepo.Add(user); //write this only inside code cause you will always get valid email now.
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }

I hope this will work. For more information please read this article. https://msdn.microsoft.com/en-us/library/gg508808(vs.98).aspx


问:
how to get get_theme_mod value into array in wordpress?
I want to make an array by theme_mod value in wp theme customizer.

for example in this code:

```<code>$arr = array(com, net, org);
foreach ($arr as &$value) {
    echo "<div id='domain-$value'></div>";
}
</code>```

I have an array like above with some tlds and want to set it dynamically by wp mcomstomizer.

I had a try by put "get_theme_mod( 'tlds' );" (like below) in array but no success and it put all the value in just one array key.

```<code>$arr = array(get_theme_mod( 'tlds' ););
foreach ($arr as &$value) {
    echo "<div id='domain-$value'></div>";
}
</code>```

How to put values into array and separate every array by comma,?

答:
I found the soloution by explode. Thank You</p>

```<code>$tlds = get_theme_mod( 'tlds' );
$arr = explode(', ', $tlds);
foreach ($arr as &$value) {
    echo "<div id='domain-$value' class='col-md-4 col-xs-6 col-xxs-12 otherdomains'></div>";
}
</code>```

Body:
I want to make an array by theme_mod value in wp theme customizer.

for example in this code:

$arr = array(com, net, org);
foreach ($arr as &$value) {
    echo "

";
}

I have an array like above with some tlds and want to set it dynamically by wp mcomstomizer.

I had a try by put "get_theme_mod( 'tlds' );" (like below) in array but no success and it put all the value in just one array key.

$arr = array(get_theme_mod( 'tlds' ););
foreach ($arr as &$value) {
    echo "

";
}

How to put values into array and separate every array by comma,?

Body:
I found the soloution by explode. Thank You

$tlds = get_theme_mod( 'tlds' );
$arr = explode(', ', $tlds);
foreach ($arr as &$value) {
    echo "<div id='domain-$value' class='col-md-4 col-xs-6 col-xxs-12 otherdomains'></div>";
}


问:
javafx deleting contents of an accordion pane
I have an accordion pane which contains three titled panes. I wish to delete these in the java program, however the Accordion object doesn't seem to have a clear or remove method to do this.

I have tried some ways to get around this such as the following:

```<code>    if (!measureAccordion.getChildrenUnmodifiable().isEmpty()) {
        ObservableList<javafx.scene.Node> accordionContent = measureAccordion.getChildrenUnmodifiable();
        accordionContent.clear();
        }
</code>```

But this raised an UnsupportedOperationException.

答: If you check here accordion in javaFX , you will see that the accordion object has a method, getPanes(), which returns an ObservableList of TitledPane. The ObservableList has a lot of methods that you could use such as removeAll. You can see here the documentation for ObservableList.</p>

Body:
I have an accordion pane which contains three titled panes. I wish to delete these in the java program, however the Accordion object doesn't seem to have a clear or remove method to do this.

I have tried some ways to get around this such as the following:

    if (!measureAccordion.getChildrenUnmodifiable().isEmpty()) {
        ObservableList<javafx.scene.Node> accordionContent = measureAccordion.getChildrenUnmodifiable();
        accordionContent.clear();
        }

But this raised an UnsupportedOperationException.


问:
Error: incompatible types: Application cannot be converted to AnalyticsApplication.: Android Studio 2.3.2
I updated my Android Studio to 2.3.2 after which the gradle build fails with the below error:

```<code>error: incompatible types: Application cannot be converted to AnalyticsApplication.
</code>```

I have tried searching about it but could not find anything relevant.

The build.gradle file:

```<code>android {
  compileSdkVersion 25
  buildToolsVersion "25.0.2"

defaultConfig {
    applicationId "com.xxx.xxx"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 17
    versionName "1.6.7"
    multiDexEnabled true
}
</code>```

I am getting error here,

```<code>        // Obtain the shared Tracker instance.
        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        sharedPrefsEditor = sharedPrefs.edit();

        defineFields();

    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

AnalyticApplication.java:

```<code>import android.app.Application;
import android.support.multidex.MultiDexApplication;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

 /**
 * This is a subclass of {@link Application} used to provide shared          objects for this app, such as the {@link Tracker}.*/
    public class AnalyticsApplication extends MultiDexApplication {
    private Tracker mTracker;

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
        // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
        mTracker = analytics.newTracker(R.xml.global_tracker);
     }
        return mTracker;
    }
}
</code>```

答:
I can see that you have used

```<code>import android.support.multidex.MultiDexApplication;
</code>```

As you specifically mentioned being updated the studio version to 2.3, I suggest you have a look to Getting "package android.support.multidex does not exist" after upgrading to Android Studio 2.3

I am not quite sure but this could be the solution to your problem as I myself was having a similar issue after the studio upgrade.
Hope it helps you.

Body:
I updated my Android Studio to 2.3.2 after which the gradle build fails with the below error:

error: incompatible types: Application cannot be converted to AnalyticsApplication.

I have tried searching about it but could not find anything relevant.

The build.gradle file:

android {
  compileSdkVersion 25
  buildToolsVersion "25.0.2"

defaultConfig {
    applicationId "com.xxx.xxx"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 17
    versionName "1.6.7"
    multiDexEnabled true
}

I am getting error here,

        // Obtain the shared Tracker instance.
        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        sharedPrefsEditor = sharedPrefs.edit();

        defineFields();

    } catch (Exception e) {
        e.printStackTrace();
    }

AnalyticApplication.java:

import android.app.Application;
import android.support.multidex.MultiDexApplication;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

 /**
 * This is a subclass of {@link Application} used to provide shared          objects for this app, such as the {@link Tracker}.*/
    public class AnalyticsApplication extends MultiDexApplication {
    private Tracker mTracker;

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
        // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
        mTracker = analytics.newTracker(R.xml.global_tracker);
     }
        return mTracker;
    }
}

Body:
I can see that you have used

import android.support.multidex.MultiDexApplication;

As you specifically mentioned being updated the studio version to 2.3, I suggest you have a look to Getting "package android.support.multidex does not exist" after upgrading to Android Studio 2.3

I am not quite sure but this could be the solution to your problem as I myself was having a similar issue after the studio upgrade.
Hope it helps you.


问:
Firebase Notification in Unity
I'm using Firebase messaging for my Unity project. I saw in Firebase Unity Reference have documentation for Notification.
https://firebase.google.com/docs/reference/unity/class/firebase/messaging/firebase-notification

I'm new in Unity, how can I add the Firebase Notification to the project, so it will push notification when message is received.

答:
I found an answer is to add notification json into POST, so the firebase will push notification when message is received.

```<code>{
"data": {
    "title": "This is my first unity project"
},
"to": "<tokenid>",
"notification": {
    "title": "Your Title",
    "text": "Your Text"
  }
}
</code>```

Title: Firebase Notification in Unity

Body:
I found an answer is to add notification json into POST, so the firebase will push notification when message is received.

{
"data": {
    "title": "This is my first unity project"
},
"to": "<tokenid>",
"notification": {
    "title": "Your Title",
    "text": "Your Text"
  }
}


问:
Build own form in Liferay
How can I build my own form in Liferay? Do I need to first create a hook or portlet and then edit the files there or is there some framework or templates I could use for making a customized form? I just need steps how to approach this, no ready made solutions. Thanks in advance!</p>

答:
You can create a portlet ( LiferayMVC or Spring-MVC ) using JSP, or you create an HTML form using UI taglibs  ...

Exemple:

```<code><aui:form action="<%= myActionURL %>" method="post" name="myForm">
        <aui:input label="My Text Input" name="myTextInput" type="text"
        value='<%= "My Text Value" %>' />

        <aui:button type="submit" />
</aui:form>
</code>```

Please refere to this link : Liferay_HTML_Form

Title: Build own form in Liferay

Body:
You can create a portlet ( LiferayMVC or Spring-MVC ) using JSP, or you create an HTML form using UI taglibs  ...

Exemple:

<aui:form action="<%= myActionURL %>" method="post" name="myForm">
        <aui:input label="My Text Input" name="myTextInput" type="text"
        value='<%= "My Text Value" %>' />

        <aui:button type="submit" />
</aui:form>

Please refere to this link : Liferay_HTML_Form


问:
Basic CSS opacity
I'm using SaaS for building my own webshop. The problem is that i dont know any code. I wish to make my menu bar look more stylish. The SaaS platform offers CSS editing but i can't change the html.
The current menu bar has this css;

```<code>#menu {
  padding: 5px 0 5px 0;
  background: #005775;
  margin: 0 0 8px 0;
}
</code>```

How can I make this better looking. I tried changing the opacity, but every time i add the word opacity the code breaks and the memu disappears.

My current Design looks like this;
http://imgur.com/a/ptSuA
I would really like to make the Menu bar a bit less rough and make it look more friendly.

Sorry for my horrible grammar and lack of knowledge.

答:
try using
background-color:rgba() instead of opacity
this adds transparency to the menu bar.

example

```<code>background-color:rgba(255,0,0,0.5);
</code>```

the last value adds transparency.

Title: Basic CSS opacity

Body:
I'm using SaaS for building my own webshop. The problem is that i dont know any code. I wish to make my menu bar look more stylish. The SaaS platform offers CSS editing but i can't change the html.
The current menu bar has this css;

#menu {
  padding: 5px 0 5px 0;
  background: #005775;
  margin: 0 0 8px 0;
}

How can I make this better looking. I tried changing the opacity, but every time i add the word opacity the code breaks and the memu disappears.

My current Design looks like this;
http://imgur.com/a/ptSuA
I would really like to make the Menu bar a bit less rough and make it look more friendly.

Sorry for my horrible grammar and lack of knowledge.

Body:
try using
background-color:rgba() instead of opacity
this adds transparency to the menu bar.

example

background-color:rgba(255,0,0,0.5);

the last value adds transparency.


问:
Using Distinct with LINQ and Objects
Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.

I now need to have it distinct on a class containing a category and country (both enums). The Distinct isn't working now.

What am I doing wrong?

答:
try an IQualityComparer

```<code>public class MyObjEqualityComparer : IEqualityComparer<MyObj>
{
    public bool Equals(MyObj x, MyObj y)
    {
        return x.Category.Equals(y.Category) &&
               x.Country.Equals(y.Country);
    }

    public int GetHashCode(MyObj obj)
    {
        return obj.GetHashCode();
    }
}
</code>```

then use here

```<code>var comparer = new MyObjEqualityComparer();
myObjs.Where(m => m.SomeProperty == "whatever").Distinct(comparer);
</code>```

Title: Using Distinct with LINQ and Objects

Body:
try an IQualityComparer

public class MyObjEqualityComparer : IEqualityComparer<MyObj>
{
    public bool Equals(MyObj x, MyObj y)
    {
        return x.Category.Equals(y.Category) &&
               x.Country.Equals(y.Country);
    }

    public int GetHashCode(MyObj obj)
    {
        return obj.GetHashCode();
    }
}

then use here

var comparer = new MyObjEqualityComparer();
myObjs.Where(m => m.SomeProperty == "whatever").Distinct(comparer);


问:
Placing UIView To Cover TabBar & NavBar
I am trying to make a popup (UIView) with a transparent background (another UIView). Everything is working fine for the 'popup UIView' but I couldn't figure out how to bring 'transparent background UIView' (above NavigationBar and TabBar).

First I created the UIView in the Storyboard and connected the outlet:

```<code>popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
self.view.addSubview(popupView)
popupView.clipsToBounds = true
popupView.alpha = 0
</code>```

Then, while displaying popupView I am creating the transparent background UIView:

```<code> func clicked() {
    self.popupView.alpha = 1

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let opaqueView = UIView()
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    opaqueView.backgroundColor = UIColor.blackColor()
    opaqueView.alpha = 0.5

    self.view.addSubview(opaqueView)
 }
</code>```

However, the background view doesn't get over NavigationBar or TabBar. I tried this but nothing changes:

```<code>myTabBar.view.bringSubviewToFront(opaqueView)
</code>```

What I want to achieve is that, while having popup UIView at the very front, having opaque UIView over everything including NavBar and TabBar, but behind popup UIView

Update:

Regarding @Alex's answer, with this chunk, I achieved displaying opaqueView over TabBar & NavBar; but now it's also going above the popupView.

```<code>func display() {
   popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
    self.view.addSubview(popupView)
    popupView.clipsToBounds = true

    let opaqueView = UIView()
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    UIApplication.sharedApplication().keyWindow!.insertSubview(opaqueView, belowSubview: popupView)
}
</code>```

How can I place opaqueView below popupView while opaqueView is above everything else?

答:
The view which you want to do transparent, use this

yourView.backgroundColor = UIColor.black.withAlphaComponent(0.7)

Title: Placing UIView To Cover TabBar & NavBar

Body:
I am trying to make a popup (UIView) with a transparent background (another UIView). Everything is working fine for the 'popup UIView' but I couldn't figure out how to bring 'transparent background UIView' (above NavigationBar and TabBar).

First I created the UIView in the Storyboard and connected the outlet:

popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
self.view.addSubview(popupView)
popupView.clipsToBounds = true
popupView.alpha = 0

Then, while displaying popupView I am creating the transparent background UIView:

 func clicked() {
    self.popupView.alpha = 1

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let opaqueView = UIView()
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    opaqueView.backgroundColor = UIColor.blackColor()
    opaqueView.alpha = 0.5

    self.view.addSubview(opaqueView)
 }

However, the background view doesn't get over NavigationBar or TabBar. I tried this but nothing changes:

myTabBar.view.bringSubviewToFront(opaqueView)

What I want to achieve is that, while having popup UIView at the very front, having opaque UIView over everything including NavBar and TabBar, but behind popup UIView

Update:

Regarding @Alex's answer, with this chunk, I achieved displaying opaqueView over TabBar & NavBar; but now it's also going above the popupView.

func display() {
   popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
    self.view.addSubview(popupView)
    popupView.clipsToBounds = true

    let opaqueView = UIView()
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    UIApplication.sharedApplication().keyWindow!.insertSubview(opaqueView, belowSubview: popupView)
}

How can I place opaqueView below popupView while opaqueView is above everything else?


问:
How can I inject an EJB from another application on the same GlassFish Server?
I have two applications running on my local glassfish server. One to rent bicylces and one to buy train tickets. I now wanted to call a remote ejb from the train application to allow the rental of bicycles for the chosen time but I'm not really sure how to do it. I already tried a few different approaches. Both applications are in different packages and the train application has to know the bicycle remote interface but I don't know how to accomplish that.

The remote interface (bicyle app):

```<code>@Remote
public interface FahrradRemote {
    public List<Fahrrad> findAvaible(Date start, Date end);
    public void addAuftrag(Fahrrad fahrrad, Date startDate, Date endDate);
    public boolean login(String name, String passwort);
}
</code>```

Bicycle EJB I want to call:

```<code>@Stateless(name="FahrradService",mappedName="FahrradService")
public class FahrradService implements javax.ejb.SessionBean, FahrradRemote, Serializable {

    @PersistenceContext
    private EntityManager em;
    Kunde customer;
...
}
</code>```

Beginning of the train app:

```<code>@Named
@SessionScoped
public class BahnPM implements Serializable {

    private String startStation;
    private String zielStation;
    private String loginName;
    private String loginPasswort;
    private String customerName;
    private String startDateString;
    private Date startDate;
    private List<Fahrt> available;
    private List stations;

    @EJB
    private BahnService service;

    @EJB(mappedName="FahrradService")
    private static FahrradRemote fahrradService;

    public BahnPM() {
    }

    ...
}
</code>```

Error I get is a class not found exception, which i can understand because it's a different application and my train app doesn't know "FahrradRemote" but how can I inject that EJB?

答:
We've made the same example work in two servers: Glassfish 4.1.1 and Websphere Traditional 8.5.5.5

In both cases we deployed two independent packages:

A war with a servlet,

And a jar with an EJB.

The servlet injects the EJB via the remote interface with @EJB without any parameter for the injection point. This worked in Glassfish. However, to make it work in Websphere we had to include the following explicit lookup in the injection point @EJB(lookup="java:global/ejbBasico/NewSessionBean")

Glassfish Servlet snippet:

```<code>/*imports omitted */
@WebServlet(name = "MiServlet", urlPatterns = {"/MiServlet"})
public class Servlet extends HttpServlet {

   @EJB
   private Interfaz miEjb;
   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
       PrintWriter out = response.getWriter();
       try {
           out.println("Result: " + miEjb.businessMethod());
       }
       finally {
        out.close();
    }
 /*Additional servlet code not included*/
}
</code>```

Glassfish EJB snippet:

```<code>/*imports omitted */
@Stateless
public class NewSessionBean implements Interfaz {
    @Override
    public String businessMethod() {
        return("You've called the EJB");
    }
}
</code>```

Interface:

```<code>/*imports omitted */
@Remote
public interface Interfaz {
    String businessMethod();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two applications running on my local glassfish server. One to rent bicylces and one to buy train tickets. I now wanted to call a remote ejb from the train application to allow the rental of bicycles for the chosen time but I'm not really sure how to do it. I already tried a few different approaches. Both applications are in different packages and the train application has to know the bicycle remote interface but I don't know how to accomplish that.

The remote interface (bicyle app):

@Remote
public interface FahrradRemote {
    public List<Fahrrad> findAvaible(Date start, Date end);
    public void addAuftrag(Fahrrad fahrrad, Date startDate, Date endDate);
    public boolean login(String name, String passwort);
}

Bicycle EJB I want to call:

@Stateless(name="FahrradService",mappedName="FahrradService")
public class FahrradService implements javax.ejb.SessionBean, FahrradRemote, Serializable {

    @PersistenceContext
    private EntityManager em;
    Kunde customer;
...
}

Beginning of the train app:

@Named
@SessionScoped
public class BahnPM implements Serializable {

    private String startStation;
    private String zielStation;
    private String loginName;
    private String loginPasswort;
    private String customerName;
    private String startDateString;
    private Date startDate;
    private List<Fahrt> available;
    private List stations;

    @EJB
    private BahnService service;

    @EJB(mappedName="FahrradService")
    private static FahrradRemote fahrradService;

    public BahnPM() {
    }

    ...
}

Error I get is a class not found exception, which i can understand because it's a different application and my train app doesn't know "FahrradRemote" but how can I inject that EJB?

Body:
We've made the same example work in two servers: Glassfish 4.1.1 and Websphere Traditional 8.5.5.5

In both cases we deployed two independent packages:

A war with a servlet,

And a jar with an EJB.

The servlet injects the EJB via the remote interface with @EJB without any parameter for the injection point. This worked in Glassfish. However, to make it work in Websphere we had to include the following explicit lookup in the injection point @EJB(lookup="java:global/ejbBasico/NewSessionBean")

Glassfish Servlet snippet:

/*imports omitted */
@WebServlet(name = "MiServlet", urlPatterns = {"/MiServlet"})
public class Servlet extends HttpServlet {

   @EJB
   private Interfaz miEjb;
   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
       PrintWriter out = response.getWriter();
       try {
           out.println("Result: " + miEjb.businessMethod());
       }
       finally {
        out.close();
    }
 /*Additional servlet code not included*/
}

Glassfish EJB snippet:

/*imports omitted */
@Stateless
public class NewSessionBean implements Interfaz {
    @Override
    public String businessMethod() {
        return("You've called the EJB");
    }
}

Interface:

/*imports omitted */
@Remote
public interface Interfaz {
    String businessMethod();
}


答:
When you added opacity to #menu, it affect on All his Childrens and menu disappears.you must use of background-color:rgba() or background-color:hsla()

```<code>#005775 = rgba(0, 87, 117, 1.0)
#005775 = hsla(195, 100%, 23%, 1.0)
</code>```

So :

#menu {
  width: 200px;
  height: 200px;
  padding: 5px 0 5px 0;
  margin: 0 0 8px 0;
  background:rgba(0, 87, 117, 0.3);/*/ I use 0.3 /*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu">I Am Menu</div></code>```

Title: Basic CSS opacity

Body:
When you added opacity to #menu, it affect on All his Childrens and menu disappears.you must use of background-color:rgba() or background-color:hsla()

#005775 = rgba(0, 87, 117, 1.0)
#005775 = hsla(195, 100%, 23%, 1.0)

So :

#menu {
  width: 200px;
  height: 200px;
  padding: 5px 0 5px 0;
  margin: 0 0 8px 0;
  background:rgba(0, 87, 117, 0.3);/*/ I use 0.3 /*/
}

<div id="menu">I Am Menu</div>


答: Accordion is a control that can contain only TitledPane components. So if you want to modify content of Accordion then use Accordion#getPanes method.

Title: javafx deleting contents of an accordion pane


问:
Tool for Azure SQL data warehouse sync
I'm looking to automatically synchronise the data from an Azure SQL database to an Azure SQL data warehouse. It probably only needs to be inserting rather than updating, it will involve 25-35 tables and several million records in a few of the tables. (later on once the data is synced we may delete synced records from the source.)

Can anyone recommend some tools or approaches that could do this, suiting most of the requirements above?

I've looked at Data factory but that does not seem suited to incremental loads

答:
The on-premise way would be a SQL Server Integration Services project. This would allow you to copy data both incrementally and in bulk, with any required transformations. Also see data flow documentation.

As noted by Peter Bons, this is not directly supported on the Azure platform.
If you have a license for SQL server available, you can set up an Azure VM with SQL Server and SSIS.

For further discussion see

Why windows azure does not support SSIS?

Running SSIS packages in Azure

One note in those other questions is:

If you use Amazon Web Services, even the free version of the service
  allows you to create Ms SQL Server databases in the cloud that have
  the SSIS catalog and the Server Agent available

I can't vouch for that, but if a full SQL Server license is not something that is available, you might want to try it.

Title: Tool for Azure SQL data warehouse sync


问:
How to implement this constraint in Python with Gurobi?
I have an expression given below and i was wondering if you can help me to formalize as an ILP constraint in order to solve by Gurobi optimizer (Python):

forall ( y in Y), forall (j in M), forall (x in X):
 IF r[x][y] = 1 and c[y,j] = 1 THEN p[x,a] = 1 , forall (a in {U[j],...,W[j] - 1} )
Where:
r[x][y], c[y,j] and p[x,a] are 3 binary variables;
U[j] and W[j] are 2 positive integer variables, where U[j] + beta = W[j]
(beta is a positive constant)

I know that this constraint can be written  as a logical implication in conjunctive normal form: x ∧ y → z
I have already tried this solution: z≥x+y−1  together with several other possibilities :(
But, i had an error with Gurobi solver

My Python code for this constraint is as follows:

for y in Y:

for j in M:

for x in X:

for a in range(int(U[j]),int(W[j])):

M1.addConstr(r[x][y] + c[y,j] - 1 <=  p[x,a], 'TileRequirement_%s_%s_%s_%s'%(y,j,x,a))

I always get the error in this line: for a in range(int(U[j]),int(W[j])):, because both U[j] and W[j] are defined as positive integer variables
So, can someone help me ?
Thanks :)

Best regards
Khadija

答:
You can't build constraints based on yet-to-optimize variables like in:

```<code>for a in range(int(U[j]),int(W[j]))  # optimized value unknown @ build-constr-time
</code>```

Casting like that looks also dangerous and it solely depends on gurobipy, if that's possible in general (but not helping here).

Your question is hard to read and there is no information about the motivation for these constraints, but the general idea could be:

get rid of the range defined by U[j] and W[j]

formulate your constraint for the full-range

with one modification:

introduce one more activating-variable a:

(x^y)->z becomes: (a^x^y)->z == !a v !x v !y v z

as linear expression: (1-a) + (1-x) + (1-y) + z >= 1

now use the concept of indicator-variables to formulate your activating-variables

Yes, it's messy and because of this (and because information is sparse) i won't post a full solution.

Body:
You can't build constraints based on yet-to-optimize variables like in:

for a in range(int(U[j]),int(W[j]))  # optimized value unknown @ build-constr-time

Casting like that looks also dangerous and it solely depends on gurobipy, if that's possible in general (but not helping here).

Your question is hard to read and there is no information about the motivation for these constraints, but the general idea could be:

get rid of the range defined by U[j] and W[j]

formulate your constraint for the full-range

with one modification:

introduce one more activating-variable a:

(x^y)->z becomes: (a^x^y)->z == !a v !x v !y v z

as linear expression: (1-a) + (1-x) + (1-y) + z >= 1

now use the concept of indicator-variables to formulate your activating-variables

Yes, it's messy and because of this (and because information is sparse) i won't post a full solution.


问:
Open Graph Object Debugger does not match Facebook Share from site
I am implementing a facebook share button in an angularjs app and after doing all the necessary stuff to get my meta tags updated and read by Facebook's crawler, I am seeing a mismatch between Facebook's debugger tool and what the share dialog shows.

If I run the debugger on my link, I get a successful scrape that pulls all of the meta tag content and shows what the share dialog should look like. Then if I click on the preview to see that actual share dialog, I get a different result as if it is not reading the meta tag content. The same goes for the share button on my actual website.

Any thoughts?

答: This might be an issue with protocol inconsistancy. Check you're not using http:// on the debugger, vs https:// on the actual site, and vice versa. Ensure all of your og tags have the correct protocol set, and that the protocol is not omitted.</p>


问:
How to avoid default secret being attached to ServiceAccount?
I'm trying to create a service account with either no secrets or just secret I specify and the kubelet always seems to be attaching the default secret no matter what.

Service Account definition

```<code>apiVersion: v1
automountServiceAccountToken: false
kind: ServiceAccount
metadata:
  name: test
secrets:
  - name: default-token-4pbsm
</code>```

Submit

```<code>$ kubectl create -f service-account.yaml
serviceaccount "test" created
</code>```

Get

```<code>$ kubectl get -o=yaml serviceaccount test
apiVersion: v1
automountServiceAccountToken: false
kind: ServiceAccount
metadata:
  creationTimestamp: 2017-05-30T12:25:30Z
  name: test
  namespace: default
  resourceVersion: "31414"
  selfLink: /api/v1/namespaces/default/serviceaccounts/test
  uid: 122b0643-4533-11e7-81c6-42010a8a005b
secrets:
- name: default-token-4pbsm
- name: test-token-5g3wb
</code>```

As you can see above the test-token-5g3wb was automatically created & attached to the service account without me specifying it.

As far as I understand the automountServiceAccountToken only affects mounting of those secrets to a pod which was launched via that service account. (?)

Is there any way I can avoid that default secret being ever created and attached?

Versions

```<code>$ kubectl version
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T20:41:24Z", GoVersion:"go1.8.1", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:33:17Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
</code>```

答:
Your understanding of automountServiceAccountToken is right it is for pod that will be launched.

The automatic token addition is done by Token controller. Even if you edit the config to delete the token it will be added again.

You must pass a service account private key file to the token controller in the controller-manager by using the --service-account-private-key-file option. The private key will be used to sign generated service account tokens. Similarly, you must pass the corresponding public key to the kube-apiserver using the --service-account-key-file option. The public key will be used to verify the tokens during authentication.

Above is taken from k8s docs. So try not passing those flags, but not sure how to do that. But I not recommending doing that.

Also this doc you might helpful.

Body:
I'm trying to create a service account with either no secrets or just secret I specify and the kubelet always seems to be attaching the default secret no matter what.

Service Account definition

apiVersion: v1
automountServiceAccountToken: false
kind: ServiceAccount
metadata:
  name: test
secrets:
  - name: default-token-4pbsm

Submit

$ kubectl create -f service-account.yaml
serviceaccount "test" created

Get

$ kubectl get -o=yaml serviceaccount test
apiVersion: v1
automountServiceAccountToken: false
kind: ServiceAccount
metadata:
  creationTimestamp: 2017-05-30T12:25:30Z
  name: test
  namespace: default
  resourceVersion: "31414"
  selfLink: /api/v1/namespaces/default/serviceaccounts/test
  uid: 122b0643-4533-11e7-81c6-42010a8a005b
secrets:
- name: default-token-4pbsm
- name: test-token-5g3wb

As you can see above the test-token-5g3wb was automatically created & attached to the service account without me specifying it.

As far as I understand the automountServiceAccountToken only affects mounting of those secrets to a pod which was launched via that service account. (?)

Is there any way I can avoid that default secret being ever created and attached?

Versions

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T20:41:24Z", GoVersion:"go1.8.1", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:33:17Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}


问:
'Column Chooser' doesn't show columns anymore
Suddenly the column chooser (in executing application) stopped showing available columns in GridControl. I re-installed the application on the client machine but I still have the same issue.</p>

答: Check that the generateMember-property is set to true for the columns in the designer.</p>


问:
On click of each row,corresponding row data should get print in Angular js

Hello friends, I am new in angular js.I need help to print the each
row's data on click of button assigned to each row. Below is my
code.

HTML code:

List item

enter code here

```<code><div class="jumbotron">
  <table border='1'>
    <tr ng-show="reports.length!=0" ng-repeat="report in reports">

      <td>{{report.first_name}}</td>
      <td>{{report.emp_id}}</td>
      <td>{{report.month_calendar_days}}</td>
      <td>{{report.pay_days}}</td>
      <td>{{report.paid_days}}</td>
      <td> 5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}</td>
      <td><button ng-click="PrintRow()">Print Row</button></td>
    </tr>

  </table>
</div>   </div>
</code>```

Controller Code:

    angular.module('app', [])

```<code>.controller('mainController', ['$scope', '$filter', function($scope,
$filter) {
    $scope.noAlphabetSortPlease = function(obj){
      return Object.keys(obj);
    }
     $scope.reports = [{"emp_id":"10001","first_name":"siva","status":1,"month_calendar_days":29,"pay_days":29,"paid_days":21,"salary_head_value1":0,"salary_head_value2":7550,"salary_head_value3":1600,"salary_head_value4":1800,"salary_head_value5":345,"salary_head_value6":6400,"salary_head_value7":5000,"salary_head_value8":31955,"salary_head_value9":1250,"salary_head_value10":12000,"salary_head_value11":6000,"salary_head_value12":47900,"salary_head_value13":15945,"salary_head_value14":4000,"salary_head_value15":2400},
{"emp_id":"10002","first_name":"naren","status":1,"month_calendar_days":29,"pay_days":29,"paid_days":21,"salary_head_value1":15501,"salary_head_value2":7551,"salary_head_value3":1601,"salary_head_value4":1801,"salary_head_value5":346,"salary_head_value6":6401,"salary_head_value7":5001,"salary_head_value8":31957,"salary_head_value9":1251,"salary_head_value10":12001,"salary_head_value11":6001,"salary_head_value12":47907,"salary_head_value13":15950,"salary_head_value14":4001,"salary_head_value15":2401},
{"emp_id":"10003","first_name":"Bhaki","status":1,"month_calendar_days":29,"pay_days":29,"paid_days":21,"salary_head_value1":15502,"salary_head_value2":7552,"salary_head_value3":1602,"salary_head_value4":1802,"salary_head_value5":347,"salary_head_value6":6402,"salary_head_value7":5002,"salary_head_value8":31959,"salary_head_value9":1252,"salary_head_value10":12002,"salary_head_value11":6002,"salary_head_value12":47914,"salary_head_value13":15955,"salary_head_value14":4002,"salary_head_value15":2402}];

  $scope.PrintRow=function($index){          window.print();
            }   }]); </script>
</code>```

答:
Pass the corresponding object to the function call and overide your reports variable.

```<code><tr ng-show="reports.length!=0" ng-repeat="report in reports">

      <td>{{report.first_name}}</td>
      <td>{{report.emp_id}}</td>
      <td>{{report.month_calendar_days}}</td>
      <td>{{report.pay_days}}</td>
      <td>{{report.paid_days}}</td>
      <td> 5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}</td>
      <td><button ng-click="PrintRow(report)">Print Row</button></td>
    </tr>

  $scope.PrintRow=function(obj){
    $scope.reports=[];
    $scope.reports.push(obj);
            }
</code>```

Or If you want all data to persist and want to print the corresponding data of each row below the new table.Then you could do something like this

```<code><tr ng-show="reports.length!=0" ng-repeat="report in reports">

      <td>{{report.first_name}}</td>
      <td>{{report.emp_id}}</td>
      <td>{{report.month_calendar_days}}</td>
      <td>{{report.pay_days}}</td>
      <td>{{report.paid_days}}</td>
      <td> 5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}</td>
      <td><button ng-click="PrintRow(report)">Print Row</button></td>
    </tr>
</code>```

{{newArray}}

```<code>$scope.newArray=[];
  $scope.PrintRow=function(obj){
    $scope.newArray.push(obj);
            }
</code>```

Format new array to your desire.

```<code>  <tr ng-show="reports.length!=0" ng-repeat="report in newArray">

      <td>{{report.first_name}}</td>
      <td>{{report.emp_id}}</td>
      <td>{{report.month_calendar_days}}</td>
      <td>{{report.pay_days}}</td>
      <td>{{report.paid_days}}</td>
      <td> 5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}</td>
      <td><button ng-click="PrintRow(report)">Print Row</button></td>
    </tr>
</code>```

Body:
Hello friends, I am new in angular js.I need help to print the each
row's data on click of button assigned to each row. Below is my
code.

HTML code:

List item

enter code here

      {{report.first_name}}
      {{report.emp_id}}
      {{report.month_calendar_days}}
      {{report.pay_days}}
      {{report.paid_days}}
       5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}
      <button ng-click="PrintRow()">Print Row</button>

Controller Code:

    angular.module('app', [])

.controller('mainController', ['$scope', '$filter', function($scope,
$filter) {
    $scope.noAlphabetSortPlease = function(obj){
      return Object.keys(obj);
    }
     $scope.reports = [{"emp_id":"10001","first_name":"siva","status":1,"month_calendar_days":29,"pay_days":29,"paid_days":21,"salary_head_value1":0,"salary_head_value2":7550,"salary_head_value3":1600,"salary_head_value4":1800,"salary_head_value5":345,"salary_head_value6":6400,"salary_head_value7":5000,"salary_head_value8":31955,"salary_head_value9":1250,"salary_head_value10":12000,"salary_head_value11":6000,"salary_head_value12":47900,"salary_head_value13":15945,"salary_head_value14":4000,"salary_head_value15":2400},
{"emp_id":"10002","first_name":"naren","status":1,"month_calendar_days":29,"pay_days":29,"paid_days":21,"salary_head_value1":15501,"salary_head_value2":7551,"salary_head_value3":1601,"salary_head_value4":1801,"salary_head_value5":346,"salary_head_value6":6401,"salary_head_value7":5001,"salary_head_value8":31957,"salary_head_value9":1251,"salary_head_value10":12001,"salary_head_value11":6001,"salary_head_value12":47907,"salary_head_value13":15950,"salary_head_value14":4001,"salary_head_value15":2401},
{"emp_id":"10003","first_name":"Bhaki","status":1,"month_calendar_days":29,"pay_days":29,"paid_days":21,"salary_head_value1":15502,"salary_head_value2":7552,"salary_head_value3":1602,"salary_head_value4":1802,"salary_head_value5":347,"salary_head_value6":6402,"salary_head_value7":5002,"salary_head_value8":31959,"salary_head_value9":1252,"salary_head_value10":12002,"salary_head_value11":6002,"salary_head_value12":47914,"salary_head_value13":15955,"salary_head_value14":4002,"salary_head_value15":2402}];

  $scope.PrintRow=function($index){          window.print();
            }   }]); </script>

Body:
Pass the corresponding object to the function call and overide your reports variable.

<tr ng-show="reports.length!=0" ng-repeat="report in reports">

      <td>{{report.first_name}}</td>
      <td>{{report.emp_id}}</td>
      <td>{{report.month_calendar_days}}</td>
      <td>{{report.pay_days}}</td>
      <td>{{report.paid_days}}</td>
      <td> 5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}</td>
      <td><button ng-click="PrintRow(report)">Print Row</button></td>
    </tr>

  $scope.PrintRow=function(obj){
    $scope.reports=[];
    $scope.reports.push(obj);
            }

Or If you want all data to persist and want to print the corresponding data of each row below the new table.Then you could do something like this

<tr ng-show="reports.length!=0" ng-repeat="report in reports">

      <td>{{report.first_name}}</td>
      <td>{{report.emp_id}}</td>
      <td>{{report.month_calendar_days}}</td>
      <td>{{report.pay_days}}</td>
      <td>{{report.paid_days}}</td>
      <td> 5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}</td>
      <td><button ng-click="PrintRow(report)">Print Row</button></td>
    </tr>

{{newArray}}

$scope.newArray=[];
  $scope.PrintRow=function(obj){
    $scope.newArray.push(obj);
            }

Format new array to your desire.

  <tr ng-show="reports.length!=0" ng-repeat="report in newArray">

      <td>{{report.first_name}}</td>
      <td>{{report.emp_id}}</td>
      <td>{{report.month_calendar_days}}</td>
      <td>{{report.pay_days}}</td>
      <td>{{report.paid_days}}</td>
      <td> 5" ng-repeat="key in noAlphabetSortPlease(report)" style="padding-left:10px;">{{report[key]}}</td>
      <td><button ng-click="PrintRow(report)">Print Row</button></td>
    </tr>


问:
FB Graph Error: "(#100) User must be on whitelist"
I'm calling

```<code>https://graph.facebook.com/{the id of one of my app's actions}
</code>```

and getting the following response body:

```<code>{
  "error": {
    "message": "(#100) User must be on whitelist",
    "type": "OAuthException",
    "code": 100
  }
}
</code>```

I'm an admin on the app in question.  Anyone have any idea what this error means?

答:
Personally got this issue when requesting insights endpoint:

```<code>https://graph.facebook.com/v2.9/<ad_id>/insights?fields=account_id,account_name,action_values,actions,ad_id,ad_name,adset_id,adset_name,app_store_clicks,buying_type,call_to_action_clicks,campaign_id,campaign_name,canvas_avg_view_percent,canvas_avg_view_time,canvas_component_avg_pct_view,clicks,cost_per_10_sec_video_view,cost_per_action_type,cost_per_estimated_ad_recallers,cost_per_inline_link_click,cost_per_inline_post_engagement,cost_per_total_action,cost_per_unique_action_type,cost_per_unique_click,cost_per_unique_inline_link_click,cpc,cpm,cpp,ctr,date_start,date_stop,deeplink_clicks,estimated_ad_recall_rate,estimated_ad_recallers,frequency,impressions,impressions_dummy,....
</code>```

Finally have find out that the impressions_dummy field was causing the problem, so when have removed it from the request the issue was solved.

Body:
I'm calling

https://graph.facebook.com/{the id of one of my app's actions}

and getting the following response body:

{
  "error": {
    "message": "(#100) User must be on whitelist",
    "type": "OAuthException",
    "code": 100
  }
}

I'm an admin on the app in question.  Anyone have any idea what this error means?

Body:
Personally got this issue when requesting insights endpoint:

https://graph.facebook.com/v2.9/<ad_id>/insights?fields=account_id,account_name,action_values,actions,ad_id,ad_name,adset_id,adset_name,app_store_clicks,buying_type,call_to_action_clicks,campaign_id,campaign_name,canvas_avg_view_percent,canvas_avg_view_time,canvas_component_avg_pct_view,clicks,cost_per_10_sec_video_view,cost_per_action_type,cost_per_estimated_ad_recallers,cost_per_inline_link_click,cost_per_inline_post_engagement,cost_per_total_action,cost_per_unique_action_type,cost_per_unique_click,cost_per_unique_inline_link_click,cpc,cpm,cpp,ctr,date_start,date_stop,deeplink_clicks,estimated_ad_recall_rate,estimated_ad_recallers,frequency,impressions,impressions_dummy,....

Finally have find out that the impressions_dummy field was causing the problem, so when have removed it from the request the issue was solved.


问:
Remove a string in all the languages Android
I have an app with several translations, and I want to delete some strings.

How can I refactor and delete them only once for example in the default strings.xml file and automatically propagate the deletion to the other strings.xml file of other translations?

答:
You can remove all translations by "Translations Editor" in Android Studio.

Select string's key

Click on "Remove key" button

Uncheck all checkboxes in "Delete" dialog

Click "OK" button in "Delete" dialog


问:
Quantize grayscale images
I have grayscale images which I want to quantize to different gray levels.

To be more precise, in the EBImage package, we have a function equalize() which has an argument levels. we can set levels value to 256 or 128 or 64 etc to quantize our grayscale images. (But the equalize() function will perform a histogram equalization of the given grayscale image, which is not preferred for my current situation)

Can somebody suggest a formula or a function which we can use to change the number of gray levels in the given grayscale image.

答:
The default image data representation in EBImage is a continuous range between 0 and 1. In order to quantize an image to a given number of levels, first convert it to integers in the range of 0:(levels-1), and then back to 0:1, as in the quantize function from the following example.

```<code>library(EBImage)

## sample grayscale image
x = readImage(system.file("images", "sample.png", package="EBImage"))

## function for performing image quantization
quantize = function(img, levels) round(img * (levels-1)) / (levels-1)

## quantize the image
y = quantize(x, levels = 8)

## show the result
display(y)
</code>```

Title: Quantize grayscale images

Body:
The default image data representation in EBImage is a continuous range between 0 and 1. In order to quantize an image to a given number of levels, first convert it to integers in the range of 0:(levels-1), and then back to 0:1, as in the quantize function from the following example.

library(EBImage)

## sample grayscale image
x = readImage(system.file("images", "sample.png", package="EBImage"))

## function for performing image quantization
quantize = function(img, levels) round(img * (levels-1)) / (levels-1)

## quantize the image
y = quantize(x, levels = 8)

## show the result
display(y)


问:
Plotting Venn diagram in Jupyter after changes (matplotlib-venn)
By following the commands in the matplotlib-venn README I can produce the initial plots in the examples.  However, when I change the settings of the Venn diagram (label text etc.) I cannot work out how to replot the figure.  Running:

```<code>%matplotlib inline
from matplotlib_venn import venn3
v = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))
</code>```

gives the Venn diagram inline.  I then proceed to change a label

```<code>v.get_label_by_id('100').set_text('Arbitrary1')
</code>```

but I cannot then replot the figure.  I have tried

```<code># from matplotlib import pyplot as plt
plt.plot()
plt.plot(v)
v
v()
</code>```

but I am really feeling around in the dark.  I feel like I am missing something very basic about %matplotlib or the matplotlib plot function, but I have not been able to find an answer yet online.

How do I plot this figure again in Jupyter?

答:
If you use fig=plt.figure() to store a reference to figure instance, then you will have access to the figure in future notebook cells. If you don't do this, then you won't be able to access the existing figure in new cells.

So, after you set the label, you would simply need to write fig again afterwards to show the figure again.

Here's a working example:

Cell 1:

```<code>%matplotlib inline
from matplotlib_venn import venn3
import matplotlib.pyplot as plt
fig = plt.figure()
set1 = set(['A', 'B', 'C'])
set2 = set(['A', 'D', 'E'])
set3 = set(['A', 'F', 'B'])

v = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))
</code>```

Cell 2:

```<code>v.get_label_by_id('100').set_text('Arbitrary1')
fig
</code>```

Body:
By following the commands in the matplotlib-venn README I can produce the initial plots in the examples.  However, when I change the settings of the Venn diagram (label text etc.) I cannot work out how to replot the figure.  Running:

%matplotlib inline
from matplotlib_venn import venn3
v = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))

gives the Venn diagram inline.  I then proceed to change a label

v.get_label_by_id('100').set_text('Arbitrary1')

but I cannot then replot the figure.  I have tried

# from matplotlib import pyplot as plt
plt.plot()
plt.plot(v)
v
v()

but I am really feeling around in the dark.  I feel like I am missing something very basic about %matplotlib or the matplotlib plot function, but I have not been able to find an answer yet online.

How do I plot this figure again in Jupyter?

Body:
If you use fig=plt.figure() to store a reference to figure instance, then you will have access to the figure in future notebook cells. If you don't do this, then you won't be able to access the existing figure in new cells.

So, after you set the label, you would simply need to write fig again afterwards to show the figure again.

Here's a working example:

Cell 1:

%matplotlib inline
from matplotlib_venn import venn3
import matplotlib.pyplot as plt
fig = plt.figure()
set1 = set(['A', 'B', 'C'])
set2 = set(['A', 'D', 'E'])
set3 = set(['A', 'F', 'B'])

v = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))

Cell 2:

v.get_label_by_id('100').set_text('Arbitrary1')
fig


问:
IHttpModule inserting an inbound Filter break WCF, how to tweak Content-Length?
In ASP.NET 4.0, I have an IHttpModule that apply a filter on HttpRequest.Filter. As the result, the content stream length is changed, and it breaks WCF with now returns 400 bad request because of the mismatch between the body length and the HTTP headers.

Any idea how to solve this behavior of WCF?

答:
Guess this is for your question:

http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/fa132e84-3e3f-4152-9ffa-3f860a266e9f/


问:
C# Linq - Combobox not filled
I have a problem with the comboBoxContainer. While comboBoxategory and comboBoxMarket are filled, comboBoxContainer is not filled.

selected.Container has the right variable but the combobox doesn't get this variable.

```<code>private void listBoxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        ProductList_Variables selected = ProductList_Variables)listBoxProducts.SelectedItem;

        textBoxProduct.Text = selected.Product;
        comboBoxCategory.SelectedItem = selected.Category;
        comboBoxMarket.SelectedItem = selected.Market;
        comboBoxContainer.SelectedItem = selected.Container;
        textBoxPrice1.Text = selected.Price.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
class ProductList_Variables
{
    public int Id { get; set; }
    public string Product { get; set; }
    public string Category { get; set; }
    public string Size { get; set; }
    public string Market { get; set; }
    public string ProductName { get { return Product + " - " + Category + " - Size: " + Size +", Market: "+ Market; } }
    public string Flavour { get; set; }
    public decimal Price { get; set; }
    public string Container { get; set; }
    public int IdContainer { get; set; }

}
void Fillcombo()// is filling the combobox
{
    try
    {
        using (var db = new GelatoProjectDBEntities())
        {
            var products = (from x in db.ProductsLists
                            select new ProductList_Variables { Id = x.Id, Product = x.Product, Category = x.Category, Size = x.Size, Market = x.Market, Container=x.Container, Price=x.Price, IdContainer=x.IdContainer }
                            ).OrderBy(c => c.Product).ToArray();
            listBoxProducts.Items.AddRange(products);
            listBoxProducts.DisplayMember = "ProductName";
            listBoxProducts.ValueMember = "Id";
            var goods = (from x in db.Goods
                         select new ProductList_Variables { Id = x.Id, Product=x.item, Container = x.item}
                         ).OrderBy(c => c.Product).ToArray();

           comboBoxContainer.Items.AddRange(goods);
           comboBoxContainer.DisplayMember = "Product";
           comboBoxContainer.ValueMember = "Id";
       }
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message);
   }
    }
</code>```

答:
seems your comboBoxContainer is filled with objects, not with strings so when you assign you should match the object.

Try replacing your line

```<code>        comboBoxContainer.SelectedItem = selected.Container;
</code>```

as follows

```<code>        comboBoxContainer.SelectedItem =
            comboBoxContainer.Items.OfType<ProductList_Variables>().SingleOrDefault(x => x.Container == selected.Container);
</code>```

Title: C# Linq - Combobox not filled

Body:
I have a problem with the comboBoxContainer. While comboBoxategory and comboBoxMarket are filled, comboBoxContainer is not filled.

selected.Container has the right variable but the combobox doesn't get this variable.

private void listBoxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        ProductList_Variables selected = ProductList_Variables)listBoxProducts.SelectedItem;

        textBoxProduct.Text = selected.Product;
        comboBoxCategory.SelectedItem = selected.Category;
        comboBoxMarket.SelectedItem = selected.Market;
        comboBoxContainer.SelectedItem = selected.Container;
        textBoxPrice1.Text = selected.Price.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
class ProductList_Variables
{
    public int Id { get; set; }
    public string Product { get; set; }
    public string Category { get; set; }
    public string Size { get; set; }
    public string Market { get; set; }
    public string ProductName { get { return Product + " - " + Category + " - Size: " + Size +", Market: "+ Market; } }
    public string Flavour { get; set; }
    public decimal Price { get; set; }
    public string Container { get; set; }
    public int IdContainer { get; set; }

}
void Fillcombo()// is filling the combobox
{
    try
    {
        using (var db = new GelatoProjectDBEntities())
        {
            var products = (from x in db.ProductsLists
                            select new ProductList_Variables { Id = x.Id, Product = x.Product, Category = x.Category, Size = x.Size, Market = x.Market, Container=x.Container, Price=x.Price, IdContainer=x.IdContainer }
                            ).OrderBy(c => c.Product).ToArray();
            listBoxProducts.Items.AddRange(products);
            listBoxProducts.DisplayMember = "ProductName";
            listBoxProducts.ValueMember = "Id";
            var goods = (from x in db.Goods
                         select new ProductList_Variables { Id = x.Id, Product=x.item, Container = x.item}
                         ).OrderBy(c => c.Product).ToArray();

           comboBoxContainer.Items.AddRange(goods);
           comboBoxContainer.DisplayMember = "Product";
           comboBoxContainer.ValueMember = "Id";
       }
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message);
   }
    }

Body:
seems your comboBoxContainer is filled with objects, not with strings so when you assign you should match the object.

Try replacing your line

        comboBoxContainer.SelectedItem = selected.Container;

as follows

        comboBoxContainer.SelectedItem =
            comboBoxContainer.Items.OfType<ProductList_Variables>().SingleOrDefault(x => x.Container == selected.Container);


问:
Toast on Broadcast receiver
I have a receiver that is called when a sms is sent.
When this happen, I want to show a toast. I know it is not a good practice to show a toast from a receiver, but I would like to know why my code does not work

```<code>public class SmsSentReceiver extends BroadcastReceiver
{

  @Override
  public void onReceive(Context context, Intent intent)
  {
    if (getResultCode() == Activity.RESULT_OK)
      Toast.makeText(context, R.string.sent, Toast.LENGTH_SHORT).show();
    else
      Toast.makeText(context, R.string.error_sending_sms, Toast.LENGTH_LONG).show();
    context.unregisterReceiver(this);
  }

}
</code>```

The receiver receives the event correctly but it does not show none of the toasts.
Instead, if I run the app in debug mode, one of the toasts appear correctly.

Thank you in advance.

答:
Try this:</p>

```<code>Context c;
...
...
....

Toast.makeText(c,"Succesfully Written",Toast.LENGTH_SHORT).show();
</code>```

Title: Toast on Broadcast receiver

Body:
I have a receiver that is called when a sms is sent.
When this happen, I want to show a toast. I know it is not a good practice to show a toast from a receiver, but I would like to know why my code does not work

public class SmsSentReceiver extends BroadcastReceiver
{

  @Override
  public void onReceive(Context context, Intent intent)
  {
    if (getResultCode() == Activity.RESULT_OK)
      Toast.makeText(context, R.string.sent, Toast.LENGTH_SHORT).show();
    else
      Toast.makeText(context, R.string.error_sending_sms, Toast.LENGTH_LONG).show();
    context.unregisterReceiver(this);
  }

}

The receiver receives the event correctly but it does not show none of the toasts.
Instead, if I run the app in debug mode, one of the toasts appear correctly.

Thank you in advance.

Body:
Try this:

Context c;
...
...
....

Toast.makeText(c,"Succesfully Written",Toast.LENGTH_SHORT).show();


问:
Querying rows with coupled conditions
I've got an SQLite table where I store user settings with the following schema :

```<code>CREATE TABLE settings (
  [id] varchar(50) NOT NULL,
  [token] varchar(20) NOT NULL,
  [value] varchar(40) NOT NULL,
  [created] datetime NOT NULL,
  [user_id] INT(10) NOT NULL,
  PRIMARY KEY (id)
);
</code>```

The name of the setting is [token].
The value of the setting is [value].

I'd like to SELECT users who have 2 specific settings (both) :

english speaking users ([token]='language' AND [value]='en'),

subscribed to the newsletter ([token]='newsletter' AND [value]='1'),

So I tried :

```<code>SELECT user_id FROM settings
WHERE
        (token = 'language' AND value = 'en')
    OR  (token = 'newsletter' AND value = 1)
)
GROUP BY user_id
</code>```

But it doesn't work as I get users which ONLY have one of the 2 conditions (I want both).
How can I do?

答:
Simply aggregate your table per user_id and use HAVING to ensure both conditions are met for the user.

```<code>select user_id
from settings
group by user_id
having count(case when token = 'language' and value = 'en' then 1 end) > 0
   and count(case when token = 'newsletter' AND value = 1 then 1 end) > 0
</code>```

You can add a WHERE clause to speed this up, if you like:

```<code>where (token = 'language' and value = 'en') or (token = 'newsletter' AND value = 1)
</code>```

Title: Querying rows with coupled conditions

Body:
I've got an SQLite table where I store user settings with the following schema :

CREATE TABLE settings (
  [id] varchar(50) NOT NULL,
  [token] varchar(20) NOT NULL,
  [value] varchar(40) NOT NULL,
  [created] datetime NOT NULL,
  [user_id] INT(10) NOT NULL,
  PRIMARY KEY (id)
);

The name of the setting is [token].
The value of the setting is [value].

I'd like to SELECT users who have 2 specific settings (both) :

english speaking users ([token]='language' AND [value]='en'),

subscribed to the newsletter ([token]='newsletter' AND [value]='1'),

So I tried :

SELECT user_id FROM settings
WHERE
        (token = 'language' AND value = 'en')
    OR  (token = 'newsletter' AND value = 1)
)
GROUP BY user_id

But it doesn't work as I get users which ONLY have one of the 2 conditions (I want both).
How can I do?

Body:
Simply aggregate your table per user_id and use HAVING to ensure both conditions are met for the user.

select user_id
from settings
group by user_id
having count(case when token = 'language' and value = 'en' then 1 end) > 0
   and count(case when token = 'newsletter' AND value = 1 then 1 end) > 0

You can add a WHERE clause to speed this up, if you like:

where (token = 'language' and value = 'en') or (token = 'newsletter' AND value = 1)


问:
Move imageview smoothly
I am trying to build an app that has an imageview in it. The user can drag the imageview horizontally to some position on screen using below code:

```<code>@Override
    public boolean onTouchEvent(MotionEvent event){
       img.getLocationOnScreen(viewCoords);
       newimgpos[0]=event.getX()-(viewCoords[0]-img.getX());
       img.setX(newimgpos[0]);
    }
</code>```

Now, I want that when user lifts up his finger off the screen, the imageview be moved back to x=0. I can directly set the x coordinate of the imageview to be zero but it looks like a very abrupt change; I want the imageview to move smoothly to x =0. Can this be done? I tried using below logic:

```<code>for(int i= (int)newimgpos[0]; i>=0; i--){
    img.setX(i);
}
</code>```

It moves and I can see the actual movement; still it is not smooth enough.

答: You need to use Animation here. Check the following thread for more info: Android translate animation - permanently move View to new position using AnimationListener</p>

Title: Move imageview smoothly

Body:
I am trying to build an app that has an imageview in it. The user can drag the imageview horizontally to some position on screen using below code:

@Override
    public boolean onTouchEvent(MotionEvent event){
       img.getLocationOnScreen(viewCoords);
       newimgpos[0]=event.getX()-(viewCoords[0]-img.getX());
       img.setX(newimgpos[0]);
    }

Now, I want that when user lifts up his finger off the screen, the imageview be moved back to x=0. I can directly set the x coordinate of the imageview to be zero but it looks like a very abrupt change; I want the imageview to move smoothly to x =0. Can this be done? I tried using below logic:

for(int i= (int)newimgpos[0]; i>=0; i--){
    img.setX(i);
}

It moves and I can see the actual movement; still it is not smooth enough.


问:
Deserializing a JSON file with c#
My problem is
i have this JSON file:

and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException, as if my list is empty. this is my code:

```<code>JavaScriptSerializer ser = new JavaScriptSerializer();
        Causali o = new Causali();
        List<CausaliList> lista = new List<CausaliList>();
        WebRequest causali = (HttpWebRequest)WebRequest.Create("http://trackrest.cgestmobile.it/causali");
        WebResponse risposta = (HttpWebResponse)CreateCausaliRequest(causali).GetResponse();
        Stream data = risposta.GetResponseStream();
        StreamReader Leggi = new StreamReader(data);
        string output = Leggi.ReadToEnd();
        lista = ser.Deserialize<List<CausaliList>>(output);
        lst2.Items.Add(lista[0]);
</code>```

and these are my two class for the saves:

```<code>class Causali
    {
        public int id;
        public string causaliname;
        public string identificationcode;
        public string expired;
    }
</code>```

and

```<code>class CausaliList
    {
        public Causali causali;
    }
</code>```

can you help me solve it?

答:
To deserialize the code in c#:
Lets assume you have data in var getContent then you may use this:</p>

```<code>dynamic getDesearilize = JsonConvert.DeserializeObject(getContent);
</code>```

Title: Deserializing a JSON file with c#

Body:
My problem is
i have this JSON file:

and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException, as if my list is empty. this is my code:

JavaScriptSerializer ser = new JavaScriptSerializer();
        Causali o = new Causali();
        List<CausaliList> lista = new List<CausaliList>();
        WebRequest causali = (HttpWebRequest)WebRequest.Create("http://trackrest.cgestmobile.it/causali");
        WebResponse risposta = (HttpWebResponse)CreateCausaliRequest(causali).GetResponse();
        Stream data = risposta.GetResponseStream();
        StreamReader Leggi = new StreamReader(data);
        string output = Leggi.ReadToEnd();
        lista = ser.Deserialize<List<CausaliList>>(output);
        lst2.Items.Add(lista[0]);

and these are my two class for the saves:

class Causali
    {
        public int id;
        public string causaliname;
        public string identificationcode;
        public string expired;
    }

and

class CausaliList
    {
        public Causali causali;
    }

can you help me solve it?

Body:
To deserialize the code in c#:
Lets assume you have data in var getContent then you may use this:

dynamic getDesearilize = JsonConvert.DeserializeObject(getContent);