text:
Q: Adding new tab in between Account Information and Address Book in account dashboard I want to display some information in account dashboard. How to override default one with new one
I want a tab similar to the one highlighted in yellow box(with custom content like User Name, Dob, etc) to be displayed between the 'Account Information' block and 'Address Block'(where the red arrow is pointing).

A: Manage from Custom module
If you want to changes the section from a custom module then

*

*create customer_account_index.xml at app/code/{Vendor}/{Module}/view/frontend/layout

*create a template mycustominfo.phtml  at app/code/{Vendor}/{Module}/view/frontend/templates
Now, you add below code at  customer_account_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Customer\Block\Account\Dashboard\Info"
            name="customer_account_dashboard_mycustominfo"
            as="mycustominfo"
            before ="customer_account_dashboard_info"
        template="{Vendor}_{Module}::mycustominfo.phtml" cacheable="false"/>
        </referenceContainer>
    </body>
</page>

Manage from Theme module
If you want to changes the section from a custom theme then

*

*create customer_account_index.xml  id not exits at app/design/{VendorTheme}/{ThemeName}/Magento_Customer/layout

*create a template mycustominfo.phtml  at app/design/{VendorTheme}/{ThemeName}/Magento_Customer/templates
Now, you add below code at  customer_account_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Customer\Block\Account\Dashboard\Info"
            name="customer_account_dashboard_mycustominfo"
            as="mycustominfo"
            before ="customer_account_dashboard_info"
        template="Magento_Customer::mycustominfo.phtml" cacheable="false"/>
        </referenceContainer>
    </body>
</page>


text:
Q: PHP Explode maximum length string I'm writing a code which splits the text with the explode function, and usually it works well. This is what it does:

There's a text with some embed questions like this one: "Hey
{simple|name|What's your name?|Please write your full name}, thanks
for reading!" in the middle of a paragraph, and that's interpreted in
order to create contracts and stuff.

Here's an screenshot of this code working
Everything works fine until at real life users put really long texts and the explode function explodes and stop working. This is an example of this long texts:

{binary|Obligacion_EHS| ¿El contrato requiere el cumplimiento de
obligaciones de Seguridad Ambiental?| Si selecciona que sí, el
contrato contendrá la cláusula de obligaciones en materia ambiental|
Que cumple con las disposiciones aplicables en materia de seguridad,
salud y medio ambiente en el trabajo, respecto de sus trabajadores,
incluyendo sin limitar los lineamientos internos que se agregan al
presente Contrato como Anexo 5A, y que sus filiales y/o sus
proveedores que participen en la ejecución de los Servicios
Especializados también las cumplen. Derivado de lo anterior, EL
CONTRATISTA deberá presentar a SIEMENS ENERGY los siguientes
documentos: a. Certificado OHSAS 18001 vigente. b. El registro vigente
de sus filiales y/o sus proveedores en el Padrón Público de
Contratistas de Servicios Especializados u Obras Especializadas ante
la Secretaría del Trabajo y Previsión Social, con sus datos
correspondientes consistentes en: Números ********** y fechas
************ y que contenga los Servicios Especializados que le proporcionarán a EL CONTRATISTA. c. Cualquier documento que a
satisfacción de SIEMENS ENERGY demuestre que EL CONTRATISTA cumple con
el marco normativo Local y Federal en la República Mexicana de
seguridad y salud en el trabajo. d. Certificado de Industria Segura -
Programa de Autogestión STPS vigente. e. Acreditación reciente (1 año
máximo) que EL CONTRATISTA cumple con los requerimientos en materia de
seguridad, salud y medio ambiente, emitido por un auditor externo
donde se valide que: i. EL CONTRATISTA da cumplimiento a los
requerimientos legales aplicables en materia de seguridad, salud y
medio ambiente. ii. Sus trabajadores cuentan con las competencias de
seguridad adecuadas para los servicios especializados que EL
CONTRATISTA presta realiza. iii. Sus trabajadores cuentan con las
certificaciones de competencias laborales, las certificaciones
oficiales o conforme a las leyes con las constancias de capacitación y
adiestramiento necesarias para los servicios especializados que EL
CONTRATISTA iv. EL CONTRATISTA cuenta con un proceso efectivo para el
control del riesgo de sus actividades. En caso de incumplimiento de
cualquiera de las obligaciones establecidas en el presente inciso,
SIEMENS ENERGY, sin perjuicio de cualquier otro derecho contenido en
el presente Contrato, podrá aplicar a EL CONTRATISTA una penalización
del 10% (diez por ciento) del valor total de la Orden de Compra
correspondiente.}

The idea is that I have 6 different "input types":

*

*Simple, which is a simple question

*Binary, which print a radio button (yes/no) question that if you press "yes" you get the policy applied if you said yes.

*Multiple, which is a select list with options.

*Monetary, which transform quantities to text amounts.

*Date, which shows a date picker.

*Repeater, which copies the value of any of the previous ones.

What I usually do is first get all the "embed" questions in the "content" into the matches variable:
// Check for variables within this template file.
preg_match_all('/{(.*)}/U', $content, $matches);

And then I create html elements with those embed questions in the matches variable like this:
// Found matches.
echo '

New Dynamic Form Generated
';
foreach ($matches[0] as $id => $match) {
   $rep = $matches[1][$id];
   $generator = explode('|', $rep);
   echo '
'.$generator[2].'
';
   echo '<input type="text" class="newremplace" name="'.trim($generator[1]).'_in" id="'.trim($generator[3]).'_in" >
';
  }
echo '<input type="button" id="reemplazar" value="Remplace">

';

But as I already mention, when I used the long long "variable embed" it just don't work,
I found this question php explode is hitting maximum size and I tried changing the memory_limit in my php.ini from 128M to 512M, and I restarted the server, but the problem remains the same.
Do you have any idea how to solve this?
UPDATE
I change the test content to this one:

CONSIDERANDO QUE, {simple| Representante1_SE | ¿Cuál es el nombre del
primer Representante de SE?| Por política los contratos deben ser
firmados por 2 representantes} y {simple| Representante2_SE | ¿Cuál es
el nombre del Segundo Representante de SE?| Por política los contratos
deben ser firmados por 2 representantes} actuando en este acto como
representantes legales de SIEMENS ENERGY, tienen las facultades
legales suficientes para firmar el presente Contrato, en nombre y
representación de SIEMENS ENERGY, las cuales no les han sido
modificadas o limitadas en forma alguna, como consta en la copia del
documento integrado como Anexo 4 del presente Contrato.
{binaria|Obligacion_EHS| ¿El contrato requiere el cumplimiento de
obligaciones de Seguridad Ambiental?| Si selecciona que sí, el
contrato contendrá la cláusula de obligaciones en materia ambiental|
Que cumple con las disposiciones aplicables en materia de seguridad,
salud y medio ambiente en el trabajo, respecto de sus trabajadores,
incluyendo sin limitar los lineamientos internos que se agregan al
presente Contrato como Anexo 5A, y que sus filiales y/o sus
proveedores que participen en la ejecución de los Servicios
Especializados también las cumplen. Derivado de lo anterior, EL
CONTRATISTA deberá presentar a SIEMENS ENERGY los siguientes
documentos: a. Certificado OHSAS 18001 vigente. b. El registro vigente
de sus filiales y/o sus proveedores en el Padrón Público de
Contratistas de Servicios Especializados u Obras Especializadas ante
la Secretaría del Trabajo y Previsión Social, con sus datos
correspondientes consistentes en: Números ********** y fechas
************ y que contenga los Servicios Especializados que le proporcionarán a EL CONTRATISTA. c. Cualquier documento que a
satisfacción de SIEMENS ENERGY demuestre que EL CONTRATISTA cumple con
el marco normativo Local y Federal en la República Mexicana de
seguridad y salud en el trabajo. d. Certificado de Industria Segura -
Programa de Autogestión STPS vigente. e. Acreditación reciente (1 año
máximo) que EL CONTRATISTA cumple con los requerimientos en materia de
seguridad, salud y medio ambiente, emitido por un auditor externo
donde se valide que: i. EL CONTRATISTA da cumplimiento a los
requerimientos legales aplicables en materia de seguridad, salud y
medio ambiente. ii. Sus trabajadores cuentan con las competencias de
seguridad adecuadas para los servicios especializados que EL
CONTRATISTA presta realiza. iii. Sus trabajadores cuentan con las
certificaciones de competencias laborales, las certificaciones
oficiales o conforme a las leyes con las constancias de capacitación y
adiestramiento necesarias para los servicios especializados que EL
CONTRATISTA iv. EL CONTRATISTA cuenta con un proceso efectivo para el
control del riesgo de sus actividades. En caso de incumplimiento de
cualquiera de las obligaciones establecidas en el presente inciso,
SIEMENS ENERGY, sin perjuicio de cualquier otro derecho contenido en
el presente Contrato, podrá aplicar a EL CONTRATISTA una penalización
del 10% (diez por ciento) del valor total de la Orden de Compra
correspondiente.} CONSIDERANDO QUE, SIEMENS ENERGY requiere Contratar
y recibir los Servicios Especializados (según dicho término se define
más adelante) de EL CONTRATISTA, bajo los términos y condiciones
estipulados en el presente Contrato. CONSIDERANDO QUE, EL CONTRATISTA
es una sociedad debidamente constituida conforme a las leyes
mexicanas, cuyo domicilio fiscal está ubicado en {simple|
Registro_Patronal_Proveedores| ¿Cuál es el Número de Registro Patronal
del Proveedor?| Es el número que otorga el IMSS a todas las Empresas
para el registro de sus trabajadores}, como consta en la copia de la
escritura constitutiva integrada como Anexo 4 del presente Contrato y
cuenta con el Número de Registro Patronal {simple|
Registro_Patronal_Proveedor| ¿Cuál es el Número de Registro Patronal
del Proveedor?| Es el número que otorga el IMSS a todas las Empresas
para el registro de sus trabajadores}

And this is the code that I'm using:
echo '
Text to process

';
    var_dump($content);
    echo '
';

    // Check for variables within this template file.
    preg_match_all('/{(.*)}/U', $content, $matches);

    echo '
Found variables

';
    print_r($matches[0]);
    echo '
';

    // Found matches.  $matches[0] has the {}, $matches[1] doesn't have the {}
    echo '

New Dynamic Form Generated

';
    foreach ($matches[0] as $id => $match) {

        $rep = $matches[1][$id];
        $generator = explode('|', $rep);
        echo '
';
        print_r($generator);
        echo '
';
        echo '
'.$generator[2].'
';
        echo '<input type="text" class="newremplace" name="'.trim($generator[1]).'_in" id="'.trim($generator[1]).'_in" >
';
    }
    echo '<input type="button" id="reemplazar" value="Remplace">

';

    // {nombre_empresa | ¿Cuál es el nombre de la empresa? | Esta, es una socia }
    foreach ($matches[0] as $id => $match) {

        $rep = $matches[1][$id];
        $generator = explode('|', $rep);
        $generator = '';
        $content = str_replace($match, $generator, $content);
    }

    echo '
Dynamic Content

';
    echo $content;
    echo '
';

So, I found out that explode is not the problem, because when I print the found variables before explode them I just have 4, instead of 5.
Array
(
    [0] => {simple| Representante1_SE | ¿Cuál es el nombre del primer Representante de SE?| Por política los contratos deben ser firmados por 2 representantes}
    [1] => {simple| Representante2_SE | ¿Cuál es el nombre del Segundo Representante de SE?| Por política los contratos deben ser firmados por 2 representantes}
    [2] => {simple| Registro_Patronal_Proveedores| ¿Cuál es el Número de Registro Patronal del Proveedor?| Es el número que otorga el IMSS a todas las Empresas para el registro de sus trabajadores}
    [3] => {simple| Registro_Patronal_Proveedor| ¿Cuál es el Número de Registro Patronal del Proveedor?| Es el número que otorga el IMSS a todas las Empresas para el registro de sus trabajadores}
)

So I guess the problem is the length that preg_match_all can handle so, I research and I found that I can change the value of pcre.backtrack_limit for 10485760, I restarted the Apache but even so, I still have the same issue, I just can see 4 of five variables.
Any ideas?
UPDATE 2. (Solved)
I finally got it! The problem was in my REGEX Function, I just added an s modifier and that solve it.
preg_match_all('/{(.*)}/sU', $content, $matches);

Thank you to everyone who helped me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I set up Azure bot service within Azure VNET? I am developing a chatbot on Microsoft teams for internal use only, which needs to be deployed and hosted on the intranet. In order to NOT make the bot's APIs public I plan to use Azure VNET. Within this VNET how can I connect the azure bot service resource?
Could someone please guide me on how to set this up? Also, direct me to any concepts that I need to understand, to tackle this problem.

A: I can't advise on the VNET side of things (hopefully the Microsoft Bot engineers here on the site can advise), but here some other things that might be of use/interest in securing your bot for on premises/internal company use:

*

*Of course you'll side-load this app into the private company store, not the real Teams app store - do you need any info on how to do this?

*I'd strongly suggest blocking access to your bot from tenant(s) other than your own - Microsoft have a sample middleware to do just this, but as per this link it's now been rolled into the core Bot Framework SDK. This means that even if someone from another tenant (i.e. company) tried to access your bot, it would reject their messages.

*There are also mechanisms to sign users in, like using a signin card that could be applicable here, but I'm not sure you can lock users to a specific tenant this way. This would definitely be useful though if your bot is accessing any outside resources though, as it could be used to lock access to those.

Probably (2) above is your easiest and best bet, and it's pretty easy to implement.


text:
Q: HTTP 404: The /Media directory is not serving images I cloned a client's Orchard CMS. The repository that I cloned did not contain the Media folder (this is good). So, a next step was to restore the Media/Default directory from a .zip backup. Now that I've restored that, browsing the to site gives a 404 error for all resources in the Media folder. Why?

A: Quick Fix
The /Media folder is missing its required Web.config file. Add it.
Media/Web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>
  <system.web>
    <httpHandlers>
      <!-- iis6 - for any request in this location, return via managed static file handler -->
      <add path="*" verb="*" type="System.Web.StaticFileHandler" />
    </httpHandlers>
  </system.web>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
    </staticContent>

    <handlers accessPolicy="Script,Read">
      <!--
      iis7 - for any request to a file exists on disk, return it via native http module.
      accessPolicy 'Script' is to allow for a managed 404 page.
      -->
      <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" preCondition="integratedMode" resourceType="File" requireAccess="Read" />
    </handlers>
  </system.webServer>
</configuration>

Details
Out-of-the-box, Orchard's Media folder contains a Web.config file. Since source control excluded the Media folder it also did not have its Web.config. In IIS 7+ Integrated Mode, the following config is required for serving static files, because the root Orchard.Web/Web.config file <clear/>s all handlers.
<add name="StaticFile"
     path="*"
     verb="*"
     modules="StaticFileModule"
     preCondition="integratedMode"
     resourceType="File"
     requireAccess="Read" />


text:
Q: Grouping string ListView on Android? I have string like this :
you
me
i
me
i
i
you
me
me

I want to group that string in my ListView like this :
you (2)
me (4)
i (3)

and if I click "you (2)", show ListView again like this :
you
you

Can you help me?

A: First you need to sort your list adapter. For sorting this will be useful for you http://www.anddev.org/code-snippets-for-android-f33/alphabetical-listview-in-android-t56983.html
Then implement expandable list
As Dheeresh Singh said, please work on some code and then we can help more. Thanks


text:
Q: How do I partition a matrix into blocks and replace zeros with dots? I am using this command
\begin{equation}
W =  \left(
\begin{array}{ccccccccc}
 1 & 0 & 0 & 0 & -1 & 0 & 0 & 0 & -1 \\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
 -1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & -1 \\
 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 & 1 & 0 \\
 -1 & 0 & 0 & 0 & -1 & 0 & 0 & 0 & 1 \\
\end{array}
\right)
\end{equation}

to display a 9x9 matrix.
I would like to show this matrix as partitioned into 3x3 blocks, and also the zeros replaced with dots.

A: Doing a "search and replace" would not be a big problem, but if there's a dirty trick available…
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\begin{equation}
W =  \left(\mathcode`0=\cdot
\begin{array}{ *{3}{c} | *{3}{c} | *{3}{c} }
   1 & 0 & 0 & 0 & -1 & 0 & 0 & 0 & -1 \\
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
   0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\hline
   0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
   -1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & -1 \\
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \hline
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
   -1 & 0 & 0 & 0 & -1 & 0 & 0 & 0 & 1 \\
  \end{array}
\right)
\end{equation}
\end{document}

For the duration of the group initiate by \left(, I'm telling TeX that 0 in math mode (that is, in every cell) should be interpreted as \cdot.

A: You can use string replacement within LaTeX (xstring and collcell packages). For the blocks, I use dashed lines from arydshln (: in header and \hdashline in rows).
\documentclass{article}
\usepackage{array,arydshln}
\usepackage{xstring,collcell}

\newcommand{\ToDot}[1]{\StrSubstitute{#1}{0}{\cdot}}

\begin{document}
\begin{equation}
W =  \left(
\begin{array}{ *{3}{>{\collectcell\ToDot}c<{\endcollectcell}} :
  *{3}{>{\collectcell\ToDot}c<{\endcollectcell}} :
  *{3}{>{\collectcell\ToDot}c<{\endcollectcell}}}
   1 & 0 & 0 & 0 & -1 & 0 & 0 & 0 & -1 \\
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
   0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\hdashline
   0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
   -1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & -1 \\
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \hdashline
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
   0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
   -1 & 0 & 0 & 0 & -1 & 0 & 0 & 0 & 1 \\
  \end{array}
\right)
\end{equation}
\end{document}


text:
Q: Access denied error while attaching files I am trying to attach my mdf files to SQL server (using windows XP) but it gives operating system error (error 5), saying Access is denied to the dbMaster.mdf
I gave full control to folder in Windows Vista and 7 and it worked but I did not find how to give control in Windows XP.  Please help.
Thanks

A: For XP Professional you may have to uncheck simple file sharing first to see ntfs security tab. Follow these steps (taken from here)

*

*Launch Windows Explorer or My Computer.

*Click on the Tools at the menu bar, then click on Folder Options.

*Click on View tab.

*In the Advanced Settings section at the bottom of the list, uncheck    and unselect (clear the tick) on the "Use simple file sharing
  (Recommended)" check box.

*Click OK.

For XP Home you could use some 3rd party tool like FaJo XP File Security Extension to set NTFS permissions.


text:
Q: How to remove login pop up in selenium I am trying to login to Flipkart and make a purchase. But as soon as i click on the Login/SignUp button, a pop up comes suggesting existing usernames and has a Cancel button.
I am unable to find code for Cancel button through Inspect. How can i handle this?

A: To interact with the new window you have to change the element with which Selenium interacts, you can use the switchTo method and then indicate the name of the window:
driver.switchTo().window("windowName");

If you do not know the name of that popup that appears to you, you can get all the windows and look for the cancellation button:
for (String window : driver.getWindowHandles()) {
  driver.switchTo().window(window);
  List<WebElement> elements = driver.findElements(By.id("cancel"))
  if (!elements.isEmpty()) {
    elements.get(0).click();
    break;
  }
}


text:
Q: Fatal error: Class 'PHPUnit_Framework_TestCase' not found in dbunit\PHPUnit\Extensions\Database\TestCase.php on line 24 I want to write tests for MySQL Database. When I try to extend the database extension, it gives me the above error in title:
class FixtureTestCase extends PHPUnit_Extensions_Database_TestCase

Note: I have installed PHPUnit globally and I can access it through phpunit in cmd. I have latest PHPUnit 4.5.1.
I also installed Dbunit globally through composer:
composer global require phpunit/dbunit

Any help will be much appreciated. I've used PHP 5.4.

A: For referring to classes that are located within the global namespace, you can simply prefix them with a backward ( \ ) slash.
Try with this:
class FixtureTestCase extends \PHPUnit_Extensions_Database_TestCase

With the leading backward ( \ ) slash, PHP knows that we are referring to the PHPUnit_Extensions_Database_TestCase class in the global namespace, and located that one.
More info here
Hope this help.

A: It just might be the version of DBUnit. For example I'm using PHPUnit 4.8 and it works with DBUnit 1.4.
I had the above error when I was using composer with "phpunit/dbunit": ">=1.2" and I ended up with DBUnit 2.0.

A: Test your DB how? Through an API you created or direct accesses to DB? i would recommend you to write an API to access your DB and then write the tests to the API.
for exemple if you want to insert a user you call your web-server address (localhost:3000) or something you have and then call /users through POST to insert and make the routes to that.
I would suggest using LARAVEL for that.


text:
Q: VBA - Set Excel Workbook Default Save As Name I'm having a similar problem to one I described in a previous question of mine, only this time with Excel rather than Word.
I have created a spreadsheet with VBA in Access by creating a new Excel.Application then using Workbooks.Add.
I'm trying to change the suggested name that appears when a user first tries to click "Save As" in this document, but without opening the dialog immediately.
I have tried to modify the solution given to my previous problem, which solved this problem for Word. However, it seems that "xlDialogFileSummaryInfo" does not exist as a dialog, and I have been unable to find a suitable analogue.
Again, approaches such as setting
.ActiveWorkbook.BuiltInDocumentProperties("Title") = "My Title"

do not seem to work.
Any help would be much appreciated.


text:
Q: Is there any R package that supports fitting an HMM using multiple sequences of observations Is there any R package that supports fitting an HMM using multiple sequences of observations? to the best of my knowledge depmixS4 does not support this feature

A: You can fit multiple sequences of observations in the depmixS4 package with the argument ntimes.


text:
Q: One Slick texture is blurry, one not I want to bind two different textures to a cube using the Texture class of Slick.
The problem is that the first Texture I bind to the cube is shown correct, namely pixelwise but the other one I bind to the sides of the cube is blurred, as if I haven't entered
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

This is the code that renders the cube
    public void render(){
    float x = coordinate.x;
    float y = coordinate.y;
    float z = coordinate.z;

    top.bind();
    glBegin(GL_QUADS);

        //TOP
        glNormal3f(0f, 1f, 0f);
        glTexCoord2f(0f, 0f);
        glVertex3f(x,y,z);
        glTexCoord2f(0f, 1f);
        glVertex3f(x, y, z+1);
        glTexCoord2f(1f, 1f);
        glVertex3f(x+1, y, z+1);
        glTexCoord2f(1f, 0f);
        glVertex3f(x+1, y, z);
    glEnd();

    bottom.bind();
    glBegin(GL_QUADS);
        //BOTTOM
        glNormal3f(0f, -1f, 0f);
        glTexCoord2f(0f, 0f);
        glVertex3f(x,y-1,z);
        glTexCoord2f(0f, 1f);
        glVertex3f(x, y-1, z+1);
        glTexCoord2f(1f, 1f);
        glVertex3f(x+1, y-1, z+1);
        glTexCoord2f(1f, 0f);
        glVertex3f(x+1, y-1, z);
    glEnd();

    sides.bind();
    glBegin(GL_QUADS);
        //BACK
        glNormal3f(0,0,-1);
        glTexCoord2f(0f, 0f);
        glVertex3f(x,y,z);
        glTexCoord2f(1f, 0f);
        glVertex3f(x+1, y, z);
        glTexCoord2f(1f, 1f);
        glVertex3f(x+1, y-1, z);
        glTexCoord2f(0f, 1f);
        glVertex3f(x, y-1, z);

        //FRONT
        glNormal3f(0,0,1);
        glTexCoord2f(0f, 0f);
        glVertex3f(x,y,z+1);
        glTexCoord2f(1f, 0f);
        glVertex3f(x+1, y, z+1);
        glTexCoord2f(1f, 1f);
        glVertex3f(x+1, y-1, z+1);
        glTexCoord2f(0f, 1f);
        glVertex3f(x, y-1, z+1);

        //LEFT
        glNormal3f(-1,0,0);
        glTexCoord2f(0f, 0f);
        glVertex3f(x,y,z);
        glTexCoord2f(0f, 1f);
        glVertex3f(x, y-1, z);
        glTexCoord2f(1f, 1f);
        glVertex3f(x, y-1, z+1);
        glTexCoord2f(1f, 0f);
        glVertex3f(x, y, z+1);

        //RIGHT
        glNormal3f(1,0,0);
        glTexCoord2f(0f, 0f);
        glVertex3f(x+1,y,z);
        glTexCoord2f(0f, 1f);
        glVertex3f(x+1, y-1, z);
        glTexCoord2f(1f, 1f);
        glVertex3f(x+1, y-1, z+1);
        glTexCoord2f(1f, 0f);
        glVertex3f(x+1, y, z+1);
    glEnd();

}

A: If you want both textures to be "blurry" as you call it, you need to bind each texture individually, and call the following functions.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

If you them to be pixelated / "not blurry" you can call the following functions instead.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

Remember that you need to call them individually, like this.
texture1.bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

texture2.bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);


text:
Q: data driven in the conditional logic does't work as expected I'd like to data-driven test another feature files in the conditional logic (normal programming language there is if - else if - else if - else, but maybe not support in karate for more than two conditions).
Here is my demo feature file:
Feature: conditional logic call demo

  Scenario:

    * def switchVar1 = 1
    * def switchVar2 = 2

    * table testVars
    |switchVar1|switchVar2|
    |'theOne1'  | 'theTwo1' |
    |'theOne2'  | 'theTwo2' |

# here I can not do data-driven test the feature file: 'callUsage/module1/demo_module1.feature'
 * eval if(switchVar1 == 1)
     karate.call('classpath:callUsage/module1/demo_module1.feature') testVars

the error log
flow.feature:30 - javascript evaluation failed: if(switchVar1 == 1) karate.call('classpath:callUsage/module1/demo_module1.feature') testVars, <eval>:1:84 Expected ; but found testVars
if(switchVar1 == 1) karate.call('classpath:callUsage/module1/demo_module1.feature') testVars
                                                                                ^ in <eval> at line number 1 at column number 84

A: passing value to karate.call is different from call as karate.call should be invoked like a function
try,
* eval if(switchVar1 == 1) karate.call('<FILE_PATH>', testVars)

https://github.com/intuit/karate#karate-call


text:
Q: javascript setInterval() load I am trying to figure out what kind of load the window function setInterval() places on a user's computer. I would like to place a setInterval() on a page that is viewable only by my company's employees that will be checking a basic text file every 5 seconds or so and then if there is something to display, it will throw up some html code dynamically on the screen.
Any thoughts? Any better, less intrusive way to do this?

A: Appears it should not cause a problem, pending that the function setInterval() fires off is not heavy. Since I will only be reading a text file which should never be too large (text file will be overwritten about every minute by a completely separate job or bash script), the load should be minimal since it will be read in as a string, analyzed, and if necessary throw out a small amount of HTML code to the page.

A: I agree with all the comments regarding a single, polling setInterval() to be trivial.
However, if you want alternatives:
Long Polling

The browser makes an Ajax-style request to the server, which is kept
  open until the server has new data to send to the browser, which is
  sent to the browser in a complete response.

Also see:

*

*PHP example and explanation

*SignalR
Web Sockets

WebSockets is an advanced technology that makes it possible to open an
  interactive communication session between the user's browser and a
  server. With this API, you can send messages to a server and receive
  event-driven responses without having to poll the server for a reply.


text:
Q: Android - Speech recognition one word? Is there a way to get SpeechRecognizer to listen, wait for one word, then stop listening? I only need the first word that the user speaks.

A: You need to use:
EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS
flag rather than:
SPEECH_INPUT_MINIMUM_LENGTH_MILLIS flag.
If we set EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS flag than the speech recognition will terminate after the specified time in millis of silence. So in your case the user speaks a word and pauses for 100 milliseconds it will give you the word only. Below is the code I've used and tested also. Edit the time of silence as per your requirement. Just call this function in your activity for testing.
    public void provideTextToConvert()
{
    Intent speechintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    speechintent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS , 100);
    speechintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,  RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    speechintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    speechintent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));

    try {
        startActivityForResult(speechintent, REQ_CODE_SPEECH_INPUT);
    } catch (ActivityNotFoundException a) {
        Toast.makeText(getApplicationContext(),
                getString(R.string.speech_not_supported),
                Toast.LENGTH_SHORT).show();
    }
}


text:
Q: LinearLayout onClick works, but the state does not change A Layout has the following structure:
 <LinearLayout
        android:id="@+id/card_pack_clickable_area"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/card_pack_bg_selector">

            <FrameLayout
                android:id="@+id/card_pack_body_frame_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/bg_card_pack_body">

                <...>

            </FrameLayout>

            <TextView
            android:id="@+id/card_pack_percentage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="@color/bg_card_pack_body"/>

  </LinearLayout>

Content of @drawable/card_pack_bg_selector":
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_pressed="true">
      <shape>
          <solid android:color="#536dfe" />
      </shape>
  </item>

  <item android:state_focused="true">
      <shape>
          <solid android:color="#536dfe" />
      </shape>
  </item>

  <item android:drawable="@android:color/transparent"/>

</selector>

Problem statement
So the LinearLayout card_pack_clickable_area has two elements: a FrameLayout card_pack_body_frame_layout and a TextView card_pack_percentage.
What I'm trying to achieve is to have the FrameLayout and the TextView as a single clickable area, that's why I've wrapped them into outer LinearLayout.
In Java code I put onClickListener on this LinearLayout. Actually I'm obtaining onClick event when I click either on the FrameLayout or on TextView.
The problem is that the LinearLayout does not change its state as it should do following its background (@drawable/card_pack_bg_selector").
The question
How can I have the FrameLayout and the TextView as the united clickable area with the single background, which changes its state pressed/unpressed?

A: Can you please try to add android:clickable="true" to your outter linear layout.
If is does not work you can also try to add android:descendantFocusability="beforeDescendants" to your outter layout again..
Good luck there

A: Maybe, based on this question, you have to make your LinearLayout clickable? Remember to google before asking ;-)

A: I should've remove background attributes (android:background="@color/bg_card_pack_body") from inner elements (in my case the FrameLayout and the TextView).

A: replace this code with your old code in @drawable/card_pack_bg_selector and try i hope it's working....
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="#536dfe" android:state_focused="true" android:state_pressed="true"/>
    <item android:drawable="#536dfe" android:state_focused="false" android:state_pressed="true"/>
    <item android:drawable="#536dfe" android:state_focused="true"/>
    <item android:drawable="@android:color/transparent" android:state_focused="false" android:state_pressed="false"/>

</selector>


text:
Q: How to put data in Java InputStream? My current application requires to read data and enable user to download it as a file.
Server side code is similar to this : https://stackoverflow.com/a/55788/3192744
I need data inside InputStream, my current method to get InputStream is:
    InputStream getIStream(){
    StringBuilder sb = new StringBuilder();
    String temp = "";
    while(//there is data to be read from database//){
            temp = //partial data or one entry from database
            //some other modification in temp
            sb.append(temp).append("\n");
    }
    exampleString = sb.toString();
    InputStream stream = new ByteArrayInputStream(exampleString.getBytes());
    }

This method works for now since my data is very small, about 1000 String, each of about 100 chars, hence 100000 chars. Still, before I start download, I need to wait for entire data to be written in one string. Also as my data size increases it won't fit in one string.
So Is it possible to keep updating InputStream inside the while loop.
And to read this data on server side, I am waiting the method to return InputStream, so is it possible to send InputStream as method argument, and keep reading from it while it is being updated.
Basically I want to implement something like a pipe, where modified strings from database output are being sent, and on the receiving end data is being put in the file for user to download, and download process for user can start while data is being read from database.

A: The problem is that you aggregate all your data into a StringBuilder (and later into the InputStream which you will write to your ServletOutputStream), while you could instead write it along the way.
As mentioned in my comment I suggest using the ServletResponse's PrinterWriter instead of its OutputStream if you don't need to output binary data, but it would work all the same.
With the PrinterWriter:
PrinterWriter writer = ServletResponse.getWriter();
while(/*there is data to be read from database*/){
        temp = //partial data or one entry from database
        //some other modification in temp
        writer.println(temp);
}
writer.close();

With the ServletOutputStream :
OutputStream out = ServletResponse.getOutputStream();
while(/*there is data to be read from database*/){
        temp = //partial data or one entry from database
        //some other modification in temp
        out.write(temp.getBytes());
        out.write('\n');
}
out.close();


text:
Q: Selected text and making bold apart from first word using jQuery I know this is something very simple but I am still new to jQuery, so I'm a little unsure how to approach. I have found a good few solutions with making the first word bold but not what I need.
I want to only make the words bold other than the first word; is this possible?
I.E
Buy This Product
to be
Buy This Product
I only have a example from another solution for the first word but not sure how to adjust.
$('.homepage-boxes .ty-banner__image-wrapper a').find('.ty-btn_ghost').html(function(i, h){
    return h.replace(/\w+\s/, function(firstWord){
      return '' + firstWord + '';
    });
 });

I have adjusted with the classes I need and the find class but I want to make the text  but excluding the first word.

A: There are a few ways to do this. You could use a regex like / (.*)/ to match the first space followed by every other character to the end of the string as a sub match:

$('.homepage-boxes .ty-banner__image-wrapper a').find('.ty-btn_ghost').html(function(i, h){
  return h.replace(/ (.*)/, " $1");
});

    Buy This Product

    Buy The Other Product

    Buy Some Third Product

Note that using parentheses in the regex allows you to refer to the matched bit using $1, so you can provide the replacement as a string in the second argument to .replace() rather than passing a function.


text:
Q: How to dump a YAML with an int with leading zeros? I need to dump an integer with leading zeros, but not as a string.
I can dump it like a string in this way:
import sys
from ruamel.yaml import YAML

data = {'identifier': '001'}

yaml = YAML()
yaml.dump(data, sys.stdout)

The result is:
identifier: '001'

I do not need to dump as a string, but as a number.
I need a result like:
identifier: 001

How can I do it?

A: First thing to do if you need to check if a particular output can be generated is
trying to round-trip the result:
import sys
import ruamel.yaml

yaml_str = """\
identifier: 001
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
data['another'] = double_o_one = data['identifier']
yaml.dump(data, sys.stdout)

which gives:
identifier: 001
another: 001

So this proves this can be done programmatically, and if worst comes to worst and
you cannot figure out how to make the double_o_one from scratch, you can
load it from a string.
If you investigate a bit more and have a look at the source of scalarint.py:
print(type(double_o_one))
print(double_o_one.__dict__)
print()

data['james'] = double_o_seven = ruamel.yaml.scalarint.ScalarInt(7, width=3)
yaml.dump(data, sys.stdout)

and that gives:
<class 'ruamel.yaml.scalarint.ScalarInt'>
{'_width': 3, '_underscore': None}

identifier: 001
another: 001
james: 007

So if you start out with a string x = '001', you do x = ScalarInt(int(x), len(x))

A: >>> data = {'identifier': 0o001}

This will convert to an integer. But , not in the format you specified.


text:
Q: How can I develop this using induction? I'm trying to prove using induction that $a^n +b^n = (a-b) \cdot \sum\limits_{k=1}^{n}a^{n-k}b^k-1$
So I have developed the expression for $n+1$ but I get to $a \cdot b^n - b^{n+1} + a^n - b^n$
And from here I can't simplify until $a^{n+1} + b^{n+1} \ldots$
Can someone help me?
Thanks

A: Induction step (assuming a and b are non-zero, of course);
$  (a-b) \cdot \sum\limits_{k=1}^{n+1}a^{n+1-k}b^{k-1} =$
$  \sum\limits_{k=1}^{n+1}a^{n+2-k}b^{k-1} - \sum\limits_{k=1}^{n+1}a^{n+1-k}b^k=$
$ a^{2}\sum\limits_{k=1}^{n+1}a^{n-k}b^{k-1} - ab \sum\limits_{k=1}^{n+1}a^{n-k}b^{k-1}=$
$ (a^2 - ab)\sum\limits_{k=1}^{n+1}a^{n-k}b^{k-1}=$
$ a(a - b)\sum\limits_{k=1}^{n}a^{n-k}b^{k-1} + (a^2 - ab)a^{-1}b^n=$
$ a(a^n - b^n) + (ab^n - b^{n+1})=$
$ a^{n+1} - ab^n + ab^n - b^{n+1}=$
$a^{n+1} - b^{n+1}$


text:
Q: Time Series Forecasting in SageMaker - which instance should I choose? I am currently trying to forecasting hourly values with a weekly seasonality. In the SARIMAX model that means that I have to set m = 168 (24 hours a day and 7 days a week -> 24*7).
My model looks like this:
model = SARIMAX(df['IdCount'],order=(4,1,3),seasonal_order=(2,2,1,168))
results = model.fit()

And I think because of the relatively big m=168 it takes a very long time to fit the model. When doing this locally, the kernel died.
Therefore, I chose to try it in SageMaker and I am currently using ml.t2.medium instance. In order to perform this task fast and without any issues which instance would you recommend and why? Which is the best one only in regards to performance and which is the best one regarding cost benefit ratio?

A: I know nothing about SARIMAX, but what I do with sagemaker is this.. I choose for the notebook the cheapest instance which is ml.t2.medium and then I use the notebook to launch the training job. For that training job I usually choose an instance with GPU. Anyway ml.t2.medium is very basic and I would not recommend it for anything else of what I do (launch other instances). You can take a look at this page for the available instance types, their features  and also their price.


text:
Q: How to properly partition my HDD for Ubuntu? I'm trying to install Ubuntu on my Laptop. I don't have any other OS's installed on it. I have tried "Erase disk and install Ubuntu", but that always crashed. So, I chose "Something else" , but I have no idea what to do there. My laptop has a 1 TB HDD with 8 GB of RAM
Edit: I'm trying to install Ubuntu 20.04 LTS

A: "Erase disk and install Ubuntu" is supposed to work and it would be probably then also crash if choose the other option. Maybe there is an issue with the bootstick, you could check the md5 sum of your downloaded .iso file and maybe create a new bootstick.

A: There is a nice installation guide on https://www.linuxtechi.com/ubuntu-20-04-lts-installation-steps-screenshots/, though I would suggest that, if you want to have a separate /homepartition, make it bigger than in the guide.
However, there is today no need for a separate /home partition. If you want a /home partition I would suggest the following partition scheme:
Device     Name                  Type  Mount point  Size
/dev/sda1 "EFI system partition" fat32 /boot/efi    100MB
/dev/sda2                        Ext4  /            100GB
/dev/sda3                        swap               4GB
/dev/sda4                        Ext4  /home        what's left

But, as said, there is no need for a specific /home unless you plan on trying out other Linux distributions and want to preserve your files when you change distribution. Then you can use this scheme:
Device     Name                  Type  Mount point  Size
/dev/sda1 "EFI system partition" fat32 /boot/efi    100MB
/dev/sda2                        swap               4GB
/dev/sda3                        Ext4  /            what's left

I personally have the following (I have a separate disk for /home and /opt):
Disk 1 250GB
Device     Name                  Type  Mount point  Size
/dev/sda1 "EFI system partition" fat32 /boot/efi    100MB
/dev/sda2                        Ext4  /boot        500MB
/dev/sda3                        swap               4GB
/dev/sda4                        Ext4  /            what's left

Disk 2 2TB
/dev/sdb1                        Ext4  /home        1.5TB
/dev/sdb2                        Ext4  /opt         0.5TB

But then I have worked with programming very large software projects, so I needed the large /home and a lot of extras that I stored in /opt.


text:
Q: Submit to same page with an anchor I am trying to understand how forms work , so far I understood that I could submit the form and refresh to the same page through
> action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"

and then catch the errors or not have blank inputs.
However, let's say I have anchors in the page (sections in other words like #ContactUs) how could I refresh the page using action to get to that specific place instead of going back to top of page?
Thanks for all in advance
Here is part of the code:
 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

SEND US A MESSAGE!

        We'd be happy to hear from you.
        <input name="contactname" placeholder="Name" type="text" value="<?php echo $contactname;?>"/>  <?php echo $contactnameErr;?>
        <input name="contactemail" placeholder="Email" type="text" value="<?php echo $contactemail;?>" /> <?php echo $contactemailErr;?>
        <input name="contactphone" placeholder="Phone #" type="text" value="<?php echo $contactphone;?>" /> <?php echo $contactphoneErr;?>
        <input name="contactsubject" placeholder="Subject" type="text" value="<?php echo $contactsubject;?>" /> <?php echo $contactsubjectErr;?>
        <textarea name="contactmessage" placeholder="Message"><?php echo $contactmessage;?></textarea> <?php echo $contactmessageErr;?>
        <input type="submit" name="submit" value="Send" class="contact-button" />
     </form>

A: You can Use jQuery as i given below
<?php

    if(isset($_POST['submit']))
    {

        //
        //sql query and display
        //

        ?>

        <?php

    }

    ?>

A: You should have a validation for it for example
<?php
 if(isset($_POST['submit'])){
    //then do something
    header("Location: #contactus");
   }
?>

So this way even if you load, it does not give you empty and does not ask you to resubmit


text:
Q: Mock async Get method with MOQ How do I get rid of this error message:
Error   5   Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>>' to 'System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>'. An explicit conversion exists (are you missing a cast?)

I thought my Task.FromResult would fix that but no...
mockService.Setup<IEnumerable<SchoolyearDTO>>(c => c.GetSchoolyears()).Returns(
                    Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));

public async Task<IEnumerable<SchoolyearDTO>> GetSchoolyearsAsync()
{
    var schoolyears = await ...
}

A: GetSchoolyearsAsync is an async method, so it returns a Task<IEnumerable<SchoolyearDTO>> and not just a IEnumerable<SchoolyearDTO>. You need to specify that in the type parameters for SetupGet
mockService.SetupGet<Task<IEnumerable<SchoolyearDTO>>>(c => c.GetSchoolyears()).
    Returns(Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));


text:
Q: Novell Client logout with windows logoff I have a windows 2008 R2 server that's running the Novell Client 2 SP2. I noticed that when I remote in to the system and then logoff of my remote session the Novell client also logs out. Is there a way to prevent the client from logging out as I have scripts running on the server which are expecting to see the proper drives mounted by the Novell client?

A: No.
The client is running under your user/security context, and when you logoff, your user context goes away... along anything running in it.
The only solution to this is to not log off.  If you disconnect the remote session, instead of logging off, your sessions, and anything running it, continue to run.


text:
Q: Storing dictionary values in the Data Vault DWH Let's say I have some entity, for example Order. It can have status attribute, let's say with a code N what would mean "new order". There is another dictionary table that holds all of these order statuses values. How to design the database structure for it? What should I put to satellite? The status code? Description? Or both?

A: Model the key/value structure as reference table
In the raw data vault satellite, keep the status "N" for auditing purpose (you must always be able to give back the data to the user as it were when you first fetch them).
If there's some business rules you need to apply in a business vault, then you can then keep the description in the business vault satellite.


text:
Q: reference request for cardinal number and topology This problem is really surprising how some of these cardinal numbers can be invariants.
How to find some references to this subject. Or I just have to prove this because they are just simple facts to remember.

A: I think Willard just wants you to prove these statements. By "has cardinal number $\aleph$," I'm sure means that the set has cardinality $\aleph$. Now, given two spaces that are homeomorphic, say $h : X \to Y$ is a homeomorphism, assuming that $X$ has one of the properties listed (1 through 5), you want to show that $Y$ also has that property. You may also visit Suppose X~Y, Prove that P(X) ~ P(Y) for a question that might be relevant to one of these properties.
Edit: To show that a property is not a topological property, you want to construct a homeomorphism $h : X \to Y$ that doesn't preserve the indicated property. For example, if $X = \mathbb R$ with the metric $\rho : \mathbb R^2 \to \mathbb R$ defined by $\rho(x,y) = \min\{ |x-y| , 1 \}$ (you can check that this is a metric which is compatible with the usual topology on $\mathbb R$), then the property that $\rho$ is bounded (in particular, by $1$), is not a topological property. In fact the identity $\mathrm{id} : (X,\rho) \to (X,d)$ where $d$ is the standard metric $|x-y|$ is a homeormorphism, but the metric space $(X,d)$ is not bounded.
Another edit: If you want to read about other cardinal invariant properties in topology, https://en.wikipedia.org/wiki/Cardinal_function lists a few.

A: You just have to ask the question: is this property of the topological space $X$ still true if I replace $X$ by some other space $Y$ that is homeomorphic to $X$? If so the property is topological, if not it isn't.
For problems $1$ to $5$, I think it is easy to see that the above holds: e.g., in problem $3$ if $X$ has a basis $B$ of cardinality $\aleph_1$, and $f: X \to Y$ is a homeomorphism, then $\{f(U) : U \in B\}$ will be a basis for $Y$ of cardinality $\aleph_1$.
For problem $7$, it is easy to see that the above fails to hold: e.g., the singleton set $\{(0, 1)\} \subseteq \Bbb{R}^2$ is not a subset of $\Bbb{R}$ but it is homeomorphic to $\{0\}$ which is a subset of $\Bbb{R}$.
The meaning of $6$ is a little bit unclear, because the dependency on $\rho$ is not stated: I think the point is that you can't recover the metric $\rho$ (if it exists) from the topology on $X$, e.g., if $\rho$ is any metric then so is $2\rho$ (and there are many more interesting examples). On a possible alternative reading, if you are given the metric $\rho$, then just replacing $X$ by a homeomorphic space $Y$ just by renaming all the elements gives you a space to which the metric $\rho$ just doesn't apply.


text:
Q: Run a regression with omitted category I have a dataset like these

BirthYear
walking

50-70
500

70-90
700

90-10
200

70-90
450

70-90
850

70-90
890

30-50
660

70-90
760

70-90
450

30-50
230

30-50
120

50-70
120

70-90
340

90-10
920

I want to run a regression of walking on BirthYear and that the BirthYear 90-10 is the omitted category, to find out how much 70-90 people walk less than 90-10 people on average.
I gave this code but don't  know how to fix with omitted category for 90-10.
feols(fml = walking ~ BirthYear, data = df)

A: To put the 70-90 category in the reference/intercept simply use the relevel function
> df$BirthYear=factor(df$BirthYear)
> df$BirthYear=relevel(df$BirthYear,"70-90")
> summary(lm(walking~BirthYear,data=df))

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)      634.29     105.62   6.006 0.000131 ***
BirthYear30-50  -297.62     192.83  -1.543 0.153754
BirthYear50-70  -324.29     224.05  -1.447 0.178396
BirthYear90-10   -74.29     224.05  -0.332 0.747062


text:
Q: Include a file within a folder in an Arduino library I'm currently writing an Arduino library and I want to include files in a subdirectory within the library folder. More specifically, I want the files to be accesible from the Arduino sketch.
This is my directory structure:
MyLib/MyLib.cpp
MyLib/MyLib.h
MyLib/Extra/SomeNiceFunctions.cpp
MyLib/Extra/SomeNiceFunctions.h

This is how I'm trying to include the file:
#include <MyLib.h>
#include <Extra/SomeNiceFunctions.h>

Obviously this is wrong because of the way the IDE is including the library folders. What else should I try? I could split the Extra folder to another "Library" (another folder) but that's not what I'm after.
EDIT: This is the error I'm getting undefined reference to 'font8x8'. This is defined in Extra/SomeNiceFunctions.h.

A: Don't use
#include <MyLib.h>
#include <Extra/SomeNiceFunctions.h>

instead use
#include <arduinolib.h>
#include "MyLib.h"
#include "Extra/SomeNiceFunctions.h"

Using angle-brackets, the compiler looks in the standard-folders for include-files. You want your custom files in your working directory.

A: Regarding including Arduion/Energia libraries that are in Arduino/Energia subfolders:
Look where your main include file is (eg. arduino.h / energia.h) and go up in the directory structure with ..\ or downwards until you get to the desired h file you want to include.
eg.
I have:
..hardware\cores\cc3200\energia.h
..hardware\libraries\SPI\SPI.h
In order to use in a .cpp file the SPI.h functions, I have to add:
#include <energia.h>
followed by
#include <..\..\libraries\SPI\SPI.h

A: Borrowing from this stack overflow question,

The include path includes the sketch's directory, the target directory
  (/hardware/core//) and the avr include directory
  (/hardware/tools/avr/avr/include/), as well as any library directories
  (in /hardware/libraries/) which contain a header file which is
  included by the main sketch file.

Try
// in myProject.ino
#include <arduinolib.h>
#include "MyLib.h"

// in Mylib.h
#include "./extra/SomeNiceFunctions.h"

A: I had some an issue with this.  I just wanted a simple solution and while writing a library in CPP is the correct way - I took a sketch - say robo.ino file and added it to a simple library include - so that there was just one file in the library under a folder called Robot - robo.h
├── sketchesfolder
├── libraries
│   ├── robot
│   │   ├── robot.h
├── robotsketch
│   ├── Move.ino

Now in the Move.ino - I just include the file
#include <robo.h>

The only thing you need to add for simple functions is a prototype declaration - or make sure your functions are ordered by first use.
So for example - put Setup() at the bottom and a function like:
 void halt(int wait);

as a prototype definition at the head of the robo.h file
It allows you to share a sketch as common code without converting it to a CPP lib.  But you should really do that of course.


text:
Q: How do I find the median time? severstal_df['duration'] = pd.to_datetime(severstal_df['time'], format = '%H:%M:%S')

severstal_df = severstal_df.groupby(['operation', 'date', 'user'])\
                           .duration.apply(lambda x: x.max() - x.min()).reset_index(name = 'duration')

severstal_df['duration_time'] = (pd.Timestamp('today').normalize() + severstal_df['duration']).dt.time

severstal_df['duration_median'] = severstal_df.groupby('operation')\
                                              .apply(severstal_df.median(axis = severstal_df['duration_time']))

Gives an error message:
Series' objects are mutable, thus they cannot be hashed
Types:
operation         int64
date             object
user              int64
duration_time    object
dtype: object


text:
Q: Call async await in angular 2 In my angular 2 app i got method:
myMethod(component: any): void {
  let a = console.log('start');
  if (this._something) {
    // Here i got custom modal window
    this._service.callModalWindow('message').subscribe(result => {
      if (result === 'Confirm') {
        let b = console.log('confirm);
      }
    }
  }
  let c = console.log('finish');
}

The problem is: The way this method call console.log is not what i want, i want to get first console.log('first'), then after i got my modal confirmed get console.log('confirm'), and then get the final console.log('finish');
Now i have this situation, method calls variable a, then c, then b when i confirm modal.
Does anyone have any ideas how i can work around this situation?

A: Not the most suitable way to use the async await. But if u must. use the toPromise to convert the observable to promise since async wait need promises to resolve behind the scene
async  myMethod(component: any): void {
  let a = console.log('start');
  if (this._something) {
  // Here i got custom modal window
  let result = await this._service.callModalWindow('message').toPromise();
  if (result === 'Confirm') {
    let b = console.log('confirm);
  }
  let c = console.log('finish');
}


text:
Q: Possible syntax for multi-type catch blocks in C#? Here are two previous questions regarding this topic:

*

*Catch multiple Exceptions at once?

*More Elegant Exception Handling Than Multiple Catch Blocks?
I was working today and thought this might be an appropriate syntax should this feature ever be added to the C# language. Anyone have any opinions about it?
The type of e must be a base type or interface of every exception type listed.
Edit: In this example, the catch block handles either ArgumentNullException or ArgumentOutOfRangeException and places the exception instance in a variable of type ArgumentException called e. It doesn't handle any other type of ArgumentException other than the two listed. I think there was some confusion about the associativity of the , and the as.
Edit 2: If the listed exceptions all upcast to a variable of the type of e, then the code compiles cleanly to MSIL without any casts or explicit type checks, making it faster (potentially significantly) than the current syntax of catching ArgumentException followed by a throw; if it's not one of the two you intended. The problem is even more obvious if you're catching Exception and checking for two possible types to handle and rethrowing if it's something else.
try
{
}
catch (ArgumentNullException, ArgumentOutOfRangeException as ArgumentException e)
{
}

A: See this:
Cool or Stupid? Catch(Exception[NamingException, CreateException] e)
My answer to that question is that they should let you "stack" them like with using blocks:
try
{
}
catch (ArgumentNullException e)
catch (ArgumentOutOfRangeException e)
catch (ArgumentException e)
{

}

Though I see you're going for and rather than or .  Personally I don't see the and approach as very useful, because you're already constrained to a real non-interface exception type and there's no dual-inheritance.

A: Inclusion of this feature is planned for Java 7 with the following syntax:
try {
    return klass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
    throw new AssertionError(e);
}

Edit: I think the intention is for the static type of e to be the most specific common superclass of the listed exceptions. (In Java, only instances of class java.lang.Throwable can be thrown, hence catching with a common super interface is of limited utility since the exception can not be re-thrown.)

A: I don't find myself wanting this very often in C#, whereas in Java I find there are various situations where I have to catch a bunch of checked exceptions and wrap them all in a different exception that my method is declared to throw.
That's something I'd possibly like some syntax for:
try
{
}
wrap (OneException as AnotherException)
catch (HandleableException e)
{
    // Actual handling for some exception types
}

... but again, I find myself doing that much more in Java than in C#.
There are other enhancements which are way higher up my list for C# than this :)

A: You can already do this, just
 try{}
 catch(Exception e)
 {}

since all exceptions derive from System.Exception.  And you would do just as you would above, determine the type of the exception in the catch block itself.

A: If ArgumentNullException and ArgumentOutOfRangeException have different interfaces, will be a pain to cast correctly;
For instance ArgumentOutOfRangeException have an ActualValue property; if you had to use it, you'll end with something like:

if(e is ArgumentOutOfRangeException)
{
    // use e.ActualValue
}
else
{
    // use e.Data
}

A: That would only work if you do not declare an instance (e). If you reference the e inside the block, what is it?


text:
Q: About the kernel of a linear form? Let $Af=f(0)$ be a linear form restricted to the space of $C^{\infty}$-funtions with compact support over $\mathbb{R}$ (noted $C_c^{\infty}(\mathbb{R})$). Is $A$ continuous w.r.t. the topology of $L^2(\mathbb{R})$? In other words, can we find a sequence $(f_n)$ in $C_c^{\infty}(\mathbb{R})$ such that $\|f_n-f\|_2\to 0$ with $f_n(0)\not\to f(0)$ where $f\in C_c^{\infty}(\mathbb{R})$?
Thanks a lot!
Math

A: Yes, there are such sequences. For instance, if $$g(x)=\begin{cases}\exp\frac{1}{x^2-1}&\text{if }x\in (-1,1)\\ 0&\text{if }x\notin (-1,1)\end{cases}$$
Then $f_n(x)=g(nx)$ converges in $L^2$ to $0$, and specifically $$\left\lVert f_n-0\right\rVert_2=n^{-1/2}\sqrt{\int_{\Bbb R} (g(x))^2\,dx}.$$ Yet, $f_n(0)=\frac1e$.


text:
Q: Getting the signal from a floor pressure plate in the middle of a room I have this contraption with a floor plate that causes certain changes in a wall couple of blocks away (ie, firing pistons, etc). The floor plate is on a stone floor, and I wouldn't like to mess up the floor with redstone wire - all the wiring must be under the floor, and the floor must all be at one level.
Well, I fail to understand this thing: how to get the signal down from the block on which the floor plate was pushed, without any holes around the floor. Thing is, you can't put a redstone torch upside down. If you could, then I'd put it on the bottom of the floor block and pull the redstone wire to wherever I need, and all of that in the underfloor area, so nothing of that is visible from outside. But since you can not, it seems that there is no other way than have a how just besides the floor block with plate, where to put the redstone wire.

A: The pressure plate actually powers the block below it, so you can get the signal from below the block where the pressure plate is:

There is no need to have any holes on the floor.


text:
Q: Python: Dictionary-like object in dataframe to new dataframe Hello I've done some webscraping and I have a dictionary-like object that is in one of the columns of my dataframe.
data.offerAggregate.property_aggregate.property.floors is the column name and the rest is a value inside the column.
data.offerAggregate.property_aggregate.property.floors
0  [{'units': [{'features': [{'Code': 'chairs', 'Exists': True}, {'Code': 'window', 'Exists': True}, {'Code': 'balcony', 'Exists': True}, {'Code': 'fridge', 'Exists': True}, {'Code': 'stove', 'Exists': True}, {'Code': 'oven', 'Exists': True}, {'Code': 'microwave', 'Exists': True}, {'Code': 'washing-machine', 'Exists': True}, {'Code': 'dryer', 'Exists': False}, {'Code': 'dishwasher', 'Exists': False}, {'Code': 'table', 'Exists': True}]}, {'features': [{'Code': 'toilet', 'Exists': True}, {'Code': 'sink', 'Exists': True}, {'Code': 'bathtub', 'Exists': False}, {'Code': 'shower', 'Exists': True}]}, {'features': [{'Code': 'wardrobe', 'Exists': True}, {'Code': 'chest-of-drawers', 'Exists': True}, {'Code': 'desk', 'Exists': True}, {'Code': 'chairs', 'Exists': True}, {'Code': 'sofa', 'Exists': False}, {'Code': 'sofa-bed', 'Exists': False}, {'Code': 'window', 'Exists': True}, {'Code': 'balcony', 'Exists': False}, {'Code': 'tv', 'Exists': False}]}, {'features': [{'Code': 'desk', 'Exists': False}, {'Code': 'chairs', 'Exists': True}, {'Code': 'sofa', 'Exists': True}, {'Code': 'sofa-bed', 'Exists': False}, {'Code': 'coffee-table', 'Exists': False}, {'Code': 'table', 'Exists': True}, {'Code': 'tv', 'Exists': False}]}, {'features': [{'Code': 'chest-of-drawers', 'Exists': True}, {'Code': 'desk', 'Exists': True}, {'Code': 'chairs', 'Exists': True}, {'Code': 'sofa', 'Exists': False}, {'Code': 'sofa-bed', 'Exists': False}, {'Code': 'window', 'Exists': True}, {'Code': 'balcony', 'Exists': False}]}]}]

What I would like to end up with is a new dataframe that has the Code values as the column names and the Exists values as the column value.
So instead of {'Code': 'chairs', 'Exists': True}, I would have chairs True
I tried making it into a json object so I can access the keys and store them into a new dataframe, but I'm getting errors.
df_floors = pd.DataFrame(df['data.offerAggregate.property_aggregate.property.floors'])

jsonObj = df_floors.to_json(orient='records')

print(jsonObj['Code'])
TypeError: string indices must be integers

I'm not sure if this is the right approach but any ideas or help is much appreciated!

A: Check the format of the jsonObj so you can see if its what your expecting.
print(jsonObj)

A: pd.DataFrame(row[0]['units'][0]['features'])

produces:
               Code  Exists
0            chairs    True
1            window    True
2           balcony    True
3            fridge    True
4             stove    True
5              oven    True
6         microwave    True
7   washing-machine    True
8             dryer   False
9        dishwasher   False
10            table    True

or

print(pd.DataFrame([{x['Code']: x['Exists'] for x in row[0]['units'][0]['features']}]))

produces:
   balcony  chairs  dishwasher  dryer  fridge  microwave  oven  stove  table
0     True    True       False  False    True       True  True   True   True


text:
Q: Linux: Send mail after a process id finishes or is killed I want to be notified on my email after another user's process kills or finishes.  I can identify another user's process by its process id or the name of the process appearing in "top" command.
In order to do the same I wrote the following script:
while true; do
  if ps -ef | grep -q 'process_name'; then
    sleep 1
  else
   echo "complete" | mail -s "process exiting" abc@gmail.com
  fi
done

However, I find that even after another user's process finishes or the other user kills his or her process, still I am not getting any notification or email. Can someone please help me with this a bit.

A: The problem is most likely this check:
if ps -ef | grep -q 'process_name'; then

It will always be true. Why? Just run it directly on the command line without the -q to grep and it will be obvious:
$ ps -ef | grep 'process_name'
user    4550  3349  0 09:17 pts/0    00:00:00 grep --colour=auto process_name
$ echo $?
0

The above example shows that the grep will always be successful because it finds itself!
There are many ways to fix that. One way is to use pgrep instead of grep.
if pgrep 'process_name' > /dev/null; then

A: Another common technique to prevent the grep process from matching itself is to surround one of the letters in the pattern with [], like this:
grep -q '[p]rocess_name'

If you know the process of, then you don't need grep at all, you can use the exit code of ps itself:
if ps -p pid &> /dev/null; then
    sleep 1

where pid is of course the process id.


text:
Q: Google App Engine Java Spring Web service error during deployment I am facing following error during deployment of web service using mvn appengine:update command:

Blockquote Unable to find the webapp directory /home/zeesh_arif/src/spring-greeting-webservice/master/gs-rest-hateoas/target/gs-rest-hateaos-0.1.0/gs-rest-hateoas-0.1.0
  usage: AppCfg [options]  [] []

Following is the pom.xml
<groupId>org.springframework</groupId>
<artifactId>gs-rest-hateoas</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-hateoas</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<properties>
    <java.version>1.7</java.version>
</properties>

<build>
  <directory>${project.basedir}/target/gs-rest-hateaos-${project.version}</directory>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>1.9.34</version>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

Following is the project directory structure snapshot:

A: problem fixed, added:
<packaging>war</packaging>

to pom.xml


text:
Q: Huffman code with lookup table I have read an article on Internet and know that the natural way of decoding by traversing from root but I want to do it faster with a lookup table.
After reading, I still cannot get the points.
ex:

input:"abcdaabaaabaaa"
code   data
0      a
10     b
110    c
111    d

The article says that due to variable length, it determine the length by taking a bit of string of
max code length and use it as index.

output:"010110111001000010000"
Index    Index(binary)    Code    Bits required
0        000              a       1
1        001              a       1
2        010              a       1
3        011              a       1
4        100              b       2
5        101              b       2
6        110              c       3
7        111              d       3

My questions are:

*

*What does it means due to variable length, it determine the length by taking a bit of string of
max code length? How to determine the length?

*How to generate the lookup table and how to use it? What is the algorithm behind?

A: For your example, the maximum code length is 3 bits. So you take the first 3 bits from your stream (010) and use that to index the table. This gives code, 'a' and bits = 1. You consume 1 bit from your input stream, output the code, and carry on. On the second go around you will get (101), which indexes as 'b' and 2 bits, etc.
To build the table, make it as large as 1 << max_code_length, and fill in details as if you are decoding the index as a huffman code. If you look at your example all the indices which begin '0' are a, indices beginning '10' are b, and so on.


text:
Q: Configuring Kate text editor to compile a latex file I am trying to use the KDE Kate text editor for latex.  Essentially, what I want is to be able to click "build" and have it run
pdflatex
I read the documentation for the build plugin, but I couldn't figure how to do it.  As a workaround, I can keep a terminal open and manually type pdflatex .tex whenever I want to compile.  I can also use BASH's keybinding to create a shortcut for that, but I would have to change it for each latex file I want to edit.
I'm also aware of Kile, which is based on Kate.  However, that is more like a full IDE, which is not what I want.
If it matters, I am using Ubuntu 18.04.

A: To get the Kate build plugin to compile a LaTeX file, set the "working directory/command" in the Target Settings tab to pdflatex %f.
Source: https://kate-editor.org/2011/08/09/maintainer-needed-kate-external-tools-plugin/#comment-974.


text:
Q: PowerShell -ExpandProperty and correct date format I am attempting to use the -ExpandProperty feature in PowerShell to stop the header appearing in the output and format the date without minutes and seconds. This is just to get the created date for an AD Object:
Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created |
  Select-Object -ExpandProperty @{Name="Created";Expression={$_.Created.ToString("yyyy-MM-dd")}}

This does not produce a result, only if I exclude the "-ExpandProperty" part will it produce the right date format BUT includes the header "Created" which I don't want.
Any ideas please?

A: I don't have access to an AD at the moment, but this could be what you are after
Updated
Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created | Select-Object Created | ForEach-Object {$_.Created.ToString("yyyy-MM-dd")}

A: In PowerShell there nearly always is more than one solution to a problem-
(Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created |
  Select-Object @{N="Created";E{$_.Created.ToString("yyyy-MM-dd")}} ).Created

or
Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created |
  Select-Object @{N="Created";E{$_.Created.ToString("yyyy-MM-dd")}} |
    Select-Object -Expand Created

Parameter names can be shorted as long as they are uniquely identifiable and there are also shortcuts (uppercase letters) so -EA is -ErrorAction
A calculated property does IMO make no sense here as it is the only output, so this should do also:
Get-ADComputer -Server $Server -Identity BlahBlah -Properties Created |
  ForEach-Object {$_.Created.ToString("yyyy-MM-dd")}

A: To complement LotPings' helpful answer, which offers effective solutions:
As for why your code didn't work:
While Select-Object's -Property parameter accepts hashtables that define calculated properties (such as in your code), the -ExpandProperty parameter only accepts a property name, as a string.
Therefore, your hashtable is simply stringified, resulting in string literal System.Collections.Hashtable, causing Select-Object to complain, given that there is no property by that name.
The purpose of -ExpandProperty is to output just a property value rather than a custom object with that property.
You therefore do not need a detour via Select-Object, and can just use the value-outputting script block - { $_.Created.ToString("yyyy-MM-dd") } - directly with ForEach-Object instead, as shown at the bottom of LotPings' answer.

However, there is an obscure feature that you forgo by using ForEach-Object: Select-Object allows combining -ExpandProperty with -Property, in which case the properties specified via -Property are added as NoteProperty members to the value of the property specified via -ExpandProperty:
PS> $val = [pscustomobject] @{ one = 'uno'; two = 2 } |
      Select-Object -ExpandProperty one -Property two; $val; $val.two
uno
2

Note how the output string value, 'uno' has a copy of the input object's .two property attached to it.
To emulate that with ForEach requires more work:
PS> $val = [pscustomobject] @{ one = 'uno'; two = 2 } | ForEach-Object {
      $_.one + '!' | Add-Member -PassThru two $_.two
    }; $val; $val.two
uno!
2


text:
Q: Jquery Ajax - Problemas ao renderizar gráficos utilizando requisição jquery Estou desenvolvendo uma aplicação web que tem como objetivo gerar relatórios mensais de algumas informações vindas do aplicativo mobile. Como tenho pouca experiencia com Jquery estou com dificuldade em carregar as informações no gráfico. Estou utilizando a API https://www.amcharts.com para gerar os gráficos. Minha pagina html o usuário irá escolher o determinado mes que ele queira ver os dados e clicar em carregar. Ao clicar o gráfico contendo as informações de quantidade de palhetas instaladas e quantidade de palhetas positivas por bairro serão carregados no gráfico.
segue imagem do grafico de maneira estatica.

Onde tem os paises serao os bairro que foram instaladas as palhetas.
O meu model esta assim:
@Entity
public class Palheta extends GenericModel{

@Required
@Expose
public String codigo;

public String ovos;
@Required
@Temporal(TemporalType.TIMESTAMP)
public Date data_instalacao;
@Required
@Temporal(TemporalType.TIMESTAMP)
public Date data_coleta;
@Expose
public String observacao;
@ManyToOne
@JoinColumn(name="endereco_id")
@Expose
public Endereco endereco;
@SerializedName("id")
@Expose
@Id
@GeneratedValue
public Integer id;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="agente_id")
@Expose
public Agente agente;
@Expose
@Enumerated(EnumType.STRING)
public Status status;
@Expose
@Enumerated(EnumType.STRING)
public Status situacao;
@Expose
@Enumerated(EnumType.STRING)
public Status status_palheta;
@Expose
@Enumerated(EnumType.STRING)
public Status statusMsg;
public Palheta() {
    status = Status.ATIVO;
    statusMsg = Status.NAO_LIDA;
}
}

Minha pagina html onde sao gerados os graficos esta assim:

<form action="@{Services.relatorios}" method="post">

                Selecione o mês: <select id="mes" class="custom-select mb-3 mr-sm-3 mb-sm-0"
                    name="valor">
                    <option selected>Selecione...</option>
                    <option value="1">Janeiro</option>
                    <option value="2">Fevereiro</option>
                    <option value="3">Março</option>
                    <option value="4">Abril</option>
                    <option value="5">Maio</option>
                    <option value="6">Junho</option>
                    <option value="7">Julho</option>
                    <option value="8">Agosto</option>
                    <option value="9">Setembro</option>
                    <option value="10">Outubro</option>
                    <option value="11">Novembro</option>
                    <option value="12">Dezembro</option>
                </select>

                <button id="btRelUm" type="submit" class="btn btn-primary">Carregar</button>

O script jquery para gerar o grafico:
$(function() {
        $("#btRelUm").click(function(e) {
            e.preventDefault();

            $.ajax({
              method: "POST",
              url: "/relatorios/palhetasPositivas",
              data: {
                  valor: $("#mes").val()
              }
            }).done(function(data) {
            /**
             * PRIMEIRO chart
             */
            var chart = AmCharts
                    .makeChart(
                            "chartdiv2",
                            {
                                "theme" : "light",
                                "type" : "serial",
                                "dataProvider" : [ {
                                    "country" : "USA",
                                    "year2004" : 3.5,
                                    "year2005" : 4.2
                                }, {
                                    "country" : "UK",
                                    "year2004" : 1.7,
                                    "year2005" : 3.1
                                }, {
                                    "country" : "Canada",
                                    "year2004" : 2.8,
                                    "year2005" : 2.9
                                }, {
                                    "country" : "Japan",
                                    "year2004" : 2.6,
                                    "year2005" : 2.3
                                }, {
                                    "country" : "France",
                                    "year2004" : 1.4,
                                    "year2005" : 2.1
                                }, {
                                    "country" : "Brazil",
                                    "year2004" : 2.6,
                                    "year2005" : 4.9
                                }, {
                                    "country" : "Russia",
                                    "year2004" : 6.4,
                                    "year2005" : 7.2
                                }, {
                                    "country" : "India",
                                    "year2004" : 8,
                                    "year2005" : 7.1
                                }, {
                                    "country" : "China",
                                    "year2004" : 9.9,
                                    "year2005" : 10.1
                                } ],
                                "valueAxes" : [ {
                                    "stackType" : "3d",
                                    "unit" : "%",
                                    "position" : "left",
                                    "title" : "Palhetas instaladas - Amarelo / Palhetas positivas - Verde",
                                } ],
                                "startDuration" : 1,
                                "graphs" : [
                                        {
                                            "balloonText" : "Palhetas instaladas [[value]]",
                                            "fillAlphas" : 0.9,
                                            "lineAlpha" : 0.2,
                                            "title" : "2004",
                                            "type" : "column",
                                            "valueField" : "year2004"
                                        },
                                        {
                                            "balloonText" : "Palhetas positivas  [[value]]",
                                            "fillAlphas" : 0.9,
                                            "lineAlpha" : 0.2,
                                            "title" : "2005",
                                            "type" : "column",
                                            "valueField" : "year2005"
                                        } ],
                                "plotAreaFillAlphas" : 0.1,
                                "depth3D" : 60,
                                "angle" : 20,
                                "categoryField" : "country",
                                "categoryAxis" : {
                                    "gridPosition" : "start"
                                },
                                "titles" : [ {
                                    "text" : "Relatório mensal por bairro"
                                } ],
                                "export" : {
                                    "enabled" : true,
                                    "menu" : []
                                }
                            });
            }).fail(function(jqXHR, textStatus) {

                });

            });
        });

O meu controller Services reponsável por criar o serviço que alimentará os graficos.
public static void palhetasInstaladas(Integer valor) {
    long palCount = Palheta.count("status = ? and situacao = ? or situacao =? and month(data_instalacao) = ?", Status.ATIVO,  Status.INSTALADA, Status.COLETADA, valor);

    if (valor == null || valor < 1 ||valor > 12) {
        throw new RuntimeException("ERRO!!!");
    }
    renderJSON(palCount);
}

public static void palhetasPositivas(Integer valor) {
    long positivasCount = Palheta.count("status = ? and status_palheta =? and month(data_instalacao) =?", Status.ATIVO,
            Status.POSITIVA, valor);

    if (valor == null || valor < 1 ||valor > 12) {
        throw new RuntimeException("ERRO!!!");
    }
    renderJSON(positivasCount);
}

ALguem pode me ajudar a implementar esses gráficos?


text:
Q: AWS Kinesis Stream In Detail Review I am new to AWS. I have implemented some functionalities in aws using java. My requirement is to insert a csv of 50MB to RDS PostgreSQL instance at a time.
I tried with aws lmabda service. But after 5 minutes lambda will be stopped so i dropped that way.(Limitation of lambda function)
The second step I followed I wrote a java lambda code of s3 event which will read the csv file falls on s3 to a kinesis stream using putrecord command. According to my understanding, kinesis is capable of read csv file record by record. This kinesis stream will invoke a second lambda function which is saving data to postgreSQL.
Everything was fine. But my confusion is that only 32000 record is inserting. I have 50000 records in my csv. according to kinesis stream it will reading each row as a record so each time it will invoke lambda separately right? so why it is not saving completely?
One more question in my kinesis stream configured like below.

Also in my lambda i configured kinesis as

Is this the correct configuration for my requirement? if I give batchsize as 1 will my function insert the complete record?Please let me know ur knowledge about this. It would be a great help from you thanks in advance!!!!

A: You are exceeding your limits for a single shard.
Review the following document:
Amazon Kinesis Data Streams Limits
Make sure that your code is checking for errors on each AWS call.


text:
Q: MongoDB Server Shows OpenSSL's Different Version than Installed On Ubuntu Machine, Installed OpenSSL Version is :

Used Command : openssl version

OpenSSL 1.1.0e  16 Feb 2017

But, MongoDB Version Shows OpenSSL Version as :

Used Command : mongod --version

db version v3.4.2
git version: 3f76e40c105fc223b3e5aac3e20dcd026b83b38b
OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014

Why Both Versions are different ?
Output of ldd /usr/bin/mongod is as follows :
linux-vdso.so.1 =>  (0x00007ffd13ff5000)
libssl.so.1.0.0 => /lib/x86_64-linux-gnu/libssl.so.1.0.0 (0x00007f9c660e8000)
libcrypto.so.1.0.0 => /lib/x86_64-linux-gnu/libcrypto.so.1.0.0 (0x00007f9c65d0c000)
librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f9c65b04000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9c65900000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9c655fa000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9c653e4000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9c651c6000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9c64e01000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9c6909c000)


text:
Q: how to use subtotal in SQL
I have a table with following data
 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2

I want a query which give the following output.
(Subtotal according to FLAG)
 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL

A:   SELECT Code,
         isNULL(NAME,'SUBTOTAL') AS NAME,
         SUM(Total) AS Total,
         SUM(Vat) AS Vat,
         SUM(TotalAmt) AS
         TotalAmt,
         Flag
   FROM TABLE GROUP BY ROLLUP(Flag,Code,Name);

A: Use ROLLUP:
SELECT
    MAX(CODE) AS CODE,
    NAME,
    MAX(AMOUNT) AS AMOUNT,
    MAX(VAT) AS VAT,
    MAX(TOTALAMT) AS TOTALAMT,
    FLAG
FROM yourTable
GROUP BY
    FLAG, NAME
WITH ROLLUP;

Demo

A: Try this
;with cte
as
(
 select
  CODE,
  NAME,
  AMOUNT,
  VAT,
  TOTALAMT,
  FLAG
  from t1

  union aLL

  select
  CODE=NULL,
  NAME='SUBTOTAL',
  AMOUNT = SUM(AMOUNT),
  VAT = SUM(VAT),
  TOTALAMT = SUM(TOTALAMT),
  FLAG
  from T1
  GROUP BY FLAG
)
SELECT
*
FROM CTE
ORDER BY FLAG,CODE DESC


text:
Q: I am making a class to draw a rectangle in random locations using a class to do it, I get the error cannot find symbol public void draw(Canvas canvas, int canvasHeight)
{
  drawRectangle(10,10,10,10);
}

I know I can not add
public void drawRectangle

and now I am completely stuck, any thoughts?

A: error cannot find symbol means there is no method named drawRectangle, so you should create one.
You may add:
public void drawRectangle(int x1, int y1, int x2, int y2) {
  //your implementation of drawing rectangle here
}


text:
Q: Windows 8.1 idle/auto maintenance runs on battery Just recently upgraded to Windows 8.1 from Windows 8. I noticed that, when on battery, idle and auto maintenance tasks run regardless of the power situation. Curiously, I looked in task scheduler, and they both have "Start the task only if the PC is on AC power" OFF. I tried setting them back on, but they keep resetting. It really eats away at my battery, too, as I'm on a laptop.
Any ideas?

A: Check the Windows Device Manager for any unknown devices and also look for ACPI related drivers on your laptop manufacturers web site. It might be some missing or failing driver that stops Windows from finding out that it is running on battery Power.


text:
Q: RuntimeError: size mismatch, m1: [28 x 28], m2: [784 x 128] After training my model, I tried to plot graph of the softmax output, but it resulted in the runtime error mentioned in the title.
Here is the following code snippet:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import helper

# Test out your network!

dataiter = iter(testloader)
images, labels = dataiter.next()
img = images[1]

# TODO: Calculate the class probabilities (softmax) for img
ps = torch.exp(model(img))

# Plot the image and probabilities
helper.view_classify(img, ps, version='Fashion')

A: The problem is with this part (I guess).
img = images[1]

# TODO: Calculate the class probabilities (softmax) for img
ps = torch.exp(model(img))

Problem: image you are loading is of dimension 28x28, however, the first index in input to the model is generally batch size. Since there is 1 image only, so you have to make the first dimension to be of size 1. To do that do img = img.view( (-1,) + img.shape) or img=img.unsqueeze(dim=0). Also, it seems that the first layer weight is 784 x 128. i.e the image should be converted to vector and fed to model. For that we do img=img.view(1, -1).
So, in total, you need to do
img = images[1]
img = img.unsqueeze(dim=0)
img=img.view(1, -1)

# TODO: Calculate the class probabilities (softmax) for img
ps = torch.exp(model(img))

or you can just use one command instead of two (unsqueeze is unnecessary)
img = images[1]
img=img.view(1, -1)


text:
Q: Send email django from any host I have read plenty of links for sending emails through django. I've tried all of them but they don't work. I tried sending an email through the python shell and I get '1'.
- So what are the settings that I should use for the email to work, I'm willing to use any mail server?
- I was using gmail but I read that it causes problems, if I'm going to use hotmail for example do I need to specify the email password in the settings.xml?
- how to debug this problem?

A: You can try yagmail, it should make it a lot easier:
import yagmail
yag = yagmail.Connect('user@gmail.com', 'password')
yagmail.send(email_to, subject = 'site down!', contents = 'with some error')

It has a lot more features, for example how to make it easier to send attachments etc.
yagmail can be found at github.
You will probably have to install it first using pip:
pip install yagmail  # python 2
pip3 install yagmail # python 3

A: This is pure python code for sending emails using SMTP Lib
from threading import Thread
import requests
import time
import smtplib
def email_sender(input_message, email_to, client):
    ''' function to send email '''
    to = email_to
    gmail_user = 'email of sender account'
    gmail_pwd = 'password of sender account'
    smtpserver = smtplib.SMTP("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(gmail_user, gmail_pwd)
    header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:site down! \n'
    input_message = input_message + client
    msg = header + input_message
    smtpserver.sendmail(gmail_user, to, msg)
    smtpserver.close()


text:
Q: Passing a previous date in link I want to create a link name as Previous date and Next date in my show action. Please suggest me that how should I pass the date in that . i.e. If one clicks on the previous link then the records are displayed of the previous day and vice versa.
How to pass the date in show action? Please guide.
P.S. :- I am using rails 3

A: To display date and pass as link parameter you can use either ruby code or jQuery .
Ruby : To get the date :
How to calculate next, previous business day in Rails?
Put such function in your application helper . And call into you view and also pass as link parameter .
jQuery :
Error creating a '< previous' and 'next >' (date) link for jQueryUI datepicker using setdate


text:
Q: Why is pyspark implemented such that exiting a session is stopping the underlying spark context? I just massively shot my foot by writing "pythonic" spark code like this:
# spark = ... getOrCreate() # essentially provided by the environment (Databricks)
with spark.newSession() as session:
     session.catalog.setCurrentDatabase("foo_test")
     do_something_within_database_scope(session)

assert spark.currentDatabase() == "default"

And oh was I surprised that when executing this notebook cell, somehow the cluster terminated.
I read through this answer which tells me, that there can only be one spark context. That is fine. But why is exiting a session terminating the underlying context? Is there some requirement for this or is this just a design flaw in pyspark?
I also understand that the session's __exit__ call invokes context.stop() - I want to know why it is implemented like that!
I always think of a session as some user initiated thing, like with databases or http clients which I can create and discard on my own will. If the session provides __enter__ and __exit__ then I try to use it from within a with context to make sure I clean up after I am done.
Is my understanding wrong, or alternatively why does pyspark deviate from that concept?
Edit: I tested this together with databricks-connect which comes with its own pyspark python module, but as pri pointed out below it seems to be implemented the same way in standard pyspark.

A: I looked at the code, and it calls below method:
@since(2.0)
def __exit__(
    self,
    exc_type: Optional[Type[BaseException]],
    exc_val: Optional[BaseException],
    exc_tb: Optional[TracebackType],
) -> None:
    """
    Enable 'with SparkSession.builder.(...).getOrCreate() as session: app' syntax.

    Specifically stop the SparkSession on exit of the with block.
    """
    self.stop()

And the stop method is:
@since(2.0)
def stop(self) -> None:
    """Stop the underlying :class:`SparkContext`."""
    from pyspark.sql.context import SQLContext

    self._sc.stop()
    # We should clean the default session up. See SPARK-23228.
    self._jvm.SparkSession.clearDefaultSession()
    self._jvm.SparkSession.clearActiveSession()
    SparkSession._instantiatedSession = None
    SparkSession._activeSession = None
    SQLContext._instantiatedContext = None

So I don't think you can stop just the SparkSession. Whenever a Spark Session gets stopped (irrespective of the way, in this case, when it comes out of 'with' block, __exit__ is being called), it would kill the underlying SparkContext along with it.
Link to the relevant Apache Spark code below:
https://github.com/apache/spark/blob/master/python/pyspark/sql/session.py#L1029


text:
Q: Shell manipulation to get a file from android I have an Android device from which I need to obtain a log file from. The log file changes every time it's created, so I cannot simply hardcode the name of the file into my script.
What I am thinking, is doing a
adb shell "rm /data/trace/*"

to delete everything but that file in the folder before I generate the log file. Then maybe I could do
adb pull "/data/trace/`adb shell ls /data/trace/`"

What I would think this does is execute the ls command it it'll list the only file there. And the rest of this would cause it to pull "/data/trace/file".
However, this doesn't work.
I get the error:
' does not existdata/trace/log.8290

Does anybody have any tips on how I could do this?
Thanks.

A: So it turns out that there's an added carriage return '\r' at the end which messes up the syntax.
This is what I did to solve the problem.
test_file=`adb shell ls /data/trace/`;
test_file2=`echo $test_file | tr -d '\r'`;
echo "grabbing $test_file2";
adb pull "/data/trace/$test_file2";

This strips the carriage return off the file name and makes it possible so I can use it in my adb pull code.
Cheers.


text:
Q: After Expire certificate, is it necessary to create a new Pushnotification based provisioning profile at apple I am using push notification based application with apply all the required information related to a push notification based application.
Now i want to know that after revoke or expiration of the certificate of user, is it necessary to create a new provisioning profile with new push notification enabled profile.
What are the limitations of the push notification based profiles in iOS.

A: No, you don't have to.
Unless you will update your app, you can continue to do push notifications without renewing any provisioning profiles. All you have to do is renew p12 file that is used at backend side. You can find many tutorials on the web about how to create p12 file for push licenses.

A: Yes it is, your profile needs to exist AND it needs to be valid for push notifications to be delivered.