text:
Q: Can Attribute Routing in ASP.Net MVC 5 Be Used Without Web API I have an MVC project that I am trying to use Attribute Routing in however I get keep getting 404's for the valid url's.
I have google to see what the common problems with Attribute Routing are to see if I am missing something obvious and most answers seemed to be make sure the route registration is as follows:
 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

With the line routes.MapMvCAttributeRoutes() being the code that searches the controllers for the routing attributes and configures the routes.
I have also seen a few references to Web API as I believe the attributes can be used in APIController's as well.
However the following article seems to suggest that it can be used in Mvc alone since there is no mention of Web API.
Attribute Routing in ASP.Net MVC 5
So is there a dependency and do you need to have Web API to get the Route Attributes working in MVC?
UPDATE
Using the following stripped down code:
[Route("hello")]
public class SomeController : Controller
{
    // GET: Some
    public string Index()
    {
        return "world!";
    }
}

I can get a valid response of 'world!' for the url 'localhost:58268/hello', which is a start. So it looks like you can have Attribute Routing in Mvc 5 without the dependency on Web API.
I must have made an error in defining the Route in the case of the actual code.

A: Yes, you can use MVC attribute routing without webAPI. It is a separate feature from WebAPI attribute routing. Both got introduced around at same time in WebAPI 2 and MVC 5.
Web API attribute routing is a bit more flexible than MVC, for many scenarios things should work just fine.
Note that in MVC Core, the Web API and MVC frameworks got merged.There is a single attribute routing feature which is a LOT more flexible and solves most of the limitations in the previous frameworks.


text:
Q: css - create a block element whose width is only as large as the text contained within I have this fiddle where there is a rollover style applied to a paragraph - but I want that paragraph to only be as wide as the text contained within (not the entire width of the containing element). If I do display:inline-block it brings each menu option up to the same line but sets the width of each item appropriately. How do I combine both (options on separate lines, but only as wide as the text contained inside)?
http://jsfiddle.net/heaversm/wxqeW/

A: You could add a span and set the hover state to the span
Fiddle ------> HERE

A: You could also have the background color change when you hover the entire <p> Fiddle: http://jsfiddle.net/wxqeW/11/

A: Try applying a
width: auto;

to the css. Also check that the divs are not floating.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: access multidimensional session array I want to implement the shopping cart by using multidimensional session array but don't know how to access them. For example,

*

*case1: user add one item to the cart with name "x" and size"m". then add again with name "x" and size"m"

line1: pname"x" size"m" quantity"2"

*

*case2: when user add one item to the cart with name "x" and size"m". then the user add another item to the cart with name "x" but size"s".

How can I manipulate it as 2 line of order?
line1: pname"x" size"m" quantity"1"
line2: pname"x" size"s" quantity"1"
     if (!isset($_SESSION['order'])) {
         $_SESSION['order'] = array();
     }
     $_SESSION['order'][] = array('id'=>$pID, 'size'=>$size, 'quantity'=>0);

   switch ($action) {
    case "add":
        $_SESSION['order'][]['quantity']++;
    break;

    case "remove":
        unset($_SESSION['order'][][$pID]);
    break;

    case "empty":
        unset($_SESSSION['order']);
    break;
}

A: Your session will get an element every time you call []. Add $pID as variable id:
Change to:
if (!isset($_SESSION['order'])) {
    $_SESSION['order'] = array();
}
$_SESSION['order'][$pID.'-'.$size] = array('quantity'=>0);

switch ($action) {
    case "add":
        $_SESSION['order'][$pID.'-'.$size]['quantity']++;
        break;

    case "remove":
        unset($_SESSION['order'][$pID.'-'.$size]);
        break;

    case "empty":
        // unset($_SESSION['cart']);
        unset($_SESSSION['order']);
        break;
}

You can later access that product with $_SESSION['order'][$pID.'-'.$size]
To access them:
foreach($_SESSION['order'] as $key => $one){
    list($pid, $size) = explode('-', $key);
}

A: i would suggest you to use objects instead of array for this.
Using arrays will create a kind of complication and make your code less readable and more complex;
I would suggest you to use an object oriented approach.
just create two classes:
    class ShoppingCart {

    private $items;

    public function getItems(){

     return $this->items;
    }

    public function addItem($item){

       $this->items[] = $item;
}

class Item {

private $name;
private $size;

public function getName() { return $this->name;}
public function getSize() { return $this->siez; }
public function setName($name) { $this->name = $name; }
public function setSize($size) { $this->size = $size; }

Now you can add items to the cart like this:

$cart = new ShoppingCart();

$item1 = new Item();
$item1->setName('x');
$item1->setSize('m');

$item2 = new Item();
$item2->setName('x');
$item2->setSize('s');

$cart->addItem($item1);
$cart->addItem($item2);

Did you see, this code is readable and can be easy understood.


text:
Q: How do I get ImetaField to be referenced? I'm in a sitefinity project, trying to make an ImetaField type variable, in order to integrate a date field into my widget.
The error:

My references and namespace and class header:

Not sure if this is enough information to go on...
Edit: I guess my main question is, what library do I need to reference for ImetaField?

A: So I figured out, you don't a freakin' ImetaField type to get the date, just use DateTime!
Still, I never found out how to use ImetaField, nor do I know now what it may be used for.
What I learned: googling for code in sitefinity is bad.


text:
Q: Regular expression Getting HTML Doctype My Html code is like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
or this can be like this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
I want to get the Doc Type  which will be like "XHTML 1.0 Strict" (for the first one), and "HTML 4.0" (for the second one) from it. What will be the regular expression code for this?
I like to use it in PHP preg_match() function.
Please help me in this case.

A: If the doctypes will be in the form shown, you could use
'#(?<=<!DOCTYPE HTML PUBLIC "-//W3C//DTD )[^/]+#i'

So
preg_match('#(?<=<!DOCTYPE HTML PUBLIC "-//W3C//DTD )[^/]+#i', html, $match);
echo $match[0];

A: How about using DOMDocument and DOMDocumentType?
$xml = new DOMDocument();
$xml->loadHTMLFile($url);

$name = $xml->doctype->publicId; // -//W3C//DTD XHTML 1.0 Strict//EN

$doctype now contains following values:
DOMDocumentType Object
(
    [name] => html
    [entities] => (object value omitted)
    [notations] => (object value omitted)
    [publicId] => -//W3C//DTD XHTML 1.0 Strict//EN
    [systemId] => http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
    [internalSubset] =>
    [nodeName] => html
    [nodeValue] =>
    [nodeType] => 10
    [parentNode] => (object value omitted)
    [childNodes] =>
    [firstChild] =>
    [lastChild] =>
    [previousSibling] =>
    [nextSibling] => (object value omitted)
    [attributes] =>
    [ownerDocument] => (object value omitted)
    [namespaceURI] =>
    [prefix] =>
    [localName] =>
    [baseURI] =>
    [textContent] =>
)

So you can now easily extract type:
$name = $xml->doctype->publicId;
$name = preg_replace('~.*//DTD(.*?)//.*~', '$1', $name);
echo $name;

Which will result into XHTML 1.0 Strict. Working phpfiddle example here.

A: function contains($haystack, $needle){
    if (strpos($haystack,$needle) !== false) {
        return true;
    }else{
        return false;
    }
}
                $theDocType = "";
                $stringWithHTML = ""; // load some HTML in here from somewhere

                // Create DOM from HTML
                $doc = new DOMDocument();
                //@$doc->loadHTMLFile("just_a_file.html");
                @$doc->loadHTML($stringWithHTML);

                // Grab document type
                $dtName = $doc->doctype->name;
                $dtPublic = $doc->doctype->publicId;
                if( $dtName="html" && $dtPublic!=""){
                    // HTML or XHTML?
                    if(contains($dtPublic,"xhtml")){
                        $theDocType = "XHTML 1.0";
                    }else{
                        $theDocType = "HTML 4.01";
                    }
                    // Which type?
                    if(contains($dtPublic,"strict")){
                        $theDocType .= " (Strict)";
                    }elseif(contains($dtPublic,"transitional")){
                        $theDocType .= " (Transitional)";
                    }elseif(contains($dtPublic,"frameset")){
                        $theDocType .= " (Frameset)";
                    }else{
                        $theDocType = "XHTML 1.1"; // XHTML 1.1
                    }
                }else{
                    $theDocType = "HTML 5";
                }

                // Result
                echo $theDocType;

This will output things like:
XHTML 1.1
HTML 5
HTML 4.01 (Strict)

A: Try this
<?php
   $html = file_get_contents("http://google.com");
   $html = str_replace("\n","",$html);
   $get_doctype = preg_match_all("/(<!DOCTYPE.+\">)<html/i",$html,$matches);
   $doctype = $matches[1][0];
?>

A: '<!doctype.*?//dtd\s+([^/]*)//EN.*?dtd">'

That should work as pattern for your examples.

A: This regular expression extracts everything between "DTD " and "/" without any syntax checking:
.*DTD\s+([^/]+)

This regular expression extracts the document type and checks some syntax in the string:
<!DOCTYPE\s+\w*\s*\w*\s*"[-//\w\d]*DTD\s+([\w\d\s.]*)[^"]*[^>]*>

A: I used this thread in the past, but in testing process, I detected a problem with some large doctypes. Some times, the developer split the doctype in 2 or 3 lines.
In this case, the usage of regular expression is no the best approach.
I paste an approach for doctypes in one or several lines:
<?
class Doctype {
    var $html;
    var $doctype;
    var $version;
    function Doctype($html){
       $this->html = $html;
       $this->extractDoctype();
       $this->processDoctype();
    }
    private function extractDoctype(){
        $preDoctype = "";
        $preDoctypeValid = false;
        $lines = explode(PHP_EOL, $this->html);
        foreach ($lines as &$line) {
            $preDoctype = $preDoctype . $line;
            if(
                (strpos(strtolower($preDoctype), "<!doctype") !== false) &&
                (strpos(strtolower($preDoctype), ">") !== false)){
                $preDoctypeValid = true;
                break;
            }
        }
        if($preDoctypeValid){
            //Store only the pattern: <! doctype >
            $pos1 = strpos(strtolower($preDoctype), "<!doctype");
            $pos2 = strpos($preDoctype, ">", $pos1) + 1;
            $preDoctype = substr($preDoctype, $pos1, $pos2);
        }else{
            $preDoctype = "";
        }
        $this->doctype = $preDoctype;
    }
    private function processDoctype(){
        $version = "";

        $pattern_html5 = "/<!doctype\s+?html\s?>/i";
        if (preg_match($pattern_html5, strtolower($this->doctype))) {
            $version = "HTML5";
        }else if(strpos(strtolower($this->doctype), "xhtml") !== false){
            $version = "XHTML";
        }else if(strpos(strtolower($this->doctype), "html") !== false){
            if(strpos(strtolower($this->doctype), "3.2") !== false){
                $version = "HTML 3.2";
            }
            if(strpos(strtolower($this->doctype), "4.01") !== false){
                $version = "HTML 4.01";
            }
            if(strpos(strtolower($this->doctype), "2.0") !== false){
                $version = "HTML 2.0";
            }
        }else{
            $version = "OTHER";
        }
        $this->version = $version;
    }
    public function getDoctype(){
        return $this->doctype;
    }
    public function getDoctypeVersion(){
        return $this->version;
    }
}
?>

https://github.com/jabrena/WTAnalyzer/blob/master/r_php/document/Doctype.class.php


text:
Q: Button and link styles behaving differently I have two elements ( and <button>), both of which are sharing the same classes from Tachyons:
Confirm account

<button class="f4 br2 fw9 pa3 bg-dark-blue white link db tc lh-solid fixed left-1 bottom-1 right-1 mla mra z-1  " type="submit">Next</button>

The expected behaviour is that they will both be the same width, and yet they're different (despite the same styles).
Any idea what's going on here?
Here's a Codepen demonstrating the issue.

A: In your particular case the button has a border and a different font, which is a default style for your browser. Each browser have it's own defaults for every type of elements, that's why a button and a link would look the way they do without any styling. In a matter of fact it isn't right to say "without any styling", it is rather "without any additional styling":

<button>I'm a button</button>
I'm a link

I didn't go through all the css you have, because you have 17 classes for a single element and I'm too lazy for it, but it actually possible to have different styles for different elements with a common class:

.awesome {
  display: inline-block;
  border: 5px solid;
  width: 200px;
  box-sizing: border-box;
  padding: 20px;
  text-align: center;
  margin: 10px 0 10px 10px;
  font-family: Arial, serif;
}
div.awesome {
  background-color: deepskyblue;
  border-color: royalblue;
  font-style: italic;
  color: darkslateblue;
}
span.awesome {
  background-color: orangered;
  border-color: firebrick;
  font-weight: bold;
  color: gold;
}

I'm a div

I'm a span


text:
Q: How to write a list of items, where the last item is a compound item? I have a sentence that contains a list of items, and the last item in the list contains an "and" (e.g. like a pet shop may sell "hampsters" and "cat and dog beds", but not "hamsters", "cats" and "dog beds").
I'm struggling to form the sentence correctly, as the last item's "and" gets confused with the "and" within the item itself.
The list's items are:

*

*file upload functionality

*image thumbnailing

*file and image hosting

The sentence I'm trying is:

Developers use X to add file upload functionality, image thumbnailing, and file and image hosting to their apps.

A friend suggested this:

Developers use X to add file upload functionality, image thumbnailing, file, and image hosting to their apps.

What is the correct way to write this?

A: One option:
Developers use X to add file upload functionality, image thumbnailing, file hosting and image hosting to their apps.
Another option:
Developers use X to add upload and hosting of files; and  thumbnailing and hosting of images to their apps.


text:
Q: extract manytomany field from a queryset Models.py
class AllotmentDocket(models.Model):

    sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE, related_name='allotment_sales')

class MaterialRequest(models.Model):

    kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit')
    quantity = models.IntegerField(default=0)

class Kit(models.Model):
    kit_name = models.CharField(max_length=255, default=0)
    components_per_kit = models.IntegerField(default=0)
    product = models.ManyToManyField(Product, related_name='kit_product')

How can I get all the products information through the related AllotmentDocket?
I tried :
def PrintAllotmentDocket(request, pk):
    AlotmentDocket = get_object_or_404(AllotmentDocket, id=pk)

    kit = MaterialRequest.objects.filter(id=AlotmentDocket.sales_order).values('kit')

but this gives an error:

int() argument must be a string, a bytes-like object or a number, not
  'MaterialRequest'

A: You can filter with
Product.objects.filter(
    kit_product__kit__allotment_sales=pk
)
with pk the primary key of the AllotmentDocket (so the one passed to the view).

Note: the related_name is the name of the relation in reverse, not the relation in the direction in which you define it.


text:
Q: How to find the height and width of image and fit the tableviewcell with aspect ratio? I have stretched images displayed in TableViewCell. I need to find the height and width of image from image URL. I need to find the aspect ratio and fit the image on the cell according to the height of dynamic cell in Swift 4.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.ManCell) as! ManCell
    let image = self.posts[indexPath.row]["thumbnail_images"]["medium_large"]["url"].stringValue

    let cleanString = removeHtmlTagsFromResponse(index: indexPath.row)
    cell.nutriTitle.text = self.posts[indexPath.row]["title"].stringValue
    print("labels: \(self.posts[indexPath.row]["title"].stringValue)")

    cell.nutriDetail.text = cleanString
    let lCount = calculateHeightOfLable(cellLabel: cell.nutriDetail)
    print("string: \(cleanString)")
    print("HeightCount: \(lCount)")
    cell.nutriImage.sd_setImage(with: URL(string: image), placeholderImage: UIImage(named: "no_image"))
    let heightContentSize = cell.bounds.height
    print("HeightContentSize= ",heightContentSize)
    return cell
}

A: It looks like you are using SDWebImage to load your images from a URL.  In the documentation you will find that there is another method on UIImage called: sd_setImageWithURL:placeholderImage:options:completed: which takes a completion handler with 4 parameters: image: UIImage, error: NSError, isCache: Bool, and url: URl.  Use the first parameter to get the size of the image.  Note that this is asynchronous; you don't get the size until the image is downloaded (assuming you don't already have it in the cache), so then cell may resize if you are dynamically sizing it.


text:
Q: Translate MySQL query into cakephp query I would like to translate this $query using the find() method of the cakephp's ORM.
$custom_query = $this->Agency->query(
        "SELECT a.id, a.name, a.created, c.total
          FROM agencies a
            join (SELECT agency_id, sum(price) total
                    FROM commands
                    GROUP BY agency_id) C
              on a.id = c.agency_id;"
    );

(This query does exactly what I want but I'd like to understand how to use cakephp ORM and $virtualFields)
Thank for your help and your time.

A: IF you are using CakePHP 1.3 or higher, you can define virtual fields in the model(i.e. calculated fields).
According to your query, I would define the virtual field in the model class like this:
$virtualFields = array(
   'total'=>'(SELECT SUM(price) FROM commands WHERE agency_id = Agency.id)'
);

Then you can call that field as a regular ORM field:
$this->Agency->find('all',array(
    'fields'=>array(
        'id','name','created','total'
        )
    )
);

The Cake manual page : http://book.cakephp.org/2.0/en/models/virtual-fields.html


text:
Q: Override ActiveSupport::Concern in model I have a concern that looks like this:
module Foo
  extend ActiveSupport::Concern

  def bar
    puts "bar"
  end
end

Three other models use that class methods since they need to the same thing. Then I have a one-off model that needs the method to do something else. I have the set up like this:
class FooFoo < ApplicationRecord
  def self.bar
    puts "foo bar"
  end
end

Now, when I call FooFoo.bar, it would print "foo" instead of "foo bar". How do I override the method defined in the concern? I want it to only run the method defined in my model, FooFoo, and not the one in the concern, Foo. I looked all over but I don't think I saw what I needed. some help would be greatly appreciated!
EDIT: I also tried this hoping it would work but it didn't:
class FooFoo < ApplicationRecord
  def FooFoo.bar # I used FooFoo.bar here instead of self.bar
    puts "foo bar"
  end
end

A: The problem is that you need to explicitly state that you want bar to be a class method...
module Foo
  extend ActiveSupport::Concern

  class_methods do
    def bar
      puts "bar"
    end
  end
end

Now, you can override it...
class FooFoo < ApplicationRecord
  def self.bar
    puts "foo bar"
  end
end


text:
Q: Change time zone on all sharepoint online sites Im trying to change the time zones on all sharepoint sites in the tenant, but i am getting "The remote server returned an error: (401) Unauthorized." error.
My user is Global Admin and Sharepoint Admin with MFA enabled.
$adminurl ="https://tenant-admin.sharepoint.com"
$timezone ="(UTC+01:00) Amsterdam, Berlijn, Bern, Rome, Stockholm, Wenen"

#Connect To SharePoint Online
$AdminCredentials = Get-Credential

#Connect To SharePoint Online
Connect-SPOService -Url $adminurl

#Get all Site Collections
$SitesCollection = Get-SPOSite -Limit ALL

#Change timezone for alle SPO Sites
ForEach($Site in $SitesCollection)
{
Write-host -f Yellow "Setting Timezone for Site Collection:"$Site.URL

Set-SPOnlineTimeZone -SiteURL $Site.URL -TimezoneName $timezone -cred $AdminCredentials

}


text:
Q: Moon paradox 2.0 Can anyone help me with what goes wrong with the following Moon paradox thought experiment ?
You all know the faster than light (FTL) Moon "paradox": send a beam to the moon through a "hand laser," and swipe the laser sufficiently fast from some point $A$ to some point $B$ on the lunar surface.
The beam can then easily made to move faster than light on this trajectory.
But it is not a paradox, since no actual photon travels that way, and no information is passed from $A$ to $B$.
But what if we change the experiment a little: call the person with the laser "Angie" and an observer on the moon "Billy."
Suppose Angie swipes the laser very fast from $A$ to $B$, or suppose she draws a little letter, or symbol. (The swipe from $A$ to $B$ could be a symbol for some letter.)
She can do this such that the symbol is drawn faster than the speed of light.
If Billy observes this symbol, it seems at first sight that he gets the information FTL.
What goes wrong ?

A: Suppose that Angie flips a coin and wants to communicate to Billy the result of that flip. This is what is meant by "information". She may communicate the result of the flip by drawing different symbols on the moon. The time between the flip and the symbol is not limited by the time it takes for the light to trace the symbol, but by the time it takes for the light to go from earth to the moon. This is not FTL.
The only thing that appears FTL here is the tracing of the symbol from A to B. However, this is not information transfer from A to B. Someone at A who is flipping a coin cannot use Angie's symbol drawing to inform a person at B about the outcome of the flip FTL. The information in the symbol is traveling from Earth to the moon, not from A to B. As such, the information transfer is not FTL.

A: The beam you are talking about, will not hit the position on the lunar immediately. Laser light, as most other light, has the same speed as ordinary photons. It means, that when you change the angle of the laser, it will take some time for the light to travel from you hand to the moon. Therefore, you will not get any special effect.
The FTL-moon paradox forgets that the laser beam has to travel from earth to the moon again and again every time it changes position.

A: Paradoxes appear when one is mixing up frames of reference.

Suppose Angie swipes the laser very fast from A to B,

You have already said that this is no paradox as it is not the same photons that travel in the image on the moon

or suppose she draws a little letter, or symbol. (The swipe from A to B could be a symbol for some letter.)

If she traces a letter  with her laser (mind you the drawing mechanism needs some
thinking) it will be completed as a recognized letter by Angie, or by a picture of the moon, calculations giving faster than light the motion of the writing beam on the moon. For an observer on the moon to see the information, i.e. that it is a letter, will need detecting systems and local time taken.  Maybe individual detectors in the kilometers of surface, and the information that the whole plots a letter, will arrive to Bob much slower than the speed of light, as all detectors are limited by the speed of light.
So it is mixing up the observer frame of Angie with the observer frame of Bob on the moon that makes the paradox.
She can do this such that the symbol is drawn faster than the speed of light.

A: There is no paradox. You are confusing two separate quantities, 1) being the time taken for information to travel to the moon from Angie, and 2) being the elapsed time for parts of the message to arrive at different points on the moon.
1) is subject to the rule that nothing can travel faster than light.
2) is not subject to any limits whatsoever.
Angie could use a laser to write 'The answer is 42' on the surface of the moon, as you suggest, which might take a certain time to complete. She could just as easily project it in huge letters that arrive on the surface simultaneously with each other. There is nothing in SR which prevents spatially separated events in one reference frame from happening simultaneously.
What counts is that in either case the time taken for the message to go from the Earth to the Moon is determined by the speed of light.


text:
Q: Trigger to insert on referenced table on fk failure? Is it possible to create a trigger to insert a record into a referenced table on a foreign key constraint in MySQL?
Let's say I have a table services with services.service_id and a table service_log with service_log.service_id referencing services.service_id and another field called service_log.log_id.
Upon failure of an insert into service_log because of an invalid service_id, is it possible to then create a trigger that would insert into services with a new service_id such that the original insert could be made afterwords (preferably in one step automatically)?


text:
Q: How to Authenticate User Against ADFS from my Custom SSO applicaiton i m little confused.i m creating a single sign on application for my applications.so the flow is when user try to access Login Controller of  example.com i m redirecting user to my SSO application
 FederatedAuthentication.WSFederationAuthenticationModule.RedirectToIdentityProvider("example.com", "example.com", true);

and  in this application i m showing a login page where user can input UserName and Password.So now i want  to authenticate User on the basis of these credentials from my ADFS.But i m confused how to do it
this  my Login Page

@using SingleSignOn.Models

@model LoginModel

@{
    ViewBag.Title = "Login";
}

Login

@using (Html.BeginForm(new { returnUrl = ViewBag.ReturnUrl }))
{
    @Html.ValidationSummary()

        @Html.LabelFor(m => m.Username)

        @Html.EditorFor(m => m.Username)

        @Html.LabelFor(m => m.Password)

        @Html.EditorFor(m => m.Password)

        <input type="submit" value="Login" />

}

Here is my Post Method which is using  Form Authentication but i have to Use ADFS authentication here.
 [HttpPost]
    public ActionResult Index(LoginModel loginModel, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (loginModel.Username == "user" && loginModel.Password == "password")
            {
                FormsAuthentication.SetAuthCookie(loginModel.Username, true);
                return Redirect(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "The username or password provided is incorrect.");
            }
        }

        ViewBag.ReturnUrl = returnUrl;

        return View(loginModel);
    }

This my Index Method where want to receive Claims sign in User and then Redirect to example.com
 public ActionResult Index()
    {
        if (User.Identity.IsAuthenticated)
        {
            var action = Request.QueryString[Action];

            if (action == SignIn)
            {
                var formData = ProcessSignIn(Request.Url, (ClaimsPrincipal)User);
                return new ContentResult() { Content = formData, ContentType = "text/html" };
            }
            else if (action == SignOut)
            {
                ProcessSignOut(Request.Url, (ClaimsPrincipal)User, (HttpResponse)HttpContext.Items["HttpResponse"]);
            }
        }

        return View();
    }

A: ADFS does not allow a custom login page. ADFS itself provides the login page when you redirect to it and returns after successful authentication with a SAML token.
This example is for Azure AD but illustrates the principles.
Just use the ADFS metadata address.


text:
Q: Is there a callback function for internal page links On - window.location.hash - Change?
The above question talks about hash change while this question talks about callback whenever internal link is clicked
I have many links in a page that points to another location in the same page using # links. Whenever, I click one such link, the page scrolls to that location. But I need to adjust the scroll manually after the automatic scroll happens. So would like to know if there is any callback function for such events?
Also the event should fire if the # tag was present in the initial page load (not only when it is clicked with a link) and when the same link is clicked again (hashchange event won't fire in this case)

A: You can register one by calling this function on the element:
addEventListener('click', function(){/*update your stuff here/*});
in jQuery, it's even easier
$('a').on('click', function(){/*update your stuff here/*}); will update after every link click.

A: There is no specifica callback that I know of but you could bind a function to the window.onscroll (https://developer.mozilla.org/en-US/docs/DOM/window.onscroll) event. That will detect when the window has been scrolled by the links being clicked and will let you make your adjustments. Then only problem is that it will also fire off when a user scrolls the page normally.
Other than that you would add a class to all your # links that will allow you to detect when one has been clicked. In jQuery:
$("a.HASH-LINK-CLASS").on("click", function (event) { ... });


text:
Q: How to generate ATOM and RSS2 feeds with ASP.NET Web API? What steps are needed to adjust the default XML output of the ASP.NET Web API to generate ATOM and RSS2 feeds?

A: You will need to implement a custom MediaTypeFormatter.  You might want to check Filip's blog post on RSS & Atom MediaTypeFormatter for ASP.NET WebAPI.


text:
Q: Event horizon around branes I'm wondering if a brane is a massive topological defect, does it have an event horizon?
Is it related to the effect capuring matter fields on the brane?
Thanks for the answers


text:
Q: data binding with as3 I have a bit of a problem (since I'm not used to binding with AS3), the thing is that I want to do this kind of data binding:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="vertical"
    verticalAlign="middle"
    backgroundColor="white">

<mx:XML id="dp" source="countries_states_cities.xml" format="e4x" />

<mx:Form>
    <mx:FormItem label="Country:">
        <mx:ComboBox id="countryCB"
                dataProvider="{dp.country}"
                labelField="@name" />
    </mx:FormItem>
    <mx:FormItem label="State:">
        <mx:ComboBox id="stateCB"
                dataProvider="{countryCB.selectedItem.state}"
                labelField="@name" />
    </mx:FormItem>
    <mx:FormItem label="City:">
        <mx:ComboBox id="cityCB"
                dataProvider="{stateCB.selectedItem.city}"
                labelField="@name" />
    </mx:FormItem>
</mx:Form>

but the ComboBoxes are being created dynamically with AS3, everything is working except I cant bind the second ComboBox dataProvider to be the XMLList in the first ComboBox's selectedItem.

A: I guess you need runtime binding. It is done with BindingUtils class, see this for example. As for your case, it must be something like
BindingUtils.bindProperty(secondCombobox, "dataProvider",
    firstCombobox, "selectedItem");

A: Are you creating it dynamically based on data?  If so, you could always use the Repeater component to repeat what you're trying to accomplish.
<mx:Repeater dataProvider="{someData}">
    <mx:FormItem label="{data.label}">
        <mx:ComboBox dataProvider="{data.stateCB.selectedItem.city}"
                labelField="@name" />
    </mx:FormItem>
</mx:Repeater>

A: Thanks, that is exactly what I was looking for, the code line that works for me is something like:
BindingUtils.bindProperty(comboBox, 'dataProvider', parentCB, {name: 'selectedItem', getter: function (host:ComboBox):XMLList {
                                var dp:XMLList;
                                if (host.selectedIndex >= 0) dp = host.selectedItem.children();
                                else dp = new XMLList();
                                return dp;
                            }}, true);

However, I haven't been able to access the "site" inside the function, only the "host". Basically what I'm trying to do is make the second ComboBox start with selectedIndex = -1


text:
Q: Setting up Docker repository using subdomain method docker login - how to log in only once for any docker repositories
I set up the on premise Artifactory to host some Docker repositories, using the subdomain approach, i.e. repo1.mycompany.com, repo2.mycompany.com, etc.  Everything is working fine.  My question is, look like I need to do the 'docker login repo1.mycompany.com' for each repository.  Is there a way to log in only once, for all the repositories, and then when pulling/pushing images from/to any repository, there's no need to log in again?
No code to shown here.  This is all about setup.
No need to login for each repo.

A: With subdomain method each docker repository is considered as a docker registry for the client this is why you need to login to each one you want to use.
For the pull from any without login you can use a virtual repository and aggregate all your locals in it. So you'll need to login the the virtual only to be able to pull from any (through the virtual). But push will be limited to the default deployment target repo defined in the virtual one.
Another alternative is to use repo path instead of subdomains. With this approach you'll be able to login on Artifactory and use all repo :
docker login mycompany.com
docker pull/push mycompany.com/repo1/imageName
docker pull/push mycompany.com/repo2/imageName


text:
Q: Why do Firefox and Chrome render this scrollable region in a flex child differently and how do I make Firefox work as Chrome does? I am constructing a toolbar with a dynamic amount of elements to the right side of a page with height that always equals viewport height.
The toolbar is split in two regions, and if too many elements are included, the upper region is supposed to scroll.
However, with my solution, in Firefox the scrollbar is above the elements. In Chrome, it renders just as expected and shifts the elements to be scrolled to the side.
I searched some time, but my search words are overlapped with older issues regarding min-height:0 and min-width:0 for a flex child issue. The issue where the scrollbar itself is just above the scrollable region's content I could not find.
Reproduction on JSFiddle: https://jsfiddle.net/3o65an7m/4/
Reproduction also copied here, but imo easier to see the issue on JSFiddle:

html {
  height: 400px;
}

body, .wrap {
  height: 100%;
  margin: 0;
}

.wrap {
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.right-bar {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  min-height: 0;
}

.upper {
  flex-grow: 1;
  overflow-y: auto;
}

.footer {
  color: white;
  width: 100%;
  background: blue;
}

.b {
  height: 20px;
  width: 20px;
  background: red;
  margin: 4px;
  padding: 4px;
}

Text

Image comparison; left FF, right Chrome. I desire the behaviour to always be as visible in Chrome:


text:
Q: Inserting reactive values in ReactiveValues I have the following Shiny App
server <- function(input, output, session) {
  rv <- reactiveValues(i = 0)

  output$myplot <- renderPlotly({
    dt = data.frame(x = 1:10, y = rep(rv$i,10))
    plot_ly(dt, x = ~x, y =~y, mode = "markers", type = 'scatter') %>%
      layout(yaxis = list(range = c(0,10)))
  })

  observeEvent(input$run,{
    rv$i <- input$valstart
  })

  observe({
    isolate({rv$i = rv$i + 1})
    if (rv$i < 10){invalidateLater(1000, session)}
  })
}

ui <- fluidPage(
  sliderInput('valstart','Start Value', min = 1, max =3, value= 3),
  actionButton("run", "START"),
  plotlyOutput("myplot")
)

shinyApp(ui = ui, server = server)

I would, however that the value of rv at the beginning when I launch the app to depend on a parameter (here my slider input). I would like something like that:
rv <- reactiveValues(i = input$valstart)

But this give me the following error :

Error in .getReactiveEnvironment()$currentContext() :    Operation not
  allowed without an active reactive context. (You tried to do something
  that can only be done from inside a reactive expression or observer.)

It seems that I can't insert reactive values inside reactiveValues... any solution?

A: Does observeEvent not get triggered at the start of the app?
How about:
rv <- reactiveValues(i = 0)

observeEvent(input$valstart,{
    rv$i <- input$valstart
  })


text:
Q: Spotify Web Player style UI in AngularJS I know this is a pretty big and vague question, but if someone good give me a push in the right direction that would be great. I'm trying to build a UI in the vein of Spotify's web player (play.spotify.com), and have been struggling trying to get anything workable (using angular-ui-router and ngAnimate). The main part of the interface I'm looking to replicate is the cascading panels sliding in from the left; that is, how would I implement that using ui-views, when there are potentially infinite views transitioning in from the right, and I can't simply replace one view with another (the previous view stays on the left side of the screen). It's tough to articulate, so this may not make any sense unless you actually use their web player, but if you have had/have a play with it then you might understand.
But yeah, any conceptual overview or hints on how I would implement this with angular-ui-router (or perhaps another module I don't know about) would be greatly appreciated.

A: Your question will probably get downvoted because it's so vague, as you mentioned, but I'll try and help out...
Use ui-router (from the Angular UI team) instead of angular's ngRoute. You can then programmatically load in the left side view based on whatever state you want. So you'll have something like the below in your .config...
.state('home', {
    url: '/',
    views: {
        '': {
            templateUrl: 'app/home.html',
            controller: 'homeController'
        },
        'nav@home': {
            templateUrl: 'app/nav.html',
            controller: 'navController'
        },
        'footer@home': {
            templateUrl: 'app/footer.html'
        },
        'rightContent@home': {
            templateUrl: 'app/default.html'
        },
        'leftContent@home': {
            templateUrl: 'app/menu.html'
        }
    }
})

.state('home.leftSideOne', {
    url: 'leftSideOne',
    views: {
        'content@home.leftSideOne': {
            templateUrl: 'app/leftSideOne.html',
            controller: 'leftSideOneController'
        }
    }
})

.state('home.leftSideTwo', {
    url: 'leftSideTwo',
    views: {
        'content@home.leftSideTwo': {
            templateUrl: 'app/leftSideTwo.html',
            controller: 'leftSideTwoController'
        }
    }
})

Then your html could have

And in your controller...
var leftLeftSide = function () {
  $state.go('home.leftSideTwo');
  // or whatever state you should be moving to
}


text:
Q: How to start imacros from html or php? I'd like to call imacros files from web pages to start automatically after button click or something. I have followed the imacros docs but i got confused.
Is there any method to do that?
thanks

A: I found a simple code did the job in new iMacros version.
imacros://run/?m=macrofile.iim
for example

Run macro


text:
Q: Cant set textLabel because it contradicts parseDouble I have an ItemListener that looks like this:
private class Listener implements ItemListener
{
    public void itemStateChanged(ItemEvent e)
    {
        calculate();
    }
}

At the bottom of my calculate() method, I set these labels like this:
subtotalLbl.setText("\t\t\t\t\t\t\t\tSubtotal:\t\t\t\t\t\t\t\t\t " + String.valueOf(determinedSubTotal + priceIncrease) + "\t\t\t\t\t\t\t\t\t");
taxLbl.setText("\t\t\t\t\t\t\t\tTax:\t\t\t\t\t\t\t\t\t " + String.valueOf(determinedTax + priceIncrease) + "\t\t\t\t\t\t\t\t\t");
totalLbl.setText("\t\t\t\t\t\t\tTotal:\t\t\t\t\t\t\t\t\t " + String.valueOf(determinedTotal + priceIncrease) + "\t\t\t\t\t\t\t\t\t");

Then I have an ActionListener that uses the text from the totalLbl for parseDouble
private class BtnClicked implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String input = totalLbl.getText().trim();
        Double parsedString = Double.parseDouble(input) * 0.20;

        Object src = e.getSource();

        if(src == submit)
        {
            JOptionPane.showMessageDialog(null,"Thank you for your order - the tip will be " + fmt.format(parsedString), "Thank you" , JOptionPane.INFORMATION_MESSAGE);
        }
        else if(src == cancel)
        {
            JOptionPane.showMessageDialog(null,"Order was canceled" ,"Order Canceled" , JOptionPane.INFORMATION_MESSAGE);
        }
    }

Obviously the program is crashing at the line inside of the BtnClicked's actionPerformed method where parseDouble(input) is at, because the totalLbl JLabel has "Total:" in it.. where else would I set this or how would I work around this? The "Total:" is required. (can't use split() )
Here's a screenshot of what the entire JFrame looks like, program crashes when clicking the submit button:

A: Create two JLables, one which says Total: the other which actually holds the total value.
So your total calculation would look more like...
totalLblText.setText("Total:");
totalLbl.setText(String.valueOf(determinedTotal + priceIncrease));

Then you won't need to care.
You should make better use of your layout managers in order to support the formatting your trying to achieve rather than using formatting characters like \t, these will always end up in a mess
Updated with layout example
This simple example demonstrates how you might use a layout managers (and a technique known as compound layouts) and relieve the need to try and use a single label for displaying more information then it should...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestLayout {

    public static void main(String[] args) {
        new TestLayout();
    }

    public TestLayout() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextField numberOfPizzas;
        private JCheckBox pepperoni;
        private JCheckBox sausage;
        private JCheckBox peppers;
        private JCheckBox onions;
        private JCheckBox mushrooms;
        private JCheckBox extracheese;

        private JLabel lblSubTotal;
        private JLabel lblTax;
        private JLabel lblTotal;

        public TestPane() {

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            JPanel header = new JPanel();
            JPanel extras = new JPanel(new GridBagLayout());
            JPanel totals = new JPanel(new GridBagLayout());

            add(header, gbc);
            gbc.gridy++;
            add(extras, gbc);
            gbc.gridy++;
            add(totals, gbc);

            numberOfPizzas = new JTextField(5);
            header.add(new JLabel("Number of pizzas"));
            header.add(numberOfPizzas);

            gbc = new GridBagConstraints();

            pepperoni = new JCheckBox("Pepperoni");
            sausage = new JCheckBox("Sausage");
            peppers = new JCheckBox("Peppers");
            onions = new JCheckBox("Onions");
            mushrooms = new JCheckBox("mushrooms");
            extracheese = new JCheckBox("Extra Cheeses");

            JCheckBox left[] = new JCheckBox[] {pepperoni, peppers, mushrooms};
            JCheckBox right[] = new JCheckBox[] {sausage, onions, extracheese};

            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(left, extras, 0, 1, gbc);
            gbc.gridx = 1;
            gbc.gridy = 0;
            add(right, extras, 0, 1, gbc);

            gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.EAST;
            gbc.insets = new Insets(2, 12, 2, 12);

            totals.add(new JLabel("Subtotal:"), gbc);
            gbc.gridy++;
            totals.add(new JLabel("Tax:"), gbc);
            gbc.gridy++;
            totals.add(new JLabel("Total:"), gbc);

            gbc.weightx = 0;
            gbc.gridx = 1;
            gbc.gridy = 0;

            lblSubTotal = new JLabel("8.0");
            lblTax = new JLabel("0.78");
            lblTotal = new JLabel("8.78");

            totals.add(lblSubTotal, gbc);
            gbc.gridy++;
            totals.add(lblTax, gbc);
            gbc.gridy++;
            totals.add(lblTotal, gbc);

        }

        protected void add(JComponent[] comps, JComponent parent, int deltaX, int deltaY, GridBagConstraints gbc) {

            for (JComponent comp : comps) {
                parent.add(comp, gbc);
                gbc.gridy += deltaY;
                gbc.gridx += deltaX;
            }

        }
    }

}

A: Lots of different ways to do this, the easiest is probably:
String[] parts = totalLbl.getText().split(":");
String input = parts[1].trim();
Double parsedString = Double.parseDouble(input) * 0.20;

A: you can do this
str = str.replaceAll("\\D+","");

this will delete non digits from the string
so you would want it to be like this
 Double parsedString = Double.parseDouble(input.replaceAll("\\D+","")*0.20);

A: You can use separate widgets for the label and the value. E.g. The total label, create a JLabel object and set the text with static value "Total:", then for the total value, create a JTextField object and set the text with the actual value. When submitting, get the value from the textfield instead of from the label. Don't forget to call setEditable(false) to the textfield because the textfield is meant to display the value only, not to accept input.


text:
Q: java.net.MalformedURLException: no protocol: Why I am getting no protocol if i have http in the url path?
Log:
network: Connecting http://xxx.ccc.local/upload/up.php?aa=0&bb=Ap%F3lice+de+Seguro&cc=1028&from=documentos with cookie "CLinkLanguage=en; __utma=232844939.1396040569.1356709687.1357294077.1357902500.12; __utmz=232844939.1356709687.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=232844939.24.10.1357902500; symfony=e0lpbkrcu0bidkpiujd1if4pt4; __utmc=232844939; CLinkLanguage=en; PHPSESSID=uv31kr1vpojvqgnc9ae9nda921"

Exception:
    java.net.MalformedURLException: no protocol:
        at java.net.URL.<init>(Unknown Source)
        at java.net.URL.<init>(Unknown Source)
        at java.net.URL.<init>(Unknown Source)

html
 <APPLET  CODE = "wjhk.jupload.JUploadApplet" ARCHIVE = "upload/wjhk.jupload.jar" WIDTH = "600" HEIGHT = "400" MAYSCRIPT></XMP>
        <PARAM NAME = CODE VALUE = "wjhk.jupload.JUploadApplet" >
        <PARAM NAME = ARCHIVE VALUE = "upload/wjhk.jupload.jar" >
        <PARAM NAME = "type" VALUE="application/x-java-applet;version=1.4">
        <PARAM NAME = "scriptable" VALUE="false">
        <PARAM NAME = "postURL" VALUE ="{$url}">
        <PARAM NAME = "anexosID" VALUE ="{$anexosID}">
        <PARAM NAME = "subanexosID" VALUE ="{$IdConsulta}">
        <PARAM NAME = "companyID" VALUE ="{$companyID}">
        <PARAM NAME = "resultURL" VALUE ="{$resultUrl}">
        <param name="debug" value="true">

    Java 1.4 or higher plugin required.

<APPLET  CODE = "wjhk.jupload.JUploadApplet" ARCHIVE = "upload/wjhk.jupload.jar" WIDTH = "600" HEIGHT = "400" MAYSCRIPT></XMP>
    <PARAM NAME = CODE VALUE = "wjhk.jupload.JUploadApplet" >
    <PARAM NAME = ARCHIVE VALUE = "upload/wjhk.jupload.jar" >
    <PARAM NAME = "type" VALUE="application/x-java-applet;version=1.4">
    <PARAM NAME = "scriptable" VALUE="false">
    <PARAM NAME = "postURL" VALUE ="http://xxx.ccc.local/upload/up.php?aa=0&bb=Alvar%E1%2Ffg&cc=1028&from=documentos">
    <PARAM NAME = "anexosID" VALUE ="">
    <PARAM NAME = "subanexosID" VALUE ="">
    <PARAM NAME = "companyID" VALUE ="">
    <PARAM NAME = "resultURL" VALUE ="">
    <param name="debug" value="true">

Java 1.4 or higher plugin required.
</APPLET>

A: The value of the postURL parameter is a URL that can be parsed without exceptions, therefore the problem is somewhere else. What you can do:

*

*Experiment with various applet parameters

*Ask for support from the developers of the applet

*If you don't have the source code of the applet, you can probably still decompile it, and find out how it works: Where can I find a Java decompiler?
The following program shows only that the postURL value is OK for Java:
public class A {
    public static void main(String[] args) throws MalformedURLException {
        String s = "http://xxx.ccc.local/upload/up.php?aa=0&bb=Alvar%E1%2Ffg&cc=1028&from=documentos";

        URL url = new URL(s);
        String protocol = url.getProtocol();
        System.out.println(String.format("A::main: protocol = '%s'", protocol));
    }
}


text:
Q: Can I use Hibernate with JTA? If JTA is an API, can I use Hibernate as an implementation of JTA?
I have an application with Spring and Hibernate and I wonder which framework should be responsible for transactions, Spring or Hibernate?

A: Hibernate is not an implementation of JTA. Hibernate is a JPA implementation.
JTA is an enterprise transaction spec, that's implemented by Java EE providers or stand-along transaction managers (e.g. Bitronix).
Hibernate offers a Transaction API abstraction because ORM tools employ a transactional write-behind Persistence Context.
Spring offers a transaction management abstraction, which allows you to switch from RESOURCE_LOCAL to JTA transactions with just some trivial configuration changes.
Spring manages to integrate on top of Hibernate/JPA Transaction API abstraction too.
If you use Spring, then you should take advantage of its transaction management abstraction, and so you don't have to use the Hibernate/JPA Transaction API.
Because Spring uses AOP, the transaction management is decoupled from your business logic, which would not be the case if you were using the programmatic Hibernate/JPA Transaction API.


text:
Q: Nginx url mapping Right now I have my website running on tomcat, www.domain:11000/projectName, I am trying to map when the user enters www.domain:10000 (would do port 80 but my ISP blocks port 80 so I use port forwarding 10000-->80) I created a new site in my site-available with the code:
server{ location / { include /etc/nginx/conf.d/proxy.conf; } }

and inside the proxy.conf file i have:
proxy_set_header Host $host:11000/*projectName*;

When I try to access the site now it just gives me a 404.
What am I doing wrong? and what can I do to make it work.

A: You should carefully read the documentation: http://wiki.nginx.org/JavaServers
After that, you can try this sample virtual host configuration and tweak it as needed in your case:
server {
  listen          80;
  server_name     YOUR_DOMAIN;
  root            /PATH/TO/YOUR/WEB/APPLICATION;

  location / {
    index.jsp;
  }

  location /projectName/ {
    proxy_pass              http://localhost:11000;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        Host $http_host;
  }
}

If your port 10000 is not redirected to port 80 (I didn't really understand your explanation above), you should replace listen 80; with listen 10000;.


text:
Q: compound layout doesn't show inner views I extended from LinearLayout and inflated views, but on the screen those views in my layout are not appeared. I see my view group in editor, but it seems like it's empty. No views inside it.
FragmentPickerViewGroup looks like this:
package com.test.pecode.myapplication;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class FragmentPickerViewGroup extends LinearLayout {
   private ImageView background;
   private Button minusButton;
   private Button plusButton;

    public FragmentPickerViewGroup(Context context) {
        super(context);

        init();
    }

    private void init() {
        setOrientation(LinearLayout.HORIZONTAL);

        inflate(getContext(), R.layout.view_fragment_picker, this);
        minusButton = findViewById(R.id.minus_btn);
        plusButton = findViewById(R.id.plus_btn);
        background = findViewById(R.id.background_rectangle);

        minusButton.setVisibility(INVISIBLE);
        minusButton.setGravity(Gravity.TOP | Gravity.START);
        minusButton.setBackgroundResource(R.mipmap.button_bg);

        background.setBackgroundResource(R.mipmap.rectangle);
        background.setBackgroundResource(R.mipmap.rectangle);

        plusButton.setBackgroundResource(R.mipmap.button_bg);
        plusButton.setGravity(Gravity.TOP | Gravity.END);
   }

   public FragmentPickerViewGroup(Context context, @Nullable AttributeSet
    attrs) {
        super(context, attrs);
        init();
   }

     public FragmentPickerViewGroup(Context context, @Nullable AttributeSet
        attrs,
        int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
   }

     public FragmentPickerViewGroup(Context context, AttributeSet attrs, int
        defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
   }
}

I used merge tag for my layout. Probably something goes wrong there? This is my layout, which I inflate into my view group:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <Button
        android:id="@+id/minus_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/background_rectangle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|top"
        android:contentDescription="@string/background_rectangle" />

    <Button
        android:id="@+id/plus_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</merge>


text:
Q: Pygame flip keeps flipping at the wrong time I am trying to make my image flip on pygame horizontally but I am slightly confused by how it works
I have tried to use the the pygame.transform.flip(bool_x, bool_y) function but it appears to take two boolean parameters which is quite confusing to understand and I am trying to make my player so that when the x_speed is negative or zero (going left) the player will be facing left and when the x_speed is positive (going right) the player will be facing right.
class Player:
    [...]

    def turn_around(self, direction):
        if direction == "left":
            self.picture = pygame.transform.flip(self.picture, True, False)

        elif direction == "right":
            pass

while True:
    [...]

    if keyboard_in == False:
        if joystick:
            movement = 3
            axis_x, axis_y = (joystick.get_axis(0), joystick.get_axis(1))
            if abs(axis_x) > 0.1:
                player_one.speed_x = movement * axis_x

    if player_one.speed_x >= 0:
        player_one.turn_around("left")

    if player_one.speed_x < 0:
        player_one.turn_around("right")

The actual results are that the player constantly keeps flipping left or right when the player is moving and when I let go of the joystick it appears to face a random direction:

sorry if the diagram is difficult to understand it was difficult to get an exact picture because the sprite was flipping left and right really quickly

A: Use 2 images. One for the left and one for the right:
class Player:
    def __init__():
        # [...]

        self.right = self.picture
        self.left = pygame.transform.flip(self.picture, True, False)

Choose the image dependent on the direction:
class Player:
    # [...]

    def turn_around(self, direction):
        if direction == "left":
            self.picture = self.left

        elif direction == "right":
            self.picture = self.right


text:
Q: Multiple pattern recognition in awk I have a file with the following format :
COL1 COL2 COL3 COL4

and I'm interested in COL2 (string) and COL4 (number) .
I need to verify, simultaneously that COL2="PATTERN" and that the COL4 without decimals = 32 (for example) .
I know how to do the COL2 pattern recognition doing something like:
awk -F"\t" '$2="PATTERN" {print }' file

but I've failed to impose the second condition or to combine both.
Any help to solve this problem will be welcomed .
Thanks

A: try this:
awk '$2 == "pattern" && int($4) == 32 {print $4}' file

I did a test here and it works:
echo "foo1 foo2 foo3 123.43" | awk '$2 == "foo2" && int($4) == 123 {print $4}'
output: 123.43

A: The second condition is ^[0-9]$. Chain the regexp using the &&.


text:
Q: Running Selenium 2.0 tests on a test web server I've got a bunch of web (integration) tests, that are coded in C# as nunit tests, using the Selenium.WebDriver nuget package which means I can run them from my test runner - I don't need to a selenium server or anything, they just work on my dev machine.
I want to get these tests to run on our test server, triggered from our build server (which happens to be team city but I don't think that's relevant).
So... How can I do this? Because these tests are wrapped up as c# unit tests, is the only way I'm going to be able to run them to install nunit on the test server, and run nunit against the tests, or does selenium support another way?
Thanks

A: We used jenkins, but we installed nunit and have it let the tests run then. I do not think that the selenium server setup would work without nunit or having these tests additional in an non-c# format.


text:
Q: FuelPHP ORM one to one relation is not saving? I'm trying to execute the following, the array contains some data that should be saved to the timeline table and the rest to the calendar table. However only the defaults or null data gets saved to the calendar while the timeline is updated correctly, the calendar_id field is set to 0.
/controller.php
$model = \Timeline\Model_Timeline::forge();
$model->calendar = \Timeline\Model_Calendar::forge();
$model->set($item);
$model->save();

/model/timeline.php
namespace Timeline;

class Model_Timeline extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'user_id' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
        ),
        'calendar_id' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
            'default' => '0'
        ),
        'created_at' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
            'default' => '0'
        ),
        'updated_at' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
            'default' => '0'
        )
    );

    protected static $_has_one = array(
        'calendar' => array(
            'key_from' => 'calendar_id',
            'model_to' => 'Timeline\\Model_Calendar',
            'key_to' => 'id',
            'cascade_save' => true,
            'cascade_delete' => true,
        )
    );

/model/calendar.php
namespace Timeline;

class Model_Calendar extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'start',
        'end',
        'recurrenceRule',
        'recurrenceException',
        'isAllDay',
        'created_at',
        'updated_at'
    );

    protected static $_belongs_to = array(
        'calendar' => array(
            'key_from' => 'id',
            'model_to' => 'Timeline\\Model_Timeline',
            'key_to' => 'calendar_id',
            'cascade_save' => true,
            'cascade_delete' => true,
        )
    );
}

A: Can I see $item variable.
I think you need to do something like that :
$model = \Timeline\Model_Timeline::forge();
$model->calendar = \Timeline\Model_Calendar::forge();
$model->calendar->set($calendar_properties);
$model->set($timeline_properties);
$model->save();

Because you just set some properties to Timeline and the Calendar item is empty and this is why you have calendar_id set to 0. Have you a new item on calendar table ?

A: Assuming these variables are arrays of columns => values, you can directly do
$model = \Timeline\Model_Timeline::forge($timeline_properties);
$model->calendar = \Timeline\Model_Calendar::forge($calendar_properties);
$model->save();


text:
Q: A word for a non-famous person/thing you have heard a lot about Someone or something you have heard a lot about. Not really a widely known person, but a friend of a friend or a local person (from your school/workplace/..). A thing you have discussed before, but is not well-known to outsiders.
Similar question: Looking for a word to describe someone who is famous to a small group of people
Cult hero from above question does NOT apply, and the best fit is the awkward and nondescript demicelebrity.

In my experience, people tend to colloquially use infamous with that sense (cf. The Infamous Swoosh) even though this does not match the dictionary definition.

infamous: well known for some bad quality or deed

I think peeps use infamous because they think of the word famous, but would feel silly using famous (the object in question has a more limited sort of "fame"). Familiar is close but not quite specific and expressive enough.

Contrived example:

I can't wait to meet your son Logan! I've heard so much (good stuff) about him! He's ________ [= well-known to me].

Actual examples from me texting:
> Me: https://68.media.tumblr.com/0dc47d322a9f8615dada2510ce522d20/tumblr_ojpmf5nYc41uy57v5o1_400.jpg
> Them: lol, I thought about the fast-food chains first, too!
> Me: i thought about Domains in the context of haskell
> Me: the infamous 'Dom' chain >_>

> [talking about modular smartphones]
> Me: that black guy from yesterday even has a video on them
> Me: next to techaltar's infamous video on them

What would be a better fit in this situation? Or am I stuck with demi-famous?

A: If I knew somebody wasn't famous objectively, but I kept hearing about them from people I met, I might say that—within my social group at least—they were ubiquitous.

existing or being everywhere at the same time : constantly encountered : widespread · a ubiquitous fashion
seeming to be seen everywhere

In other words, not necessarily famous, but still the "talk of the town."


text:
Q: Accessing class methods like instance methods class Foo
  def self.bar
    puts "foobar"
  end

  def bar
    self.class.bar
  end
end

I want to refrain from needing to define the instance method bar. Is there a way to automatically make class methods accessible as instance methods? Maybe with some method_missing? magic?

A: Try something like:
class Foo

  def self.bar
    puts "foobar"
  end

  def respond_to? name
    super or self.class.respond_to? name
  end

  def method_missing name, *args, &block
    if self.class.respond_to? name
      self.class.send name, *args, &block
    else
      super
    end
  end

end

You can also do this (simple version):
module ChainsToClass
  def respond_to? name
    super or self.class.respond_to? name
  end
  def method_missing name, *args, &block
    if self.class.respond_to? name
      self.class.send name, *args, &block
    else
      super
    end
  end
end

class Foo
  def self.bar
    puts "foobar"
  end
end

Foo.send :include, ChainsToClass

A: The easiest way would be to define methods in a submodule and extend and include it into the class:
class Foo

  module FooMethods
    def bar
      puts "foobar"
    end
  end

  # Add methods from module FooMethods as class methods to class Foo
  extend FooMethods

  # Add methods from module FooMethods as instance methods to class Foo
  include FooMethods
end


text:
Q: get line number within matcher.find() using matcher.start() I am using while(matcher.find()) to loop through and retrieve things from a file. I was wondering how would I get a line number from within this loop, if I knew the index of what I have found is at matcher.start().
I am confused, could someone please explain?
 String expr = "<[^<?!>]+>";
     String[] response = new String[5];

        Pattern p = Pattern.compile(expr);
        Matcher m = p.matcher(xmlDocument);
        while (m.find()) {
        //  System.out.println(m.group() + " located at " + m.start());
       //   txtMatches.append(m.group() + " located at " + m.start() + "\n");
            if (itemStack.getCount() == 0 && m.group().contains("</")) {
                response[0] = "Orphan closing tag" ;
                response[1] = stripUnwantedChars(m.group(), true);
                response[2] =  String.valueOf(m.start()); //right here is where i want to return line number
                return response;
            }
        //rest of code

itemStack is a stack of pushed matches and then I am comparing them to see if there is no more items in the stack but there is a match with a closing tag.

A: You can use a reverse method to get line number by creating a region from 0 to character number returned from start().
For example,
class MatchTest {
public static void main(String...args) {
    try {
        FileInputStream fis = new FileInputStream("source.txt");
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        String data = new String(buffer);
        fis.close();

        Pattern pattern = Pattern.compile(args[0]);
        Matcher matcher = pattern.matcher(data);
        while(matcher.find()) {
            out.println(matcher.group());
            out.println(getLine(data, matcher.start()));

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

static int getLine(String data, int start) {
    int line = 1;
    Pattern pattern = Pattern.compile("\n");
    Matcher matcher = pattern.matcher(data);
    matcher.region(0, start);
    while(matcher.find()) {
        line++;
    }
    return(line);
}

}
Here, the getLine method will return line number.

A: You need to separately create an array of the indexes where each line starts, and then you can use this array together with the index returned by start() to figure out which line your match is on. A binary search of that line index array would do nicely. You could actually create this list of line indexes also by using a regex that matches a line end (matching just '\n' would be fine) and then starting each line at the next character.


text:
Q: Usando o TvideoImage para capturar imagem da webCam Estou utilizando o componente TvideoImage para capturar imagem através da webCam, porém estou com problema, foi criado um aplicativo que permite que tire fotos dos clientes para cadastro, o aplicativo foi incorporado no sistema principal para tirar fotos dos clientes, quando eu abro o aplicativo pelo sistema, na primeira vez funciona perfeitamente, mas quando eu fecho e tento abrir novamente, quando eu clico no botão ligar a imagem fica em branco.
Código no evento OnCreate:
fVideoImage := TVideoImage.Create;
bActivated := False;

DeviceList := TStringList.Create;
fVideoImage.GetListOfDevices(DeviceList);
cbListaCameras.Items := DeviceList;
DeviceList.Free;

Código usado para ligar a câmera:
procedure TFormCamera.btnLigarClick(Sender: TObject);
var
  camDevice: string;
begin
  try
     if not(bActivated)then
     begin
        camDevice := trim(cbListaCameras.Items.Strings[cbListaCameras.ItemIndex]);
        if(camDevice = '')then
        begin
           ShowMessage('Atenção, informe o dispositivo!');
           cbListaCameras.SetFocus;
           Exit;
        end;

        fVideoImage.SetDisplayCanvas(imgCamera.Canvas);
        fVideoImage.VideoStart(camDevice);
        bActivated := True;

        lblCameraStatus.Caption := 'Ligada';
        lblCameraStatus.Font.Color := clGreen;

     end else
        MessageDlg('Atenção, camera já está ligada!', mtWarning, [mbOK], 0);>>

  except
     bActivated := False;
     lblCameraStatus.Caption := 'Desligada';
     lblCameraStatus.Font.Color := clRed;
     ShowMessage('Atenção, erro ao tentar ligar a camera!');
  end;
end;

Código usado no botão para fechar:
fVideoImage.VideoStop;
bActivated := false;
imgCamera.Picture := nil;
//imgCamera.Picture.Bitmap.Assign(nil);
Close;


text:
Q: Verify real-time email verification FirebaseAuth I need to verify that the email is confirmed as soon as the user confirms the email, because in the main screen of my application I open a dialog informing the user that he needs to confirm the email in order to use the application.
While it does not confirm the email the dialog is displayed and if it closes the dialog will open again.
I am validating as follows:
auth.service.ts:
export class AuthService {

 usuario: any;

  constructor(private afAuth: AngularFireAuth) {}

      getUser() {
        return new Promise((resolve, reject) => {

          this.afAuth.auth.onAuthStateChanged((user: any) => {
            if (user) {
              this.user = user;
            }
            resolve(user);
          },
            (response: any) => {
              reject(response);
            });
        });
      }

main.component.ts:
    export class MainComponent {

    constructor( private authService: AuthService,){
            this.checkConfirmEmail();
    }

        checkConfirmEmail() {
            this.authService.getUser().then((user: any) => {
                if (user.emailVerified == false) {
                    this.showConfirmEmail();
                }
            });
        }
}

As above, it is only updated user.emailVerified when I refresh the page, I need a way so I do not have to refresh the page for user.emailVerified to come up to date.

A: A better real-time approach (HTTP polling is expensive and inefficient) is to build your own custom email verification landing page:
https://firebase.google.com/docs/auth/custom-email-handler
Then on that landing page you set some flag in a Database node that only that user can access to confirm the email was verified when you apply the code. For more security, you can make that node readonly and send the code to your server (or some http endpoint hosted with cloud functions), verify it there and then use Admin SDK to write the status change to that user's node.
On the client device were the user is logged in (and has read access to that node), you listen to that database node changes to detect email verification.


text:
Q: Brightness fn key adjustment problems My brightness function key controls work after setting grub boot parameter to "acpi_osi=" but using them I cannot adjust the brightness higher than around 70% (there is empty bar left over and I can't adjust higher) unless I go to Brightness & Lock settings manually than I can use the slider to adjust it higher... I primarily use intel_backlight to adjust my backlight and I am running Linux kernel 3.14.1 on Ubuntu 14.04 LTS on an ASUS X550LA Laptop
when I try:

cd /sys/class/backlight/intel_backlight
cat max_brightness
937
cat brightness
811

It seems that I can only adjust to a maximum of 811 using the fn brightness controls
If I instead do

cd /sys/class/backlight/acpi_video0
cat max_brightness
10
cat brightness
4
cat actual_brightness
10

With the FN keys actual_brightness is not equal to the value returned from brightness
on acip_video0 (which is always 4) but on intel_backlight actual_brightness = brightness
The adjustment problem seemingly arises because both intel_backlight and acpi_video0 are trying to adjust brightness


text:
Q: ZFS prevents server to shut down as it keeps disk active I have a small home sever running with Debian Buster where I have a ZFS filesystem (ZFS: Loaded module v0.7.12-2+deb10u2, ZFS pool version 5000, ZFS filesystem version 5) with a RAID.
As the server is sometimes not used for days I have configured a autoshutdown script which shuts down the server if my 2 big WD red hard disks are in standby for more than 45 minutes (not the system hard disk). Now I figured out that the server is not shutting down anymore as both drives are only a few minutes in standby before getting active again. I tested with iotop and figured out that ZFS with the command txg_sync is waking them up. Even if no other process is writing or reading anything on the drives.
By using iosnoop (https://github.com/brendangregg/perf-tools) I was able to identify that dmcrypt is writing to my disk in regular intervals. Please note that my underlying disks are encrypted with LUKS.
./iosnoop -d 8,16
Tracing block I/O. Ctrl-C to end.
COMM         PID    TYPE DEV      BLOCK        BYTES     LATms
dmcrypt_writ 1895   W    8,16     2080476248   4096    6516.10
dmcrypt_writ 1895   W    8,16     3334728264   4096    6516.14
dmcrypt_writ 1895   W    8,16     2080429048   16384      0.16
dmcrypt_writ 1895   W    8,16     3334728272   20480      0.21
dmcrypt_writ 1895   W    8,16     2080476256   20480      0.16
dmcrypt_writ 1895   W    8,16     3328225336   16384      0.20

What is the reason for that and how can I prevent this occuring?

A: It's not easy to identify I/O activity on a disk when using ZFS and a LUKS encrypted device. One way is to use a combination of iotop and iosnoop and killing processes to identify when I/O activity is stopped.
I was able to identify the process which was accessing my drive with
cut -d" " -f 1,2,42 /proc/*/stat | sort -n -k +3


text:
Q: IFELSE in R returning incorrect values I have a data frame with categorical values that were entered manually and there are several mistakes. Someone cleaned up the bad data and I loaded that into R and merged that with the rest of my data. Everything so far is good.
As an example, let's say this is the data I have with the original (mix of good and bad data) in the "Value" column and the corrections of the bad data in the "Value_Clean" column. Obviously this is a small example but my actual data frame has dozens of corrections of different values and several thousand rows.
test <- data.frame(ID = c(1, 2, 3)
               , Value = c("Discuss plan", "Discuss plan", "Discuss paln")
               , Value_Clean = c(NA, NA, "Discuss plan"))

I would like to create a new column called "Value_Final" that has "Discuss plan" for IDs 1, 2, and 3.
It seems pretty straightforward that I should be able to accomplish this with an ifelse:
test$Value_Final <- ifelse(is.na(test$Value_Clean), test$Value, test$Value_Clean)

However, when I do that I get the following:
> test
  ID        Value  Value_Clean Value_Final
1  1 Discuss plan         <NA>           2
2  2 Discuss plan         <NA>           2
3  3 Discuss paln Discuss plan           1

What the hell? I feel like I've done similar things with ifelse in R without running into this issue, so what is going?
Thanks!

A: It is a case of factor coercing to integer storage value.  Can be corrected with stringsAsFactors = FALSE while creating the data.frame
test <- data.frame(ID = c(1, 2, 3)
                , Value = c("Discuss plan", "Discuss plan", "Discuss paln")
                , Value_Clean = c(NA, NA, "Discuss plan"), stringsAsFactors = FALSE)
ifelse(is.na(test$Value_Clean), test$Value, test$Value_Clean)
#[1] "Discuss plan" "Discuss plan" "Discuss plan"

Or if the data is already created, then can convert to character with as.character
test[1:2] <- lapply(test[1:2], as.character)

Or do this within the ifelse
ifelse(is.na(test$Value_Clean), as.character(test$Value),
         as.character(test$Value_Clean))

A: The dplyr version of ifelse doesn't have this issue
ifelse(is.na(test$Value_Clean), test$Value, test$Value_Clean)

# [1] 2 2 1

dplyr::if_else(is.na(test$Value_Clean), test$Value, test$Value_Clean)

# [1] Discuss plan Discuss plan Discuss plan
# Levels: Discuss paln Discuss plan

FYI for this particular example you might use coalesce instead
dplyr::coalesce(test$Value_Clean, test$Value)
# [1] Discuss plan Discuss plan Discuss plan
# Levels: Discuss plan

A: you could try dplyr and tibbles as an alternative:
library(dplyr)

tibble(ID = c(1, 2, 3)
       , Value = c("Discuss plan", "Discuss plan", "Discuss plan")
       , Value_Clean = c(NA, NA, "Discuss plan")) %>%
  mutate(Value_Final = ifelse(is.na(Value_Clean), Value, Value_Clean))

tibbles don't convert character columns to factors per default, which comes in handy in many many cases
Edit:
use as_tibble(dataframe) to convert an existing dataframe to a tibble


text:
Q: gap between footer and contentwrapper that doesnt go away I am working on the following website http://bestofdesigns.be/studioregenbogen/index.html.
Can somebody please look at the css and tell me why the footer is not attached to the content and why there is a gap between the menu and the contentwrapper?
I have looked at this for 2 days and cannot seem to find what goes wrong.
Thanks,
Ben

A: #footer p {
padding-top: 5px;
margin: 0;
}

A:
why there is a gap between the menu and the contentwrapper?

The gap is due to the margin applied by default by each browser to the list <ul> element and the title <h1>.
Remove it or adjust it
Screenshot

A: hi now give to #footer overflow:hidden and give to your footer p tagmargin :0;`
as like this
        #footer{
        overflow:hidden;
}

    #footer p{
    margin:0;
    }

A: I am suggesting one more thing did you ever opened your design using firebug and checked how your middle content looks. It's bad design. Use div tags extensively don't use padding much.In the body style put text-align:justify property.
Your error is in
#footer p {
 padding-top: 5px;
 margin: 0;
}

Divide the content wrapper class into two vertical div classes and then divide the below vertical classes into another two vertical classes. Divide the first vertical tag into two horizontal div classes. In that put your image in first horizontal tag and in second your paragraph. In the bottom vertical class your second paragraph.


text:
Q: Site is loading HTML before CSS? No @import is being used It happens for a fraction of a second every time I get into the site and the CSS is not cached.
Here is the link:
http://69.89.31.88/~intrasc1/index.php

All my CSS files are using the link tag and this started to happen right after I upgraded from joomla 1.5 to 2.5. Also the template was from 1.5 and I upgraded it too.

A: You have a very unusual setup there.  No scripts except for livezilla tracking and google analytics. Kudos.
The style that's being loaded last is http://www.intras.com.do/livezilla/templates/style.css, and is causing the flicker effect.  But the script is not in your markup, nor in any @import inside one of the other css files.
Only one possible cause is left: the "livezilla - tracking" script. If you open it, here's the inclusion of the css:
if(lz_overlay_chat_available)
{
    createCSSCheck("csschkoc");
    LazyLoad.css(lz_poll_server + "templates/overlays/chat/style.css", function (arg) {}, '');
...

Which dynamically loads the
http://www.intras.com.do/livezilla/templates/style.css

In order to fix the issue, simply include this style in your template header, or add it with $document->addStyleSheet($url).
Since you've gone a long way optimizing the site and removing all scripts, why not take this as an opportunity and take the last step, join and minify all the css files into one?


text:
Q: How can i scan a qr code from ARScene Camera usin ARCORE Here I need some suggestion or a want to a way of doing this
Scenario: i want to scan a qr code in the ar scene and when i scan the qr code what ever content is there in qr code i will place in the ar scene here i dont want to use google vision instead i want to use the below package but the below package opens camera instead i want to use it in the AR scene it self
I used this package for qr scan https://github.com/zxing/zxing
below is my ar code
public class MainActivity extends AppCompatActivity {

    private ArFragment arFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment);
        arFragment.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {
          Anchor anchor = hitResult.createAnchor();
            ModelRenderable.builder()
                    .setSource(this, Uri.parse("anchor.sfb"))
                    .build()
                    .thenAccept(modelRenderable -> addModelToScene(anchor,modelRenderable))
                    .exceptionally(throwable -> {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setMessage(throwable.getMessage()).show();
                        return  null;
                    });
        });
    }

    private void addModelToScene(Anchor anchor,ModelRenderable modelRenderable){
        AnchorNode anchorNode  = new AnchorNode(anchor);
        TransformableNode transformableNode  = new TransformableNode(arFragment.getTransformationSystem());
        transformableNode.setParent(anchorNode);
        transformableNode.setRenderable(modelRenderable);
        arFragment.getArSceneView().getScene().addChild(anchorNode);
        transformableNode.select();
    }
}

A: I recommend trying the existing Augmented Images feature in ARCore
What you think is a QR code, the AR software sees as a fiducial marker. These markers need to known beforehand. For example in the video on the ARCore page, the painting is a fiducial marker which allows the 3D image to be overlaid.
The ARCore feature I linked to supports up to 1000 reference images/markers per marker database and you can create and use new predefined marker databases.
As long as you know what QR codes will have 3D effects, you can prepare them in a marker database.
If you want/need to have dynamic QR code with ARCore, I would suggest trying to create fiducial around/next to the QR code so that you can scan and then hand off to AR Core to generate the 3d image, but may not work as QR code may be mixed in with the fiducial both need white space to work.
If you can't use ARCore, then you are in the world of OpenCV and various scene engines (3D renderers) like Ogre or you can draw the AR scene in OpenGL ES.

A: ARCore gives you the frame or use a wrapper like sceneform. In sceneform you are able to get your frame from ARFragment.

*

*First get your fragment:

var arFragment = (supportFragmentManager.findFragmentById(R.id.your_ar_fragment) as ArFragment?)
arFragment.arSceneView?.scene?.addOnUpdateListener {
    onUpdateFrame()
}

*Analyze your frames for example read QR Codes

fun onUpdateFrame() = runBlocking {
    launch {
        analyze()
    }
}

private fun analyze() {
    frame = arFragment.arSceneView.arFrame
    //Do fancy stuff with your frame, e.g. reading QR Codes
    readingQRCodes(image)
}

private fun readingQRCodes() {
    val mediaImage = InputImage.fromMediaImage(image, 0)
    val scanner = BarcodeScanning.getClient()
    scanner.process(mediaImage)
        .addOnSuccessListener { qrCodes ->
            //...
        }
         .addOnFailureListener {
            //...
        }
        .addOnCompleteListener {
            image.close()
        }
}

Of course you can also use the ARCore library to get the camera frames.


text:
Q: Firefox doesn't post form Element Values I have a very simple form (.cfm page).  I'm submitting the form via AJAX in my javascript file.  The form works fine in IE, Safari and Chrome, but doesn't work in FF (v18.0).
Here is my form:
<form name="LoginForm">
<input class="newstext" type="text" name="userLogin" id="userLogin">
<input class="newstext" type="password" name="passLogin" id="passLogin">
<input type="button" name="login" value=" Login " onClick="validateLogin();">
</form>

Javascript code:
function validateLogin() {

    if (document.getElementById('userLogin').value == '') {
    alert('Please enter your username');
    document.getElementById('userLogin').style.backgroundColor='yellow';
    document.getElementById('userLogin').focus();
    return false;
}

if (document.getElementById('passLogin').value == '') {
    alert('Please enter your password');
    document.getElementById('passLogin').style.backgroundColor='yellow';
    document.getElementById('passLogin').focus();
    return false;
}

ColdFusion.Ajax.submitForm("LoginForm", "loginForm_action.cfm", submitLoginCallback, submitLoginerrorHandler);
return true;

}
When I try to login in, the form element values aren't being passed. So when it hits the cfc, the cfc says "Element USERLOGIN is undefined in FORM. The error occurred on line 9."   Any ideas?

A: When you posted the question did StackOverflow invite you to look at this?
Edit starts here
If you were not invited to look, you weren't.
The answer that got 6 votes was, "document.getElementsByName() returns an array, so you have to access it by an index: document.getElementsByName('staff_counter')[0] (depending on how many of these you have).
You also have access to a length property to check how many Elements were matched."
It makes sense to me given that you were presented with undefined variable problems.

A: Okay guys here is what I did to fix this issue.
It seems when the form was processed by Firefox there was malformed HTML caused by my <form> tag being inside a <table> tag and the cooresponding end tag (</form>) was also within the <table> tag.  After moving the form tags around the table the form work as expected.
Thank you all for trying to help me solve this issue that was difficult to figure out and I apologize for the confusion within my initial question.
David


text:
Q: Out of process video player on mac (vlcj) I've been using VLCJ to embed a number of media players in the same window - on Windows and Linux this works fine, because they can be out of process (which they need to be to be stable - in short because of native libraries underneath there's no way round this) and just alter the window in the other process.
However, does this out of process approach work on MacOS? The information I've found seems to suggest that it's not possible the way it is on Windows / Linux, but there's possibly some native call that can be made from one process to allow it to be controlled from another. Is this the case, and if so has anyone more information on any native code that might allow it to be the case? Apologies for the sparse information, I haven't got a Mac available to test on at the moment so can't run anything to try it out and see what happens!

A: It is possible to play video out-of-process in OS X 10.6 and later. The CoreVideo IOSurface API appears to allow this capability, though documentation is very sparse. This blog post on the subject may be a good place to start.
For IPC communication, you can use NSDistributedNotificationCenter for basic (string) messages, or Distributed Objects or the new XPC framework in 10.7. I'm not sure how accessible these technologies are from Java.


text:
Q: Injection in Injected class with Jersey I am having problems understanding injection principles in Java (im originally coming frm .NET world).
I have class extending frm AbstractBinder that contains two bindings:
bind(new Class1()).to(Class1Interface.class);
bind(Class2.class).to(Class2Interface.class).in(Singleton.class);

In Class2 i have:
@Inject
Class1Interface Instance;

Instance value is always null... What do i do wrong?
ADD0:
I assume there might be some configuration issue. Here is my web.xml
<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>com.myapp.configuration.AppMain</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

ADD1: Class1 and Class2
public interface Class1Interface{
Properties getProperties();
}

public Class1 extends Class1Interface{
@Override
public getProperties(){...}
}

public interface Class2Interface{
void SomeMethod();
}

public class Class2 extends Class2Interface{

@Inject
Class1Interface Config;

@Override
public void SomeMethod(){...}
}

Binder details listed earlier in the question.


text:
Q: Glassfish 3.1.2 with Infinispan 5.1.2 I'm using Glassfish 3.1.2 and Infinispan 5.1.2.
I want to override the config of the default cache manager and start some named caches in advance. Then I want to inject that cache manager into a stateless EJB and use name caches.
Code that I have:
Config.java:
@Produces
@ApplicationScoped
public EmbeddedCacheManager defaultEmbeddedCacheManager() {
    DefaultCacheManager returnCacheManager;

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.eviction().strategy(EvictionStrategy.NONE)
            .maxEntries(Integer.MAX_VALUE)
            .transaction().transactionManagerLookup(new GenericTransactionManagerLookup())
            .expiration().lifespan(Long.valueOf(-1)).maxIdle(Long.valueOf(-1));
    Configuration config = builder.build();

    returnCacheManager = new DefaultCacheManager(config);
    String cacheNames[] = new String[2];
    cacheNames[0] = "cache1";
    cacheNames[1] = "cache2";
    returnCacheManager.startCaches(cacheNames);

    return returnCacheManager;
}

CacheBean.java:
@Stateless
public class CacheBean implements CacheBeanLocal {
    public static final String _rev = "$Id";
    @Inject
    private EmbeddedCacheManager defaultCacheManager;

    @Override
    public void addToCache1(String key, String value) {
        Cache<String, String> cache1 = defaultCacheManager.getCache("cache1", true);
        cache1.put(key, value);
    }
}

When I deploy the EAR to Glassfish server I get this:
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [CacheContainer] with qualifiers [@Default] at injection point [[field] @Inject private org.infinispan.cdi.AdvancedCacheProducer.defaultCacheContainer]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:274)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:243)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:106)
    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:347)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:330)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:366)
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:199)
    at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:313)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
    at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)

What am I doing wrong?


text:
Q: AlloyDB: Drop database How could I drop an exisitng AlloyDB database programatically?
I'd like to run a test suite of our application on AlloyDB. I'm able to connect to the cluster using the proxy. However, when I try to drop database to cleanup the test environment, using code like:
echo "DROP DATABASE IF EXISTS application_test" | psql

I'm getting:
 ERROR:  syntax error at or near "DROP"
 LINE 2: DROP DATABASE IF EXISTS application_test

I'm sure I can connect to the cluster correctly, because I run other queries before this one.
How could I remove an existing database from a script? I can't find a good way to do that in the docs.

A: To run psql from the CLI you'll want syntax like:
psql -d postgresql://\<user>:\<password>@\<AlloyDB IP>:5432/postgres \
  -c "DROP DATABASE IF EXISTS \<dbname>"


text:
Q: Flash classic textfield with embedded font stop working when I use antialias I'm using Flash CS5.5, working with some graphics and using some classic textfields. But, one day I opened the fla and all the embedded textfields were blank. I changed it to other fonts and worked perfectly, but not the font I was using (Myriad Pro). It only works if I choose "Use device fonts".
So, does it has to do with some cache or something?
I've erased all the fonts, rebooted my computer, and again the same problem.
It's not a scripting problem, may be a bug in flash?
UPDATE:
In fact none of the OpenType CFF are working in my Flash. How can I restore these fonts?
UPDATE 2:
Does it has to do with the Windows XP updates of 13/12/12? Someone has another SO with the same problem?

A: I'm having the same problem with CS5 in Win7. And I also got a Windows update last night.
This info may be relevant: http://graphics-unleashed.unleash.com/2012/12/windows-update-kb2753842-will-make-some.html?showComment=1355447264092
....
Okay, I've tried it and can confirm that uninstalling KB2753842 fixes the problem for me.