text:
Q: apache-tomcat-9.0.0.M10: Change Context-Path in META-INF/context.xml not working I have a standard Tomcat9 installation. I just put a helloworld.war in the webapps folder and inside the META-INF I put the context.xml with a different path like:
<Context path="/newcontext" />
But the context is still http://localhost/helloworld instead http://localhost/newcontext.
I tried so many things, but it is not possible to get Tomcat convinced to use the new path. Anybody who can help?
Thanks.

A: I found that Tomcat will simply ignore the path attribute defined in context.xml. This is not explicitly stated in their documentation (https://tomcat.apache.org/tomcat-9.0-doc/config/context.html) but it is a behaviour I keep observing in every application we build.
As per Tomcat docs:

In individual files (with a ".xml" extension) in the
  $CATALINA_BASE/conf/[enginename]/[hostname]/ directory. The context
  path and version will be derived from the base name of the file (the
  file name less the .xml extension). This file will always take
  precedence over any context.xml file packaged in the web application's
  META-INF directory.

Though this discusses the conf files placed outside your WAR, it appears that the same applies to META-INF/context.xml
This is what the documentation suggests for your pains:

If you want to deploy a WAR file or a directory using a context path
  that is not related to the base file name then one of the following
  options must be used to prevent double-deployment:

*

*Disable autoDeploy and deployOnStartup and define all Contexts in server.xml

*Locate the WAR and/or directory outside of the Host's appBase and use a context.xml file with a docBase attribute to define it.

yet, then they go on to discourage Option 1.
I personally found the easiest solution to be simply to name your WAR file appropriately for non-root contexts and for root contexts (/) to simply use ROOT.war as per Tomcat's conventions.

A: To spare anyone else the time and effort of trying to deploy to a different path using META-INF/context.xml, and with respect to Pavel's answer and others, it would seem that it is simply not possible (in tomcat 9.x).
I was hoping to deploy to the root context through configuration of the war's META-INF/context.xml, but it would seem that it's not currently possible (tomcat 9.x).
With Host copyXML="true", the context.xml is deployed (to tomcat's conf/Catalina/<host>) using the war's base name. Due to path configuration rules, this then takes precendence in determining the path. That is, the path is named according to the .xml's base name - hence the war's basename. As the docs and the answer mentioned address, the Context path field is not respected unless it is used in the server.xml.
This is actually in the docs but is not immdiately obvious and you have to piece it together a bit, especially as the path attribute is readily available to the META-INF/context.xml.
See:
Tomcat 9.0/ Config Guide/ Naming

When autoDeploy or deployOnStartup operations are performed by a Host, the name and context path of the web application are derived from the name(s) of the file(s) that define(s) the web application. Consequently, the context path may not be defined in a META-INF/context.xml embedded in the application and there is a close relationship between the context name, context path, context version and the base file name (the name minus any .war or .xml extension) of the file.
If you want to deploy a WAR file or a directory using a context path that is not related to the base file name then one of the following options must be used to prevent double-deployment:
Disable autoDeploy and deployOnStartup and define all Contexts in server.xml
Locate the WAR and/or directory outside of the Host's appBase and use a context.xml file with a docBase attribute to define it.

Tomcat 9.0/ Config Guide/ Defining a Context

*

*Individual Context elements may be explicitly defined:

*

*In an individual file at /META-INF/context.xml inside the application files. Optionally (based on the Host's copyXML attribute) this may be copied to $CATALINA_BASE/conf/[enginename]/[hostname]/ and renamed to application's base file name plus a ".xml" extension.

Tomcat 9.0/ Config Guide/ Defining a Context/ Common Attributes/ path attribute

This attribute must only be used when statically defining a Context in server.xml. In all other circumstances, the path will be inferred from the filenames used for either the .xml context file or the docBase.

It seems to me, after a lot of play, that the only use of the META-INF/context.xml is in defining other configuration items of an application on deployment - e.g. resource configuration - though I'd be interested to know other's thoughts.
See Pavel's answer and others (below) for how to deploy to a different context path and to the root context (without using META-INF/context.xml - no autodeploy here(!)):

*

*Deploying my application at the root in Tomcat

*How to change the ROOT application?

*How to specify path in META-INF/context.xml for Tomcat

*How to set the context path of a web application in Tomcat 7.0

*Tomcat wiki/ Default application


text:
Q: Как в Glide добавить json body request и sertificate для получения картинки? Для получения картинки с сервера мне необходимо прикрепить хедеры, метод запроса (POST), тело запроса (JSONObject с несколькими полями ключ-значение) и сертификат.
Всё хорошо работает в ручной установке картинок в ImageView, но сейчас требуется использовать библиотеку Glide, в которую неизвестно как добавить все эти данные.
Так выглядит мой запрос на сервер, в котором Request - это класс-контейнер, который хранит в себе хедеры, HttpMethod и тело запроса (JSONObject):
private String executeRequest(Request request) {
    return executeRequest(buildHttpRequest(request));
}

private String executeRequest(HttpRequestBase httpRequest) {

    String response = "";

    String url = httpRequest.getURI().toString();

    boolean useCerificates = url.contains(HOST_SUBSTRING);

    try{

        URL URLObject = new URL(url);
        HttpURLConnection connection;

        connection = (HttpURLConnection) URLObject.openConnection();
        if(connection instanceof HttpsURLConnection) {
            if (useCerificates)
            ((HttpsURLConnection)connection)
                    .setSSLSocketFactory(getSSLContext().getSocketFactory());
            else {
                SSLContext sslContext;
                sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, null, new java.security.SecureRandom());
                ((HttpsURLConnection)connection)
                        .setSSLSocketFactory(sslContext.getSocketFactory());
            }
        }

        connection.setRequestMethod(httpRequest.getMethod());

        Header[] requestHeaders = httpRequest.getAllHeaders();
        for (Header requestHeader : requestHeaders)
            connection.setRequestProperty(requestHeader.getName(), requestHeader.getValue());

        if (connection.getRequestMethod().equals("POST")) {
            String requestBody = getRequestBody(httpRequest);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWriter.write(requestBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();
        }

        int statusCode = connection.getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_OK)
            response = getResponseString(connection.getInputStream(),"utf-8");
        else{
            response = getResponseString(connection.getErrorStream(),"utf-8");
        }

        connection.disconnect();

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

    return response;
}

A: В Glide к запросу можно добавить заголовки, используя GlideUrl:
GlideUrl glideUrl = new GlideUrl("url", new LazyHeaders.Builder()
        .addHeader("key1", "value1")
        .addHeader("key1", "value2")
        .build());

Glide.with(context)
        .load(glideUrl)
        .into(targetImageView);

Установить SSL-сертификат так просто не получится, но вообще это возможно, используя OkHttp. Подробнее можно почитать в статье:
Glide Module Example: Accepting Self-Signed HTTPS Certificates

redpajama_set_name: RedPajamaStackExchange


text:
Q: Looking for the .NET or iOS equivilant of SetConcat for Matrix Concatonation I'm working on a system that is detecting multi-touch at two points and then handling zoom and pan concurrently within the one gesture.
I'm using the Matrix class on Android to perform the Concatonations and that is working exactly as I expected.
The Android work is executing the following code that is using the transformations:
Matrix pivotFrom = new Matrix ();
pivotFrom.SetTranslate (-pivot0_x, -pivot0_y);
Matrix pivotTo = new Matrix ();
pivotTo.SetTranslate (pivot0_x, pivot0_y);
Matrix scaleMat = new Matrix ();
scaleMat.SetScale (scale, scale);
Matrix pivotToCurrent = new Matrix ();
pivotToCurrent.SetTranslate (pivot1_x, pivot1_y);

Matrix tt = new Matrix ();

tt.SetConcat (scaleMat, pivotFrom);
tt.SetConcat (pivotToCurrent, tt);

_currentMatrix.SetConcat (tt, _startMatrix);

This is working fine for Android which is great, but I'm finding that moving it to iOS the Matrix class in .NET from System.Drawing2D does not have the SetConcat method. I'm thinking maybe there is a mechanism that I could use as a replacement to get this to work. I also have access to a CGAffineTransform reference as part of the IOS Matrix implementation so if you know that equivalent there that could help.
Any help is appreciated, my Matrix math is beyond rusty.


text:
Q: C# Finding Position of Hex Flag in Binary File I have been tasked with parsing out (via C#) an image from legacy binary files with a format that's around 20 years old now; the image data is embedded in the binary file and is prefixed by a hex flag. Below is the definition of the flags I am looking for (in C):
#define C_THUMBNAIL    0x0008        /* thumbnail bitmap */
#define C_CTHUMBNAIL   0x000d        /* compressed thumbnail bitmap */

How do I find one of these flags (are they even flags?) in the file? If I can figure out where the flag is and how to read the value coming after the flag (the size of the image in bytes), I can do what I need. This is what I have so far:
var binReader = new BinaryReader(new FileStream(fileLocation, FileMode.Open));

//1. find flag
//2. get image size in bytes
//3. take the slice of the byte array containing the image
//4. write that slice of the array to a .png file.

My original idea was to walk through the binary stream until I found the flag, but I'm really confused at how, if my hex flag is the number 8 (0x0008 == 8, right?), I'm supposed to find it in the file and differentiate it from all the other 8's in the file.
Sorry if this is a duplicate question, but I don't know enough about this problem to know what to research to solve it. I've read the MSDN documentation on binary files and read some similar questions here, but can't tell if they answer my question.

A: Your questions are correct.
0x08 is 8.
You cannot simply look for the flag in the file.
You'll need to find a document detailing how the file format is defined.
For example, "tar" (the compressed file format) has very specific information about which flags go where in the header, and how to parse a tar file.

A: If that is the only information you have how to find the embedded image data then this will be hard. Prefixed by a flag could mean many thing. I could mean a leading 0x8 (1000 binary) or 0xd (1100 binary) byte but it could also be part of a bit mask.
If you don't have any other information of what kind of header it might have as a prefix then you could try and find all 0x8 or 0xd bytes, assume that it denotes the possible start of the image data and extract the image and then check if it results in a sensible image. However there could be a lot of them. You might be able to narrow down the search if you know approximate positions of the data in the file.
This requires that you know the actual image format as well, apparently. If you don't then you have pretty much lost unless it's some form of plain RGB bitmap or so.


text:
Q: indexerror for loop issue I am having difficulty converting a camel case string into separate words and appending these into a list. It almost completes the code but it gives an IndexError: string index out of range.
Please could anyone help with this??
The output when run is:
['This']
['This', 'Is']
['This', 'Is', 'A']
['This', 'Is', 'A', 'Camel']
['This', 'Is', 'A', 'Camel', 'Case']
Traceback (most recent call last):
for i in string[char]:
IndexError: string index out of range

Picture of code
List = []
string = "ThisIsACamelCaseString"
newstring = ""
count = 0
char = 0
null = 0

for i in string[char:]:
    if i == i.upper():
        newstring = newstring + i
        count += 1
        char += 1
    for i in string[char]:      **< error here**
        if i == i.upper() and char == 1:
            null += 1
        elif i == i.lower():
            newstring = newstring + i
            char += 1
            count += 1
        elif i == i.upper() and count > 0:
            List.append(newstring)
            print(List)
            newstring = ""
            break

A: This is my way of accomplishing this task. I have a counter called lastword, which keeps track of where the previous 'word' ended. Then I loop through the entire string letter by letter (like you do) and if I get to an uppercase letter, then you reset the lastword variable to the current position.
x = "ThisIsACamelCaseString"

#list to store results
sentence = []
lastword = 0
#count keeps track of what position we are at
for count, letter in enumerate(x):
    #I use the isupper() methd to see if letter is uppercase
    if letter.isupper():
        word = x[lastword:count]
        lastword = count
        #if word is needed because otherwise the first 'word' will be literally nothing
        if word:
            sentence.append(word)
print sentence


text:
Q: Incrementing value of an object when is called (JS) I have an object part of an class and I want to increment it's value everytime when is called.
var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object
verbose: true

    data: { 'file_number' : value },
});

"data:" is part of [POST]; I would like to have incremental value on 'file_number' everytime when a POST call is executed (next time value = value + 1)
(the class FancyUpload2 uses Swiff.Uploader class and MooTools 122 and I found it on internet as freeware)
Thanks !

A: to change the value you could use something like this externally (if the class implements Options, which i think it does):
up.setOptions({
    data: {
        file_number: up.options.data.file_number++
    }
});

you can attach to your fileComplete event:
eg, on instigate, add to options:
onFileComplete: function() {
    // bad practice to access the options object like so but it works.
    this.options.data.file_number++;
}

have fun.


text:
Q: PHP MyAdmin:Table relation view is not working My table engine is InnoDB.A month ago, I was able to see and create table relations, but now, when I press Relation view in Structure tab, I see only Foreign key constraints table.However I need to see relation or design view, to be able to create relations between tables.
Here is the screen:


text:
Q: Symfony2: How to validate an input field is not-blank, only when checkbox is true? Within Symfony2 how to validate an inputfield is not-blank, only when the value of a checkbox is 1 (True) - otherwise blank is allowed?
To be more precise, I have a form with a checkbox and an input field with type text. On the Entity in Symfony there should be a check that when the value of the checkbox is True (1) / checked, the value of the input can't be blank. I am using annotations within the Entity.
Any advise would be much appreciated.
UPDATE / SOLUTION - based on GeLo's remark:
<?php

// src/ZeroSpace/Invoicing/Entity/Customer.php

namespace ZeroSpace\InvoicingBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="customers")
 * @UniqueEntity("billing_id")
 * @UniqueEntity("billing_name")
*/

class Customer {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="integer", length=6, unique=true)
     * @Assert\Length(min="6", max="6")
     */
    protected $billing_id;

    /**
     * @ORM\Column(type="string", length=100, unique=true)
     */
    protected $billing_name;

    /**
     * @ORM\Column(type="string", nullable=true, length=100)
     */
    protected $billing_consignee;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $billing_street;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $billing_address;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $billing_zip;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $billing_city;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $billing_country;

    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\Email()
     */
    protected $billing_email;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $billing_debit=false;

    /**
     * @ORM\Column(type="string", nullable=true, length=100)
     * @Assert\NotBlank(groups={"iban_required"})
     * @Assert\Iban(message = "This is not a valid International Bank Account Number (IBAN).")
     */
    protected $billing_iban;

    protected $locations;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set billing_id
 *
 * @param integer $billingId
 * @return Customer
 */
public function setBillingId($billingId)
{
    $this->billing_id = $billingId;

    return $this;
}

/**
 * Get billing_id
 *
 * @return integer
 */
public function getBillingId()
{
    return $this->billing_id;
}

/**
 * Set billing_name
 *
 * @param string $billingName
 * @return Customer
 */
public function setBillingName($billingName)
{
    $this->billing_name = $billingName;

    return $this;
}

/**
 * Get billing_name
 *
 * @return string
 */
public function getBillingName()
{
    return $this->billing_name;
}

/**
 * Set billing_consignee
 *
 * @param string $billingConsignee
 * @return Customer
 */
public function setBillingConsignee($billingConsignee)
{
    $this->billing_consignee = $billingConsignee;

    return $this;
}

/**
 * Get billing_consignee
 *
 * @return string
 */
public function getBillingConsignee()
{
    return $this->billing_consignee;
}

/**
 * Set billing_street
 *
 * @param string $billingStreet
 * @return Customer
 */
public function setBillingStreet($billingStreet)
{
    $this->billing_street = $billingStreet;

    return $this;
}

/**
 * Get billing_street
 *
 * @return string
 */
public function getBillingStreet()
{
    return $this->billing_street;
}

/**
 * Set billing_address
 *
 * @param string $billingAddress
 * @return Customer
 */
public function setBillingAddress($billingAddress)
{
    $this->billing_address = $billingAddress;

    return $this;
}

/**
 * Get billing_address
 *
 * @return string
 */
public function getBillingAddress()
{
    return $this->billing_address;
}

/**
 * Set billing_zip
 *
 * @param string $billingZip
 * @return Customer
 */
public function setBillingZip($billingZip)
{
    $this->billing_zip = $billingZip;

    return $this;
}

/**
 * Get billing_zip
 *
 * @return string
 */
public function getBillingZip()
{
    return $this->billing_zip;
}

/**
 * Set billing_city
 *
 * @param string $billingCity
 * @return Customer
 */
public function setBillingCity($billingCity)
{
    $this->billing_city = $billingCity;

    return $this;
}

/**
 * Get billing_city
 *
 * @return string
 */
public function getBillingCity()
{
    return $this->billing_city;
}

/**
 * Set billing_country
 *
 * @param string $billingCountry
 * @return Customer
 */
public function setBillingCountry($billingCountry)
{
    $this->billing_country = $billingCountry;

    return $this;
}

/**
 * Get billing_country
 *
 * @return string
 */
public function getBillingCountry()
{
    return $this->billing_country;
}

/**
 * Set billing_email
 *
 * @param string $billingEmail
 * @return Customer
 */
public function setBillingEmail($billingEmail)
{
    $this->billing_email = $billingEmail;

    return $this;
}

/**
 * Get billing_email
 *
 * @return string
 */
public function getBillingEmail()
{
    return $this->billing_email;
}

/**
 * Set billing_debit
 *
 * @param boolean $billingDebit
 * @return Customer
 */
public function setBillingDebit($billingDebit)
{
    $this->billing_debit = $billingDebit;

    return $this;
}

/**
 * Get billing_debit
 *
 * @return boolean
 */
public function getBillingDebit()
{
    return $this->billing_debit;
}

/**
 * Set billing_iban
 *
 * @param string $billingIban
 * @return Customer
 */
public function setBillingIban($billingIban)
{
    $this->billing_iban = $billingIban;
    return $this;
}

/**
 * Get billing_iban
 *
 * @return string
 */
public function getBillingIban() {
    return $this->billing_iban;
}

}
    <?php
// src/Blogger/BlogBundle/Form/CustomerType.php

namespace ZeroSpace\InvoicingBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;

class CustomerType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('billing_id');
        $builder->add('billing_name');
        $builder->add('billing_consignee');
        $builder->add('billing_street');
        $builder->add('billing_address');
        $builder->add('billing_zip');
        $builder->add('billing_city');
        $builder->add('billing_country');
        $builder->add('billing_email', 'email');
        $builder->add('billing_debit', 'checkbox');
        $builder->add('billing_iban');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'ZeroSpace\InvoicingBundle\Entity\Customer',
            'validation_groups' => function(FormInterface $form) {
                $data = $form->getData();
                if($data->getBillingDebit() == 1) {
                    return array('Default', 'iban_required');
                }
                else {
                    return array('Default');
                }
            },
        ));
    }

    public function getName() {
        return 'customer';
    }
}

?>

<?php

namespace ZeroSpace\InvoicingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use ZeroSpace\InvoicingBundle\Entity\Customer;
use ZeroSpace\InvoicingBundle\Form\CustomerType;

class CustomerController extends Controller {

    public function createAction(Request $request) {

        $form = $this->createForm(new CustomerType(), new Customer());
        $form->handleRequest($request);

        if ($form->isValid()) {
            $data = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($data);
            $em->flush();

            return $this->redirect($this->generateUrl('customer_list'));
            // return $this->redirect($this->generateUrl('task_success'));
        }

        return $this->render('InvoicingBundle:Page:customers.html.twig', array(
            'form' => $form->createView()
        ));
    }

    public function listAction() {
        $customers = $this->getDoctrine()->getManager()
            ->createQuery('SELECT c FROM InvoicingBundle:Customer c')
            ->execute();

        return $this->render(
            'InvoicingBundle:Customer:list.html.twig',
            array('customers' => $customers));
    }

    public function showAction($id) {
        $customer = $this->get('doctrine')
            ->getManager()
            ->getRepository('InvoicingBundle:Customer')
            ->find($id);

        if (!$post) {
            // cause the 404 page not found to be displayed
            throw $this->createNotFoundException();
        }

        return $this->render(
            'InvoicingBundle:Page:customers.html.twig',
            array('customer' => $customer)
        );
    }

}

?>

A: I think this is the solution:
<?php

namespace ZeroSpace\InvoicingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use ZeroSpace\InvoicingBundle\Entity\Customer;
use ZeroSpace\InvoicingBundle\Form\CustomerType;

class CustomerController extends Controller {

    public function createAction(Request $request) {

        $form = $this->createForm(new CustomerType(), new Customer());
        $form->handleRequest($request);

        if ($form->isValid()) {
            $data = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($data);
            $em->flush();

            return $this->redirect($this->generateUrl('customer_list'));
            // return $this->redirect($this->generateUrl('task_success'));
        }

        return $this->render('InvoicingBundle:Page:customers.html.twig', array(
            'form' => $form->createView()
        ));
    }

    public function listAction() {
        $customers = $this->getDoctrine()->getManager()
            ->createQuery('SELECT c FROM InvoicingBundle:Customer c')
            ->execute();

        return $this->render(
            'InvoicingBundle:Customer:list.html.twig',
            array('customers' => $customers));
    }

    public function showAction($id) {
        $customer = $this->get('doctrine')
            ->getManager()
            ->getRepository('InvoicingBundle:Customer')
            ->find($id);

        if (!$post) {
            // cause the 404 page not found to be displayed
            throw $this->createNotFoundException();
        }

        return $this->render(
            'InvoicingBundle:Page:customers.html.twig',
            array('customer' => $customer)
        );
    }

}

?>
    <?php
// src/Blogger/BlogBundle/Form/CustomerType.php

namespace ZeroSpace\InvoicingBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;

class CustomerType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('billing_id');
        $builder->add('billing_name');
        $builder->add('billing_consignee');
        $builder->add('billing_street');
        $builder->add('billing_address');
        $builder->add('billing_zip');
        $builder->add('billing_city');
        $builder->add('billing_country');
        $builder->add('billing_email', 'email');
        $builder->add('billing_debit', 'checkbox');
        $builder->add('billing_iban');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'ZeroSpace\InvoicingBundle\Entity\Customer',
            'validation_groups' => function(FormInterface $form) {
                $data = $form->getData();
                if($data->getBillingDebit() == 1) {
                    return array('Default', 'iban_required');
                }
                else {
                    return array('Default');
                }
            },
        ));
    }

    public function getName() {
        return 'customer';
    }
}

?>

    <?php

    // src/ZeroSpace/Invoicing/Entity/Customer.php

    namespace ZeroSpace\InvoicingBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    use Symfony\Component\Validator\Constraints as Assert;

    /**
     * @ORM\Entity
     * @ORM\Table(name="customers")
     * @UniqueEntity("billing_id")
     * @UniqueEntity("billing_name")
    */

    class Customer {

        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;

        /**
         * @ORM\Column(type="integer", length=6, unique=true)
         * @Assert\Length(min="6", max="6")
         */
        protected $billing_id;

        /**
         * @ORM\Column(type="string", length=100, unique=true)
         */
        protected $billing_name;

        /**
         * @ORM\Column(type="string", nullable=true, length=100)
         */
        protected $billing_consignee;

        /**
         * @ORM\Column(type="string", length=100)
         */
        protected $billing_street;

        /**
         * @ORM\Column(type="string", length=100)
         */
        protected $billing_address;

        /**
         * @ORM\Column(type="string", length=100)
         */
        protected $billing_zip;

        /**
         * @ORM\Column(type="string", length=100)
         */
        protected $billing_city;

        /**
         * @ORM\Column(type="string", length=100)
         */
        protected $billing_country;

        /**
         * @ORM\Column(type="string", length=100)
         * @Assert\Email()
         */
        protected $billing_email;

        /**
         * @ORM\Column(type="boolean")
         */
        protected $billing_debit=false;

        /**
         * @ORM\Column(type="string", nullable=true, length=100)
         * @Assert\NotBlank(groups={"iban_required"})
         * @Assert\Iban(message = "This is not a valid International Bank Account Number (IBAN).")
         */
        protected $billing_iban;

        protected $locations;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set billing_id
     *
     * @param integer $billingId
     * @return Customer
     */
    public function setBillingId($billingId)
    {
        $this->billing_id = $billingId;

        return $this;
    }

    /**
     * Get billing_id
     *
     * @return integer
     */
    public function getBillingId()
    {
        return $this->billing_id;
    }

    /**
     * Set billing_name
     *
     * @param string $billingName
     * @return Customer
     */
    public function setBillingName($billingName)
    {
        $this->billing_name = $billingName;

        return $this;
    }

    /**
     * Get billing_name
     *
     * @return string
     */
    public function getBillingName()
    {
        return $this->billing_name;
    }

    /**
     * Set billing_consignee
     *
     * @param string $billingConsignee
     * @return Customer
     */
    public function setBillingConsignee($billingConsignee)
    {
        $this->billing_consignee = $billingConsignee;

        return $this;
    }

    /**
     * Get billing_consignee
     *
     * @return string
     */
    public function getBillingConsignee()
    {
        return $this->billing_consignee;
    }

    /**
     * Set billing_street
     *
     * @param string $billingStreet
     * @return Customer
     */
    public function setBillingStreet($billingStreet)
    {
        $this->billing_street = $billingStreet;

        return $this;
    }

    /**
     * Get billing_street
     *
     * @return string
     */
    public function getBillingStreet()
    {
        return $this->billing_street;
    }

    /**
     * Set billing_address
     *
     * @param string $billingAddress
     * @return Customer
     */
    public function setBillingAddress($billingAddress)
    {
        $this->billing_address = $billingAddress;

        return $this;
    }

    /**
     * Get billing_address
     *
     * @return string
     */
    public function getBillingAddress()
    {
        return $this->billing_address;
    }

    /**
     * Set billing_zip
     *
     * @param string $billingZip
     * @return Customer
     */
    public function setBillingZip($billingZip)
    {
        $this->billing_zip = $billingZip;

        return $this;
    }

    /**
     * Get billing_zip
     *
     * @return string
     */
    public function getBillingZip()
    {
        return $this->billing_zip;
    }

    /**
     * Set billing_city
     *
     * @param string $billingCity
     * @return Customer
     */
    public function setBillingCity($billingCity)
    {
        $this->billing_city = $billingCity;

        return $this;
    }

    /**
     * Get billing_city
     *
     * @return string
     */
    public function getBillingCity()
    {
        return $this->billing_city;
    }

    /**
     * Set billing_country
     *
     * @param string $billingCountry
     * @return Customer
     */
    public function setBillingCountry($billingCountry)
    {
        $this->billing_country = $billingCountry;

        return $this;
    }

    /**
     * Get billing_country
     *
     * @return string
     */
    public function getBillingCountry()
    {
        return $this->billing_country;
    }

    /**
     * Set billing_email
     *
     * @param string $billingEmail
     * @return Customer
     */
    public function setBillingEmail($billingEmail)
    {
        $this->billing_email = $billingEmail;

        return $this;
    }

    /**
     * Get billing_email
     *
     * @return string
     */
    public function getBillingEmail()
    {
        return $this->billing_email;
    }

    /**
     * Set billing_debit
     *
     * @param boolean $billingDebit
     * @return Customer
     */
    public function setBillingDebit($billingDebit)
    {
        $this->billing_debit = $billingDebit;

        return $this;
    }

    /**
     * Get billing_debit
     *
     * @return boolean
     */
    public function getBillingDebit()
    {
        return $this->billing_debit;
    }

    /**
     * Set billing_iban
     *
     * @param string $billingIban
     * @return Customer
     */
    public function setBillingIban($billingIban)
    {
        $this->billing_iban = $billingIban;
        return $this;
    }

    /**
     * Get billing_iban
     *
     * @return string
     */
    public function getBillingIban() {
        return $this->billing_iban;
    }

}

A: An efficient approach can be to use the validation group which can be determined on the fly. Then, given the checkbox is not checked, you use the Default validation group whereas if the checkbox is checked, you use the Default group and a custom group which will check if your field is not empty.
See this part of the documentation for more details: http://symfony.com/doc/current/book/forms.html#groups-based-on-the-submitted-data

A: could you do something like this ?
/**
 * @Assert\True()
 */
public function customValidate()
{
    return (!$this->checkboxField) or (strlen($this->inputField) > 0);
}


text:
Q: Innodb file format - Percona Server I had my innodb file format changed from antelope to barracuda recently.
Is it safe to have both antelope and barracuda at the same time? I have my setup running properly now.
What issues I would face? Or should I change it back to antelope.


text:
Q: Why it say to me that 'value' attribute is not a valid text area attribute in HTML5? I have the following problem.
I am working on a C#.NET web application and I am implementing some HTML 5 view that contains a some text area field. For example I have something like this:
<label for="nome">Description*:</label>
<textarea data-clear-btn="true" name="mitigatingStrategy.Description" id="description" data-mini="true" data-inline="true"  required="required" value="@Model.mitigatingStrategy.Description" rows="5" cols="40">Inserire qui la descrizione della nuova Mitigating Strategy</textarea>

It work well (the **@Model.mitigatingStrategy.Description is correctly setted) but Visual Studio sign this line and give me the following validation warning:

Validation (HTML5): Attribute 'value' is not a valid attribute of element 'textarea'

So what is the problem? how can I fix it to obtain that my HTML is validated?

A: The value of a textarea goes between its tags:
<textarea>@Model.mitigatingStrategy.Description</textarea>

A: Use a custom field like data-value instead of value.

A: It says that the value attribute is invalid, because it is invalid in all HTML versions, for a textarea element.
It depends on the intended effect of the attribute what (if anything) you should use instead.


text:
Q: How do you create an array of classes? I want to make an array of classes in TypeScript. This is possible in vanilla JavaScript:
class A {
    constructor() {console.log('constructor');}
    a() {}
}

const array = [A];

new (array[0])(); // Prints 'constructor'

I want to make the array type safe using an interface. This is my attempt to implement this in TypeScript:
interface I {
    a();
}

class A implements I {
    constructor() {console.log('constructor')}
    a() {}
}

const array: I[] = [A];

new (array[0])();

When I compile this, I get this error:
Error:(16, 21) TS2322: Type 'typeof A' is not assignable to type 'I'.
  Property 'a' is missing in type 'typeof A'.

Because this error message mentions that typeof A is not assignable to type 'I', it seems that arrays can not contain classes, as typeof is used for instantiated objects.
What I need is a way to group all my classes in a single variable without instantiating them, and be able to access the class by index. How can I achieve this in TypeScript?

A: Interfaces define properties and method available on instances, so this would work:
 const array: I[] = [new A()];

It's not what you want, but it should demonstrate why it's not working: Class and instance are two different things.
What you want to say is "it's an array of types and new() will return an instance of I".
I think it should look like this:
class Test implements I {
    a() {}
}

interface I {
    a();
}

interface TI {
    new (): I;
}

const arr: TI[] = [Test];

const inst = new arr[0]();


text:
Q: About android,how to use the AccessibilityService hello every one
    i am trying to use AccessibilityService.but it not work.can somebody help me to point my mistake? thanks.
MyAccessibilityService.java
 public class MyAccessbilityService extends AccessibilityService {

 @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
    // TODO Auto-generated method stub
      switch(event.getEventType()){
        case AccessibilityEvent.TYPE_VIEW_CLICKED:
          Toast.makeText(getApplicationContext(),"Click", Toast.LENGTH_SHORT).show();
          break;

        case AccessibilityEvent.TYPE_VIEW_LONG_CLICKED:
          Toast.makeText(getApplicationContext(),"Long click", Toast.LENGTH_SHORT).show();
          break;

        case AccessibilityEvent.TYPE_VIEW_FOCUSED:
           Toast.makeText(getApplicationContext(),"Focuse change", Toast.LENGTH_SHORT).show();
           break;

        case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED:
           Toast.makeText(getApplicationContext(),"Text change", Toast.LENGTH_SHORT).show();
           break;
         }
       }

         @Override
         public void onInterrupt() {
          // TODO Auto-generated method stub
         }

         @Override
         protected void onServiceConnected() {
          // TODO Auto-generated method stub
          super.onServiceConnected();
          AccessibilityServiceInfo info = new AccessibilityServiceInfo();
          info.feedbackType = AccessibilityServiceInfo.DEFAULT;
          setServiceInfo(info);
         }
        }

the mainfest.xml like this

A: The AccessibilityServiceInfo.DEFAULT should be applied to info.flags.  And the info.feedbackType should be FEEDBACK_xxxxx.
If you are interested in any feedback types, you should specify FEEDBACK_GENERIC.


text:
Q: stdin: error 0 - what does it mean? In the course of my adventures in Ubuntu, I've encountered the mysterious black screen with the single line

stdin: error 0

at boot many times. But what does it mean? Is it Kernel level? Is it bootloader? Or is it just a generic error that means "oops"?

A: In short its an error reading something although what is a little hard to diagnose without a little more information.
I've seen it on my machine, at boot, if I've got a CD in my drive that can't be read. It also turns up on drives/ram that is failing.
Those examples are not exhaustive, however, so I wouldn't go worrying unless you've got any other evidence of hardware issues.


text:
Q: Will longer keys make an NSKeyedArchiver file significantly longer When I fill in the encodeWithCoder: for objective c classes for an iPhone app will it make make the archive file larger if I use long keys as opposed to short keys for all of my variables?
For example if I use really long keys like this:
[coder encodeBool:myBoolean forKey:@"My_Excesively_Long_Boolean_Key"];

will it make the archive file longer than if I use stuff like this:
[coder encodeBool:myBoolean forKey:@"Key01"];

Assuming I have a large number of ints and BOOLs.

A: Unless you have hundreds of thousands of keys, you won't see any noticeable size increase. On modern systems text is trivial. You could store tens of thousands of keys in a couple of megs.
The use of long highly unique keys, constants, class names, ivars etc is actively encourage because of Objective-C's open name space.

A: Larger the archive grows, longer is the time it takes to restore it into your data structure. The size of your archive is too small compared the the flash memory size available these days (in 2011)


text:
Q: Cross Domain Silverlight Problem with localhost I am currently looking into developing a silverlight app. I want to develop the app on my local machine for ease of development. I am using Apache Server on Windows which is hosting php. I am doing a WebClient DownloadStringASync to http://localhost/getData.php but the Silverlight webpage is running in visual studio asp server at http://localhost:54994/MySilverlight.aspx. I think because the silverlight app is running from the vs2010 server and I am making a call to my standard apache server it is having a cross domain problem. When the app is run the innerexception says System.Security.SecurityException at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse.
I have tried putting accesspolicy.xml file in the root of the asp server and the apache server but it still isn't fixing the problem. I know its not a problem with the code as if I run it from my website server and call the webclient request to the same domain it works fine.
Any help you can provide would be great thanks.

A: I've managed to solve the problem. I needed to have to crossdomain.xml and clientaccesspolicy.xml with the same code. For some reason if I only have one or the other it keeps on bringing up the security exception. As soon as both files in the root of the localhost directory of apache (i.e. in the root of htdocs) the silverlight app works fine


text:
Q: How to save an image dynamically I am using photo library in my app. And after selecting image from photo library or camera i want to save that image into my Documents folder. So here i want to give name to that image while saving is it possible to set name to the selected image? If means please let me know. I am trying that only if possible i will post that.Thank you.

A: This is how I do it.. I'm copying and pasting my code so there's some additional functionality.
// image is a UIImage
// inputText is the user selected imagename
// date is a string I inserting to make pictures a unique identifier (i.e. no duplicate names)
NSData *imageData1 = UIImageJPEGRepresentation(image, 1.0);
NSString *imageFilename = [NSString stringWithFormat:@"%@-%@.jpg", inputText,date];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *path = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], imageFilename];

if([imageData1 writeToFile:path atomically:YES]){
    NSLog(@"Write to Document folder success filename = %@",path);
}

A: Use following :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

UIImage *photoImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/myImageName.png"];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];

if(status){

[[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];

}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
}

You can set any desired name when saving to document directory.

A: Declare an integer counterNo and initialize it to 0. And increase its value to change name dynamically.
UIImage *photoImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

counterNo++;

NSString *aaa = [NSString stringWithFormat:@"Documents/myImage-%d.png" , counterNo];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:aaa];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];

if(status){

    [[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];

}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];


text:
Q: R parallel system call on files I have to convert a large number of RAW images and am using the program DCRAW to do that. Since this program is only using one core I want to parallelize this in R. To call this function I use:
system("dcraw.exe -4 -T image.NEF")

This results in outputting a file called image.tiff in the same folder as the NEF file, which is totally fine. Now I tried multiple R packages to parallelize this but I only get nonsensical returns (probably caused by me). I want to run a large list (1000+ files) through this system call in r , obtained by list.files()
I could only find info on parallel programming for variables within R but not for system calls. Anybody got any ideas? Thanks!

A: It doesnt' matter if you use variables or system. Assuming you're not on Windows (which doesn't support parallel), on any decent system you can run
parallel::mclapply(Sys.glob("*.NEF"),
  function(fn) system(paste("dcraw.exe -4 -T", shQuote(fn))),
  mc.cores=8, mc.preschedule=F)

It will run 8 jobs in parallel. But then you may as well not use R and use instead
ls *.NEF | parallel -u -j8 'dcraw.exe -4 -T {}'

instead (using GNU parallel).

A: On Windows I use a modification of this solution (the top voted one) to run many commands with no more than, say, 4 or 8 simultaneously:
Parallel execution of shell processes
It's not an R solution, but I like it.


text:
Q: Custom date range EXPLAINATION
There are 2 work shifts, day shift = from 07:00:00 to 19:00:00 and night shift = from 19:00:00 to 07:00:00

SAMPLE DATA
Name    Date        Time        WorkShift
John    2015-09-14  19:14:24    N
John    2015-09-14  23:43:27    N
John    2015-09-15  03:21:36    N
John    2015-09-15  11:29:48    D

DESIRED RESULT
For example I have @dateStart = 2015-09-14 and @dateEnd = 2015-09-14 variables. I need to select records from 2015-09-14 19:00:00 to 2015-09-15 07:00:00 in following:
John    2015-09-14  19:14:24    N
John    2015-09-14  23:43:27    N
John    2015-09-15  03:21:36    N

As you see above, here is date 2015-09-15, but Time is 03:21:36 so It should be selected (because time is lower than 07:00:00, N workshift).

PROBLEMS
My query selecting as expected, but there are 2 problems.
If I pass @dateStart = 2015-09-15 and @dateEnd = 2015-09-15 It selecting:
John    2015-09-15  03:21:36    N -- this shouldn't be selected again, this should go as 2015-09-14
John    2015-09-15  11:29:48    D

Another problem is that If I have record like this
John    2015-09-15  03:21:36    N

As you see there is no any records for John in 2015-09-14 so It should be selected when I pass variables in following: @dateStart = 2015-09-15 and @dateEnd = 2015-09-15

QUERY
select *
from SampleTable
where /* Some conditions.... and*/
      (convert(date, StartTime) >= @dateStart) and
      (case when (DateCreated between cast(cast(cast(DateCreated as date) as varchar(40)) + ' 19:00:00' as datetime)
                              and cast(cast(cast(DateCreated as date) as varchar(40)) + ' 23:59:59' as datetime)
                  or
                  DateCreated between cast(cast(cast(DateCreated as date) as varchar(40)) + ' 00:00:00' as datetime)
                              and cast(cast(cast(DateCreated as date) as varchar(40)) + ' 07:00:00' as datetime)
                  )
                  and Workshift like '%N'
            then dateadd(day,-1,cast(cast(DateCreated as date) as varchar(40)))
            else DateCreated
        end <= @dateEnd)

If something is unclear - ask me and I will try to explain.

A: How about just adding hours to the start and end times?
where datetime >= dateadd(hour, 19, @datestart) and
      datetime < dateadd(hour, 7, @dateend)

If you are storing "date" and "time" in separate columns (which is not generally recommended), you can add them after converting to datetime:
where cast(date as datetime) + cast(time as datetime) >= dateadd(hour, 19, @datestart) and
      cast(date as datetime) + cast(time as datetime) < dateadd(hour, 7, @dateend)

A: try this one
select  *
from SampleTable
where convert(dateTime,DateCreated) + convert(dateTime,StartTime)
between DATEADD(HH,7, @dateStart) and DATEADD(HH,24+7, @dateEnd)
or
(
    convert(dateTime,DateCreated) + convert(dateTime,StartTime)
    between DATEADD(HH,00, @dateStart) and DATEADD(HH,7, @dateStart) -- Morning records
    and not exists
        (
        select 1 from SampleTable where
        convert(dateTime,DateCreated) + convert(dateTime,StartTime)
        between DATEADD(HH,7-24, @dateStart) and DATEADD(HH,0, @dateStart)
        ) -- Data from previous day
)


text:
Q: How to use MassTransit with RabbitMQ for .net framework 4.6.1? I want to use MassTransit with RabbitMQ for .net framework 4.6.1 project. I've followed this  official doc to setup in WebAPI2 project using OWIN, but it is showing errors while building. It seems like i've missed to install some packages. This official doc doesnot mention which packages i need to install, also VS2022 intellisense does not suggests the missing packages to install. Errors shown on these lines:
    app.UseAutofacMiddleware(container);
    app.UseAutofacWebApi(config);
    app.UseWebApi(config);

And another problem is in this line: var busHandle = bus.Start();
Here, bus.Start() methods returns nothing(void). That's why cannot assign the result to busHandle.
NOTE: I am using these nuget packages
MassTransit 6.3.2
MassTransit.RabbitMQ 6.3.2

A: After some google search I've figured it out: need to install nuget package Autofac.WebApi2.Owin v5.0.0.
Also note that need to install package Microsoft.AspNet.WebApi.OwinSelfHost for OWIN to work and Microsoft.Owin.Host.SystemWeb.
For the second error, in this code var busHandle = bus.Start(); bus.Start() doesnot return any result that's why I decided to call it like this:
bus.Start();
And, one more
In the Configuration method of Startup.cs file, need to add this line (before builder.Build())
           // Register anything else you might need...
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // Build the container
            var container = builder.Build();

I hope this helps you.
If you want a complete step-by-step solutions, please let me know.
Happy coding...


text:
Q: Using Raster Images in Silverlight for buttons I have buttons supplied to me from photoshop for different button states.
It looks like this
<Button x:Name="ResultsBtn" Click="ResultsBtn_Click" FontSize="27" BorderThickness="0"  Padding="-10"  Margin="-10">
    <Grid>
        <Image Source="..But_01_Idle.png"  Width="496"/>
        <TextBlock Text="Results" Margin="174,21,172,23" Width="90" Height="40" Foreground="White" />
    </Grid>
</Button>

The button looks right for just one state.
I want to use expression blend to record a state and change the background behind an image (in this instance an outer glow) or change the source on a state change.
I've noticed that blend only seems to record position and transforms and not changes in attributes.
Should I be doing this in code or rather have the photoshop file sent in a particular format so that it can be automatically converted by blend

A: Okay, I'm actually quite surprised at Blend: it does not seem to allow you to animate the source property.  However, Silverlight allows it so I assume WP7 will also allow it; this looks like a bug in Blend 4.  However, I still would not recommend it using an image based approach because the images will deform and look bad/pixelated when significantly scaled up or down.  A better approach is to edit your button's control template and modify it to match your reference artwork.  You can even using File -> Import Adobe Photoshop File ... to pull the basic artwork into Blend.  Then it's just a matter of shuffling it into the control template.
If you're dead set on using images (which will increase the size of your XAP and actually cause slower load UserControl load times), you can go about it as follows in Blend:

*
*Create a new project and add a Button to your root visual element.

*Create a new project folder called Images and add two images to it.  (I used Koala.jpg and Penguins.jpg from the Sample Pictures folder.)

*Right click the button and select Edit Template -> Edit a Copy...

*The default template will contain a Grid that contains a Border named Background.  Inside the Background border is a Grid that contains a Rectangle and another Border.  Delete both of those innermost elements.

*Now add an Image as a child of the Background border's Grid.

*Now switch to the XAML editor and modify your control template's visual state groups to match the following code.  (Look for the two "Added" comment blocks.)

*Run the project.  On mouse over you'll see penguins.  Click and hold the left mouse and you'll see a koala.

<Setter Property="Template">
  <Setter.Value>
    <ControlTemplate TargetType="Button">
      <Grid>
        <VisualStateManager.VisualStateGroups>
          <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="Normal"/>
            <VisualState x:Name="MouseOver">

             <!-- Added -->
             <Storyboard>
               <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TheImage" Storyboard.TargetProperty="Source">
                 <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="/Images/Penguins.jpg"/>
               </ObjectAnimationUsingKeyFrames>
             </Storyboard>
             <!-- End of Added -->

             </VisualState>
             <VisualState x:Name="Pressed">
               <Storyboard>
                 <ColorAnimation Duration="0" To="#FF6DBDD1" Storyboard.TargetProperty="(Border.Background).**(SolidColorBrush.Color)" Storyboard.TargetName="Background"/>

                 <!-- Added -->
                 <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TheImage" Storyboard.TargetProperty="Source">
                   <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="/Images/Koala.jpg"/>
                 </ObjectAnimationUsingKeyFrames>**
                 <!-- End of Added -->

               </Storyboard>
             </VisualState>
             <VisualState x:Name="Disabled">
               <Storyboard>
                 <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"/>
                </Storyboard>
              </VisualState>
            </VisualStateGroup>
            <VisualStateGroup x:Name="FocusStates">
              <VisualState x:Name="Focused">
                <Storyboard>
                  <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="FocusVisualElement"/>
                </Storyboard>
              </VisualState>
              <VisualState x:Name="Unfocused"/>
            </VisualStateGroup>
          </VisualStateManager.VisualStateGroups>
        <Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="White" CornerRadius="3">
          <Grid Background="{TemplateBinding Background}" Margin="1">
            <Image x:Name="TheImage" Source=""/>
          </Grid>
        </Border>
        <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        <Rectangle x:Name="DisabledVisualElement" Fill="#FFFFFFFF" IsHitTestVisible="false" Opacity="0" RadiusY="3" RadiusX="3"/>
        <Rectangle x:Name="FocusVisualElement" IsHitTestVisible="false" Margin="1" Opacity="0" RadiusY="2" RadiusX="2" Stroke="#FF6DBDD1" StrokeThickness="1"/>
      </Grid>
    </ControlTemplate>
  </Setter.Value>
</Setter>

A: Visual States are built with animations, so you can only change things that can be animated (and expect typical results).  I've never tried it, but my instinct tells me an Image source cannot be animated so the VSM is probably not a viable way to manage that.
Opacity, however, can be animated, so you could have both Image's in ytour button and control their Opacity with States.  Just a thought.

A: You have to create a ControlTemplate:
Code for Button:
<Button Template={DynamicResource ButtonTemplate}/>

In your Resource Dictionary:
<ControlTemplate x:Key="ButtonTemplate" {x:Type Button}>
    <Grid Padding="-10"  Margin="-10">
        <Image x:Name="IdleState" Source="..But_01_Idle.png"  Width="496"/>
        <Image x:Name="MouseOverState" Source="..But_01_MouseOver.png" Width="496"/>
        <Image x:Name="PressedState..." etc/>
        <TextBlock Text="Results" Margin="174,21,172,23" Width="90" Height="40" Foreground="White" FontSize="27"/>
    </Grid>
</ControlTemplate>

Then, in Blend, Edit the Template and you'll find the States as Mike said. Use the Properties panel to hide / show your images for each state you want to style and you should be done.


text:
Q: To show the data in weekly basis I have a date column in a table. Based on the selection of the date it should calculate the order count for last 6 weeks as Week1,Week2...Week6 (This is not the week number its the simple serial number). For example, If user selects the date as 12/10/2017(dd/mm/yyyy) then it should calculate the order count for the week dates as

Can someone please let me know whether this is possible in SQL ?

A: This is possible with SQL code.
Query
SELECT
   CONCAT(week1.first_day, '-', week1.second_day) AS Week1
 , CONCAT(week2.first_day, '-', week2.second_day) AS Week2
 , CONCAT(week3.first_day, '-', week3.second_day) AS Week3
 , CONCAT(week4.first_day, '-', week4.second_day) AS Week4
 , CONCAT(week5.first_day, '-', week5.second_day) AS Week5
 , CONCAT(week6.first_day, '-', week6.second_day) AS Week6
FROM (
 SELECT
     DATE_FORMAT(@first_date_of_week, '%d/%m/%Y') AS first_day
   , DATE_FORMAT(@date, '%d/%m/%Y') AS second_day
)
 week1
CROSS JOIN (
  SELECT
      DATE_FORMAT(@first_date_of_week - INTERVAL 1 WEEK, '%d/%m/%Y') AS first_day
    , DATE_FORMAT(@first_date_of_week - INTERVAL 1 WEEK + INTERVAL 1 WEEK - INTERVAL 1 DAY, '%d/%m/%Y') AS second_day
)
 week2
CROSS JOIN (
  SELECT
      DATE_FORMAT(@first_date_of_week - INTERVAL 2 WEEK, '%d/%m/%Y') AS first_day
    , DATE_FORMAT(@first_date_of_week - INTERVAL 2 WEEK + INTERVAL 1 WEEK - INTERVAL 1 DAY, '%d/%m/%Y') AS second_day
)
 week3
CROSS JOIN (
  SELECT
      DATE_FORMAT(@first_date_of_week - INTERVAL 3 WEEK, '%d/%m/%Y') AS first_day
    , DATE_FORMAT(@first_date_of_week - INTERVAL 3 WEEK + INTERVAL 1 WEEK - INTERVAL 1 DAY, '%d/%m/%Y') AS second_day
)
 week4
CROSS JOIN (
  SELECT
      DATE_FORMAT(@first_date_of_week - INTERVAL 4 WEEK, '%d/%m/%Y') AS first_day
    , DATE_FORMAT(@first_date_of_week - INTERVAL 4 WEEK + INTERVAL 1 WEEK - INTERVAL 1 DAY, '%d/%m/%Y') AS second_day
)
 week5
CROSS JOIN (
  SELECT
      DATE_FORMAT(@first_date_of_week - INTERVAL 5 WEEK, '%d/%m/%Y') AS first_day
    , DATE_FORMAT(@first_date_of_week - INTERVAL 5 WEEK + INTERVAL 1 WEEK - INTERVAL 1 DAY, '%d/%m/%Y') AS second_day
)
 week6

CROSS JOIN (
  SELECT
      @date := STR_TO_DATE('12/10/2017', '%d/%m/%Y') AS DATE
    , @first_date_of_week := @date - INTERVAL (DAYOFWEEK(@date) - 1) DAY AS first_date_of_the_week
) init_user_params

Result
Week1                  Week2                  Week3                  Week4                  Week5                  Week6
---------------------  ---------------------  ---------------------  ---------------------  ---------------------  -----------------------
08/10/2017-12/10/2017  01/10/2017-07/10/2017  24/09/2017-30/09/2017  17/09/2017-23/09/2017  10/09/2017-16/09/2017  03/09/2017-09/09/2017

A: Here is another way to achieve the same result -
select CONCAT(subdate(CURDATE(), INTERVAL (weekday(CURDATE())+1) DAY), ' - ', CURDATE())
      ,CONCAT(subdate(date_sub(CURDATE(), interval 7 day), INTERVAL (weekday(CURDATE())+1) DAY), ' - ', subdate(CURDATE(), INTERVAL (weekday(CURDATE())+2) DAY))
      ,CONCAT(subdate(date_sub(CURDATE(), interval 14 day), INTERVAL (weekday(CURDATE())+1) DAY), ' - ', subdate(date_sub(CURDATE(), interval 7 day), INTERVAL (weekday(CURDATE())+2) DAY))
      ,CONCAT(subdate(date_sub(CURDATE(), interval 21 day), INTERVAL (weekday(CURDATE())+1) DAY), ' - ', subdate(date_sub(CURDATE(), interval 14 day), INTERVAL (weekday(CURDATE())+2) DAY))
      ,CONCAT(subdate(date_sub(CURDATE(), interval 28 day), INTERVAL (weekday(CURDATE())+1) DAY), ' - ', subdate(date_sub(CURDATE(), interval 21 day), INTERVAL (weekday(CURDATE())+2) DAY))
      ,CONCAT(subdate(date_sub(CURDATE(), interval 35 day), INTERVAL (weekday(CURDATE())+1) DAY), ' - ', subdate(date_sub(CURDATE(), interval 28 day), INTERVAL (weekday(CURDATE())+2) DAY))


text:
Q: How to give space in between the fields in material UI? I'm new to material UI, My objective is to gives spaces in between every text fields, i've given spacing but it is not working. Can anyone assist me in giving space in between textfields?
Here is the code:
import React from "react";
import Grid from "@material-ui/core/Grid";
import { makeStyles, withStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const styles = theme => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
      width: "25ch"
    }
  }
});

class TextFields extends React.Component {
  render() {
    const { classes } = this.props;
    return (
      <Grid>
        <form className={classes.root} noValidate autoComplete="off">
          <Grid item spacing={3}>
            <TextField label="First Name" variant="outlined" />
          </Grid>
          <Grid item spacing={3}>
            <TextField label="Last Name" variant="outlined" />
          </Grid>
          <Grid item spacing={3}>
            <TextField label="Address" variant="outlined" />
          </Grid>
          <Grid item spacing={3}>
            <TextField label="Email" variant="outlined" />
          </Grid>
        </form>
      </Grid>
    );
  }
}
export default withStyles(styles)(TextFields);

"https://codesandbox.io/s/material-demo-kcn7d"

A: Some notice points

*

*direction set to column

*parent Grid set as container

*add distance using spacing
<Grid container direction={"column"} spacing={5}>
  <Grid item>
    <TextField label="First Name" variant="outlined" />
  </Grid>
  <Grid item>
    <TextField label="Last Name" variant="outlined" />
  </Grid>
  <Grid item>
    <TextField label="Address" variant="outlined" />
  </Grid>
  <Grid item>
    <TextField label="Email" variant="outlined" />
  </Grid>
</Grid>

If you look at the dom structure in a browser developer mode, you would find out that the space is settled. And the spaces are equal between each field, the reason why it shows different is that there are outer elements.
Try it online:

Related QA: How to have different horizontal and vertical spacing in ReactJs Material UI Grid


text:
Q: How to add andThen() in a Completable.complete() programmatically in Rx / Reactive Java how do i make a chain of andThen() operator on an Completable ?
for example, the original code is this:
return Completable.complete()
        .andThen(processdata("01"))
        .andThen(processdata("02"))
        .andThen(processdata("03"))
        .andThen(processdata("04"))
        .andThen(processdata("05"))
        .andThen(processdata("06"))
        .andThen(processdata("07")); //working

it worked perfectly!
but i dont want a "static" defined value, and tried to convert the code above into this:
    Completable x = Completable.complete();
    String[] allID = {"01","02","09"}
    for (String Id : allID) {
        x.andThen(processdata(Id));
    }
    return x; //not working

and it is not woking, as if nothing happened
and then i realized that :
        Completable x = Completable.complete();
        x.andThen(processdata("01"));
        x.andThen(processdata("02"));
        x.andThen(processdata("03"));
        return x; //not working

is also not working ...
can anybody help how the proper way to chain a Completable in my case

A: The idiomatic RxJava way would be to do it like this, so you don't have to keep reassigning Completable instances to the same reference:
return Observable.fromArray("01","02","09")
   .concatMapCompletable(id -> processData(id));

A: Try to chain the Completable this way because each call to andThen() is returning new instance of Completable.
Completable x = Completable.complete();
String[] allID = {"01","02","09"}
for (String Id : allID) {
  x = x.andThen(processdata(Id));
 }
return x;


text:
Q: svn, ssh: Connection refused most of the time; other computers can connect I am running Ubuntu 12.04.3 and svn as well as ssh (to servers) only works sometimes in a short time window after booting my computer, but most of the time I get "Connection refused". The problem only started some weeks ago, before it, everything worked perfectly fine.
It should not be a server issue and also not a router issue, since using my notebook I can connect without problems.
I have already reinstalled Ubuntu and tried 12.10 and 13.04, the problem happens also in these versions. However, after reinstalling Ubuntu 12.04.3, it seemed to work, I may re-introduced the problem by copying back my home folder from the previous installation (if there is some config in this folder?).
Uncommenting "dnsmasq" in NetworkManager.conf seems to help in regard to the ssh problem, but for svn I still can get no connection.
   ssh -vvvvv

gives
   OpenSSH_5.9p1 Debian-5ubuntu1.1, OpenSSL 1.0.1 14 Mar 2012
   debug1: Reading configuration data /etc/ssh/ssh_config
   debug1: /etc/ssh/ssh_config line 19: Applying options for *
   debug2: ssh_connect: needpriv 0
   debug1: Connecting to xxxx port 22.
   debug1: connect to address xxx port 22: Connection refused
   ssh: connect to xxx port 22: Connection refused

What other output do you need?
Thank you for your help, the problem really drives me crazy.
Edit: Now ssh works and svn not and I did not change anything, before the last boot svn worked.
I tried
 arp-scan -I eth0 -l

and got a (DUP:2) with two times the same IP and MAC adress.

A: You might be connecting from the network with port 22 closed. Try for example to connect from 3G network or some kind of.

A: In burp:
proxy -- options -- proxy listeners -- (table) -- interface
by default it is loopback only, changed it (via the [edit] button on the left) to "all interfaces", and it began to work.


text:
Q: Polymer: access polymer element objects I have a polymer element called his-service:
 <polymer-element name="gis-service" attributes="response url">
  <template>
    <style>
    </style>
    <core-ajax id="ajax"
      auto
      url="{{url}}"
      method="get"
      contentType = 'application/json'
      on-core-response="{{postsLoaded}}"
      body="{{body}}"
      handleAs="xml">
    </core-ajax>
  </template>
  <script>
  Polymer('gis-service', {
    created: function() {
      this.response = [];
    },
    postsLoaded: function() {
        this.response = [];
        this.labels = [];
        this.coordinates = [];
        x = this.$.ajax.response.getElementsByTagName("CustomerServiceCenterData");
        for (i=0;i<x.length;i++) {
            if (x[i].getElementsByTagName("language")[0].innerHTML == "EN")
            {
                this.labels[i] = x[i].getElementsByTagName("label")[0].innerHTML;
                this.coordinates.push({
                    lat:x[i].getElementsByTagName("lat")[0].innerHTML,
                    lng:x[i].getElementsByTagName("lng")[0].innerHTML
                })
            }
        }
        console.log(this.coordinates);
    }
  });
  </script>
</polymer-element>

In the index file, I try to access the object labels and coordinates. The following is part of the index:
<gis-service id="gservice" response="{{labels}}" url="someUrl">
</gis-service>
<script>
    var gis_service = document.querySelector('gis-service');
    console.log(gis_service);
</script>

As you can see, I am trying to access labels and coordinates through querySelector. However, When I try to get labels for instance via:
gis_service.labels

It gives me undefined. The same thing with the variable coordinates.
I can see the two variables when I do: console.log(gis_service), but cannot access them.
Any help is appreciated.

A: Define it outside of the function and then you should be able to use it externally.  This format will work for the .8 version.  1.0 version will need to use the new format.

created: function() {
      this.response = [];
    },
 labels: undefined,
    postsLoaded: function() {

A: You should read about databinding here
Don't do this:
 <core-ajax id="ajax"
      auto
      url="{{url}}"
      method="get"
      contentType = 'application/json'
      on-core-response="{{postsLoaded}}"
      body="{{body}}"
      handleAs="xml">
    </core-ajax>

Do this instead:
 <core-ajax id="ajax" auto url="{{url}}" method="get" contentType ='application/json' on-core-response="{{postsLoaded}}" body="{{body}}" handleAs="xml"></core-ajax>

Putting the bindings on different lines isnt supported yet

A: There is other ways you can try to access the values, try
var yourElement = document.getElementById('gservice'); if This doesn't work, try with 'querySelector' as shown below:
<gis-service id="gservice" class="gservice"
                  response="{{labels}}"   url="someUrl">
     </gis-service>
     <script>
        var gis_service = document.querySelector('gservice');
        console.log(gis_service);
     </script>
See the additional class attribute.
Also i recommend you to upgrade to Polymer 1.0, because it allows more robust ways to do things...


text:
Q: Cake PHP Error - Parse error: syntax error, unexpected T_STRING on Model I building my first cake PHP application, all things configured correctly, but when i calling to model on controller as below it gives an error message when i browse this url on localhost
class NotesController extends AppController{
var $name = "Notes";

function index(){
    $this->set('notes',$this->Note->find('all'));
}
}

this gives an error like this.
Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in D:\wamp\www\cakephp\app\Model\note.php on line 4
my model file has follow codes
class Note extends AppModel{
  $name = "Note";
}

i think db connection and other configurations are ok,please any one can help me, i ll highly appreciated you. thanks lot....

A: Change:
$name = "Note";

To:
var $name = "Note";

or:
public $name = "Note";

CakePHP recommends using var to keep code compatible with PHP4. However, this is completely unnecessary and it's better to use public.
That being said, the code you posted should not give an unexpected T_STRING error but, rather, an unexpected T_VARIABLE error. So there may be something else going on as well.

A: It has to be
var $name = "Note";

but that's php4, you want php5+
public $name = "Note";

when there are errors like this I suggest you to google them first. They're really easy to find and resolve. Also you might want to read about OOP first because it does not look like you have experience with it -> http://php.net/manual/en/language.oop5.php


text:
Q: in ubuntu the sound card is dummy I have mac mini 2009 and installed ubuntu 20.04 on it sucessfully,but the sound card is dummy i don't get any tone. I searched a lot but i did not find a solution that works for me. I would appreciate if somebody knows it well, to guide me.The sound driver should be realtk hd audio manager. The pc is connected to HDMI that has NVIDIA chip.
user@linux:~$ aplay -l
**** List of PLAYBACK Hardware Devices ****

sherif@linux:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal

I used alsa info and uploaded the information to this link, i am adding the alsa-info data also.
!!DMI Information
!!---------------

Manufacturer:      Apple Inc.
Product Name:      Macmini3,1
Product Version:   1.0
Firmware Version:      MM31.88Z.00AD.B00.0907171535
System SKU:        System SKU#
Board Vendor:      Apple Inc.
Board Name:        Mac-F22C86C8

!!ACPI Device Status Information
!!---------------

/sys/bus/acpi/devices/APP0001:00/status      11
/sys/bus/acpi/devices/PNP0103:00/status      15
/sys/bus/acpi/devices/PNP0A08:00/status      15
/sys/bus/acpi/devices/PNP0C0E:00/status      11
/sys/bus/acpi/devices/PNP0C0F:00/status      9
/sys/bus/acpi/devices/PNP0C0F:01/status      9
/sys/bus/acpi/devices/PNP0C0F:02/status      9
/sys/bus/acpi/devices/PNP0C0F:03/status      9
/sys/bus/acpi/devices/PNP0C0F:04/status      9
/sys/bus/acpi/devices/PNP0C0F:05/status      9
/sys/bus/acpi/devices/PNP0C0F:06/status      9
/sys/bus/acpi/devices/PNP0C0F:07/status      9
/sys/bus/acpi/devices/PNP0C0F:08/status      9
/sys/bus/acpi/devices/PNP0C0F:09/status      9
/sys/bus/acpi/devices/PNP0C0F:0a/status      9
/sys/bus/acpi/devices/PNP0C0F:0b/status      9
/sys/bus/acpi/devices/PNP0C0F:0c/status      9
/sys/bus/acpi/devices/PNP0C0F:0d/status      9
/sys/bus/acpi/devices/PNP0C0F:0e/status      9
/sys/bus/acpi/devices/PNP0C0F:0f/status      9
/sys/bus/acpi/devices/PNP0C0F:10/status      11
/sys/bus/acpi/devices/PNP0C0F:11/status      9
/sys/bus/acpi/devices/PNP0C0F:12/status      9
/sys/bus/acpi/devices/PNP0C0F:13/status      9
/sys/bus/acpi/devices/PNP0C0F:14/status      11
/sys/bus/acpi/devices/PNP0C0F:15/status      9
/sys/bus/acpi/devices/PNP0C0F:16/status      9
/sys/bus/acpi/devices/PNP0C0F:17/status      9
/sys/bus/acpi/devices/PNP0C0F:18/status      9
/sys/bus/acpi/devices/PNP0C0F:19/status      9
/sys/bus/acpi/devices/PNP0C0F:1a/status      9
/sys/bus/acpi/devices/PNP0C0F:1b/status      9
/sys/bus/acpi/devices/PNP0C0F:1c/status      9
/sys/bus/acpi/devices/PNP0C0F:1d/status      9
/sys/bus/acpi/devices/PNP0C0F:1e/status      9
/sys/bus/acpi/devices/PNP0C0F:1f/status      9
/sys/bus/acpi/devices/PNP0C0F:20/status      9
/sys/bus/acpi/devices/PNP0C0F:21/status      11
/sys/bus/acpi/devices/PNP0C0F:22/status      11
/sys/bus/acpi/devices/PNP0C0F:23/status      11
/sys/bus/acpi/devices/PNP0C0F:24/status      11
/sys/bus/acpi/devices/PNP0C0F:25/status      11
/sys/bus/acpi/devices/PNP0C0F:26/status      9
/sys/bus/acpi/devices/PNP0C0F:27/status      11
/sys/bus/acpi/devices/PNP0C0F:28/status      9
/sys/bus/acpi/devices/PNP0C0F:29/status      11
/sys/bus/acpi/devices/PNP0C0F:2a/status      11
/sys/bus/acpi/devices/PNP0C0F:2b/status      11
/sys/bus/acpi/devices/device:2e/status   15
/sys/bus/acpi/devices/device:32/status   15
/sys/bus/acpi/devices/device:34/status   15

!!Kernel Information
!!------------------

Kernel release:    5.4.0-91-generic
Operating System:  GNU/Linux
Architecture:      x86_64
Processor:         x86_64
SMP Enabled:       Yes

!!ALSA Version
!!------------

Driver version:     k5.4.0-91-generic
Library version:    1.2.2
Utilities version:  1.2.2

!!Loaded ALSA modules
!!-------------------

snd_hda_intel (card 0)

!!Sound Servers on this system
!!----------------------------

Pulseaudio:
      Installed - Yes (/usr/bin/pulseaudio)
      Running - Yes

!!Soundcards recognised by ALSA
!!-----------------------------

 0 [NVidia         ]: HDA-Intel - HDA NVidia
                      HDA NVidia at 0xd3480000 irq 21

!!PCI Soundcards installed in the system
!!--------------------------------------

00:08.0 Audio device [0403]: NVIDIA Corporation MCP79 High Definition Audio [10de:0ac0] (rev b1)
    Subsystem: NVIDIA Corporation Apple iMac 9,1 [10de:cb79]

!!Modprobe options (Sound related)
!!--------------------------------

snd_pcsp: index=-2
snd_usb_audio: index=-2
snd_atiixp_modem: index=-2
snd_intel8x0m: index=-2
snd_via82xx_modem: index=-2
snd_atiixp_modem: index=-2
snd_intel8x0m: index=-2
snd_via82xx_modem: index=-2
snd_usb_audio: index=-2
snd_usb_caiaq: index=-2
snd_usb_ua101: index=-2
snd_usb_us122l: index=-2
snd_usb_usx2y: index=-2
snd_cmipci: mpu_port=0x330 fm_port=0x388
snd_pcsp: index=-2
snd_usb_audio: index=-2

!!Loaded sound module options
!!---------------------------

!!Module: snd_hda_intel
    align_buffer_size : -1
    bdl_pos_adj : -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    beep_mode : N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N
    dmic_detect : Y
    enable : Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y
    enable_msi : -1
    id : (null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null)
    index : -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    jackpoll_ms : 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
    model : (null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null)
    patch : (null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null),(null)
    pm_blacklist : Y
    position_fix : -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    power_save : 1
    power_save_controller : Y
    probe_mask : -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    probe_only : 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
    single_cmd : -1
    snoop : -1

!!Sysfs card info
!!---------------

!!Card: /sys/class/sound/card0
Driver: /sys/bus/pci/drivers/snd_hda_intel
Tree:
    /sys/class/sound/card0
    |-- controlC0
    |   |-- dev
    |   |-- device -> ../../card0
    |   |-- power
    |   |-- subsystem -> ../../../../../../class/sound
    |   `-- uevent
    |-- device -> ../../../0000:00:08.0
    |-- id
    |-- number
    |-- power
    |   |-- async
    |   |-- autosuspend_delay_ms
    |   |-- control
    |   |-- runtime_active_kids
    |   |-- runtime_active_time
    |   |-- runtime_enabled
    |   |-- runtime_status
    |   |-- runtime_suspended_time
    |   `-- runtime_usage
    |-- subsystem -> ../../../../../class/sound
    `-- uevent

!!ALSA Device nodes
!!-----------------

crw-rw----  1 root audio 116,  2 Dec 19 15:55 /dev/snd/controlC0
crw-rw----  1 root audio 116,  1 Dec 19 15:55 /dev/snd/seq
crw-rw----  1 root audio 116, 33 Dec 19 15:55 /dev/snd/timer

/dev/snd/by-path:
total 0
drwxr-xr-x 2 root root  60 Dec 19 15:55 .
drwxr-xr-x 3 root root 120 Dec 19 15:55 ..
lrwxrwxrwx 1 root root  12 Dec 19 15:55 pci-0000:00:08.0 -> ../controlC0

!!Aplay/Arecord output
!!--------------------

APLAY

**** List of PLAYBACK Hardware Devices ****

ARECORD

**** List of CAPTURE Hardware Devices ****

!!Amixer output
!!-------------

!!-------Mixer controls for card NVidia

Card hw:0 'NVidia'/'HDA NVidia at 0xd3480000 irq 21'
  Mixer name    : ''
  Components    : ''
  Controls      : 0
  Simple ctrls  : 0

!!Alsactl output
!!--------------

--startcollapse--
state.NVidia {
    control {
    }
}
--endcollapse--

!!All Loaded Modules
!!------------------

ahci
applesmc
aufs
autofs4
binfmt_misc
bluetooth
bnep
bpfilter
br_netfilter
bridge
btbcm
btintel
btrtl
btusb
cfg80211
coretemp
crc_itu_t
drm
ecc
ecdh_generic
firewire_core
firewire_ohci
forcedeth
hid
hid_appleir
hid_generic
hid_logitech_dj
hid_logitech_hidpp
i2c_nforce2
input_leds
input_polldev
ip6_tables
ip6t_REJECT
ip6t_rpfilter
ip6table_filter
ip6table_mangle
ip6table_nat
ip6table_raw
ip6table_security
ip_set
ip_tables
ipt_REJECT
iptable_filter
iptable_mangle
iptable_nat
iptable_raw
iptable_security
joydev
kvm
kvm_intel
libahci
libcrc32c
llc
lp
mac_hid
msr
nf_conntrack
nf_conntrack_netlink
nf_defrag_ipv4
nf_defrag_ipv6
nf_nat
nf_reject_ipv4
nf_reject_ipv6
nf_tables
nfnetlink
nft_counter
nvidia
nvidia_uvm
overlay
parport
parport_pc
pata_acpi
ppdev
rfcomm
sch_fq_codel
snd
snd_hda_codec
snd_hda_core
snd_hda_intel
snd_hwdep
snd_intel_dspcfg
snd_pcm
snd_rawmidi
snd_seq
snd_seq_device
snd_seq_midi
snd_seq_midi_event
snd_timer
soundcore
stp
usbhid
wl
x_tables
xfrm_algo
xfrm_user
xt_MASQUERADE
xt_addrtype
xt_conntrack
xt_tcpudp

!!ALSA/HDA dmesg
!!--------------

[    0.368300] ACPI: Added _OSI(Linux-Dell-Video)
[    0.368300] ACPI: Added _OSI(Linux-Lenovo-NV-HDMI-Audio)
[    0.368300] ACPI: Added _OSI(Linux-HPI-Hybrid-Graphics)
--
[   29.006676] PCI Interrupt Link [LAZA] enabled at IRQ 21
[   29.006687] snd_hda_intel 0000:00:08.0: Disabling MSI
[   29.019376] snd_hda_intel 0000:00:08.0: no codecs found!
[   29.040902] applesmc: key=154 fan=1 temp=8 index=8 acc=0 lux=0 kbd=0

!!Packages installed
!!--------------------

ii  alsa-oss                                   1.1.8-1                               amd64        ALSA wrapper for OSS applications
ii  alsa-topology-conf                         1.2.2-1                               all          ALSA topology configuration files
ii  alsa-ucm-conf                              1.2.2-1ubuntu0.11                     all          ALSA Use Case Manager configuration files
ii  alsa-utils                                 1.2.2-1ubuntu2.1                      amd64        Utilities for configuring and using ALSA

sudo lspci -v

00:08.0 Audio device: NVIDIA Corporation MCP79 High Definition Audio (rev b1)
    Subsystem: NVIDIA Corporation Apple iMac 9,1
    Flags: bus master, 66MHz, fast devsel, latency 0, IRQ 21
    Memory at d3480000 (32-bit, non-prefetchable) [size=16K]
    Capabilities: [44] Power Management version 2
    Kernel driver in use: snd_hda_intel
    Kernel modules: snd_hda_intel

$ lsmod | grep snd_hda_intel

snd_hda_intel          53248  0
snd_intel_dspcfg       28672  1 snd_hda_intel
snd_hda_codec         135168  1 snd_hda_intel
snd_hda_core           90112  2 snd_hda_intel,snd_hda_codec
snd_pcm               106496  3 snd_hda_intel,snd_hda_codec,snd_hda_core
snd                    90112  8 snd_seq,snd_seq_device,snd_hwdep,snd_hda_intel,snd_hda_codec,snd_timer,snd_pcm,snd_rawmidi

i found this article but it even does not help. It states there may be a bug.

sherif@linux:~$ dmesg | grep snd
[   19.429829] snd_hda_intel 0000:00:08.0: dmic_detect option is deprecated, pass snd-intel-dspcfg.dsp_driver=1 option instead
[   19.430433] snd_hda_intel 0000:00:08.0: Disabling MSI
[   19.434742] snd_hda_intel 0000:00:08.0: no codecs found!
[  426.152644] snd_hda_intel 0000:00:08.0: dmic_detect option is deprecated, pass snd-intel-dspcfg.dsp_driver=1 option instead
[  426.152907] snd_hda_intel 0000:00:08.0: Disabling MSI
[  426.157224] snd_hda_intel 0000:00:08.0: no codecs found!

for some reason, which i still dont know, it worked after restart, may be the sound card was has a lose contact. It is unclear to me, what made it work, but i tried many things.


text:
Q: Optional Template parameter Is it possible to have optional template parameter in C++ , for example
template < class T, class U, class V>
class Test {
};

Here I want user to use this class either with V or without V
Is following possible
Test<int,int,int> WithAllParameter
Test<int,int> WithOneMissing

If Yes how to do this.

A: You can have default template arguments, which are sufficient for your purposes:
template<class T, class U = T, class V = U>
class Test
{ };

Now the following work:
Test<int> a;           // Test<int, int, int>
Test<double, float> b; // Test<double, float, float>

A: Sure, you can have default template parameters:
template <typename T, typename U, typename V = U>

template <typename T, typename U = int, typename V = std::vector<U> >

The standard library does this all the time -- most containers take two to five parameters! For example, unordered_map is actually:
template<
    class Key,                        // needed, key type
    class T,                          // needed, mapped type
    class Hash = std::hash<Key>,      // hash functor, defaults to std::hash<Key>
    class KeyEqual = std::equal_to<Key>, // comparator, defaults to Key::operator==()
    class Allocator = std::allocator<std::pair<const Key, T>> // allocator, defaults to std::allocator
> class unordered_map;

Typicall you just use it as std::unordered_map<std::string, double> without giving it any further thought.


text:
Q: USB-C Travel Hub: Ethernet port not working on Ubuntu 20.04 I have a T480s with Ubuntu 20.04 LTS. My USB-C Travel Hub from Lenovo (see https://download.lenovo.com/pccbbs/options_iso/usbc_travel_hub_qsg_sp40m60799_en.pdf) nicely works for the HDMI monitor and another USB device. However, the Ethernet port does not work. I can neither shift the PCI or USB Ethernet toggle to the right in Settings > Network. It says: "Cable unplugged". When I plug the cable directly into the laptops RJ45 port, it works.
Do I need to install additional drivers, or might the device be broken?
Btw, I found the firmware for Windows, but there doesn't seem to be one for Linux. Is there a generic one maybe? https://pcsupport.lenovo.com/us/en/downloads/ds542615


text:
Q: Warning: file_get_contents() failed to open stream Currently, I am trying to get the results of a https website and I am getting this error while using simple_html_dom.php, can anybody give me an idea on how to fix this or what's potentially causing it?
Warning: file_get_contents(https://crimson.gg/jackpot-history): failed to open stream: HTTP request failed! HTTP/1.1 503 Service Temporarily Unavailable in /tickets/simple_html_dom.php on line 75

Line line 75 of simple_html_dom.php is this.
function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
// We DO force the tags to be terminated.
$dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
// For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
$contents = file_get_contents($url, $use_include_path, $context, $offset);
// Paperg - use our own mechanism for getting the contents as we want to control the timeout.
//$contents = retrieve_url_contents($url);
if (empty($contents) || strlen($contents) > MAX_FILE_SIZE)
{
    return false;
}
// The second parameter can force the selectors to all be lowercase.
$dom->load($contents, $lowercase, $stripRN);
return $dom;
}

And the code I am currently using is.
$html = file_get_html('https://crimson.gg/jackpot-history');
foreach($html->find('#contentcolumn > a') as $element)
{
    print '

';
    echo $url = 'https://crimson.gg/'.$element->href;
    $html2 = file_get_html($url);

    $title = $html2->find('#contentcolumn > a',0);
    print $title = $title->plaintext;
}

Line 4.
foreach($html->find('#contentcolumn > a') as $element)


text:
Q: Docker: Level of separation between database, client and API I always separate client, database and API into completely separate scopes (i.e. they are designed to run on separate servers). Should this separation also be reflected when you set up your Docker compose? I feel relatively confident in separating the client (for example Vue or React project) into its own scope with its own docker compose file.
But I have some doubt as to how I should handle the API and the database. Are they expected to be two completely separate scopes with their own Docker and docker-compose files? Or are they expected to be in the same docker-compose?
I understand that both are possible - I'm interested in what's considered the best practice :-)
I hope the question is phrased to make sense. Thanks in advance

A: Usually, when talking about the same overall application you'd use one docker-compose.yml file and a different Dockerfile for each one if building them yourself.
If you check out this commercial application docker-compose file you can see their entire stack is defined in a single compose file.
If you're interested in best practices maybe check out Kubernetes or its simple one machine (node) personal use product minikube. generally, if you run these services not in production a compose file would be just fine, but, if you care about redundancy with resources and minimizing downtime (i.e. you have 3 machines, one becomes unavailable but the other two still have the other app instances running on them) then Kubernetes might be a better option


text:
Q: Extending Ruby in C - converting arguments to c types How I can do similar for ruby. I am not able to find a example/documentation for casting a variable to object. For example
Local<Object> obj = args[0]->ToObject();
Local<Array> props = obj->GetPropertyNames();

I am re-writing a node extension in ruby. Any sort of help will be very helpful. Thanks
static Handle<Value> SendEmail(const Arguments& args)
{
    HandleScope scope;

    list<string> values;
    Local<Object> obj = args[0]->ToObject();
    Local<Array> props = obj->GetPropertyNames();

    // Iterate through args[0], adding each element to our list
    for(unsigned int i = 0; i < props->Length(); i++) {
        String::AsciiValue val(obj->Get(i)->ToString());
        values.push_front(string(*val));
    }

    // Display the values in the list for debugging purposes
    for (list<string>::iterator it = values.begin(); it != values.end(); it++) {
        cout << *it << endl;
    }

    return scope.Close(args.This());
}

A: I'm not entirely sure that I understand your question, as you flagged this question as C and your code example is C++, but either way, if you're attempting to extend ruby you'll need to convert ruby values to C types, and if you plan on using C++ data structures, from C types to C++ objects.
Using the Ruby C Api:
#include "ruby.h"
//Define module my_module (this can be any name but it should be the name of your extension
VALUE MyModule = Qnil;
//Initialization prototype - required by ruby
void Init_MyModule();
//method prototype declarations - all methods must be prefaced by method_
VALUE method_get_some_ruby_value();

//actual method
VALUE get_some_ruby_value(VALUE self, VALUE some_value)
{
    //If your value is a ruby string - the StringValue function from ruby will ensure
    //that you get a string no matter what, even if the type being passed is not a string.
    VALUE r_string_value = StringValue(some_value);

    //Now we tell the Ruby API to give us the pointer to the ruby string
    //value and we assign that to a native char * in C.
    char *c_string_value = RSTRING_PTR(r_string_value);

    //Now do something with the char * - for example, turn it into a C++ string
    std::string str(c_string_value);
    // ...do something useful here...

    return Qnil; // If you want to return something back to ruby, you can return a VALUE.
}
//Ruby calls this to initialize your module in ruby
VALUE Init_MyModule()
{
    //This defines your module in ruby
    MyModule = rb_define_module("MyModule");
    //This defines the method - the module it is in, the ruby method name, the actual method ruby will call, and the number of arguments this function is expected to take
    rb_define_method(MyModule, "get_some_ruby_value", get_some_ruby_value, 1);
}

If you want to learn about passing structs back and forth between Ruby/C/C++, you'll need to have a thorough understanding of Ruby and the Ruby C API before you start trying to work with C++ objects.
Here are a few excellent resources to get you started:
http://silverhammermba.github.io/emberb/c/
http://java.ociweb.com/mark/NFJS/RubyCExtensions.pdf


text:
Q: Issue in dynamic renderUI in Shiny I am using renderUI() to display dynamic UI. The dropdown list boxes are updated dynamically but when I select a specific value from the drop down  it does the needful but falls back to the 1st element in the list. Why does this happen? Why cannot it stay at the value selected.
ui.R
fluidRow(
                            column(3,
                                   radioButtons("matchType", label = h3("Match type"),
                                                choices = list("Test" = "Test",
                                                               "ODI" = "ODI",
                                                               "Twenty20" = "TT"),
                                                inline=TRUE,
                                                selected = "Test"),
                                   uiOutput("players"),
                                   uiOutput("functions")

                            ),

 server.R
 testBatsman <- c("X","Y","Z")
 odiBatsman <- c("XX","YY","ZZ")
 funcs <- c("A","B","C")
 funcsODITT <- c("AA","BB","CC")
 output$batsmanPlot <- renderPlot({
    # Include the list to display in the drop downs on choice of matchType
    if(input$matchType == "Test"){
        player = testBatsman
        f = funcs
    } else if(input$matchType == "ODI"){
        player = odiBatsman
        f = funcsODITT
    }

    output$players = renderUI({
        selectInput('batsman', 'Columns',choices=player)
    })
    output$functions = renderUI({
        selectInput('batsmanFunc', 'Column1',choices=f)
    })

    print(input$batsman)
    analyzeBatsman(input$batsman,input$batsmanFunc,input$matchType)

While it is able to dynamically adjust the 2 drop downs it goes back to first element of the selected list. For e,g when
testBatsman('Z') and funcs('C") it displays this briefly before returing back to testBatsman('X') and funcs("A").
Why does this happen? How can I make it stay at the values selected?
Thanks

A: I made the following change and it seems to work now. It stays on the selected value.
output$batsmanPlot <- renderPlot({
    # Include the list to display in the drop downs on choice of matchType
    if(input$matchType == "Test"){
        player = testBatsman
        f = funcs
    } else if(input$matchType == "ODI"){
        player = odiBatsman
        f = funcsODITT
    }
    else {
        player = ttBatsman
        f = funcsODITT
    }
output$players = renderUI({
    selectInput('batsman', 'Columns',choices=player,selected=input$batsman)
})
output$functions = renderUI({
    selectInput('batsmanFunc', 'Column1',choices=f,selected=input$batsmanFunc)
})


text:
Q: Alternative Save/OpenBinaryDirect methods for CSOM for SharePoint Online Based on the doc from MS https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/using-csom-for-dotnet-standard, Save/OpenBinaryDirect methods is not available for .NET core app, they suggest to use regular file API, so what is the alternative way to read/write files stored in SharePoint online? what is the regular file API? does anyone done this? any example code/documentation?

A: Download file in .NET Core CSOM:
  using (var authenticationManager = new AuthenticationManager())
  using (var context = authenticationManager.GetContext(site, user, password))
  {
    context.Load(context.Web, p => p.Title);
    context.ExecuteQuery();
    Microsoft.SharePoint.Client.File file = context.Web.GetFileByUrl("https://tenant.sharepoint.com/sites/michael/Shared%20Documents/aa.txt");
    context.Load(file);
    context.ExecuteQuery();
    string filepath = @"C:\temp\" + file.Name;

    Microsoft.SharePoint.Client.ClientResult<Stream> mstream = file.OpenBinaryStream();
    context.ExecuteQuery();

    using (var fileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Create))
    {
      mstream.Value.CopyTo(fileStream);
    }

    using (System.IO.StreamReader sr = new System.IO.StreamReader(mstream.Value))
    {
      String line = sr.ReadToEnd();
      Console.WriteLine(line);
    }

  }

Upload file in .NET Core CSOM:
string filepath = @"C:\temp\aa.txt";
FileCreationInformation newfile = new FileCreationInformation();
newfile.Url = System.IO.Path.GetFileName(filepath);
newfile.Content= System.IO.File.ReadAllBytes(filepath);

List library = context.Web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = library.RootFolder.Files.Add(newfile);
context.Load(uploadFile);
context.ExecuteQuery();

A: Jerry's answer got me there, but I wanted to add a couple of extras that weren't mentioned in his answer.
If your file destination isn't the main Documents list, instead of the Lists.GetByTitle call use
var folder = context.Web.GetFolderByServerRelativeUrl(...);
File uploadFile = folder.Files.Add(newfile);

If you're updating a file, you've got to set
newFile.Overwrite = true;

And if the file you're uploading/replacing is greater than 2MB, you've got to use the ContentStream instead of Content
FileCreationInformation newfile = new FileCreationInformation
{
    Url = relativeUrl,
    ContentStream = stream,
    Overwrite = true
};