text:
Q: For change in entropy dS = dq/T, is T the temperature of system or surrounding or both? For change in entropy dS = dqrev/T, is T the temperature of system or surrounding or both?
I am confused about Thot, Tcold, Tsys and Tsurr.
If qrev, are we talking about the reversible cycle such as the carnot engine?

A: If the heat is transferred reversibly, the temperatures of the two bodies have to be the same. Transfer of heat from hotter to colder body is irreversible.

A: I can't comment, so to reply to your question:

But in a Carnot engine, it involves transfer of heat from a hot reservoir to a cold >reservoir, and the process is reversible. Will you please explain a bit more about that? >Thanks!

Carnot engine involves isothermal and isentropic processes. For the isentropic process, $dS = 0$. For the isothermal process, because $T_{hot} = T_{cold}$, so
$$dS_{tot} = dS_{sys} + dS_{surr}$$
$$dS_{tot} = \frac{Q_{rev}}{T} - \frac{Q_{rev}}{T} = 0$$
Since the same amount of heat gained by system is obtained from surroundings.
For a reversible process, $dS_{tot} = 0$.But it does not mean that no heat transfer has occured.


text:
Q: Redirect Magento user to different store view checkout / product page based on product attribute Is there a way to force a switch to a different store view in Magento when a user clicks on checkout or the product page?
To clarify the issue, let's presume we have 2 different store views in Magento:

*

*One main store view (View A) that all users go to upon arriving to the store. This view displays products that are set to appear in all store views in the system

*One customized store view (View B) that has some specific branding and some other specific settings related to checkout, payment gateways etc.

When the user is browsing products in View A and clicks on either the checkout link or the product page link, we want to redirect them to View B and let them proceed with the checkout in that View.
Is this possible to accomplish in a relatively easy manner, and how?
Thanks.

A: In Magento each store is assigned an interface. An interface can have multiple themes in it. This is what I understand by what you call a View. Your templates can refer to theme1/css or theme2/css to give you different looking View A and View B.
To create a different looking checkout page you will have to code app/design/frontend/myinterface/default/template/checkout/onepage.phtml or whatever to use the appropriate theme1/css or theme2/css to change its look.
If however you are using different interfaces then they can only be assigned to different stores. This would be a multi-store setup. In which case you can change the Checkout button in View A (Store A) to link to View B (Store B). You will also have to write some code to allow automatic population of information for the order from Store A to be passed to Store B.

A: Add a new store config which will store the base url of the product listing store.
We want the user to land on the checkout site home page, that will be the main page and you can override:
/Catalog/Model/Product/Url.php
getProductUrl and getUrl functions

where you would simply string replace the returned parent::getUrl's base url value with the base value in your new config.
Therefore what will happen is when the user clicks on catalog navigation they will be taken to the other store. Finally when they again click back on checkout or any other link that will bring them back to the checkout store.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MKCoordinateSpanMake: why specify longitude AND latitude delta? If the distance corresponding to one degree of longitude is a function of latitude, why do you have to specify longitudeDelta and latitudeDelta when calling MKCoordinateSpanMake in the iOS MapKit? Moreover, how am I supposed to know what the correct ratio is?

A: You don't need to specify both nor do you need to pre-calculate the ratio.
Both parameters are provided as a convenience if you have a previously saved span or you happen to know the exact span you want.
No matter what values you pass, the map view will still adjust the span so that it fits the map view frame and matches the zoom level that it can display.
You can in fact pass 0.0 for either parameter if you only know or care about one of them.  The map view will do the calculations and adjust the span as needed.
To see what the adjusted span will be (or if you want to pre-calculate it), call the regionThatFits: method with a region containing a span such as (10,0).
Also, after calling setRegion:, mapView.region.span will contain the adjusted span as well.


text:
Q: Bézier surfaces patch for a surface It is easy in Mathematica to generate a surface form cubic Bézier patch (as a list of 3D points) by using "BezierFunction"
Example:
pts = {{{0, 0, 0}, {0, 1, 0}, {0, 2, 0}, {0, 3, 0}}, {{1, 0, 0}, {1,
     1, 1}, {1, 2, 1}, {1, 3, 0}},
   {{2, 0, 0}, {2, 1, 1}, {2, 2, 1}, {2, 3, 0}},
   {{3, 0, 0}, {3, 1, 0}, {3, 2, 0}, {3, 3, 0}}};

f = BezierFunction[pts]

Show[Graphics3D[{PointSize[Medium], Red, Map[Point, pts]}],
 Graphics3D[{Gray, Line[pts], Line[Transpose[pts]]}],
 ParametricPlot3D[f[u, v], {u, 0, 1}, {v, 0, 1}, Mesh -> None]]

But now i have an inverse question, if we have a 3D surface, how can we get an cubic Bézier patch basing in it (by some rules)?


text:
Q: Why isn't my cookie being removed? I'm trying to create a persistent cookie (not using the built-in auth) when the user logs in.
The only way I could figure to do this was to create a cookie with an expiry date set to DateTime.Now.AddYears(1)
Since I want to allow the user to log out, I do have a logout button on the layout for every page behind the login form.
This logout button looks like this:
<li>@Html.ActionLink("Log Out", "Logout", "Home")</li>

The confusing thing to me is that this code doesn't get rid of the cookie from the browser. it takes me back to the login form, but I can still easily navigate back to the protected pages and it'll still remember who I am based on my previous login.
Here's my code:
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Login(User model)
    {
        try
        {
            DoLogin(model.EmailAddress, model.Password);
            return Json(new
            {
                Message = "Success",
                IsOK = bool.TrueString
            });
        }
        catch (Exception ex)
        {
            SendError("/", ex);
            return ReportError(ex, "USER LOGIN");
        }
    }

    private void DoLogin(string EmailAddress, string Password)
    {
        var user = db.Users.Include("UserRole").FirstOrDefault(x => x.EmailAddress == EmailAddress);

        if (Hashing.ValidatePassword(Password, user.Password))
            generateCookie(user);
    }

    private void generateCookie(Models.User u)
    {
        HttpCookie userCookie = new HttpCookie("Ortund");
        userCookie.Values["userid"] = Convert.ToString(u.Id);
        userCookie.Values["fname"] = u.FirstName;
        userCookie.Values["lname"] = u.LastName;
        userCookie.Values["role"] = u.UserRole.RoleName;
        userCookie.Expires = DateTime.Now.AddYears(1);
        Response.Cookies.Add(userCookie);
    }

So why isn't this clearing my cookie?
EDIT
So now I've modified my code (see below) as per suggestions in the answers on the question.
I added in a Logout Action on my controller and it does this:
    public ActionResult Logout()
    {
        Session.Clear();
        HttpCookie userCookie = new HttpCookie("Ortund");
        userCookie.Expires = DateTime.Now.AddYears(-1);
        Response.Cookies.Add(userCookie);

        return View("Index");
    }

While my login still appears to work okay, the Request Cookie isn't updating with the new login details. Here's what it looks like after I do the login:
    Request.Cookies["Ortund"] {System.Web.HttpCookie} System.Web.HttpCookie
    Domain null string
    Expires {0001-01-01 12:00:00 AM} System.DateTime
    HasKeys true bool
    HttpOnly false bool
    Name "Ortund" string
    Path "/" string
    Secure false bool
    Shareable false bool

A: You need to write the expired cookie to the Response, not read and set it back to the Request.
var cookie = Request.Cookies["Ortund"];
cookie.Expires = DateTime.Now.AddSeconds(-1);
Response.Cookies.Add(cookie);

I would do some reading on how to implement Forms Authentication in c#. This will give you a better starting point then trying to roll your own authentication cookie which will lead to security holes. The standard forms authentication already has much to offer and a simple API to access it including ways to encrypt the ticket, provide identity information etc.
Alternatively you can also look into asp.net identity. This is Microsoft's newest API to managing identities and providing authentication and authorization. It also integrates with SSO like using Facebook or Microsoft identity stores to authenticate the user.
EDIT - based on request for more information
Here is some sample code using basic built in asp.net forms authentication. This example is cookie based. You would also need to configure the web.config to make use of it. Once this is done the rest happens automatically and you can get the user's information at any time using HttpContext.User.Identity. In the web.config you also need to add your decryption and validation keys.
public sealed class AuthController : Controller
{
    [AllowAnonymous] // get the view to login
    public ActionResult Login()
    {
        return View();
    }
    [HttpPost]
    [AllowAnonymous] // execute a login post
    public ActionResult ExecuteLogin(LoginModel model)
    {
        // validate credentials
        var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddHours(3), model.RememberMe, /*anything else you want stored in the ticket*/ null);
        var encryptedTicket = FormsAuthentication.Encrypt(ticket);
        var isSsl = Request.IsSecureConnection; // if we are running in SSL mode then make the cookie secure only

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            HttpOnly = true, // always set this to true!
            Secure = isSsl,
        };

        if (model.RememberMe) // if the user needs to persist the cookie. Otherwise it is a session cookie
            cookie.Expires = DateTime.Today.AddMonths(3); // currently hard coded to 3 months in the future

        Response.Cookies.Set(cookie);

        return View(); // return something
    }
    [Authorize] // a secured view
    public ActionResult SecuredView() {
        return View();
    }
    [Authorize] // log the user out
    public ActionResult Logout()
    {
        System.Web.Security.FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home");
    }
}

Here is the web.config changes
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
...
  <system.web>
    <authentication mode="Forms">
      <forms name="myAuthCookie" ticketCompatibilityMode="Framework40" cookieless="UseCookies" requireSSL="false" timeout="180" protection="Encryption" />
    </authentication>
    <machineKey decryption="AES" decryptionKey="key here" validation="HMACSHA256" validationKey="validation key here" />
  </system.web>
</configuration>

A: you need to write the cookie again into the browser
HttpCookie userCookie = new HttpCookie("Ortund");
userCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(userCookie);

and not only
Request.Cookies["Ortund"].Expires = DateTime.Now.AddSeconds(1);

a good explanation why, it's in my own answer from same time ago...


text:
Q: show images/blocks horizontally I'm trying to get a div to show images/blocks without overflowing y-axis but overflowing x-axis.
here is my attempt with no luck
http://fiddle.jshell.net/VJX3p/1/

A: Apply white-space: nowrap; style to child div images will align horizontally
#child {
  position:relative;
  background:#fde;
  width:400px;
  height:300px;
  overflow-x:auto;
  white-space: nowrap;
}

A: #parent {
  position:relative;
  background:#fd2;
  width:500px;
  height:350px;
  overflow:hidden;
}
#child {
   position:relative;
  white-space:nowrap;
  background:#fde;
  width:400px;
  height:300px;
  overflow-x:auto;
}

Just so if anyone was interested in knowing the final answer. Thank you all and sreejithsdev white-space: nowrap; is the trick.

A: You can solve this problem with just CSS.  The following code will get the vid to overflow only on the x-axis:
#parent {
  overflow-x: scroll;
}
#child {
  overflow: hidden;
  width: 2650px;
}
img {
  float: left;
  margin-right: 9px;
  display: block;
}

To better explain what is going on, here is my thought process:
1) First we float the images to the left so that they will line up next to each other (only if there is enough space, which we will set later).  I set a margin-right of 9 px to space out the images.  I set the image as display block out of habit (I don't believe it is required).
2) In order to get all the images in one line we either need to give #parent or #child a width of 2650px.  I decide to set #child with 2650px so that I can then set #parent to overflow-x (thus creating the scroll area).  I also have to set overflow: hidden to #child to fix the "clearfix" problem that occurs because all of it's children are floated.
Please note that if you add an image or change the size of the images then you will have to recalculate the width value of #child.  You can do this dynamically on the server side or on the client side through javascript if you're dynamically loading more images.


text:
Q: Adding JAR to eclipse project I am trying to use JTidy on google app engine. In Eclipse, I add JTidy jar to the build path and add the jar again as the source attachment.  When I make a tidy object it shows up as a org.w3c.tidy.Tidy.  but when I run my app i get the error java.lang.NoClassDefFoundError: org/w3c/tidy/Tidy.  Am I not adding the jar correctly?  Does JTidy not work on google app engine?

A: The JAR needs to be added to the lib folder in war/WEB-INF

A: Add the jar to war/WEB-INF/lib  and also right-click on the project, configure build path. Their add external libraries.


text:
Q: How to dynamically add select menu option in Rails Does anyone know if there is a simple solution to dynamically adding new options to a select menu in a form in Rails?
The Dynamic Forms railscast (http://railscasts.com/episodes/403-dynamic-forms) is focused on dynamically filtering a second selet menu based on the selection made in another select menu which is not what I am looking for. I am looking for a solution where the form contains only one select menu and new options can be added to it on the form.
I feel the solution may be similar to that touched upon in the Nested Model Form railscast (http://railscasts.com/episodes/196-nested-model-form-revised) but in that example the form must be submitted before the values are updated in the database. I would like the user to be able to add a new select menu option and then continue with the rest of the form before submitting it.
At this stage I would also like to avoid using the railscast jquery autocomplete solution as this uses a text field rather than a select menu.
Currently I see the solution as having a "Add New" button next to the select menu. When the button is clicked a Modal is opened that allows the user to enter the new select menu option and then save (update the database), the modal is closed and the form is updated. I'm just wondering whether an existing elegant solution is already out there.
Any help would be greatly appreciated.
Thanks.
UPDATE:
I haven't created any code to implement this yet but here is my form:
<%= simple_form_for @other, :html => { :class => 'form-horizontal' } do |f| %>
<fieldset>
  <%= f.error_notification %>
  <%= f.association :other_type, :include_blank => false %>
  <%= f.input :cost%>
  <%= f.input :invoice %>
  <%= f.input :notes, :input_html => {:class => "row-fluid"} %>
<%= f.error :base %>
<div id="eze_form_actions" class="form-actions">
  <%= f.submit nil, :class => 'btn btn-primary' %>
  <%= link_to 'Cancel', others_path, :class => 'btn' %>
</div>
</fieldset>
<% end %>

A: I've done something similar to this in our CMS for categories, users can easily add a new category and we POST to the server, which responds with HTML (render through a partial) and we inject it into our set of checkboxes. You can easily replicate this for your purposes:
To get this to work, you'll need your a form, an endpoint and some javascript:
Form
Not sure what you're form will include, but use regular form helpers and make sure the form is set to remote: true.
End Point
Your endpoint should render a partial, which should only contain the html for the .. which we'll render to a string and pass back to the front-end to be added.
def endpoint
  # create your new model with the params
  @model = Model.create(some: attribute)
  if @model.errors.empty and @model.save
    render json: { html: render_to_string(partial: "path/to/partial", locals: { model: @model })
  end
end

** JavaScript **
$(form)
  .bind('ajax:success', function(data, status) {
    $(select).append(status.html)
  })

status.html should be something like <option>...</option> and so we just append to our select.
Let me know if this doesn't make sense. I hope it helps.


text:
Q: Наследуют ли псевдоклассы правила своих селекторов? Для ссылок задано:
a { text-decoration: none; }

Наследуется ли это правило псевдоклассами селектора (a:hover, a:focus, a:active и пр.)?

A: Селекторы: a, a:hover, a:active и т.п. задают правила на теги a.
Следовательно задав свойство тегу a
a { text-decoration: none; }

и не переопределив его в других селекторах, то оно будет работать и с псевдоселекторами. Это никак не связано с наследованием.

A: Посмотри на пример и сам ответь на свой вопрос наследуют ли ???
Только в данном примере не проверить active, так как он в фокус срабатывает сразу

* {
  margin: 0;
  padding: 0;
}

html,
body {
  width: 100%;
  height: 100%;
  background: #272727;
  perspective: 100px;
  color: white;
}

a {
  display: block;
  width: 100px;
  height: 100px;
  background: red;
  border: 5px solid red;
  margin: auto;
  color: black;
  background: white;
  text-decoration: none;
}

a:hover {
  color: red;
  background: green;
}

a:active {
  color: red;
  background: yellow;
}

a:focus {
  color: black;
  background: orange;
}
я ссылка

A: В чистом css наследуют. Но если подключен внешний css (например bootstrap), то это уже от него зависит.


text:
Q: Received incompatible instance in Graphql query When i hit insomnia with this request bellow then it shows this response. How can i solve this issue?
Request:
query{
    datewiseCoronaCasesList{
        updatedAt,
        affected,
        death,
        recovered
    }
}

Response:
{
    "errors": [
        {
            "message": "Received incompatible instance \"{'updated_at': datetime.date(2020, 4, 8), 'affected': 137, 'death': 42, 'recovered': 104}\"."
        }
    ],
    "data": {
        "datewiseCoronaCasesList": [
            null
        ]
    }
}

My expectation which i have already gotten in errors message but this way:
{
    'updated_at': datetime.date(2020, 4, 8),
    'affected': 137,
    'death': 42,
    'recovered': 104
}

My GraphQL query:
class CoronaQuery(graphene.ObjectType):
    datewise_corona_cases_list = graphene.Field(CoronaCaseType)

    def resolve_datewise_corona_cases_list(self, info, **kwargs):
        return CoronaCase.objects.values('updated_at').annotate(
affected=Sum('affected'),death=Sum('death'), recovered=Sum('recovered'))

My model:
class CoronaCase(models.Model):
    affected = models.IntegerField(default=0)
    death = models.IntegerField(default=0)
    recovered = models.IntegerField(default=0)
    district = models.CharField(max_length=265, null=False, blank=False)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return "Affected from: {}".format(self.district)

A: Under CoronaQuery class, since you are returning a list of objects (instances),  graphene.Field should be changed to graphene.List.
I mean:
class CoronaQuery(graphene.ObjectType):
    datewise_corona_cases_list = graphene.List(CoronaCaseType)


text:
Q: Logstash Filter Http Bad request error (ELK) Below is the code written in logstash. i want to access the API through logstash in schedule of every 1 min and send the data to elasticsearch
input {
exec {
    command => 'bin/true'
    tags => "myaccount_test"
    schedule => "* * * * *"
    }
  }

filter {
if "myaccount_test" in [tags] {
    ruby { code => "event.set('end', event.get('@timestamp').to_i)" }
    ruby { code => "event.set('start', event.get('@timestamp').to_i - 1917)" }
    http {
  body_format => "json"
  follow_redirects => false
  body => {
    "query" => "SELECT pagename AS ErrorPage, referrer AS GeneratedPage, count(*) AS ErrorTraffic FROM browser_records WHERE appkey = 'AAA-AAB-AUB'"
    "start" => "%{start}"
    "end" => "%{end}"
  }
  url => "http://<domainname>:<port>/events/query?limit=200"
  verb => "POST"
  headers => {
    "X-Events-API-AccountName" => "custxxxxx_xxxxxxxxxxxx"
    "X-Events-API-Key" => "xxxxxxx-xxxxxxx-xxxx"
    "Content-type" => "application/vnd.appd.events+json;v=2"
  }
}
}
}

output {
if "myaccount_test" in [tags] {
 stdout { codec => json_lines }
  }
}

But i'm getting error for http filter (Bad request in accessing /events/query
[2020-08-07T16:15:00,165][ERROR][logstash.filters.http    ][main][e70ac31237ba1ca2ac387603953776f0cb06c3aecbd113db0915a1404334ad85] error during HTTP request {:url=>"http://<domainname>:<port>/events/query?limit=200", :code=>400, :response=>"\n\n<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/>\n<title>Error 400 Bad Request</title>\n\n
HTTP ERROR 400
\n
Problem accessing /events/query. Reason:\n
    Bad Request

\n\n\n"}
{"@timestamp":"2020-08-07T12:15:00.041Z","end":1596802500,"start":1596800583,"message":"","@version":"1","command":"bin/true","host":"hostname","tags":["myaccount_test","_httprequestfailure"]}

below is the http request example which im trying to access
POST http://api.example.com/events/query?limit=100 HTTP/1.1
X-Events-API-AccountName:<global_account_name>
X-Events-API-Key:<api_key>
Content-Type: application/vnd.appd.events+json;v=2
Accept: application/vnd.appd.events+json;v=2
[
    {
      "query": "SELECT * FROM county WHERE population>50000",
      "limit": 10,
      "start": "2017-02-23T0:0:0Z",
      "end": "2017-03-1T0:0:0Z"
    },
]

Kindly help


text:
Q: CSS: Any tests on when two classes give an element different values? Here is what I mean:

Lorem ipsum

And in CSS:
.red {
  color: red;
}
.blue {
  color: blue;
}

It is pretty easy to test it yourself in a browser, but I was wondering if there are any existing tests done on a wide range of browsers and mobile devices.
Thanks

A: This shouldn't vary from browser to browser but instead follows the guidelines of CSS specificity. In your particular case the color will always be blue because the blue selector has the same level of specificity as the red selector but was defined later and whatever is defined later trumps that which is defined earlier for equal specificity.


text:
Q: Python: can function be defined inside of another function's argument list? Is there a way to achieve something like this in python?
another_function( function(x) {return 2*x} )

A: Yes:
another_function( lambda x: 2*x )

To be clear: this is taking place when another_function is called, not when it is defined.

A: def another_function( function=lambda x: 2*x ):
    print(function(10))  #an example

I'm not sure what happens with the example code you posted, but with the solution shown if you call another_function it will call function(10) and print 20.
More to the point, you cannot call another_function(7) and get 14 because 7 will get assigned to function and 7(10)' will get youTypeError: 'int' object is not callable`.


text:
Q: my basic 'guess the number program', it will not acknowledge 'a correct guess to the computer's number' I made a simple guess the number program, in my quest to learn python! lol
however, the computer will not acknowledge the user's guess was correct, and it will always go to the "incorrect", even though the computers number displays as the users guess. My code seems correct, so i am at a loss. Any help is appreciated!
def randomNumGen():
    userGuess = input('The Computer has thought of a number between 1-5, deposit    your guess now!: ')

    if finalValue == userGuess:
        print("You've guessed correctly!, Very lucky you are!")

    else:
        print("You're guess was incorrect, try again please")
        print("The computer's guess was",finalValue)
        main()

EDIT:
the output looks like this, which explains the obvious issue here:
>The Computer has thought of a number between 1-5, deposit your guess now!: 2
>You're guess was was incorrect
>The computer's guess was 2

so the 'computer' will not recognize a correct guess when one has been given.

A: Most likely finalValue is an integer, while the input from input() will be a string. You should make both into strings, or both into integers before you compare them.
To convert an integer to a string, you can simply do this:
my_string = str(my_integer)

This will take an integer named my_integer and return a string which will be assigned to be my_string
def randomNumGen():
    userGuess = input('The Computer has thought of a number between 1-5, deposit    your guess now!: ')

    if str(finalValue) == userGuess:
        print("You've guessed correctly!, Very lucky you are!")

    else:
        print("You're guess was incorrect, try again please")
        print("The computer's guess was",finalValue)
        main()

This is the simplest change I can see that will make this work. Note the line:
if str(finalValue) == userGuess:

I am comparing finalValue cast into a string with the userGuess.

A: I believe the issue is that your input is being processed as a string when it needs to be recognized as an integer. Try this:
def randomNumGen():
userGuess = input('The Computer has thought of a number between 1-5,     deposit    your guess now!: ')
userGuess = int(userGuess)

if finalValue == userGuess:
    print("You've guessed correctly!, Very lucky you are!")

else:
    print("You're guess was incorrect, try again please")
    print("The computer's guess was",finalValue)
    main()


text:
Q: How to allow only a single instance of a widget android I want to allow the addition of a single widget, I tried to put a boolean flag and i have:
Inside WidgetConfig:
public final static String ADDED_KEY = "IsAdded";
public static boolean isAdded = false;

onCreate (inside WidgetConfig)
isAdded = prefs.getBoolean(ADDED_KEY, false);
    if (isAdded){
        Toast.makeText(this.getApplicationContext(), "Only one Widget", Toast.LENGTH_SHORT).show();
        finish();
    }
 [...]
editor.putBoolean(ADDED_KEY, true); //disable adding here
editor.commit();

Inside WidgetProvider extends AppWidgetProvider
public void onDisabled(Context context) {

    super.onDisabled(context);
    [...]
//cancel alarm
   configEditor.putBoolean(WidgetConfig.ADDED_KEY, false); //enable adding here
    configEditor.commit();
}

public void onDeleted(Context context, int[] appWidgetIds){
super.onDeleted(context, appWidgetIds);
//I should not need this if there is only one widget
}

But it does not always work.
How can I do? Thanks

A: Get the Ids of your added widget(s) from the AppWidgetManager directly and check how many have already been added in your Configuration Activity.
int[] ids = AppWidgetManager.getInstance(getApplicationContext()).getAppWidgetIds(
            new ComponentName(getApplicationContext(), YOUR_WIDGET.class));

    if(ids.length > 0){
        //do not add the widget
    }else{
        //add the widget
    }

That's what I usually do to check if there are any instances of my widget.


text:
Q: What is CPCTC: Property, definition..? So we're doing proofs in class and I was wondering:
Normally in two-column proofs you need Statements and Reasons, where Reasons are normally postulates, definitions, other theorems, or givens.
What category does CPCTC (Corresponding Parts of Congruent Triangles are Congruent) fit into? If it is a theorem, is there a proof for it?

Congruent has been defined as an equivalence relation; a relation that fulfills Reflexivity, Symmetry, and Transitivity.

A: It is a theorem that immediately follows from the definition of congruence (depending on what definition you're using), From Wikipedia:
"Two triangles are congruent if their corresponding sides are equal in length and their corresponding angles are equal in size."
So if sides and angles of a triangle are equal they are clearly congruent. Also see this


text:
Q: Mixing page orientations in wkhtmltopdf I'm using wkhtmltopdf to produce a PDF from a single HTML file, formatted into separate pages using page-break-before: always.  For example:

    Cover Page

    Page 1

    Page 2

With CSS:
.page {
    page-break-before: always;
}

Right now, I have the wkhtmltopdf command written to print the PDF in portrait orientation on letter-size pages.  I need one of the pages to be in landscape orientation and the rest to be in portrait orientation (so that when the PDF is viewed on screen, all of the content will be oriented correctly).
Is there a way to mix orientations in a single PDF?
If this is not possible, is there a way to merge multiple PDFs using wkhtmltopdf?  (I have seen other suggestions of different pdfmerge software.)  I could split my HTML source file into multiple files for each page if necessary.

A: In case someone is looking for this answer in the future, I will complete this with my solutions.  Based on the lack of answers, I guess there really is no way to create a PDF with multiple page orientations using wkhtmltopdf.

*

*The first solution I implemented was creating a single PDF using one HTML file and rotating the content of the landscape page using the following CSS:
width: 1275px;
height: 1650px;

-webkit-transform: translateY(1650px) rotate(270deg); /* Chrome, Safari 3.1+ */
-moz-transform: translateY(1650px) rotate(270deg); /* Firefox 3.5+ */
-o-transform: translateY(1650px) rotate(270deg); /* Opera 10.5-12.0 */
-ms-transform: translateY(1650px) rotate(270deg); /* IE 9 */
transform: translateY(1650px) rotate(270deg); /* IE 10+, Firefox 16.0+, Opera 12.1+ */
filter: progid:DXImageTransform.Microsoft.Matrix(M11=6.123031769111886e-17, M12=1, M21=-1, M22=6.123031769111886e-17, SizingMethod='auto expand'); /* IE 6-7 */
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=6.123031769111886e-17, M12=1, M21=-1, M22=6.123031769111886e-17, SizingMethod='auto expand')"; /* IE 8 */

-webkit-transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-o-transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
transform-origin: 0% 0%;

(To write similar compatible CSS3 transforms, check out this great site to calculate all of the IE matrix values: http://www.useragentman.com/IETransformsTranslator/)
This would be a decent solution if your users would only be printing the PDF after it was produced.  Since my users need to view the PDF on screen, it would not be practical for them to have to rotate the page using their PDF viewing software.

*So, my second solution was to create each page as a separate PDF from individual HTML files, and then I used Ghostscript to merge them into a single file.  This worked perfectly, but just added some extra processing time to create all of the files and merge them.  In my case, the PDF would not be downloaded too often and the number of pages was minimal so the extra time was not a significant burden.

A: To @sacohe - hello from the future! Yes, still looking.
In case someone is still looking for this answer in the future, I am leaving a link to the feature request: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1564
At this time it is still open, but likely to be fixed sooner or later.


text:
Q: Javascript, PHP and MySQL relations I am currently working on a little project and I only just realised that the way I thought it would work, won't in fact work as JavaScript variables can't be sent to PHP that easily.
I have a Database full of members and each member has an id from 0 to x (lets just say x = 10) and I wanted to use a JavaScript for loop to iterate through and create everything easily.
Basically, the end product should be the following (except where it says id = 0 it would be different for each entry)

    <?php echo mysql_fetch_assoc(mysql_query("SELECT name FROM squad WHERE id = 0"))['name'] ?>
    <?php switch(mysql_fetch_assoc(mysql_query("SELECT rank FROM squad WHERE id = 0"))['rank']){case 3:echo 'Lieutenant';break;case 2:echo 'Soldier';break;default:echo 'Private';} ?>
    <?php echo number_format(mysql_fetch_assoc(mysql_query("SELECT power FROM squad WHERE id = 0"))['power']); ?>
    <input type="number" name="gained0" value="<?php echo mysql_fetch_assoc(mysql_query("SELECT power FROM squad WHERE id = 0"))['power']; ?>">
    <input type="number" name="rank0" value="<?php echo mysql_fetch_assoc(mysql_query("SELECT rank FROM squad WHERE id = 0"))['rank'] ?>">

Obviously I can't type in a JavaScript variable into PHP so how would I be able to loop through and create the above for all entries?

A: My god that's an awful approach have a look in to AJAX http://en.wikipedia.org/wiki/Ajax_%28programming%29 how it is used ... You will need to implement some kind of API's with simple get requests.
With AJAX basically you can call URL-s from javascript and obtain the data that is returned from the page let that be text,html,json etc..
Here you can find a great explanation on how AJAX works How does AJAX work? read through it you can find free tutorials on youtube also and after you got the idea rethink your code.

A: If you want to use javascript, I think you should use AJAX (google it). Best practice would be using only PHP and learning the difference between server side and client side.
Good luck!

A: Managed to get it done with just PHP. The switch I had to think about but it works as far as I can tell.
<?php
    for ($i=0; $i<=10; $i++) {
        $r = "";
        switch(mysql_fetch_assoc(mysql_query("SELECT rank FROM squad WHERE id = $i"))["rank"]){case 3:$r="Lieutenant";break;case 2:$r="Soldier";break;default:$r="Private";}
        echo "
" .
            "" . mysql_fetch_assoc(mysql_query("SELECT name FROM squad WHERE id = $i"))["name"] . "	" .
            "$r	" .
            "" . number_format(mysql_fetch_assoc(mysql_query("SELECT power FROM squad WHERE id = $i"))["power"]) . "	" .
            "<input type=\"number\" name=\"gained$i\" value=\"" . mysql_fetch_assoc(mysql_query("SELECT power FROM squad WHERE id = $i"))["power"] . "\">	" .
            "<input type=\"number\" name=\"rank$i\" value=\"" . mysql_fetch_assoc(mysql_query("SELECT rank FROM squad WHERE id = $i"))["rank"] . "\">	" .
        "
";
    }
?>


text:
Q: How to fix headphone audio after ubuntu update? I have a Lenovo Ideapad y400 and I recently updated to 16.04, and now the laptop speakers will play sound, but the headphone jack will not.
How could I go about fixing this?

A: It turns out my audio was muted. I ran alsamixer from the terminal, and unmuted the headphone channel by hitting m.


text:
Q: How to add Price per sqft in Product page and exact price in Magento 2?
How to add the price in per sqft in Catagory Page and search page? On the product page, the actual price will be shown as per the size chosen in the drop-down.

A: Magento doesn't actually has specific unit of measurement, I mean to say, you can consider the price for any unit you want i.e either $95 per KG or $95 per sq. ft. It's only how you think of it is. If you consider the price for sq.ft and it will be so.
So for your problem above.
In the product detail page, i can see that the price is Rs.3540 so what you have to do is add the product price to 3540. and for the option and additional price, you can manage that from custom option.
If you open the product on the right hand side you will see a tab named "Custom Options" you can add the options from there. Actually it is easy to add custom option see this  for detail info.
Hope this helps. If it does, don't forget to accept and vote up.
Cheers!!


text:
Q: Introduction to representation theory of algebraic groups This is a very basic and most definitively a naive question but coming from a student it is probably OK.
I am trying to learn representation theory of (linear) algebraic groups and looking for a an easy resource. The books and notes which I have come across start with extensive knowledge of algebraic geometry (which is essential for a comprehensive treatment) but coming from a weak background of mathematics by the time you absorb all that you are exhausted.
I am wondering if there is another way to get into representation theory of algebraic groups without worrying too much about algebraic geometry part. We have tried to go through the famous books (Humphreys, Springer, Borel), although excellent but too much for a beginner only interested in representation theory part to start with.
Any help will be highly appreciated.

A: I would suggest Procesi's Lie Groups, as a text that introduces algebraic groups with minimal prerequisites. Chapter 7 "Algebraic Groups" is

a quick introduction to algebraic groups. In this chapter I make fair use of notions from algebraic geometry, and I try to at least clarify the statements used, referring to standard books for the proofs. In fact it is impossible, without a rather long detour, to actually develop in detail the facts used. I hope that the interested reader who does not have a background in algebraic geometry can still follow the reasoning developed here.

This is followed by Chapter 8 "Representation Theory",

a first look into the representation theory of various groups with extra structure, such as algebraic or compact groups. We will use the necessary techniques from elementary algebraic geometry or functional analysis, referring to standard textbooks. One of the main points is a very tight relationship between a special class of algebraic groups, the reductive groups, and compact Lie groups.

A: I know close to nothing about algebraic groups, but the little I know comes from this article.
Basically, it assumes that you know what an algebraic variety is, and develops from scratch both the elementary properties of these groups and their actions on varieties (which I think is what motivates their introduction in the first place).


text:
Q: Points moving towards the nearest point, where will they meet?
Consider an arbitrary number of distinct points in some $n$
  dimensional space whose locations are exactly known. Every point is
  moving towards its nearest point simultaneously, at constant speed. If
  multiple points meet in a point, that's the new single point and the
  game continues.  What will be the final point where all the points
  will eventually meet?
What are the methods to finding the final meeting point?

What if a point is equidistant to multiple points? Then it moves towards all of them :
If a point is equally distant from two points, it moves towards the line determined by those two points. If a point is equally distant from three points, it moves towards the plane determined by those three points. Similarly for more equidistant points in some $n$-space.

$(n=1)$
If we are observing points on a line, then if $T(x_1)$ and $T'(x_2)$ are the outmost points (all other points are on the line segemtn $TT'$), then the final point will always be in the midpoint $P(\frac{x_1+x_2}2)$, no matter how many points and where are located on that line segment.
For the cases when a point is equally distant from two closest points, it simply won't move as it is already on the line determined by those two points, which now will meet at it.

$(n>1)$
If we are observing points on a plane, if three points are equally distant from one another, then they will end up in the center of that equilateral triangle, made of those three points. (Since each is moving towards opposing side)
But already at three points on a plane, if we have a pair of points meeting in the middle, and a third point far away gravitating towards one of those two points, its path will be a curve until the two distant points meet, and then its path will continue in a straight line towards the merged point.

I'm not sure how to show where exactly the final point will end up relative to the triangle. (white point on the picture is the meeting point; blue points are the starting points.)
However, if the third point $C$ is equally distant from the two paired points $A,B$, then it is simple to find the ending point as we don't have curved paths. The paired points will meet at the midpoint $P$ of $AB$, and $C$ would've traveled distance $AB/2$ towards $P$ by this point, to $C'$. Now final point is at the midpoint of $PC'$.

But I'm just observing certain cases and not sure how to approach this
  generally; as I'm already not sure how to handle arbitrary amount of points on arbitrary locations in the plane.

Example of paths; Random $20$ points on a plane, where red point is $(0,0)$ and white point is the point where all points eventually meet:

A: Solution for $n = 3$ (that can be extended partially)
Label the points $A,B$ and $C$ such that $\overline{AB} < \overline{AC} < \overline{BC}$ and move them such that $A = (0,0)$. Transform the coordinates for $B = (b_x,b_y) \mapsto (0,1)$
$$T = \pmatrix{b_y & b_x \\ -b_x & b_y} \qquad T^{-1} \cdot C = \pmatrix{x_0 \\ y_0}$$
$\hspace{4cm}$
$A$ and $B$ will meet at $(0,0.5)$. According to this $C$ will have moved to the following coordinates
$$c_x = x_0 \sqrt{\frac{1}{k} \operatorname{W} \left( k \exp{\left( k - \frac{2}{r_0 - y_0} \right)} \right)} \qquad k = \frac{r_0 + y_0}{r_0 - y_0} \quad r_0 = \sqrt{x_0^2 + y_0^2}$$
$$c_y = \frac{1}{4} \left( (y_0 + r_0) \left( \frac{c_x}{x_0} \right)^2 + 2 \, (y_0 - r_0) \ln{\left( \frac{c_x}{x_0} \right)} + 3y_0 - r_0 \right)$$
We then transform back to obtain the coordinates of the final point
$$T \cdot \left[ \frac{1}{2} \pmatrix{c_x \\ c_y + 0.5} \right] = \pmatrix{x \\ y}$$
This also applies to $n = 4$ if there are two pairs of points that don't influence each other
$\hspace{4cm}$


text:
Q: Validate only uppercase words, ignore if a word continues with lowercase using REGEX I have the following paragraph:
AUTOCAD is the best CAd program and it wins an AWARD for this.
I want to use a regex which captures only AUTOCAD, AWARD and ignore CAd because it contains lowercase.
I wrote a regex like:
\b[A-Z0-9]+(?![a-z]+)

but it takes also C from CAd... But I don't want it !
How to improve my regex ?

A: The point is that the \b[A-Z0-9]+(?![a-z]+) pattern matches C and then tests A in CAd, but since the A is right before a lowercase letter d, the (?![a-z]+) lookahead makes the engine backtrack, step back and test C again to check it is not followed with a lowercase letter. Thus, the match is C.

To make the regex fail in this case, you need to either use a possessive quantifier ++ (or its equivalent atomic group (?>[A-Z0-9]+)) to prohibit backtracking into [A-Z0-9]+ - \b[A-Z0-9]++(?![a-z]+) - or the trailing \b as Maria suggests.


text:
Q: Can I safely delete a record, manually, in the wp postmeta table? I have an error in the metadata for a post.  It's preventing me from correcting or adding in a new value from the post itself.
If I go into the database postmeta table and go to the entry for that post ID I can see the error.
Can I safely just delete that entire entry in the postmeta table?  There's no other post meta to worry about.
Alternatively, I see the WordPress function delete_post_meta().  However, I'm not sure how to correctly use this in functions.php and hook-wise.
I could just delete and re-enter the entire post from the dashboard but I think the entry in the postmeta table for the old post would still be there, orphaned - right?)

A: It's unclear what the postmeta actually does so it could effect your website in any number of ways.At best it will just clear the field / option and the user will need to re-enter it for that specific page.At worst it could change a pages layout or orphan a media file in your media library ( assuming the field holds an attachment ID ). Other than that I cannot see a reason why deleting a row in the postmeta table would be extremely harmful.
Whenever a post is deleted WordPress does delete all the postmeta assigned to that post ID. The wp_delete_post() function says...

When the post and page [gets deleted], everything that is tied to it is deleted also. This includes comments, post meta fields, and relationships between the post and taxonomy terms.

The delete_post_meta() function can be ran almost anywhere core has been loaded. You could put it inside an init or save_post hook and run it once then remove the function call. For example:
function delete_somemeta() {
    // This will run every single time a page is loaded.
    delete_post_meta( $POST_ID, 'META_KEY_NAME' );
}

You could add this to your functions.php, reload the front-end of your website, then remove it and it will effectively do the same thing as removing the row from the database.
This type of function is most commonly seen as conditional removal of postmeta in save_post hook though when saving metabox data.


text:
Q: Pandas: How do I insert DataFrame columns in another column with the resulting MultiIndex? I got the following data structure for object 1:
dayofweek  A  B  C
Monday     1  2  3
Tuesday    4  5  6

All those items A, B, C I got for other objects, let's say Obj1. Obj2, Obj3.
I wanna put all the date in one dataframe with the MultiIndex columns structure:
object        Obj1      Obj2      Obj3
dayofweek  A  B  C   A  B  C   A  B  C
Monday     1  2  3   2  1  3   3  2  1
Tuesday    4  5  6   5  4  6   6  5  4

How can I do it easily? I tried to use .unstack(), but it puts objects' label below A, B, C columns

A: Use concat with keys parameter for MultiIndex with rename columns:
df = df.set_index('dayofweek')
df1 = df.rename(columns={'A':'B', 'B':'A'}).sort_index(axis=1)
df2 = df.rename(columns={'A':'C', 'C':'A'}).sort_index(axis=1)

df3 = pd.concat([df, df1, df2], keys=('Obj1','Obj2','Obj3'), axis=1)
print (df3)

          Obj1       Obj2       Obj3
             A  B  C    A  B  C    A  B  C
dayofweek
Monday       1  2  3    2  1  3    3  2  1
Tuesday      4  5  6    5  4  6    6  5  4

If there are 3 DataFrames with dayofweek column use:
dfs = [df, df1, df2]
df3 = pd.concat([x.set_index('dayofweek') for x in dfs], keys=('Obj1','Obj2','Obj3'), axis=1)
print (df3)

A: Try to use merge:
print(obj1.merge(obj2, on='dayofweek').merge(obj3, on='dayofweek'))

result:
  dayofweek  A_x  B_x  C_x  A_y  B_y  C_y  A  B  C
0    Monday    1    2    3    2    1    3  3  2  1
1   Tuesday    4    5    6    5    4    6  6  5  4


text:
Q: Recursion using template meta programming Can somebody explain to me, why the first call using the template function  is falling into an infinite loop, while the second compile-time function runs correctly?
#include <iostream>
using namespace std;

template<int N, int M>
struct commondivs {
  static const int val = (N<M) ? commondivs<N,(M-N)>::val : commondivs<(N-M),M>::val;
};

template<int N>
struct commondivs<N,N> {
  static const int val = N;
};

int commondiv(int N, int M){
    if(N==M){
        return N;
    }
    return (N<M)?commondiv(N,(M-N)):commondiv((N-M),M);
}

int main() {

    cout << commondivs<9,6>::val << endl;
    cout << commondiv(9,6) << endl;
    return 0;
}

A: The ternary operator is not like if constexpr: when a compiler sees it, it has to generate code for both branches. In other words, to instantiate a template commondivs<M, N>, a compiler instantiates both templates commondivs<N, M - N> and commondivs<N - M, M>.
In contrast to that, commondiv(N, M - N) and commondiv(N - M, M) are translated into two function calls. Which one is taken, will be decided when the function is actually called.
Addition.
HolyBlackCat gave a solution with std::conditional_t. Here is another one:
template<int N, int M>
struct commondivs {
    static constexpr int min = (N < M) ? N : M;
    static constexpr int max = (N < M) ? M : N;
    static constexpr int val = commondivs<min, max - min>::val;
};

template<int N>
struct commondivs<N, N> {
    static constexpr int val = N;
};

A: (N<M) ? commondivs<N,(M-N)>::val : commondivs<(N-M),M>::val

This line causes instantiation of both commondivs<N,(M-N)>::val and commondivs<(N-M),M>::val, even if the condition is known at compile time and one of the branches will never be taken.
Replace ? : with std::conditional_t, which doesn't have this limitation:
static const int val = std::conditional_t<N < M, commondivs<N,(M-N)>, commondivs<(N-M),M>>::val;

A: The problem is all the operands of conditional operator will be evaluated, so both commondivs<N,(M-N)> and commondivs<(N-M),M> get instantiated and their val get evaluated and then leads to recursive template instantiation.
You can apply constexpr if and put it in a constexpr static member function.

If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.

template<int N, int M>
struct commondivs {
  constexpr static int get_val() {
    if constexpr (N<M) return commondivs<N,(M-N)>::val; // if true, the else part won't be evaluated
    else return commondivs<(N-M),M>::val;               // vice versa
  }
  static const int val = get_val();
};

LIVE

A: You get infinite recursion because:
static const int val = (N<M) ? commondivs<N,(M-N)>::val : commondivs<(N-M),M>::val;

isn't metatemplate programming at all because ?:, as @Eng says, isn't constexpr.
You want to look at @HolyBlackCat's answer.


text:
Q: Select MKMarkerAnnotationView with custom callout after adding annotation I have an MKMapView on which I would like to add annotations on a long press gesture. After adding the annotation, I would like to select the annotation view. Quite a simple request I assumed.
The problem is that I am using the new MKMarkerAnnotationView with a custom rightCalloutAccessoryView and a custom detailCalloutAccessoryView. It is not very well documented yet, but the WWDC 2017 Session 237 states that the callout will be displayed when there is more than a title/subtitle.
Unfortunately, this is not the case for me. When I programmatically (and manually) select the annotation, I get a weird double selected state where I can see the callout AND the marker:

Here is the annotation view code:
import Foundation
import MapKit

@available(iOS 11.0, *)
protocol TemporaryUserAnnotationViewDelegate: class {
    func temporaryUserAnnotationViewDidTapOk(title: String?, userAnnotationView: TemporaryUserAnnotationView)
}

@available(iOS 11.0, *)
class TemporaryUserAnnotationView: MKMarkerAnnotationView {

    weak var delegate: TemporaryUserAnnotationViewDelegate?
    var textField: UITextField!

    init(annotation: TemporaryUserAnnotation) {
        super.init(annotation: annotation, reuseIdentifier: TemporaryUserAnnotationMarkerAnnotationView.reuseIdentifier)
        markerTintColor = .lbc_blue
        canShowCallout = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configure(annotation: TemporaryUserAnnotation) {
        let detailView = UIView()
        detailView.translatesAutoresizingMaskIntoConstraints = false
        textField = UITextField()
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.placeholder = "Titre"
        detailView.addSubview(textField)
        detailView.heightAnchor.constraint(equalToConstant: 21).isActive = true
        detailView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        textField.centerXAnchor.constraint(equalTo: detailView.centerXAnchor).isActive = true
        textField.centerYAnchor.constraint(equalTo: detailView.centerYAnchor).isActive = true
        textField.heightAnchor.constraint(equalToConstant: 21).isActive = true
        textField.widthAnchor.constraint(equalToConstant: 100).isActive = true
        detailCalloutAccessoryView = detailView

        let rightView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 70)))
        rightView.backgroundColor = .lbc_blue
        let button = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 40)))
        button.setTitle("OK", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(tapRightCalloutAccessoryViewButton), for: .touchUpInside)
        rightView.addSubview(button)
        rightCalloutAccessoryView = rightView
    }

    @objc func tapRightCalloutAccessoryViewButton() {
        delegate?.temporaryUserAnnotationViewDidTapOk(title: textField.text, userAnnotationView: self)
    }
}

and here is the controller code:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    print(#function)
    if annotation is MKUserLocation { return nil }
    if #available(iOS 11.0, *) {
        switch annotation {
        case let temporarayUserAnnotation as TemporaryUserAnnotation:
            if let view = mapView.dequeue() as? TemporaryUserAnnotationView {
                view.annotation = annotation
                return view
            } else {
                let view = TemporaryUserAnnotationView(annotation: temporarayUserAnnotation)
                view.delegate = self
                view.configure(annotation: temporarayUserAnnotation)
                return view
            }
        default:
            return nil
        }
    } else {
        let identifier = "marker"
        if let view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
            view.annotation = annotation
            return view
        } else {
            return MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        }
    }
}

I simply add annotations this way:
func addUserAnnotation(coordinate: CLLocationCoordinate2D) {
    let annotation = TemporaryUserAnnotation(coordinate: coordinate)
    mapView.addAnnotation(annotation)
    mapView.selectAnnotation(annotation, animated: true)
}

I also tried to implement the mapView(_:didAdd:) method but the result is even worse with the marker view in front of the callout.
Any help would be very appreciated! Thanks!

A: I found the following workaround: when you add your annotation, wait a second before programmatically selecting it:
func addUserAnnotation(coordinate: CLLocationCoordinate2D) {
    let annotation = TemporaryUserAnnotation(coordinate: coordinate)
    mapView.addAnnotation(annotation)
    DispatchQueue.main.asyncAfter(wallDeadline: .now() + .seconds(1)) {
        self.mapView.selectAnnotation(annotation, animated: true)
    }
}

I still think this should not be necessary, so if you have a better solution, feel free to post it here!

A: I just encountered a similar problem because I had a UITapGestureRecognizer of my own competing with MKMapView's selection gesture recognizer. I created and selected the annotation on the tap event, but because both gesture recognizers were firing, and theirs was firing last, it was deselecting immediately.
My solution was to implement UIGestureRecognizerDelegate and become the delegate of my gesture recognizer, and implement the following:
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}


text:
Q: How to edit the apple-app-site-association file auto-generated by Firebase Dynamic Links? Whenever I create a new url prefix using free Google-provided domain (for example, yourapp.page.link). The apple-app-site-association file gets automatically created at the respective https://yourapp.page.link/apple-app-site-association and https://yourapp.page.link/.well-known/apple-app-site-association.
The generated apple-app-site-association file looks something like:
{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "1234567890.com.example.ios",
        "paths": [
          "NOT /_/*",
          "/*"
        ]
      }
    ]
  }
}

and it is redirecting all paths to my app.
I want to exclude certain paths that should not be handled by my app. I know I can do this by specifying "NOT " in front of the path that i want to exclude in the paths array, but I just can't find a way to edit the auto-generated file.

A: I had a similar issue with dynamic links "hijacking" the links for email verification and password reset, forcing me to manually add exclude paths to the apple-app-site-association file. The only way forward I could find that seems to be working is to do the following:

*

*Add your apple-app-site-association file to your public folder:

*

*/public/apple-app-site-association (or whatever you have set as public folder)

*/public/.well-known/apple-app-site-association

*Add the following to the hosting section in your firebase.json (keep "appAssociation": "AUTO" or your dynamic links will stop working and you'll see an error message in the console.)

"headers": [
  {
    "source": "/.well-known/apple-app-site-association",
    "headers": [
      {
        "key": "Content-Type",
        "value": "application/json"
      }
    ]
  },
  {
    "source": "/apple-app-site-association",
    "headers": [
      {
        "key": "Content-Type",
        "value": "application/json"
      }
    ]
  }
]


text:
Q: regeneratorRuntime is not defined when using async/await I am getting a

"regeneratorRuntime is not defined"

when trying to use async/await in a project.
My babelrc file is this currently:
{
    "presets": ["env", "react"],
    "plugins": [
        "transform-runtime",
        "transform-object-rest-spread"
    ]
}

and my package.json is:
{
    "name": "****",
    "version": "1.0.0",
    "description": "****",
    "main": "index.js",
    "author": "****",
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "start": "yarn build && nodemon server/index.js --ignore dist/ --ignore public/",
        "watch": "parcel watch public/index.html --public-url /",
        "build": "parcel build public/index.html --public-url /",
        "test": "jest"
    },
    "dependencies": {
        "@babel/runtime": "^7.5.5",
        "axios": "^0.19.0",
        "express": "^4.17.1",
        "express-validator": "^6.1.1",
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "super-reset-css": "^1.0.5"
    },
    "devDependencies": {
        "babel-core": "^6.26.3",
        "babel-plugin-transform-object-rest-spread": "^6.26.0",
        "babel-plugin-transform-runtime": "^6.23.0",
        "babel-preset-env": "^1.7.0",
        "babel-preset-react": "^6.24.1",
        "jest": "^24.8.0",
        "nodemon": "^1.14.11",
        "parcel-bundler": "^1.5.1",
        "sass": "^1.22.9"
    }
}

I'm sort of new to configuring babel so not sure what to do here.

A: I fixed a similar problem using the following post
Try the following in .babelrc:
{
  "presets": ["@babel/preset-env"],
  "plugins": [
    "@babel/plugin-transform-runtime"
    ],
...

with the following dev dependencies:
@babel/plugin-transform-runtime @babel/runtime

A: I think it is because you are using @babel/runtime.
My set up is @babel/runtime, @babel/core, @babel/plugin-transform-runtime and in the .bablerc set
"plugins": ["@babel/transform-runtime"]

I hope this helps.


text:
Q: Excel 2010 VBA: Copying rows, dynamically choosing them based on a value on a certain column Just getting my feet wet with VBA for Excel. Looked around for similar issues and couldn't find anything exactly like this.
Pretty simple issue. I have some data and want to copy a section of the rows to another spot in the sheet. I don't think it'll let me post an image yet, so let's say it looks like this:
 Column A     Column B     Column C
 product1        1          #VALUE!
 product2        4            100
 product3        22            25
 product4        0             3

The rows I'd want to copy are ones where Column C is 5+. So, rows 3 and 4 in this case. The total number of rows should always be the same, if that helps.
I can do the copying and pasting in VBA, just wondering what the best way to select these rows would be. I tried a Do Loop with x being the column number, checking it was ">4", but I can't get it to work.
Thanks very much!

A: There are a ton of ways to go about it.  Here's one:
Sub Macro1()

Dim LR As Long

LR = ActiveSheet.UsedRange.Rows.Count
    Range("A1:C1").Range("$A$1:$C$" & LR).AutoFilter Field:=3, Criteria1:=">4", _
        Operator:=xlAnd
    Range("A1:C" & LR).SpecialCells(xlCellTypeVisible).Copy Destination:=Range("L1")
    Range("A1:C1").Range("$A$1:$C$" & LR).AutoFilter
End Sub

Adjust Destination range to suit.


text:
Q: Why do I get compiler errors when I try to use print() in my Xcode? I would like to use print() to debug, but every time I try, I get some compiler errors.
For example this is my code:
import Foundation
import Combine

class LoginInputs: ObservableObject {

    @Published var email = ""
    @Published var password = ""
    print(email)
}

And these are the errors I get:

Cannot find type 'email' in scope

Expected 'func' keyword in instance method declaration

Unnamed parameters must be written with the empty name '_'

Another frequent error that shows up in SwiftUI views is "Expressions are not allowed at the top level".
Could you please explain to me what I am doing wrong and how to fix this?

A: Not sure if this is what you are asking, but you could try something like this to print the value of email every time it changes:
class LoginInputs: ObservableObject {
    @Published var email = "" {
        didSet {
           print(email)
        }
    }
    ...
}


text:
Q: Given a Poisson distribution Poisson(n│λ) with expected value λ, which integer n is the most probable one?
*

*Given a Poisson distribution Poisson(n│λ) with expected value λ, which integer n is the most probable one?

*Prove that, if  is integer, there are two most probable values for .


text:
Q: Does projections to orthogonal summands closed $\implies$ subspace closed? Let $X$ be a inner product space, with orthogonal decomposition $X=V \oplus W$. Give $X$ the topology induced by the norm induced by the inner product. Let $E\subset X$ be a subspace such that the projections to $V, W$ (call them $\pi_V(E), \pi_W(E)$) are closed. Does this imply that $E$ is closed itself?
Note that $X$ may not be complete; in fact I am mainly interested in the case where it is not complete. Any kind of help would be appreciated!


text:
Q: Polymorphism: source and target not compatible I have a question about polymorphic assignments.
Let's assume this declarations:
CAR car;
MERCEDES mercedes;
//MERCEDES inherits from CAR

car = new MERCEDES(classA);
mercedes = car

Is the last assignment possible? I thought that the first assignment changes the type of car into MERCEDES and so the last assignment would be right.
But in the sheets I have it shows that it doesn't compile because the source of assignment and the target are not compatible.
Is this right? And why is this so?

A: Your sheets are right, because a CAR is not necessarily a MERCEDES. It just happens to be true in your case, but think about the general case.
There could be plenty of car types, and the compiler can not assure that the assignment expression is true at all.


text:
Q: firebird MON$STATEMENTS insert, delete, update I use 2.1 firebird.
I see the select commands but I not found insert, update, delete commands when MON$STATE = 0.
Why can't see insert, update, delete command in MON$STATEMENTS table after these run?
I see these when their MON$STATE = 1 but I not find these when their MON$STATE = 0.

A: MON$STATE = 1 means that a query being executed right now. MON$STATE = 0 means that a SELECT query has been executed and is in a suspended state. i.e. either waits for a row being fetched by a client application or an end of a record set is reached but query is not closed yet.
INSERT, UPDATE, DELETE queries don't have a SUSPENDED state. They are either running or finished and gone.

A: You can get MON$STATE = 0 for INSERT, UPDATE and DELETE. When your application uses prepared statements and the statement is not executing, the MON$STATEMENTS row for that query will also have MON$STATE = 0.


text:
Q: Array size in C++ I made a code in which I had to take the size of an array as the user's input and its elements too and print them.
#include <iostream>
using namespace std;
 //Compiler version g++ 6.3.0

 int main()
 {
     int i;
     cout<<"\nenter the size of array";
     cin>>i;
     int n[i];
     for(int j=0;j<=i;j++)
     {
         cout<<"\nn["<<j<<"]=";
         cin>>n[j];
     }
     for(int k=0;k<=i;k++)
     {
         cout<<endl;
         cout<<"\nn["<<k<<"]=";
         cout<<n[k];
     }
 }

Suppose in the following:
The value of i is 3 (according to user's input).
In the first loop the condition for j is up to <=i where i is the size of array (this shouldn't happen as i begins from 0) due to which the Compiler asks me to input 4 values for the array (n[0], n[1], n[2] and n[3]) but the size of the array is 3 only. How can it store 4 objects?

A: Change this:
for(int j=0;j<=i;j++)

to this:
for(int j = 0; j < i ; j++)

since array indexing ends at the size of the array minus 1. In your case i - 1.
Likewise, you neeed for(int k=0;k<i;k++).
Your posted code invoked Undefined Behavior, by accessing the array out of bounds.

This:
int n[i];

is a Variable Length Array (VLA), which is not Standard C++, but is supported by some extensions.
and if you compiled with pedantic flag, you would get:
prog.cc: In function 'int main()':
prog.cc:9:9: warning: ISO C++ forbids variable length array 'n' [-Wvla]
  int n[i];
         ^

If you want something like this data structure, then I suggest you use an std::vector instead, which is Standard C++.

By the way, it's not a syntax error or something, but i is usually used as a counter (like you used j), an index if you like. As a result, I would chnage it's name to size, for instance, or something related.

EDIT:
Example with std::vector and variable renaming:
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int tmp, n;
    cout<<"Input number of elements\n";
    cin >> n;
    vector<int> v;
    for(int i = 0; i < n; ++i)
    {
        cin >> tmp;
        v.push_back(tmp);
    }
    for(auto number: v)
        cout << number << endl;
    return 0;
}

A: You need to check for less than i and not less than equal i. Otherwise it will try to store value for 0,1,2,3 in that case the last object will cause memory corruption. In c++ it will not give you any error even if you try to add 100 members in array of size 3.
It better you read memory management in c++ before jumping into coding.


text:
Q: creating half star rating in ASP.NET I'm using C#,VS2010 to develop my ASP.NET web app, I want to create a rating system in which user can select his rate by stars, something like AjaxControlToolkit rating, I've used this control, but is there any way that user can select half stars? for instance I have 5 stars and user can select 0.5, 1, 1.5, 2 and ... up to 5?
what about telerik or other custom controls? I'm looking for the ability to select and display half stars, is it possible? I've seen several sites that display half stars in addition to stars

A: Take a look at this jquery plugin, raty. It allows you to have half star ratings.
You can use ajax to post and a asp.net webservice as the backend.
I do not know of a asp.net custom control. But writing your own isn't very difficult.
In this case, you don't really need a custom control.


text:
Q: Sistema de comentarios para noticias Estoy desarrollando una pagina web con MySQL y PHP, dispongo de una sección de noticias donde cada una puede recibir comentarios. Estos comentarios también pueden ser respuesta a otro comentario. Para esto utilizo una tabla en la base de datos con la siguiente estructura
Create table comentario
(
   id int not null,
   id_comentario_padre int,
   texto varchar(255),
   fecha datetime,
   verificado tinyint
)

Ahora, como verán no estoy almacenando un nickname o algo por el estilo para el autor porque el problema que tengo es que a veces el autor sera un usuario registrado (en cuyo caso debería almacenar su id) y en otros casos el autor sera un visitante no logueado que podrá ingresar un alias para ese comentario. Esperaba que me pudieran ayudar con el diseño de la tabla comentario y como enfrentar esta duplicidad en los posibles valores de la columna del nickname


text:
Q: Drools indecate variable as unexpected I wan't return from query Company object. But IDE indecate company as unexpected
enter image description here
What is my error:
dialect  "java"

query getBalance(World world, Company company)
    $company := Company(companyName == "Intel") from world.getCompanies()
end

rule "BMWCarsToPerson"
when
    $world : World()

    $company : Company()

    getBalance($world, $company)
    /*$company : Company() from $world.getCompanies()*/

    $manager : Manager() from $company.getManagers()
        exists Car(name == BrandOfCar.BMW) from $manager.getCars()

    $bmwCarsFromManager : Car(
        name == BrandOfCar.BMW
        ) from $manager.getCars()

    $person : Person(
        name == "Elvis"
        ) from $world.getPersons()

    /*$listMageners : List() from $manager*/

then
end

A: You shouldn't (and cannot) use a query for this simple task. Replace
$company : Company()
getBalance($world, $company)

by
$company: Company( companyName == "Intel" ) from $world.getCompanies()


text:
Q: How to change the Log file path programmatically in log4net? I am using %property% to set the output file path in the Log4Net configuration file. A log file will be created in the APP data folder every time when the application launches. I am using the Composite rolling style for rolling the files.
But now my requirement is to roll/change the file path based on some user interactions in the application. How can I achieve this, can anyone suggest me to achieve this.

*

*How to roll the file in c# code. The expected behavior is similar to rolling based on Size and date.

*What is the c# code to change the output file path in Log4Net in between program execution?

Please let me know if my requirement is not clear.
Thanks.

A: You have 2 questions:

*

*I'm not aware if this is possible. I guess the roll to next name is private in the rolling file appender. You can look in the src to see if you can access it. If not you can inherit from the RollingFileAppender and add your own implementation. You can get the appenders on runtime by:

code:
  LogManager.GetRepository().GetAppenders();

*Using a property is the right way. Your configuration should look like this:

config:
 <appender name="YourAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
 </appender>

Important is the type="log4net.Util.PatternString". Set the property before initializing log4net.
log4net.GlobalContext.Properties["LogName"] = name;


text:
Q: adding a linebreak between tags I have xml file which will be read and displayed As .html page. The xml looks something like
  <title>Title Text</title>
    <text>
    <![CDATA[ Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.]]>
    </text>

Now the problem is when we read this xml file and display it as html we don't have any line break between title and text.
What will be the best way to add line break in xml tags?

A:   is the standard line break for HTML and will work in xml as well.
I know that &#xD also breaks a line in xml but I am unsure if it breaks a line in HTML. I hope this helps.
Title Text

should solve the problem for you I hope :) If not, truly sorry...


text:
Q: Take latest row if condition met else previous row I have a table say
+--------+-----+-------------+-----------+
| ID     | REV | Description | curr      |
+--------+-----+-------------+-----------+
| 211-32 | 001 | Screw       | READY     |
| 211-32 | 002 | Screw_2     | NULL      |
| 212-41 | 001 | bolt        | READY     |
| 212-41 | 002 | bolt_v2     | READY     |
| 423-98 | 001 | Nut         | WITHDRAWN |
| 423-98 | 002 | Nut_2       | NULL      |
+--------+-----+-------------+-----------+

I want to take the ID with latest revision from this. But if the curr is "NULL" then i have to take the previous row and if the previous curr is WITHDRAWN , I don't need that ID itself. So my expected output is like below
+--------+-----+-------------+-------+
| ID     | REV | Description | curr  |
+--------+-----+-------------+-------+
| 211-32 | 001 | Screw       | READY |
+--------+-----+-------------+-------+
| 212-41 | 002 | BOLT_2      | READY |
+--------+-----+-------------+-------+

I have tried the below query using temp table but it is not giving all rows.
select *,dense_rank() over (partition by id order by rev desc) as DR
into #material_DN
from material

select * from #material_DN where DR = case when curr='NULL' then 2 else 1 end

Check the fiddle here

A: Try this ...
select m.* from (
   select id, max(rev) max_rev
   from material
   where ISNULL(curr, '') <> 'NULL'
   group by id
) s
join material m ON
   m.id = s.id and
   m.rev = s.max_rev
where
   m.curr <> 'WITHDRAWN'

You can change ISNULL(curr, '') <> 'NULL' to simply curr <> 'NULL' .. I was just trying to be safe with your sample data types.

A: Try this:
WITH DataSource AS
(
    SELECT *
          ,DENSE_RANK() OVER (PARTITION BY ID ORDER BY REV DESC) AS [row_id]
          ,LEAD(curr) OVER (PARTITION BY ID ORDER BY REV ASC) AS [next]
    FROM material
)
SELECT id, rev, description, curr
FROM DataSource
WHERE ([row_id] = 1 AND [curr] = 'READY')
    OR ([row_id] = 2 and [next] = 'NULL' and [curr] <> 'WITHDRAWN')
ORDER BY ID
        ,[Rev]

A: Here's a simpler version using window funcions ...
select * from (
    select *, max(case when curr <> 'NULL' then rev end) over (partition by id) max_rev
    from material
) s where
   rev = max_rev and
   curr <> 'WITHDRAWN';

A: You can try the following query using the reference.
;with cte as (
SELECT ID
, Rev
, Description
, curr = MAX(curr) OVER (PARTITION BY c)
, Row_Number() Over(Partition By Id Order by id desc) as SrNo
FROM
(
    SELECT ID, Rev, Description, curr
        ,c = count(curr) OVER (ORDER BY id)
    FROM material
) a
)
Select ID
, Rev
, Description
, curr
from cte where SrNo = 2 order BY id

Live Demo db<>fiddle


text:
Q: Add class to website based on post taxonomy I want to write a class to the body of all pages posts and custom posts (IE entire site)
I am using a front end editor that allows logged in users to edit posts and keep them out of the back-end.

*

*I have a custom post-type "emergency status"

*It contains one post with a taxonomy "status"

*It has the terms extreme, severe, very-high, high, moderate.

I want to add a filter that checks the taxonomy of that post and then adds it to the body of the site.

A:

*

*You can use the body_class filter in WordPress to add the Taxonomy Terms of a Custom Taxonomy as CSS classes to a post. The CSS class appears in the body element and is only used if the post has been assigned to the taxonomy.

*The code goes in your functions.php file.

add_filter( 'body_class', 'themeprefix_add_taxonomy_class' );
 // Add taxonomy terms name to body class
function themeprefix_add_taxonomy_class( $classes ){
    if( is_singular() ) {
        global $post;
        $taxonomy_terms = get_the_terms($post->ID, 'your_taxonomy'); // change to your taxonomy
        if ( $taxonomy_terms ) {
            foreach ( $taxonomy_terms as $taxonomy_term ) {
            $classes[] = 'tax_' . $taxonomy_term->slug;
            }
        }
    }
    return $classes;
}

*

*Change 'your_taxonomy' to the actual taxonomy, the body_class filter is fed the results from a foreach loop done on the custom taxonomy, if any of the terms of that custom taxonomy are used by the post, they are added to the $classes array, in the above instance they have a prefix of 'tax_' followed by the term – you can change this prefix to suit or simply not have one.

A: WordPress already does this if your theme has been built correctly. Specifically, WP will add classes to the body tag if you used body_class and to the posts containing element if you used post_class
For example, if you install WordPress, the default Hello World post is uncategorized, and has the following classes:
post-1 post type-post status-publish format-standard hentry category-uncategorized entry

Notice the category-uncategorized class.
Similarly the <body> tag has these classes:
post-template-default single single-post postid-1 single-format-standard wp-embed-responsive singular image-filters-enabled

Other classes get added depending on the context, e.g. a class gets added if the admin toolbar is showing, or if the user is logged in, etc


text:
Q: ReplaceText processor - replace \r\n with just \n GetTwitter processor returns flow file with \r\n (\0D\0A) at the end. I am building Elasticsearch bulk insert file (using MergeContent Processor) and need to replace \r\n just with \n (\0A). Otherwise I am getting error back from ES.
I am thinking to use ReplaceText processor but not sure what to use as a search and replace parameters.
Thanks in advance.

A: It appears elasticsearch can ingest JSON.  The data returned from the Apache NiFi GetTwitter processor is valid JSON.  What is the error being returned when posting the JSON document to ElasticSearch?  What technique are you using to post to ElasticSearch?
Thanks
Joe


text:
Q: Angular js : Directive Accordion Button I could not put the button after the title in my accordion  using Angular js, how can I do that please in my template directive: have you an idea please.
css :
.StyleButton {
    float : left !important;
    color: @mBlueLight !important;
    background-color: @mWhite;
    padding-left : 10px;
    padding-right :10px;
    margin-top :-3px;
    margin-right :10px;
    &:hover{
        color:@mWhite;
    }
}

.directive('spotcam', function () {
    return {
        restrict: 'EA',
        replace: true,
        transclude: true,
        require: '^accordion',
        scope: { title: '@' },
        template: '
' +
                  '
   {{title}} <button class="StyleButton"> Valider la saisie</button>
' +
                   '

' +
                   '
',
        link: function (scope, element, attrs, accordionController) {
            scope.showMe = false;
            accordionController.addSpot(scope);
            scope.toggle = function () {
                scope.showMe = !scope.showMe;
                accordionController.Open(scope);
            };
        }
    }
});


text:
Q: Static parameterized methods in Java I thought I understood generics. However, in this example, I cannot figure out why line  isIn1(new Class2(1), arr); is compiled and line  isIn2(new Class2(1), arr); is not compiled.
class E1{};
class E2{};

class Class1 implements Comparable<Class1> {
    int i;

    public Class1(int i) {
        this.i = i;
    }

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

    @Override
    public int hashCode() {
        return Objects.hash(i);
    }

    @Override
    public int compareTo(Class1 o) {
        return this.i - o.i;
    }
}

class Class2 implements Comparable<Class2> {
    int i;

    public Class2(int i) {
        this.i = i;
    }

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

    @Override
    public int hashCode() {
        return Objects.hash(i);
    }

    @Override
    public int compareTo(Class2 o) {
        return this.i - o.i;
    }
}

public class G05Demo2 {

    public static <T, V extends T> void isIn1(T x, V[] y) {
        for (int i = 0; i < y.length; i++) {
            if (x.equals(y[i])) {
                System.out.println(" Yes, is in ");
            } else {
                System.out.println(" Not is in ");
            }
        }
    }
    public static <T extends Comparable<T>, V extends T> void isIn2(T x, V[] y) {
        for (int i = 0; i < y.length; i++) {
            if (x.equals(y[i])) {
                System.out.println(" Yes, is in ");
            } else {
                System.out.println(" Not is in ");
            }
        }
    }

    public static void main(String args[]) {

        Class1[] arr = {new Class1(1)};

        isIn1(new Class1(1), arr); //  Yes, is in
        isIn1(new Class2(1), arr); //  Not is in    - why?

        isIn2(new Class1(1), arr); //  Yes, is in
        isIn2(new Class2(1), arr); //  NOT compiled - why?

        G05Demo2.<Class1, Class1>isIn1(new Class1(1), arr); //  Yes, is in
        G05Demo2.<Class2, Class1>isIn1(new Class2(1), arr); //  NOT compiled (type checking works, since they are explicitly specified)

        G05Demo2.<Class1, Class1>isIn2(new Class1(1), arr); //  Yes, is in
        G05Demo2.<Class2, Class1>isIn2(new Class2(1), arr); //  NOT compiled (type checking works, since they are explicitly specified)

        E1[] arr2 = {new E1()};
        isIn1(new E2(), arr2);

    }
}

A: isIn1(new Class2(1), arr);

prints "Not is in" because Class2.equals returns false when this and o are not instances of the exact same class:
@Override
public boolean equals(Object o) {
    if (this == o) return true;

    //          here VVVVVVVVVVVVVVVVVVVVVVVVVV
    if (o == null || getClass() != o.getClass()) return false;
    Class2 class2 = (Class2) o;
    return i == class2.i;
}

arr contains an instance of Class1, but you passed an instance of Class2 as the first parameter to isIn1.

isIn2(new Class2(1), arr);

Does not compile because there is no types that satisfy the constraints you specified in isIn2 that can be inferred. Specifically, there has to be a type T that is a subtype of Comparable<T> and a type V that is a subtype of T. Class2 would also have to be compatible with T, and Class1[] would have to be compatible with V[].

"How about T is Class2 and V is Class1?" you might say:
Main.<Class2, Class1>isIn2(new Class2(1), arr);

That doesn't work because Class1 is not a subtype of Class2. They are unrelated at all! The similar isIn1 call fails for the same reason.

Why does
isIn1(new Class2(1), arr);

compile then?
By not specifying the generic type parameters, the compiler can try its best to infer the types so that the code compiles. Also note that isIn1 has one fewer constraint than isIn2.
Here, one solution is T is Comparable<? extends Comparable<?>>, and V is Class1.
Main.<Comparable<? extends Comparable<?>>, Class1>isIn1(new Class2(1), arr);

You can check that they satisfy the constraints by using the sub typing rules described in Section 4.10 of the JLS.

A: For isIn1, both T and V can be inferred as Object. (Because of this, there is no point in these type variables, you may as well use Object explicitly).
For isIn2, T is inferred as Class1; since Class2 doesn't extend that, the compiler rejects the code.


text:
Q: Google map custom directions to Android navigation I am using a script modeled from google draggable map at http://gmaps-samples-v3.googlecode.com/svn/trunk/draggable-directions/draggable-directions.html to create custom driving directions on an android device.
So far just like the example I can drag the driving line on the map and reroute the directions causing the trip calculation and turn by turn directions to change.
I have seen documentation on an anchor link that will open map options on the device asking to choose a map app from a list of installed apps that interact with a map.
I would like to send the new turn by turn driving directions to the navigation and have the new route followed.
Any ideas a script or how to parse a link to open the map and/or nav would be interested and helpful.

A: Well to start this is how you open up that maps app dialog that you mentioned. This is when you have one address.
Uri geoUri = Uri.parse("address here");
Intent mapCall = new Intent(Intent.ACTION_VIEW, geoUri);
startActivity(mapCall);


text:
Q: Y axis bar values are overlapping with each other in apache superset bar chart When I try to show the bar value in the bar chart of apache superset, y axis bar values overlap with each other.
To fix this issue, I want to rotate the y-axis values with 45 degree so that those values will look vertically and won't overlap with each other, just like it is there in x-axis values.

A: Do you prefer grouped or stacked bars. Using stacked bars would be a shortcut to solving this.

A: I don't have an easy but bad answer for you, and a more difficult but rational answer.
The bad/easy answer: You might be able to do this with CSS, at least in any given dashboard. For that, you'd want to take your Dashboard into Edit mode, and pick "Edit CSS" from the "..." menu in the top right. There, you should have access to write some clever CSS selectors (let me know if you need help) and tweak CSS properties of the SVG text element (i.e. text-anchor, transform). That said I think you're going to have a bad time with this approach, since you don't have access in CSS to the values you might need for `translate(x, y). So, that brings us to...
The better/harder answer: You could edit the plugin! One caveat is that we'll be replacing some visualizations in the near future (including the Bar Chart) with ones based on Apache ECharts. Meanwhile, you could open up a PR on the Superset-ui repo at https://github.com/apache-superset/superset-ui. The NVD3-based plugin lies in there, as do the controls, where you might be able to add additional controls for rotation.
Door #3, of course, would be to write your own visualization plugin (or help us with the ECharts refactor!) but that's another conversation entirely.
Sorry this isn't more directly helpful, but I hope it gives you more avenues to explore.


text:
Q: Strange behavior in simple command line program I'm trying to create a Java guessing game, but the first part I'm working on is having issues and I would like some help.
The program first asks a user to input a number, then the program asks them to confirm whether their number is what they inputted.
If they enter yes to whether they inputted the correct number, it currently just outputs "bru".
If no is inputted then they re-enter the input number and the cycle will go on until the user correctly inputs their number and confirms it.
I'm trying to accomplish this with a while loop.
Unfortunately when I run the program everything works fine until I'm asked to enter yes or no to confirm my number. If I enter yes it still asks for me to re-enter the number.
But if I enter no and then I say no again confirming my number it gives me the output for when I confirm that I inputted the correct number.
import java.util.Scanner;
import java.util.Random;

public class Assignment6 {

    public static void main(String args[]) {
        Scanner input = new Scanner( System.in );
        System.out.print ( "Please enter the upper bound of the secret number.");
        int UpperBound = input.nextInt();
        System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + "Is that correct?" + "" + "If yes please enter yes, if not please enter no.");
        String TrueOrFalse = input.next();
        while (TrueOrFalse == "no" | TrueOrFalse == "No");
        {
            System.out.print ( "Please enter the new upper bound of the secret number.");
            UpperBound = input.nextInt();
            System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + " " + "Is that correct. If yes please enter yes, if not please enter no.");
            TrueOrFalse = input.next();
        }
        System.out.print ("Bru");
    }
}

A: Replace
while (TrueOrFalse == "no" | TrueOrFalse == "No");

with
while(TrueOrFalse.equalsIgnoreCase("no"))

i.e. remove ; from the while
also if possible renamme ur variable TrueOrFalse

A: Your major problem is with ; and comparing String using  equals and ==.
Also you need to check difference between  nextInt() and nextLine()
Try below code, it will help you.
public static void main(String args[]) {
        Scanner input = new Scanner( System.in );
        System.out.print ( "Please enter the upper bound of the secret number.");
        int UpperBound = Integer.valueOf(input.nextLine());
        System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + "Is that correct?" + "" + "If yes please enter yes, if not please enter no.");
        String TrueOrFalse = input.nextLine();
        while (TrueOrFalse.equalsIgnoreCase("no"))
        {
            System.out.print ( "Please enter the new upper bound of the secret number.");
            UpperBound = Integer.valueOf(input.nextLine());
            System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + " " + "Is that correct. If yes please enter yes, if not please enter no.");
            TrueOrFalse = input.nextLine();
        }
        System.out.print ("Bru");
    }


text:
Q: Stretch block vertically with CSS I have a CSS problem. There are 3 blocks on a page stacking on each other vertically.

The first one's height is not defined, can be flexible.
The second one must always fill all available height between the first and the last for any window height.
The third one has fixed height and always attached to the bottom of a page.
I could not find a solution for that. It's not a question of sticky footer, it's a question of stretching the content between header and footer, even on window resize.
I need to support IE8+ or at least IE9.
I know it can be done with JS, but any working CSS solution is appreciated.
UPDATE:
I know there are lots of similar questions on SO, but they don't address my problem. Solutions with absolutly positioned blocks don't work. For example - http://jsfiddle.net/RkX8B/561/ Solutions with display:table doesn't work as well.
My content block will have lots of text, tables etc. and there must be a scroll bar on that block.


text:
Q: How is incorrect UDP length field usually handled by network stack? I am designing yet another UDP network stack. I wonder how incorrect values of UDP field in the UDP header are usually handled. Specifically, when the UDP length field indicates larger UDP payload than it actually is. For example, this could happen when all the fragments are received (the last packet had the MF flag cleared) and as the datagram is being reassembled it is found out that not all the UDP data were received.
After some exploring it seems that no RFC defines how these datagrams should be handled. Clearly, one approach is to discard the whole datagram and the other to ignore the UDP length field inconsistency. I would welcome if somebody would share experience how this is implemented on various platforms.


text:
Q: Ошибка в vivus.min.js После подключения, анимация работала и ошибки не было, но после переноса на wordpress, появилась ошибка
vivus.min.js?ver=1:124 Uncaught Error: Vivus [constructor]: "element" parameter is not valid (or miss the "file" attribute)
at i.setElement (vivus.min.js?ver=1:124)
at new i (vivus.min.js?ver=1:13)
at arrowAnim.js?ver=1.0.0:1

Подключение скриптов правильное, все остальные скрипты работают, но ошибка остается.
Первый пункт ошибки в этом коде:
switch (e.constructor) {
        case window.SVGSVGElement:
        case window.SVGElement:
        case window.SVGGElement:
            this.el = e, this.isReady = !0;
            break;
        case window.HTMLObjectElement:
            r = this, (t = function(t) {
                if (!r.isReady) {
                    if (r.el = e.contentDocument && e.contentDocument.querySelector("svg"), !r.el && t) throw new Error("Vivus [constructor]: object loaded does not contain any SVG");
                    r.el && (e.getAttribute("built-by-vivus") && (r.parentEl.insertBefore(r.el, e), r.parentEl.removeChild(e), r.el.setAttribute("width", "100%"), r.el.setAttribute("height", "100%")), r.isReady = !0, r.init(), r = null)
                }
            })() || e.addEventListener("load", t);
            break;
        default:
            throw new Error('Vivus [constructor]: "element" parameter is not valid (or miss the "file" attribute)')
    }

Второй пункт ошибки вот тут
 function i(t, e, n) {
    r(), this.isReady = !1, this.setElement(t, e), this.setOptions(e), this.setCallback(n), this.isReady && this.init()
}

А код с подключением анимации вот этот:
const arrowAnim = new Vivus(
  'arrow',
  {
    type: 'oneByOne',
    duration: 70
  }
);
const arrowAnim2 = new Vivus(
  'arrow2',
  {
    type: 'oneByOne',
    duration: 70
  }
);

Как можно убрать эту ошибку и чтобы анимация заработала?
Код HTML до загрузки на WP
<object id="arrow" type="image/svg+xml" data="./img/svg/arrow__form.svg" class="arrow__form1"></object>
<object id="arrow2" type="image/svg+xml" data="./img/svg/arrow__form2.svg" class="arrow__form2"></object>

Код HTML после загрузки на WP
 <object id="arrow" type="image/svg+xml" data="<?php echo get_stylesheet_directory_uri(); ?>/assets/img/svg/arrow__form.svg" class="arrow__form1  cursor-btn"></object>
 <object id="arrow2" type="image/svg+xml" data="<?php echo get_stylesheet_directory_uri(); ?>/assets/img/svg/arrow__form2.svg" class="arrow__form2 cursor-btn"></object>

После изменил на прямой путь и ничего не помогло
 <object id="arrow" type="image/svg+xml" data="/wp-content/themes/WebFocus%20-%20Krasnodar/assets/img/svg/arrow__form.svg" class="arrow__form1  cursor-btn"></object>
 <object id="arrow2" type="image/svg+xml" data="/wp-content/themes/WebFocus%20-%20Krasnodar/assets/img/svg/arrow__form2.svg" class="arrow__form2 cursor-btn"></object>


text:
Q: Inject function between calls
Edit: just to be clear: My question is: is it possible to dynamically
  inject a function before all other function calls on a page.

I would like a single function to inject itself before all function calls.
I'm trying to implement access control lists for a JS app. So for eg.
User fred can access function app.addPage(), but he can't access function app.removePage();
So now how do I call the original function that was intended after calling the gatekeeper function?
I suppose I could modify my app so that every method call looks like this:
app.acl().functionCall();

But I wanted to inject acl() automatically before ever function call in some dynamic way. Possible?

A: Trying to exert that kind of security control in a client-side app is futile. Even if you could, say, override Function.prototype an unprivileged user could still come along and re-override it with the original functionality. Or change a variable to make themselves privileged. Or just build a POST request and send it directly to the server, bypassing your script entirely. There is no way to absolutely enforce what you're trying to do in client-side code.
If, however, you're doing this for convenience rather than security, consider this:
// define your functions as usual
app.showCatVideo = function (...) { /* ... */ }
app.deletePage   = function(...) { /* ... */ }
app.dropBombs    = function(...) { /* ... */ }

// specify which ones are privileged
var privilegedFunctionNames = [ "deletePage", "dropBombs" ];

for( var i = 0; i < privilegedFunctionNames.length; i++ ) {
  var funcName = privilegedFunctionNames[ i ],
    , origFunc = app[ funcName ];
  ;

  delete app[ funcName ];

  // replace the function with this one
  app[ funcName ] = function() {
    // check the user
    if( theUser.isPrivileged() ) {
      // call the original function with the arguments passed
      return origFunc.apply( app, arguments );
    }
    else {
      // hissy fit
      alert( "Unauthorized!" );
    }
  }
}

This just wraps the functions you specify (in privilegedFunctionNames) with a function that first checks if the user is privileged and, if s/he is, calls the function, and if not sounds the alarm.
Like I said, though, this has no security benefit. If someone knows how to use FireBug they're halfway to defeating this any any other client-side trick you could come up with.