text:
Q: Iterating through a custom double linked list I am implementing a double linked list. I have implemented functions for adding to the head and tail of the list. I have been trying to make a function that would print all the elements of a given object.
Though the function prints the first value it does not print any other item in the list.

d_list.h

 #include<iostream>
 #include "node.h"

 #ifndef NODE_H
 #define NODE_H

template<class T>
class d_list{
   private:
       int l_size;
       Node<T>* head;
       Node<T>* tail;

   public:
       d_list():l_size(0){
          head=nullptr;
          tail=nullptr;
       }
       Node<T>* gethead(){return this->head;}
       Node<T>* gettail(){return this->tail;}

         int getlength(){
           return this->l_size;
         }

       void addashead(T data){
          Node<T>* curr_node=new Node<T>(data);
          if(this->head==nullptr){
            this->head=curr_node;
            this->tail=curr_node;
            this->l_size=l_size+1;
          }else {
             curr_node->next=this->head->previous;
              this->head->previous=curr_node;
             this->head=curr_node;

              this->l_size=l_size+1;
          }
       }

       void addastail(T data ){
          Node<T>* curr_node=new Node<T>(data);
          if(this->tail==this->head){
            this->head->next=curr_node->previous;
            curr_node->previous=this->head;
            this->tail=curr_node;
            this->tail->next=nullptr;
            this->l_size=l_size+1;
          }
          else{
            this->tail->next=curr_node;
            curr_node->previous=this->tail;
            this->tail=curr_node;
            this->l_size=l_size+1;
          }
       }

       Node<T>* begin(){
         return this->head;
       }

       Node<T>* end(){
         return this->tail;
       }

       bool isempty(){
         return this->head==nullptr;
       }

       T& back(){
         return this->tail->m_data;
       }

       T& front(){
         return this->head->m_data;
       }

       void printlist(){
           Node<T>* temp= this->head;
        while(temp) {
        std::cout << temp->m_data<< " -> ";
        temp = temp->next;
    }

       }

};

#endif

node.h

template <class T>
class Node{
    private:

    public:
       T m_data;
       Node<T>* next;
       Node<T>* previous;
        Node()=default;
        Node(T data){
           m_data=data;
           previous=nullptr;
           next=nullptr;
        }
       ~Node();

};

main.cpp

#include "d_list.h"

#include<iostream>
using namespace std;

int main(){

    d_list<int> d1;

    d1.addashead(50);

    d1.addastail(20);

    d1.addastail(60);

    d1.addastail(80);

    d1.printlist();
    return 0;
}

A: there are some mistakes in your addastail() and addashead() method.
I removed these mistakes,Check this:
 void addashead(T data){
          Node<T>* curr_node=new Node<T>(data);
          if(this->head==nullptr){
            this->head=curr_node;
            this->tail=curr_node;
            this->l_size=l_size+1;
          }else {
             curr_node->next=this->head;
              this->head->previous=curr_node;
             this->head=curr_node;
             this->l_size=l_size+1;
           }

   }

In the first line of else part,
you wrote:
curr_node->next=this->head->previous;

But it should be: curr_node->next=this->head;
As curr_node's next should point on head,not head's previous.
void addastail(T data ){
          Node<T>* curr_node=new Node<T>(data);
          if(this->tail==this->head){
            this->head->next=curr_node;
            curr_node->previous=this->head;
            this->tail=curr_node;
            this->tail->next=nullptr;
            this->l_size=l_size+1;
          }
          else{
            this->tail->next=curr_node;
            curr_node->previous=this->tail;
            this->tail=curr_node;
            this->l_size=l_size+1;
          }
       }

In the first line of if part,you wrote:
this->head->next=curr_node->previous;

But it should be:this->head->next=curr_node;


text:
Q: Basic Selenium Cant find element by Class I am trying to fill a phone number in a web portal, using BasicSelenium, Selenium for VBA , but Selenium cant find the Text box even when the element has loaded
My Code
Sub FillPhoneNumbers()

Set ch = New Selenium.ChromeDriver

ch.Start
ch.Get "https://nestlemedconnect.com/p/38ZX1SBcKhI"

ch.FindElementByClass("checkbox_label").Click
ch.FindElementByClass("accept_button").Click
ch.FindElementByCss(".left_button_inner.generic_menu_button.ti-comments-smiley").Click
ch.Wait (30)
ch.FindElementByClass("phonemask").SendKeys "122525" ' <- line that errors
End Sub

And the element i am Trying to fill
<input class="phonemask" type="tel" name="phoneNumber" autocomplete="off" data-intl-tel-input-id="0" style="padding-left: 74px;" placeholder="201-555-0123">

i've tried using the name but that did not work either, all i get is a Web driver Cant find elemet error
What am i doing wrong?

A: Cause you need to click on this web element first Opt-out from SMS
div.ui.bottom.attached.button.optout.triggerform

do this :
ch.FindElementByCss("div.ui.bottom.attached.button.optout.triggerform").Click
ch.Wait (30)
ch.FindElementByClass("phonemask").SendKeys "122525

A: See if this works:-
ch.FindElementByXPath(".//div[@title='Manage your subscription']/div[contains(@class,'smiley')]").Click

Phone number text field is inside an iframe, so switch to the iframe first before accessing the element as
ch.SwitchToFrame.FindElementByXPath(".//iframe[contains(@src,'unsubscribe')]")
ch.FindElementByXPath(".//input[@name='phoneNumber']").SendKeys "1234567890"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Renaming a project in IntelliJ IDEA I have some projects where the directory containing the project is called "Code".
When I open IDEA, in my recent projects list all I see is that name.
Is there any method to change this in settings ?
I tried going to File->Project Structure->Project, I couldn't find the Project Name option in IntelliJ IDEA 13.

I see this in my project settings.

A: Am using intellij 2017.2.6

*

*Go to project view

*Right Click on the top root element

*Choose Refactor-> Rename

*Small dialog appear -> enter the desired name

*Click ok

A: Actually this is a maven project and its name is defined from the maven pom.xml
So if you want to change the name you need to change its name in pom.xml
from
 <artifactId>Code</artifactId>

to
 <artifactId>My-prject-name</artifactId>

A: Meanwhile I talk about IntelliJ 2016.2.
There are various names involved.

*

*Red the folder name. I.e., the folder where the project is located.
This name appears the the project structure and in the path on the top window.

*Blue the name of the iml file. You can rename the iml file, when the iml file is different from the folder name, you have them both in the project view.

*Yellow the project name can be set as described by @vikingsteve (Project Structure (ctrl-alt-shift-s) -> Project Settings / Project -> Project name) in the response above. You will find the project name written in the file ".name" in the .idea folder. It is also the name which appears in the open recent file list.

*brown if your project is a maven project, you will additionally have the artifact id in the pom.

Usually all these names are the same which makes life easier.
Sometimes they are not. There are many reasons why they should be different. E.g., this helps me to differentiate project versions (I also use the image background feature of IntelliJ 2016.2) when I have simultaneously the same project on two branches.
While you change these names, IntellJ may generate a new *.iml with the artifactId name (brown). In this case just delete the *.iml file you don't want to keep.

A: This worked for me:

*

*Renamed module folder

*Updated module name in settings.gradle

*Updated all build.gradle references

*rm -rf .idea/modules/[module]

*Rebuild project

A: Following are the steps to be followed in IntelliJ Idea Community Edition:

*

*Go to File >> Project Structure >> Project > Project Name
Update project name with its new name.

*Go to pom.xml
Update project name with its new name in the

*Select "Project" view and click root folder of the project then refactor its name.

*Exit IntelliJ Idea and Rename root folder name in the windows directory structure where this project repository is stored.

*Restart IntelliJ Idea and import the project using "Import project from existing resource" option.

A:
I completed the renaming as below.
The attached image is structured in project folder.

Must make changes in the xml into a new project name.

*

*close IDEA intellij (14.0.2)

*change intellij project name (folder)
e.g) old_project_name -> new_project_name

*change .idea in folder
We have only changed the
1) artifacts in folder -> xml
2) runConfigurations in folder -> xml
3) modules.xml
4) workspace.xml
5) [your_project_name].iml
(Depending on your project structure, your folder may not contain xml)

*restart IDEA intellij

*File -> Import Module...[your intellij project]
I hope this helps you :)

A: *

*Rename project in project tree view

*Rename project folder in project files tree view

*Rename artifactId and id in pom.xml (if maven is used)

A: Once you have changed the project name by following the other suggestions mentioned in this thread, you can also change the module name within the project settings -> Modules:

This will change the name that is included within the brackets just next to the name of the project:

After this, proceed to refactor and rename the class that contains the main method to match your new project name. (This class is normally auto-generated by intelliJ after creating a new project).
That should do it.
Cheers!

A: Tips for renaming a Gradle project

*

*Exit IntelliJ IDEA

*Edit contents of the following files

{project_root}/settings.gradle
{project_root}/.idea/.name

*Open IntelliJ IDEA

*Refresh Gradle Project

A: You can change the project name, which is the name that is shown in the recent projects list, like so:
Go to Project Structure (Ctrl+Alt+Shift+S) → Project Settings / Project → Project name:

Please note that this is not to be confused with name of the root module, or folder on the file system, which may or may not be similar.
Edit
Please try going into your .idea folder in the project, create a file named .name and enter a project name on a single line.
e.g.
my-new-project-name

Then restart IntelliJ.
This presumes you are using a folder-based Idea project in .idea (rather than file based, with .iws file etc)

A: If your project is file based, you cannot rename the project from within IDEA.
Convert your project to a directory based format, and then you will have the option to rename it under "File > Project Structure > Project > Project Name".

A: For Gradle Springboot intellij project:
 1. settings.gradle :
   rootProject.name = 'new-name-project'
   add/edit the above line at the bottom of the page
 2. application.properties
   spring.application.name=new-name-project
   add/edit the above line at the top of the page
 3. Go to file > project stricture > Project> Project-name: new-name-project
 4. Apply and restart Intellij

A: I recently figured out a way to do this.
I wrote a bash script that you run from the root folder of your project (only tested on Mac) to rename all of the files in the .idea folder that contain your project name, and do a find-replace inside those files.
BE CAREFUL: Make sure your project name is unique - i.e., a project name like 'towers-of-hanoi' is unique and the script will have no problems, but a project called 'a' will, as all instances of 'a' in the files will be replaced with the new project name.

A: UPDATE IntelliJ 2021.2.3 (complete, including maven)
Covers the project, maven configuration (including multi-module), and file system folder. Eliminates project name in brackets in project view.

*

*Backup your project!

*Go to File | Settings | Build, Execution, Deployment and delete all trusted locations. Related to some project security settings. In my case, Maven was broken until I did this and reset my Build Tools | Maven settings.

*Go to File | Project Structure and enter new name

*In IntelliJ project view: for each module, right-click top level module folder and select Replace in files… Enter current project name in find box and new project name in replace box. Either selectively replace by file or click Replace all

*Repeat step 3 for the .idea folder

*Exit IntelliJ to file system

*Rename project directory to new name

*Back in IntelliJ, the project window will open because it can't find the project

*Delete the old project entry (no files are deleted, this is just the recently used project list)

*Click Open, navigate to the new directory and click Ok
Notes My run configurations are stored in files and were updated. If not, per Jetbrains doc, they are stored in workspace.xml and should be updated but I did not test this. After my project opened, I rechecked for the old name and there was still one instance in a .idea xml file but this may have been an anamoly. I changed it and restarted IntelliJ just for good measure.

A: I had an issue renaming the project's name following the above instructions. I've tried all of the suggestions, which were very helpful and very well explained. But for some reason (maybe there is something wrong with my computer or IntelliJ installation) my project was still not renamed. I could see the new name actually between [] next to the project's old name in the left pane (i.e: oldName [newName]). I could also see the path being changed in the project's settings. However, the folder name had not changed, and when I tried to open the project in intelliJ, it was still under the old name.
If your case is like mine I found a work-around for it:

*

*Close IntelliJ IDEA.

*Rename your folder.

*Open IntelliJ IDEA. (You'll see your old project with the old name with a ~ next to it, meaning it's broken or not found).

*Click on Open project.

*Search for your project under the directory with the new name.

*Choose it and click open.

I hope that helps.


text:
Q: Unity: Animation won't play on trigger Im having trouble to let Unity play my animations.
I gave my character an Animator. In this Animator I have this Animations:

The trigger between these Animations are working fine and are running correctly on play. The idle animation it self is played, while i can't get it to play the walk or the jump Animation in the game (both work fine in the inspector).
When on play the triggers are triggered, it even shows the blue bar under the walking or the jumping box, but the animation itself just wont be played in the game.
Here is the code I use to call the triggers:
void Update()
    {
        if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow)|| Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.D))
        {
            anim.SetBool("isWalk", true);

        }
        else
        {
            anim.SetBool("isWalk", false);
        }

        if (Input.GetKey(KeyCode.Space))
        {
            anim.SetBool("isJump",true);
        }
        else
        {
            anim.SetBool("isJump", false);
        }

    }

And the Transition Conditions (but these are working fine for me):
idle->jump: isJump =true,
jump->idle: isJump =fals,
idle->walk: isWalk =true,
walk->idle: isWalk =false,

screenshot of idle-> walk:

screenshot of walk->idle:

I hope someone can help me with this and please excuse my possibly bad english...

A: I had the same issue.
Solved it by unchecking 'Can Transition To Self' inside the transition pointing to the state that didn't play.


text:
Q: How to apply Leibniz rule for this integral? I am struck with the problem of how to evaluate the following integration:
$$\frac{d}{dt}\int_0^{a(t)}{(a (t)-s)^{\alpha-1}f (s) ds}$$
where $f(s)$ is differentiable
and $\alpha\in (0,1)$. The problem is the integrand might not converge when substituting the upper limit

A: $$\int\limits_{0}^{a(t)}{(a(t)-s)^{\alpha-1}}f(s)ds = \left|-\frac{(a(t)-s)^\alpha}{\alpha}f(s) \right|_{0}^{a(t)}+\frac{1}{\alpha}\int\limits_{0}^{a(t)}{(a(t)-s)^\alpha}{f^{\prime}(s)}ds$$


text:
Q: How to confirm via PowerShell that TLS 1.2 is available on the OS? In Windows Server 2016 it is possible via Group Policy to disable use of TLS 1.2.
We would like to add a check to our installer script in PowerShell to see if TLS 1.2 is available.  Note that this is different than checking if a URL uses TLS 1.2, or if TLS 1.2 is enabled in the current PowerShell session.  We would like to check if TLS 1.2 is available from the OS or if it has been disabled through administrator Group Policy configuration.
Does anyone know how to do this?  Any help would be greatly appreciated.  Has not been great info online on the subject.

A: Use the following:
$available = try {
  $orig = [Net.ServicePointManager]::SecurityProtocol
  [Net.ServicePointManager]::SecurityProtocol = 'Tls12'
  [bool] [System.Net.WebRequest]::Create('https://example.org/')
} catch {
  $false
} finally {
  [Net.ServicePointManager]::SecurityProtocol = $orig
}

A: If the need is to check if the system has working TLS 1.2 enabled by default:
$tls12 = try {
  $resp = (New-Object System.Net.WebClient).DownloadString("https://tls-v1-2.badssl.com:1012/")
  [bool] $resp.Contains("green")
} catch {
  $false
}


text:
Q: Why does WPF have its own Color class instead of just using Drawing.Color? Why does WPF have its own Color class instead of just using Drawing.Color?

A: I don't know for certain, but I suspect it is for two reasons:
First, Drawing.Color does not support automatic conversion to and from floating point for ARGB values or color arithmetic, and both were necessary for WPF. They could have modified Drawing.Color to include it, but:
Second, Drawing.Color pollutes its namespace with static instances of itself for the various common colors. WPF wisely moves this to a separate static class called Colors to hold these instances.
I think it's likely as simple as that. Besides, Win.Forms and GDI+ will (hopefully) one day be deprecated and pruned. When that happens, there will be trouble if there's a dependency on the old .DLL. Better to just copy-pasta and enhance.


text:
Q: jenkins integration with artifactory 5.5.2 Currently I am using JFrog OSS version 5.5.2 for my artifacts which is integrated with Jenkins version 2.19.4. The artifactory plugin version is 2.13.1. I created a free-style software project. The repository type is "generic-local". I am able to run build successfully and builds are saved in repository but the artifacts are not saved.Also, there is no option called "deploy artifacts to artifactory" in Jenkins configuration.
Do I have change my settings or update Jenkins?
Please advice me what changes has to be done.

A:
Do I need to upgrade jenkins?

No: the Artifactory plugin requires a Jenkins Core 1.521.
But you would need to define a Maven 2/3 build instead.

Maven 3 Support for Jenkins Free-style Jobs
The Jenkins Artifactory plugin supports running Maven 3 builds from free-style jobs by using a Maven 3 build step + a build environment section for the Artifactory Maven 3 integration (artifact and build information deployment).
For Maven 3 builds users are encouraged to configure the Artifactory integration using Jenkins' native Maven 2/3 build projects.


text:
Q: How to add a value at some list[x][y] in C++? I am trying to add some value at cost[x][y] and the list must be a pointer type.
I declared the list like this:
list<int>* cost = new list<int>[V]; // V being user input

And here I'm trying to add the value "c" at the place of cost[x][y]. How am I supposed to add that .When I try to use iterator as below it says

*

*"Debug Assertion Failed"

*"Unable to increment end point iterator"
The Code:
    void addCost(int x, int y, int c) // adds cost in cost[x][y] and cost[y][x] indicies
    {
        auto it = cost[x].begin();
        advance(it, y);
        *it = c;
    }

A: The problem is that the lists will be initially empty. So, having 0 elements.
So, you can write cost[x] and can get an iterator. That is OK. But, as said, the list is empty. So, if you try to advance the iterator, it will fail.
Because, it will be equal to end() in the beginning. And this cannot be advanced.
Else, it would work . . .
Some demo example:
#include <iostream>
#include <list>

constexpr size_t SIZE = 10;

int main() {
    size_t numberOfElementsX{ SIZE };
    size_t numberOfElementsY{ SIZE };

    std::list<int>* cost = new std::list<int>[numberOfElementsX];

    for (size_t i = 0; i < numberOfElementsX; ++i)
        cost[i].resize(numberOfElementsY);

    auto it = cost[3].begin();
    std::advance(it, 5);

    *it = 42;

    for (auto i : cost[3])
        std::cout << i << ' ';
}


text:
Q: Reuse Component JSF2.1 with Facelets im using:

*

*JSF 2.1

*RichFaces 4.5.2.Final

*Omnifaces 2.0

I have a Table that i want to reuse as datable or subtable depends of the page that i use the component, i want to put and if but it doesnt work, here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:o="http://omnifaces.org/ui"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:composite="http://java.sun.com/jsf/composite"
      xmlns:tablas="http://java.sun.com/jsf/composite/tablas"
      >

    <!-- INTERFACE -->
    <composite:interface>
        <composite:attribute name="listaPaqueteItems" required="true" />
        <composite:attribute name="subtable" required="false" default="false" />
    </composite:interface>

    <!-- IMPLEMENTATION -->
    <composite:implementation>

        <c:if test="#{!cc.attrs.subtable}">
            <rich:dataTable id="tabla_items_del_paquete"
                value="#{cc.attrs.listaPaqueteItems}"
                var="p"
                rowKeyVar="row_tabla_items_del_paquete"
                rows="10"
                rowClasses="odd-row, even-row"
                styleClass="stable">
        </c:if>
        <c:if test="#{cc.attrs.subtable}">
            <rich:collapsibleSubTable id="subtable">
        </c:if>
                <rich:column>
                    <f:facet name="header">
                        <h:outputText value="#" />
                    </f:facet>
                    <h:outputText value="#{row_tabla_items_del_paquete + 1}" />
                </rich:column>
                <rich:column>
                    <f:facet name="header">
                        <h:outputText value="#{msgs['abm.paquete.item.tabla.codigo']}" />
                    </f:facet>
                    <h:outputText value="#{p.producto.codigo}" />
                </rich:column>
                <rich:column colspan="2">
                    <f:facet name="header">
                        <h:outputText value="#{msgs['abm.paquete.item.tabla.nombre']}" />
                    </f:facet>
                    <b>
                        <h:outputText value="#{p.producto.nombre}" />
                    </b>
                </rich:column>
                <rich:column>
                    <f:facet name="header">
                        <h:outputText value="#{msgs['abm.paquete.item.tabla.descuento.final']}" />
                    </f:facet>
                    <h:outputText value="#{p.descuentoFinal}" />
                </rich:column>

        <c:if test="#{!cc.attrs.subtable}">
            </rich:dataTable>
        </c:if>
        <c:if test="#{cc.attrs.subtable}">
            </rich:collapsibleSubTable>
        </c:if>
    </composite:implementation>

</html>

Basically the problem is that isnt valid XHTML, any idea to accomplish this scenario and try to reuse this code as table or subtable, one possible idea is externally the <rich:colum> tags in another template and wrapper that in datable or subtable something like this:
            <rich:collapsibleSubTable
            expanded="#{false}"
            id="tabla_periodos"
            rowKeyVar="row_subtable"
            expandMode="client"
            value="#{p.periodoDescuentos}"
            var="per"
            rendered="#{not empty p.periodoDescuentos}"
            >
<!-- Include Columns-->
                </rich:collapsibleSubTable>

I think that will work but maybe is another way to do the same better.

A: You can create facelet tag with following code:
TAG (myTable.xhtml):
     <c:if test="#{!subtable}">
        <rich:dataTable id="tabla_items_del_paquete"
            value="#{listaPaqueteItems}"
            var="p"
            rowKeyVar="row_tabla_items_del_paquete"
            rows="10"
            rowClasses="odd-row, even-row"
            styleClass="stable">
           <ui:insert>
         </rich:dataTable>
    </c:if>
    <c:if test="#{subtable}">
        <rich:collapsibleSubTable id="subtable">
           <ui:insert>
        </rich:collapsibleSubTable>
    </c:if>

USAGE:
    <my:mytable>
       ... your dataTable content
    </my:mytable>


text:
Q: Como enviar e-mail automaticamente? Como enviar e-mails automaticamente usando o PHP?
Tenho um formulário que recebe várias datas e quando faltasse 10 dias para terminar o prazo, envia-se uma mensagem à várias pessoas com o aviso.
Já me disseram para usar o Cron job. Mas isso serve só para fazer a rotina executar.
Preciso é de ajuda no código porque estive a experimentar por o código no gestor de tarefas do Windows e nada.
<?php
include(conectar.php);
$conn = @mysql_connect($local_serve, $usuario_serve, $senha_serve, $banco_de_dados)
    or die ("O servidor não responde!");

// conecta-se ao banco de dados
$db = @mysql_select_db($banco_de_dados,$conn)
    or die ("Não foi possivel ligar-se a Base de Dados!");

$validade = ("SELECT Nome, AlvaraValidade, AcidenteValidade, SeguroValidade, FinancasValidade, SocialValidade, RemuneracaoValidade, InstaladorValidade, MontadorValidade, MedicaValidade, ProjectistaValidade, GasValidade, RedesValidade, SoldadorValidade, MecanicoValidade, ClasSoldadorValidade, MaquinaValidade1, MaquinaValidade2, MaquinaValidade3, MaquinaTopoValidade FROM tb_eqipamentos, tb_detalhe_trabalhador, tb_trabalhador");
$now = new DateTime();
$diff = $now ($validade);

if ($diff <= 10){
    $mail_to = "MAIL@MAIL.pt";
    while ($row = mysql_fetch_array($query)){
    echo $row['name']." - ".$row['email']."\n";
    $mail_to = $row['email'].", ";
}
if (!empty($mail_to)){
    sendEmail($mail_to);
}

?>

A: Use esta minha função, basta chamá-la com as 3 variáveis com valores seus.
function EnviarMail($destinatario, $assunto, $mensagem)
{
    $de = "no-reply@mail.com";
    $headers = "From: O_TEU_NOME <".$de.">\n";
    $headers .= "Content-Type: Text/HTML; charset=UTF-8\n";

    // formatação da mensagem em HTML
    $mensagem = '
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    ' . $mensagem . '

    ';

    $ok = mail($destinatario,$assunto,$mensagem,$headers);

    return $ok;
}

A: Use datediff do mysql para efetuar o calcula entre as data.
$validade = ("SELECT Nome, AlvaraValidade, AcidenteValidade,
SeguroValidade, FinancasValidade, SocialValidade, RemuneracaoValidade,
....//sql longo);

$validadeé somente uma string e não uma consulta, é necessario usar mysql_query() para excuta-la. Caso o resultado for mais de uma linha utlilze um while em conjunto com mysql_fetch_assoc()
seu código deve ficar dessa forma:
$sql = "SELECT <campos> FROM tb_eqipamentos, tb_detalhe_trabalhador, tb_trabalhador
WHERE datediff(now(), data) = 10 "

$validade = mysql_query($sql);

while($item = mysql_fetch_assoc($validade)){
    //enviar emails
    sendMail($item['email'];
}

Recomendo dar uma olhada em inner join, para melhorar a legibilidade e a performace de sua consulta.

A: Parece mesmo que o seu problema está na configuração do servidor de e-mail.
Quando preciso enviar e-mail à partir do windows, eu uso o sendmail para windows ou configuro uma conexão smtp.
Para o sendmail, que é mais rápido, basta acessar o site abaixo e fazer o download do zip.
http://glob.com.au/sendmail/
Para funcionar no PHP, eu o descompacto na pasta C:\usr\lib\sendmail.
Localize a seguinte linha no seu php.ini local:
;sendmail=
Descomente-a para que ela fique da maneira abaixo:
sendmail_path = "C:/usr/lib/sendmail/sendmail.exe -t -i"
Para mim sempre funciona.

A: Consegui fazer com que o Php envia-se email.
Acabei por utilizar o PhpMailer. Deixo o codigo para quem necessitar. Obrigado a todos
$PHPMailer = new PHPMailer();

// define que será usado SMTP
$PHPMailer->IsSMTP();

// envia email HTML
$PHPMailer->isHTML( true );

// codificação UTF-8, a codificação mais usada recentemente
$PHPMailer->Charset = 'UTF-8';

// Configurações do SMTP
$PHPMailer->SMTPAuth = True;
$PHPMailer->SMTPSecure = '....';
$PHPMailer->Host = '....';
$PHPMailer->Port = '25';
$PHPMailer->Username = '....';
$PHPMailer->Password = '....';

// E-Mail do remetente (deve ser o mesmo de quem fez a autenticação
// nesse caso seu_login@gmail.com)
$PHPMailer->From = '....';

// Nome do rementente
$PHPMailer->FromName = '....';

// assunto da mensagem
$PHPMailer->Subject = '.....';

// corpo da mensagem
$PHPMailer->Body = '
Mensagem em HTML
';

// corpo da mensagem em modo texto
$PHPMailer->AltBody = 'Mensagem em texto';

// adiciona destinatário (pode ser chamado inúmeras vezes)
$PHPMailer->AddAddress( '......' );

// adiciona um anexo
$PHPMailer->AddAttachment( '' );

// verifica se enviou corretamente
if ( $PHPMailer->Send() )
{
echo "Enviado com sucesso";
}
else
 {
echo 'Erro do PHPMailer: ' . $PHPMailer->ErrorInfo;
 }
 ?>

A: Qual é o problema que esta recebendo ?
Exibe algum erro na tela?
Pelo que percebo em seu código, você verifica se a validade é menor que 10 e não executa mais nada.
O ponto inicial para envio de e-mail é verificar se seu servidor aceita mail
Caso seu servidor não aceitar mail, você deverá efetuar o envio utilizando SMTP. Começe pelo básico disparando e-mail com a função mail ou uma classe de envio SMTP

A: Uma opção é deixar esta página aberta em um navegador dando refresh de tempo em tempo...
Para isto você pode utilizar o código abaixo (o valor do content é em segundos):
<meta http-equiv="refresh" content="5">

A: Tem uma maneira estranha mais funcional de você usar essa rotina, eu colocaria no login master, que pode ser o ID = 1, fazer uma pesquisa se for a condição que você quer ele executa a sua função, se não continua. deu para entender?


text:
Q: Get Deltas from complex SQL query I have a complex SQL query that do joins over more than 15 tables, and bring 30 columns.
Knowing that I have an update date columns on the source tables.
How can I get the deltas of all updated/Inserted information from that query ?
Adding 15 conditions (DateDiff(d,T1.Update_Date,getdate()) <= @delta OR DateDiff(d,T2.Update_Date,getdate()) <= @delta OR .....) in the where clause is neither performant nor convenient

A: In general, you do now want to use functions on columns in the where clause.  This makes it harder for the optimizer to function.
Instead of:
DateDiff(T1.Update_Date, getdate()) <= @delta

You want something like:
t1.Update_date <= dateadd(day, - @delta, getdate())

(This is SQL Server syntax; the idea is the same but the syntax different in other databses).
If you want to check a column in each table, then you need to list out the columns.  Because you are connecting the conditions by OR, this probably won't have much impact on performance.


text:
Q: Getting "Access is Denied" on calling GetFileAttributes() for a folder My program (running as administrator) is calling GetFileAttributes() on a directory located in Program Files.
It fails, and GetLastError() returns 0x80070005 ("Access is Denied"). I'm not able to identify how users might end up in this scenario. This folder was created by my application previously. And it works for most of the users but not all.
Questions:

*

*How can I simulate "access is denied" for a folder such that GetFileAttributes() function fails?

*Will running the program with administrator and requesting se_backup_name and se_restore_name resolve this issue?
I tried removing users from security tab still GetFileAttributes did not fail.
Issue is reproduced on Win 7, 8, 10.


text:
Q: "DBF file can not be opened" error using shp2pgsql I am trying to import a shapefile using shp2pgsql. I wrote this command:
shp2pgsql -I -s 2154 -W "LATIN1" W:\IGN\BDPARCELLAIRE-RGF93-LB93-MAJ2013-V4\BDPV_1-2_SHP_LAMB93_D01\COMMUNE.shp CADASTRE.COMMUNE | psql -U postgres -d omexom

But, when I execute this, I have an error :
Unable to open W:\IGN\BDPARCELLAIRE-RGF93-LB93-MAJ2013-V4\BDPV_1-2_SHP_LAMB93_D01\COMMUNE.shp or W:\IGN\BDPARCELLAIRE-RGF93-LB93-MAJ2013-V4\BDPV_1-2_SHP_LAMB93_D01\COMMUNE.SHP.
W:\IGN\BDPARCELLAIRE-RGF93-LB93-MAJ2013-V4\BDPV_1-2_SHP_LAMB93_D01\COMMUNE.shp: dbf file (.dbf) can not be opened.

I really don't understand, because I tried to import the same layer using the graphical interface PostGIS and it works.
Where am I wrong in my code?

The dbf file is present.


text:
Q: postgresql syntax error when creating a table Hey everyone I need some help with creating tables. I have the script below and it creates a few tables. When i try to run the script it give me this error:
psql:script.sql:10: ERROR:  syntax error at or near "Group"
LINE 6: CREATE TABLE Group(

Can anyone tell me what is going on?
CREATE TABLE Group(
    name        varchar(40) PRIMARY KEY    NOT NULL
);

CREATE TABLE Artist(
    name        varchar(30) PRIMARY KEY    NOT NULL,
        birthplace  varchar(20)                NOT NULL,
        age     int                        NOT NULL   CHECK (age > 0),
        style       varchar(20)                NOT NULL
);

CREATE TABLE Artwork(
    title      varchar(40) PRIMARY KEY     NOT NULL,
        artist     varchar(30)                 NOT NULL   references Artist(name),
        group_name varchar(40)                 NOT NULL   references Group(name),
        year       int                         NOT NULL   CHECK (year > 0),
        type       varchar(30)                 NOT NULL,
        price      money                       NOT NULL,
);

CREATE TABLE Customer(
    cust_id      int PRIMARY KEY   NOT NULL,
    name         varchar(40)       NOT NULL,
        address      varcahr(60)       NOT NULL,
        amount       money             NOT NULL    CHECK(amount > 0),
        like_artist  varchar(30)       NOT NULL    references Artist(name),
        like_group   varchar(40)       NOT NULL    references Group(name)
);

A: it had a lot of problems
this worked for me. In postgres, names that are not all lowercase need to be double quoted. also some of your table names are reserved words, money can't be > and int, and there was a comma out of place.
CREATE TABLE "group"( name varchar(40) PRIMARY KEY NOT NULL );

CREATE TABLE artist( name varchar(30) PRIMARY KEY NOT NULL, birthplace varchar(20) NOT NULL, age int NOT NULL CHECK (age > 0), style varchar(20) NOT NULL );

CREATE TABLE artwork( title varchar(40) PRIMARY KEY NOT NULL, artist varchar(30) NOT NULL references artist(name),
group_name varchar(40) NOT NULL references "group"(name), year int NOT NULL CHECK (year > 0), type varchar(30) NOT NULL, price money NOT NULL );

CREATE TABLE customer( cust_id int PRIMARY KEY NOT NULL, name varchar(40) NOT NULL, address varchar(60) NOT NULL,
amount money NOT NULL CHECK(amount > cast(0.0 as money)), like_artist varchar(30) NOT NULL references artist(name), like_group varchar(40) NOT NULL references "group"(name) );


text:
Q: Accessing Spell Check through PPTX Do we have an option in python-pptx to read the spell check mode used in the presentation? I am working on a project in which I have to check the spell check mode is set to "UK English". Can you help?

A: The spellchecker language is part of a font. You can get it via font.language_id. For possible values, have a look here.


text:
Q: MIC5216 Achieve minimum quiescent current draw I have the MIC5216 as voltage regulator. I am regulating 2 18650 down to 5v in order to supply enough power to my circuit. I am using a 328p as MCU. The chip goes to sleep and is awoken again by an external interrupt. That way I can reduce the energy consumption down to a minimum in order for the batteries to last as long as possible. I managed to get my 328p circuit in sleep mode to 80uA whereas the MIC5216 is using 190uA in a quiet state. I know the 5216 can go as low as 8uA. In order to achieve this low state a voltage of not more than 0.16V has to be applied to the Enable pin. As mentioned, I have 8.2V applied through the 18650's and if I remove these the chip of course will fully stop working and not provide any power at all to my circuit.
My question is: Is there a way, to reduce the power on the enable pin to 0.18V while the 328p is asleep without completely pulling that particular pin low and as soon as an interrupt is triggered to wake the whole circuit up again?
I have not worked with these kind of voltage regulators before so I appreciate any help I can get.
The datasheet for the MIC5216 is here
I am using the standard circuit shown in Figure 5 on page 11.
EDIT1
Sorry for the delay. Below a diagram of my circuit.

As you can see I added sections to the circuit in order to make the visual a little more legible. the voltage regulation part is the one that I have issues with. Even though the voltage supply is stable and provides enough current, I would like to bring it's current idle state closer to the quiescent advertised in the datasheet. My only issue is that I am not quite clear how.
The datasheet speaks about reducing the input voltage on the Enable pin (3) to 0.4V and 0.18V to achieve a quiescent state of 3 to 8μA. I cannot control the regulator with the 328p as it is going to go asleep. I was thinking about a voltage divider from the battery to the enable pin with an output of that above mentioned voltage. That could work up to the point where I want to wake the 328p up. I would now have to increase the voltage on the Enable pin of the regulator to the voltage of the battery for long enough to trigger a constant high on one pin of the MCU. With that idea though I have the problem how do I ensure to provide enough energy to the MCU in order wake it up and trigger that signal.
OK so much for my ideas. Let me know if they are totally bonkers or if there is some merit to them. Let me know if there is another way, maybe in the datasheet, that I missed.
Appreciate any feedback.
regards

A:
Is there a way, to reduce the power on the enable pin to 0.18V while
  the 328p is asleep without completely pulling that particular pin low
  and as soon as an interrupt is triggered to wake the whole circuit up
  again?

At 0.4V and below the regulator is turned off, so the 328p won't just be 'asleep', it will be dead, and the only way to make it 'wake up' again will be to turn the regulator back on via an external circuit. To do this you could make the pushbutton pull the Enable input high when pressed. On startup the MCU would also pull the Enable input high to keep the power on, and let it go low to power off. If you need to remember the program state while the MCU is off it could save the required info in the EEPROM just before powering down (remembering to give it time to write the data!)
If the MCU must stay powered all the time then to get lower sleep current you will need a different regulator. The MCP1703 should do it if peak current doesn't exceed 200mA. However you are powering a servo which which might need more than this.


text:
Q: SQL - Correct dates not being presented in result set with date ranges in WHERE clause Result set without the where clause shows there is data from the 30th September, when using the below where clause the 30th data doesn't come through in the result set (see images below for result sets) - my main aim is to show data from between the first day of the previous month and the last day of the previous month - Any help is much appreciated:
SQL Query
DECLARE @date1 datetime
DECLARE @date2 datetime
SET @date1 = getdate()
SET @date2 = getdate()-15 -- reason for less 15 days is because this will only be run within the first 15 days
                          -- of the current month, it will enable me to get the last day of the previous
                          -- month even if I run the SQL in the next month.

SELECT
        A.TA_SEQ as 'WO No',
        A.TA_DUE_DATEUTC

FROM
        F_TASKS A WITH (NOLOCK)
        INNER JOIN FINFILE B WITH (NOLOCK) ON A.TA_FKEY_IN_SEQ = B.IN_SEQ
        INNER JOIN InstructionSetGroups C WITH (NOLOCK) ON B.InstructionSetGroupId = C.InstructionSetGroupId

WHERE
        A.TA_TASK_DESC = 'BREAKDOWN' AND
        A.TA_STATUS IN ('ACTIVE', 'ASSIGNED', 'COMPLETE', 'HISTORY') AND
        A.TA_DUE_DATE >= DATEADD(DAY, 1, EOMONTH(@date1, -2)) AND
        A.TA_DUE_DATE <= EOMONTH(@date2)

ORDER BY
        A.TA_DUE_DATE desc

Result Sets
Result set using date ranges in where clause:

Result set without using date ranges in where clause - as you can see there's lots of data from the 30th too which isn't being captured

A: EOMONTH is terribly ambiguous, because it returns the last day of the month at midnight. I talk about why I don't like this function in Will you use EOMONTH()?
If you want the whole previous month, there are easier and safer ways than assuming the code will run within the first 15 days:
DECLARE @ThisMonth date = DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1);

SELECT ... FROM ...
  WHERE TA_DUE_DATE >= DATEADD(MONTH, -1, @ThisMonth)
    AND TA_DUE_DATE <  @ThisMonth;

I explain why DATEFROMPARTS is best suited for this kind of work in Simplify Date Period Calculations in SQL Server.
With the rest, where do we begin?

*

*getdate()-15 is lazy, unintuitive shorthand that will break in other contexts. Please use DATEADD(DAY, -15, GETDATE()) and see Bad Habits to Kick : Using shorthand with date/time operations.

*You can declare/set in a more readable way than an explicit line for each declare and again for each set:
 DECLARE @date1 datetime = GETDATE(),
         @date2 datetime = DATEADD(DAY, -15, GETDATE());

*as 'WO No' - please use AS [Wo No] or AS "Wo No" - string delimiters make those aliases look like, well, strings, and some forms of that syntax are deprecated.

*please always specify the schema and never use meaningless aliases like A, B, C.

*>= AND <= is the same as BETWEEN. I talk about why BETWEEN is always a terrible idea for date ranges in What do BETWEEN and the devil have in common?

*Lots of resources on NOLOCK in I'm using NOLOCK; is that bad?

*General date tips in Dating responsibly

A: I would take a different approach to handling your date values. That whole -15 stuff is bizarre and will cause issues on days towards the end of the month. Instead using a single variable is sufficient if you understand some date math.
DECLARE @date1 date --use the data datatype here because time is important in this case
SET @date1 = getdate()

--this is to show you the values and can be removed.
select BeginningOfLastMonth = dateadd(month, datediff(month, 0, @date1) - 1, 0)
    , BeginningOfCurrentMonth = dateadd(month, datediff(month, 0, @date1), 0)

--Your select statement here
where A.TA_DUE_DATE >= dateadd(month, datediff(month, 0, @date1) - 1, 0)
        A.TA_DUE_DATE <= dateadd(month, datediff(month, 0, @date1), 0) --ANY datetime value less than this is before the end of last month


text:
Q: Segmentation Fault when attempting to use variable "i" to access a certain element in an array of strings in C programming This is the code for running the Major scale program. The debugging using gdb is shown after the code. I am new to using pointers and allocating memory and what not.
// This is a program to generate a major scale based upon user input in C
// programming using formula WS WS HS WS WS WS

#include <stdio.h>
#include <stdint.h>
#include <string.h>

int
main()
{

    int j = 0;
    int i = 0;
    // This tells you which turn you are on on turns 0,1,3,4,5,6 i will be
    // added by 2 and on turn 2 i will be added by 1
    int t = 0;

    char *notes[12] = {
        "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"
    };

    char pickedNote[100];

    for (i = 0; i < 12; ++i) {
        printf("Your notes are  %s\n", notes[i]);
    }

    printf("Please type in a note\n");
    fgets(pickedNote, sizeof(pickedNote), stdin);
    pickedNote[strcspn(pickedNote, "\n")] = 0;
    printf("Your note is %s\n", pickedNote);

    for (i = 0; i < 12; ++i) {
        int notePositionTester = (strcmp(pickedNote, notes[i]) == 0);

        if (notePositionTester == 1) {
            int notePosition = i;

            printf("Your note is in position %d\n", notePosition);
        }
        else;

    }

    printf("%s\n", notes[i]);

    return 0;
}

Here is the text version of the dubugging
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...
(gdb) ls
Undefined command: "ls".  Try "help".
(gdb) run
Starting program: /home/rudy/Documents/C/MusicTheoryPractice/MajorScaleNotes/a.out

Here is our program promt and printouts
Your notes are  A
Your notes are  A#
Your notes are  B
Your notes are  C
Your notes are  C#
Your notes are  D
Your notes are  D#
Your notes are  E
Your notes are  F
Your notes are  F#
Your notes are  G
Your notes are  G#
Please type in a note
G
Your note is G
Your note is in position 10

From this point forward is our debugging output:
Program received signal SIGSEGV, Segmentation fault.
__strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:65
65  ../sysdeps/x86_64/multiarch/strlen-avx2.S: No such file or directory.
(gdb) backtrace
#0  __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:65
#1  0x00007ffff7e48464 in __GI__IO_puts (str=0x47 <error: Cannot access memory at address 0x47>) at ioputs.c:35
#2  0x00005555555553ea in main () at MajorScaleNotes.c:37
(gdb) frame 2
#2  0x00005555555553ea in main () at MajorScaleNotes.c:37
37      printf("%s\n",notes[i]);
(gdb) print notes[i]
$1 = 0x47 <error: Cannot access memory at address 0x47>
(gdb)

A: A few issues ...

*

*After the loop, i is 12. This is one beyond the end of the array, so the final printf has UB (undefined behavior). This can produce a segfault.

*else; does nothing.

*Once a match is found, there is no need to loop further, so we can add a break to exit the loop early.

Here is the corrected code. It is annotated with the bugs and fixes:
/* This is the code for running the Major scale program. The debugging using
gdb is shown after the code. I am new to using pointers and allocating memory
and what not */

// This is a program to generate a major scale based upon user input in C
// programming using formula WS WS HS WS WS WS

#include <stdio.h>
#include <stdint.h>
#include <string.h>

int
main(void)
{

    int j = 0;
    int i = 0;
    // This tells you which turn you are on on turns 0,1,3,4,5,6 i will be
    // added by 2 and on turn 2 i will be added by 1
    int t = 0;

    char *notes[12] = {
        "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"
    };

    char pickedNote[100];

    for (i = 0; i < 12; ++i) {
        printf("Your notes are  %s\n", notes[i]);
    }

    printf("Please type in a note\n");
    fgets(pickedNote, sizeof(pickedNote), stdin);
    pickedNote[strcspn(pickedNote, "\n")] = 0;
    printf("Your note is %s\n", pickedNote);

// NOTE/FIX: we want this accessible _after_ the loop
#if 1
    int notePosition = -1;
#endif

    for (i = 0; i < 12; ++i) {
        int notePositionTester = (strcmp(pickedNote, notes[i]) == 0);

        if (notePositionTester == 1) {
// NOTE/BUG: we want this to be at an outer scope
#if 0
            int notePosition = i;
#else
            notePosition = i;
#endif

            printf("Your note is in position %d\n", notePosition);

// NOTE/FIX: no need to loop further -- we've found the result
#if 1
            break;
#endif
        }
    }

// NOTE/BUG: as this point, i is 12 which is one _beyond_ the end of the
// array
#if 0
    printf("%s\n", notes[i]);
#else
    if (notePosition >= 0)
        printf("%s\n", notes[notePosition]);
#endif

    return 0;
}

In the above code, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif

#if 1
// new code
#endif

Here is the cleaned up code (run through unifdef -k with the NOTE comments removed):
/* This is the code for running the Major scale program. The debugging using
gdb is shown after the code. I am new to using pointers and allocating memory
and what not */

// This is a program to generate a major scale based upon user input in C
// programming using formula WS WS HS WS WS WS

#include <stdio.h>
#include <stdint.h>
#include <string.h>

int
main(void)
{

    int j = 0;
    int i = 0;
    // This tells you which turn you are on on turns 0,1,3,4,5,6 i will be
    // added by 2 and on turn 2 i will be added by 1
    int t = 0;

    char *notes[12] = {
        "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"
    };

    char pickedNote[100];

    for (i = 0; i < 12; ++i) {
        printf("Your notes are  %s\n", notes[i]);
    }

    printf("Please type in a note\n");
    fgets(pickedNote, sizeof(pickedNote), stdin);
    pickedNote[strcspn(pickedNote, "\n")] = 0;
    printf("Your note is %s\n", pickedNote);

    int notePosition = -1;

    for (i = 0; i < 12; ++i) {
        int notePositionTester = (strcmp(pickedNote, notes[i]) == 0);

        if (notePositionTester == 1) {
            notePosition = i;

            printf("Your note is in position %d\n", notePosition);

            break;
        }
    }

    if (notePosition >= 0)
        printf("%s\n", notes[notePosition]);

    return 0;
}


text:
Q: Proving that a set isn't dense Let $A$ be a set of real numbers such that $A \subseteq [0,1]$. I'm having a hard time proving that $C=\left\{\frac{a+1}{n^2} \colon a \in A, n \in \mathbb{N} \right\}$ is not dense in $[0,1]$. How should I approach this? I know that I must find an interval $(x,y) \subseteq [0,1]$ such that $C \cap (x,y) = \phi $. I tried demanding $\frac{a+1}{n^2}<x$ or $\frac{a+1}{n^2}>y$ for every $a \in A$ and $n \in \mathbb{N}$. The problem is that I know nothing about $A$. I'd appreciate any suggestions.

A: If the statement is true, I think it would suffice to show the result for $A=[0,1]$.
Regardless, I think the interval $(1/2,1)$ does not intersect $C$.

A: Suppose that $A=[0,1]$.  Then, you can find a set that contains $C$.  Namely, for $n=1$, $\frac{A+1}{n^2}=[1,2]$.  For $n=2$, $\frac{A+1}{n^1}=[1/4,1/2]$.  If you continue in this way, you'll see that all intervals are in the range $[0,1/4]$.  More precisely, you know that since $A\subseteq [0,1]$, it follows that
$$
C\subseteq \cup_{n=1}^\infty [1/n^2,2/n^2].
$$
Therefore, $C$ does not intersect $(1/2,1)$.

A: If $n=1$ you have $\forall a\in A: c\colon= \frac{a+1}{1} \geq 1$, thus $c\notin C$
If $n\geq2$ it follows
$$\forall n\in\mathbb{N}-\{1\} \forall a\in A: \frac{a+1}{n^2}\leq \frac{1+1}{2^2}=\frac{1}{2}$$
Thus your set $C$ does not intersect $\left(0.5, 1\right)$


text:
Q: ASP.NET MVC Edit problem - "entity" data from controller aren't passed to the view I'm pretty sure that I complicated my question. Sorry, I didn't know how to express myself. Situation is next :
public ActionResult Edit(int id)
    {
        CreateTrainingModel editTrainingModel = new CreateTrainingModel();

        editTrainingModel.Training = training.GetByID(id);
        editTrainingModel.Player = player.GetAll();

        return View(editTrainingModel);
    }

and Editor template for Html.EditorFor() :
@inherits System.Web.Mvc.WebViewPage<TrainingStatistics.Models.ViewModels.CreateTrainingModel>

@Html.ValidationSummary()

 @Html.HiddenFor(x => x.Training.TrainingID)

  Training Date
  <input type="text" id="datepicker" name="Training.Date">
  @Html.ValidationMessageFor(x => x.Training.Date)

Problem is that when I want to edit this, data from model aren't passed to the view. I think that problem is because of using ViewModels and I'm doing something wrong here..When I try to update something which is consist of only one entity (example Player) and when I'm not using ViewModel everything is fine.
Thank you in advance!

A: I believe you need to create editor template for the view model.
You can see the exmaples of this below
http://www.codecapers.com/post/Display-and-Editor-Templates-in-ASPNET-MVC-2.aspx
http://davidhayden.com/blog/dave/archive/2009/08/21/htmleditorforscaffoldcolumnattribute.aspx


text:
Q: Is the ThreadFactory generated by TheadFactoryBuilder thread safe? Suppose I have the following code and makePool can be called by multiple threads. I'm using ThreadFactoryBuilder to make sure the threads have a unique name.
private final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(
                    "MyBusinessClass-%d").build();

public ExecutorService makePool() {
    return Executors.newFixedThreadPool(1, threadFactory);
}

or do I have to assume the pool is not thread safe, and have to do something like:
private static final AtomicLong poolCount = new AtomicLong(0L);

public ExecutorService makePool() {
    private final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(
        "MyBusinessClass- " + poolCount.incrementAndGet() + "-%d").build();
    return Executors.newFixedThreadPool(1, threadFactory);
}

A: My reading of the source code (Guava 10.0.1) is that it is thread safe, so long as the backing thread factory is thread safe.  In your code, the backing thread factory will be an instance of Executors.DefaultThreadFactory which is thread-safe.
Note that none of this is specified ... as far as I can see..  However, the way that these classes are coded says to me that they are thread-safe by design.  The mutable components of the respective objects consist of counters implemented as atomics, and thread creation / starting has a happens-before.


text:
Q: Right Drawable in Android. Not Working I am drawing a line beside a TextView using the drawableRight property. There are a number of TextViews in the table and all I want is column divider. Heres the TextView code:
<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="units"
     android:drawablePadding="2pt"
     android:drawableRight="@drawable/linetable"
     android:gravity="center"
     android:layout_margin="2pt"
     android:padding="2pt" />

Linetable Code:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="line">

       <solid android:color="#000000"></solid>
       <stroke
            android:width="2pt"
            android:color="#000000"
            android:dashWidth="8pt"
            android:dashGap="8pt"/>

</shape>

So I expected to draw a column beside all TextViews and this may look like a column border. But it isnt working.
The images show what I am trying to achieve and what I have achieved.
I just need guidance. Thank You.

A: You can use android-wheel.


text:
Q: Does the inverse trigonometric identity $\tan^{-1}{x} = \cot^{-1}{1 \over x}$ hold for all $x>0$? I differentiate both sides, and after a few steps I get that derivations are equal to each other, but I do not know what to conclude from those characteristics. Should I use Cauchy's or/and Lagrange's Theorem to prove that those functions are (not) equal for $x > 0$, or there is an easier way to check this?

A: In general, if $f'(x) = g'(x)$ for all $x\in D$ and $f(y) = g(y)$ for some $y\in D$ where $D$ is a connected subset of $\mathbb R$, then $f = g$ identically on $D$.

A: If two differentiable functions $f, g$ on an interval $I$ satisfy $f' = g'$ and $f(a) = g(a)$ for some $a \in I$, then $f = g$. So, the claim follows from your work so far and, e.g., the particular value $\arctan 1 = \frac{\pi}{4} = \operatorname{arccot} 1$.
Alternatively, one can just draw a right triangle with leg lengths $x, 1$ and write the acute angle adjacent to the side of length $1$ in two different ways using the definitions of $\arctan$ and $\operatorname{arccot}$.

A: If we switch the trig function we have to correspondingly change the co-function, holding the Pythagorean right angle triangle relation the same.
$$ \tan ^{-1}(x)= \cot^{-1} \left(\frac1x\right) = \cos ^{-1}\left(\frac{1}{\sqrt{1+x^2}}\right) = \sec^{-1}\left(\sqrt{1+x^2}\right)= \sin ^{-1}\left(\frac{x}{\sqrt{1+x^2}}\right) = \csc^{-1}\left(\frac{\sqrt{1+x^2}}{x}\right)...$$
They are identities and so hold for all values of $x$.
Unless there is an error, derivatives also should match. For example,
$$ \frac{d(tan^{-1} x)}{dx} = \frac{1}{1+x^2} $$
$$ \frac{d\left(cot^{-1} \left(\frac1x\right)\right)}{dx} =    \dfrac{-1}{\left(1+\frac{1} {x^2}\right)} \cdot \dfrac{-1}{x^2} = \frac{1}{1+x^2}. $$


text:
Q: Java Mail is not supporting UTF-8 Characters in Subject of the email Here is my code of setting subject to the email:
  String bodyMessage="Dear Renavçilçleç Françoisç InCites™";
  String subject = "Your new InCites™ subscription";

  Properties _sessionProperties = new Properties();
  _sessionProperties.put("mail.transport.protocol", "smtp");
  _sessionProperties.put("mail.smtp.host", "hostname");
  _sessionProperties.put("mail.smtp.port", "25");

  Session session = Session.getInstance(_sessionProperties, null);

  MimeMessage mimemsg = new MimeMessage(session);
  mimemsg.addRecipients(Message.RecipientType.TO, "xxx@gmail.com");
  mimemsg.setSubject(subject, "UTF-8");

  // Create a multi-part message
  MimeMultipart multipart = new MimeMultipart();
  // Set the subType
  multipart.setSubType("alternative");
  BodyPart part = new MimeBodyPart();

  part.setContent(bodyMessage, "charset=UTF-8");

  // Set the emailBody and emailType to MIME BodyPart
  part.setDataHandler(new DataHandler(new ByteArrayDataSource(
      bodyMessage, "text/html;")));

  // Add the MIME BodyPart to MIME multiPart
  multipart.addBodyPart(part);

  // Put parts in message
  mimemsg.setContent(multipart);

  // Send message
  Transport.send(mimemsg);

But still in email subject it still shows as "Your new InCites™ subscription"

A: The subject you mention here consists completely of ASCII characters. This includes the funny special characters ™. If you want it to be Unicode, just use Unicode and not the HTML-escaping. Mails don't have anything to do with HTML.
mimemsg.setSubject("Your new InCites\u2122 subscription", "UTF-8");

This should encode the subject as something like =?UTF-8?Q?Your...subscription?=, as specified in RFC 2047.
The complete example code:
package so4406538;

import java.io.IOException;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

public class MailDemo {

  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);
    message.setSubject("Your new InCites\u2122 subscription", "UTF-8");
    message.setContent("hello", "text/plain");
    message.writeTo(System.out);
  }
}

The output:
Message-ID: <7888229.0.1291967222281.JavaMail.roland@bacc>
Subject: =?UTF-8?Q?Your_new_InCites=E2=84=A2_subscription?=
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

hello

You can see that the subject header is encoded, and this is necessary and correct.
[Update: I fixed the Unicode escape sequence, as indicated in one of my comments.]


text:
Q: Querying using subqueries on a SQLite database approx 10x slower using newer versions of System.Data.SQLite/sqlite3.dll (See update below)
I am having an issue of slow query performance when querying a very simplistic Sqlite datatable of about 500,000 rows from within a C#.Net application (~5sec).
I have tried the exact same query on exactly the same database using LinqPad, as well as 2 database browsers (both based on QtSql), and it runs 10x faster (~0.5secs). Same query, same db, different apps, only mine doesn't run fast.
It makes negligible difference whether I'm returning values or just a Count(*).
I've tried:

*

*building for each of .Net 3.5/4/4.5

*building for each of of AnyCPU/x86/x64

*using each of System.Data.Sqlite, sqlite-net, as well as directly accessing a sqlite3 dll via COM

*building for each of WPF/WinForms

*different variations of the queries

None of these make any noticible difference to the query time.
I know that rewriting the query using JOINs may help, but what I can't figure out is why the same query works fine in LinqPad/Sql browers but not from any app I try to create. I must be missing something pretty fundamental.
Example Table:
"CREATE TABLE items(id INTEGER PRIMARY KEY, id1 INTEGER, id2 INTEGER, value INTEGER)"

Example Query String (though basically any query using a subquery takes a long time):
SELECT count(*)
FROM items WHERE
id2 IN
(
    SELECT DISTINCT id2 FROM items WHERE id1 IN
    (
        SELECT DISTINCT id1 FROM items WHERE id2 = 100000 AND value = 10
    )
    AND value = 10
)
AND value = 10
GROUP BY id2

I know this could probably be re-written using JOINS and indexing to speed it up, but the fact remains that this query works significantly faster from other apps. What am I missing here as to why the same query runs so much slower no matter what I try?
UPDATE: It seems the version of sqlite has something to do with the issue. Using the legacy System.Data.Sqlite v1.0.66.0 the query runs just like the other apps, however using a more recent version it is slow. I haven't pinpointed what at what version exactly this changed, but am pretty sure it's to do with the underlying sqlite3 version not System.Data.Sqlite specifically. If anyone knows what could have changed that would cause subqueries to slow down so much in this situation, or if there are settings or something that can make subqueries run faster in new versions of sqlite please let me know!
Again, the query is an example and is not ideal and partially redundant... the question is more about why it works in one and not the other.
Thanks in advance for any additional input!
UPDATE: SOLVED
See my answer below.

A: Some suggestions:
You say you don't want to rework your queries nor add indexes. That is the obvious thing to do here. Without any indexes sqlite has to scan your 500,000 row table at least one time (or more likely multiple times).
Based on your query above I would add indexes to columns id1 and id2.

One other thing is that your query above seems a little redundant. Maybe you have your reasons, but I cannot see why the query should be so complicated. Simplified query:
select count(*)
from items
where id2 = 100000 and value = 10

A: try
SELECT ID1.id2, count(*)
FROM items ID2
JOIN items ID1
  on ID2.id2 = ID1.id1
 and ID1.id2 = 100000
 and ID1.value = 10
 and ID2.valu3 = 10
group by ID1.id2

A: Ok turns out it was to do with Automatic Indexing, which was introduced with SQLite 1.7.0. In my situation using subqueries on this kind of table without indexes meant that the time it took SQLite to create the automatic indexes was causing the additional overhead that the queries were experiencing.
The solution was to use:
PRAGMA automatic_index=OFF;

at the start of any query that uses the "IN" clause.
Creating indexes on the columns may also solve this (untested), however in this particular situation the additional size/disk usage necessary to create the indexes is not worth it.
This would also suggest that the LinqPad SQLite plugin and the database viewers I was using are based on old sqlite versions.
More information can be found at:
http://www.sqlite.org/src/info/8011086c85c6c4040
http://www.sqlite.org/optoverview.html#autoindex
Thanks to everyone that responded.


text:
Q: OfAppNoWindow and ofFbo video IO behaviour conflict in OpenFrameworks I am trying to render a video using ofxVideoRecorder on a headless server. The video renders correctly with a normal window, i.e.
ofSetupOpenGL(640,420, OF_WINDOW);

However, I get messed up frames (could not attach image) with a ofAppNoWindow.
ofAppNoWindow headless;
ofSetupOpenGL(&headless,640,420,OF_WINDOW);
ofRunApp(new testApp());

I have also tried,
    ofAppNoWindow headless;
    headless.setupOpenGL(640,420,OF_WINDOW);
    headless.runAppViaInfiniteLoop(new testApp());
I render objects in ofFbo in update method(). I tried saving image with and without headless window. The image saves correctly without headless window.
I think the issue is with FBO drawing incorrectly with ofApppNoWindow
This is the Fbo draw code
fbo.begin();
 ofClear( 255, 255, 255, 0 );
 ofEnableAlphaBlending();
 element.draw(); //element is my class
fbo.end();

Here is the screen capture code.
fbo.readToPixels(pixels);
pixels.setNumChannels(3);
vidRecorder.addFrame(pixels); //ofxVideoRecorder object

Would appreciate any help to enable near realtime video rendering and writing.

A: I had to setup an Openframeworks in a remote private server with GPU from Rapidswitch, and after struggling few hours I could make it work.
In order to have OpenGL you must have a X server running. Xvfb is not an option because it is not HW accelerated, so you will have to config your Xserver with no screen attached.
My system is Ubuntu 14.04.5 LTS

*

*First, I checked that the GPU was present:
$ lspci  | grep NVIDIA
01:00.0 VGA compatible controller: NVIDIA Corporation GM107 [GeForce GTX 750 Ti] (rev a2)

*Then, I've installed the nvidia drivers (I've chosen that version for no special reason, following a comment in a post).
$ sudo apt-get install nvidia-346  nvidia-settings

*I run sudo nvidia-xconfig and this is the top of my /etc/X11/xorg.conf
# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig: version 352.93  (buildmeister@swio-display-x86-rhel47-07)  Tue Apr  5 18:55:28 PDT 2016

*Then, I modified /etc/X11/xorg.conf adding the AllowEmptyInitialConfiguration option:
Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    Option         "AllowEmptyInitialConfiguration"
EndSection

*Finally, I could start my X server on display :0
sudo /usr/bin/X :0
If everything was ok the command will launch the X server with HW acceleration. We can run glxinfo -display :0 | grep renderer to check that it is indeed using the GPU. This was my output:
$ glxinfo -display :0 | grep renderer
OpenGL renderer string: GeForce GTX 750 Ti/PCIe/SSE2

Finally, you just export your display export DISPLAY=:0 and run any OPENGL code. You can check that it is working using the toy example glxgears.
This is my output:
 $ glxgears
 Running synchronized to the vertical refresh.
 The framerate should be approximately the same as the monitor refresh rate.
 63388 frames in 5.0 seconds = 12677.544 FPS
 63382 frames in 5.0 seconds = 12676.304 FPS
 ...

Now you're ready to run your OpenFrameworks projects. You don't need to make any change to the source code.

A: Answering my question. Thanks to @arturo at forums.openframeworks.co Hope this helps others.
The ofAppNoWindow does not create a OpenGL context. Hence OpenGL resources such as FBO are unavailable. Therefore you cannot really "read" the FBO. This can be verified by checking if the fbo is allocated (fbo.isAllocated() in openFrameworks).


text:
Q: IFrame log out service after page refreshing I've got a website with an iframe in it with another website and every time user refreshes the page he becomes logged out. I thought this is because reloading clears cookies (with JSESSIONID cookie), but navigation on other sites doesn't logs the user out.
For example, if I click https://google.com link, then click back button, I will be still logged in in the website that is in iframe. But if I click refresh button, I will be logged out.


text:
Q: Validation in code behind In my ASP.net application, I am referring the following dll file for validation in my business object class file..
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

and I am validating the properties like this
[StringLengthValidator(1, 50, MessageTemplateResourceName = "INVALID_NAME",
 MessageTemplateResourceType = typeof(ValidatioinErrors))]
[RegexValidator("[A-Za-z]*", MessageTemplateResourceName = "INVALID_NAME",
 MessageTemplateResourceType = typeof(ValidatioinErrors))]
public string Name
{
  get { return name; }
  set { name = value; }
}

Now I am passing the value for Name as "test123", when I check this validation by using the IsValid() function like
public bool IsValid()
{
   return Validation.Validate<myclassname>(this).IsValid;
}

And when I check this IsValid() function after passing the value for name as "test123", it accepts this given name instead of returning invalid name by rejecting it.
where am I committing mistake? can anyone help me here....

A: Try it with a regex of ^[A-Za-z]*$.
The added '^' and '$' mean that that regex should match the entire string instead of just a part of it.
The asp.net regexvalidator doesn't need these but that's an exception. Regular regexes need these anchors to match only the full input, and this attribute apparently does also.


text:
Q: JavaScript form validation not working I have a very simple form with a very simple JavaScript validator.
I want an alert to popup if the first nae isnt filled out only it doesnt seem to be alerting and still submits.
I've uploaded a fiddle here http://jsfiddle.net/nvgMq/

A: You code is correct but it's jsfiddle's problem. After inspecting the jsfiddle's HTML page, I found out that the JavaScript code has become:
window.addEvent('load', function() {
    function validateForm()
     {
       var x=document.forms["subForm"]["ajijjt-ajijjt"].value

        if (x==null || x=="")
        {
            alert("First name must be filled out");
            return false;
        }
      }
});

So the function validateForm is no longer a global variable, it can not be accessed in the <form>'s onsubmit.
You can use code like:
window.validateForm = function() {}

This will create the global variable for validateForm.

A: Have you checked the value of x?  Try putting a semi colon after the .value
var x=document.forms["subForm"]["ajijjt-ajijjt"].value;


text:
Q: How to track an inactive mouse once a page loads? Right now, I have a function set up to do something if a mouse is inactive for 10 seconds for mobile only. However my console.log doesn't appear unless there is some activity before it is triggered by the inactivity. here is my code:
    if (width <= 480) {
       const inactiveUserMessage = () => {
             console.log("mouse has been inactive for 10 seconds");
       };
       document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000));
    }

***In another file, lives the debounce function:
export function debounce(func, timeout) {
    let timer;
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}

There needs to be some kind of activity before the inactiveUserMessage triggers. However how do i do it where the debounce function runs right away without needing some kind of movement before?? Please help!!!
Please let me know if this makes sense or if you need some more information.
I tried to create a mousemove event listener with a debounce function but it doesn't work unless there is some kind of movement on the page before hand.
I tried to create a mousemove event listener with a debounce function but it doesn't work unless there is some kind of movement on the page before hand.

A: Use the window's "load" event to start the timer and pass the timer to the debounce function. Something like this;
let timer;
const inactiveUserMessage = () => {
     console.log("mouse has been inactive for 10 seconds");
};

window.addEventListener("load", () => {
     timer = setTimeout(inactiveUserMessage, 10000);
});

...

if (width <= 480) {
    document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000), timer);
}
...

export function debounce(func, timeout, timer) {
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}


text:
Q: A custom Image DataGen for stacked denoising autoencoder (DAE) in Keras on GPU (exceptions) Have you ever created a custom ImageDataGenerator for Keras?
For one of our projects we have already created two sets of "clean images" and multiple noisy versions of each one as the "noisy images", in two folders. I want to design and train an stacked denoising autoencoder to learn denoising these images (document scans).
I have searched around and found multiple sample codes for DAE on MNIST, where they directly load all images into memory. But in my case I can not load all images at once, so I think I should use Keras ImageDataGenerator or something like that. I even have found sample AutoEncoders that use ImageDataGenerators to load the data where it returns the same exact image both as the input and output, and even add some augmentation to both input and output images in their flow_from_directory() here.
But as I mentioned earlier, I want to design a "Denoising AutoEncoder" and want to train it on an "existing" set of clean/noisy images. I found here a nice description on defining custom DataGenerators in Keras, and have tried to adopt it to my case, but I am getting exceptions!
Please find my Code:
I have created a Jupyter Notebook shared on Google Colab here and appreciate it if you guys can take a look at it and let me know what the source of problem is.
Current Exception:
Epoch 1/5
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
h:\Projects\DenoisingAutoencoder\DAE_DataGen.ipynb Cell 7' in <cell line: 2>()
      1 # Train model on dataset
----> 2 model.fit(training_generator,
      3             validation_data=validation_generator,
      4             steps_per_epoch=500,
      5             epochs=5,
      6             # use_multiprocessing=True,
      7             # workers=6,
      8             # callbacks=[tensorboard_callback]
      9             )

File c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\utils\traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File c:\Users\.conda\envs\me_env_gpu\lib\site-packages\tensorflow\python\eager\execute.py:54, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     52 try:
     53   ctx.ensure_initialized()
---> 54   tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     55                                       inputs, attrs, num_outputs)
     56 except core._NotOkStatusException as e:
     57   if name is not None:

InvalidArgumentError: Graph execution error:

Detected at node 'model_1/conv2d_transpose_2/conv2d_transpose' defined at (most recent call last):
    File "c:\Users\.conda\envs\me_env_gpu\lib\runpy.py", line 196, in _run_module_as_main
      return _run_code(code, main_globals, None,
    File "c:\Users\.conda\envs\me_env_gpu\lib\runpy.py", line 86, in _run_code
      exec(code, run_globals)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel_launcher.py", line 17, in <module>
      app.launch_new_instance()
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\traitlets\config\application.py", line 965, in launch_instance
      app.start()
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel\kernelapp.py", line 712, in start
      self.io_loop.start()
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\tornado\platform\asyncio.py", line 199, in start
      self.asyncio_loop.run_forever()
    File "c:\Users\.conda\envs\me_env_gpu\lib\asyncio\base_events.py", line 600, in run_forever
      self._run_once()
    File "c:\Users\.conda\envs\me_env_gpu\lib\asyncio\base_events.py", line 1896, in _run_once
      handle._run()
    File "c:\Users\.conda\envs\me_env_gpu\lib\asyncio\events.py", line 80, in _run
      self._context.run(self._callback, *self._args)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel\kernelbase.py", line 504, in dispatch_queue
      await self.process_one()
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel\kernelbase.py", line 493, in process_one
      await dispatch(*args)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel\kernelbase.py", line 400, in dispatch_shell
      await result
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel\kernelbase.py", line 724, in execute_request
      reply_content = await reply_content
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel\ipkernel.py", line 383, in do_execute
      res = shell.run_cell(
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\ipykernel\zmqshell.py", line 528, in run_cell
      return super().run_cell(*args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\IPython\core\interactiveshell.py", line 2880, in run_cell
      result = self._run_cell(
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\IPython\core\interactiveshell.py", line 2935, in _run_cell
      return runner(coro)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\IPython\core\async_helpers.py", line 129, in _pseudo_sync_runner
      coro.send(None)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\IPython\core\interactiveshell.py", line 3134, in run_cell_async
      has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\IPython\core\interactiveshell.py", line 3337, in run_ast_nodes
      if await self.run_code(code, result, async_=asy):
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\IPython\core\interactiveshell.py", line 3397, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "C:\Users\AppData\Local\Temp\ipykernel_40284\3459445018.py", line 2, in <cell line: 2>
      model.fit(training_generator,
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\training.py", line 1384, in fit
      tmp_logs = self.train_function(iterator)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\training.py", line 1021, in train_function
      return step_function(self, iterator)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\training.py", line 1010, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\training.py", line 1000, in run_step
      outputs = model.train_step(data)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\training.py", line 859, in train_step
      y_pred = self(x, training=True)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\base_layer.py", line 1096, in __call__
      outputs = call_fn(inputs, *args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\utils\traceback_utils.py", line 92, in error_handler
      return fn(*args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\functional.py", line 451, in call
      return self._run_internal_graph(
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\functional.py", line 589, in _run_internal_graph
      outputs = node.layer(*args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\engine\base_layer.py", line 1096, in __call__
      outputs = call_fn(inputs, *args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\utils\traceback_utils.py", line 92, in error_handler
      return fn(*args, **kwargs)
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\layers\convolutional.py", line 1336, in call
      outputs = backend.conv2d_transpose(
    File "c:\Users\.conda\envs\me_env_gpu\lib\site-packages\keras\backend.py", line 5720, in conv2d_transpose
      x = tf.compat.v1.nn.conv2d_transpose(x, kernel, output_shape, strides,
Node: 'model_1/conv2d_transpose_2/conv2d_transpose'
Conv2DSlowBackpropInput: Size of out_backprop doesn't match computed: actual = 98, computed = 293 spatial_dim: 2 input: 586 filter: 3 output: 98 stride: 2 dilation: 1
     [[{{node model_1/conv2d_transpose_2/conv2d_transpose}}]] [Op:__inference_train_function_1189]

A: I just checked your code on Google Colab, and I see quite good comments. You probably need to restart your server to make things roll.
I am not yet an expert in Keras's DataImageGenerator, but the first thing that comes to my mind is to replace your DAE with a normal feedforward net!


text:
Q: Google Maps V3 Polygon Drawing I don't know why I am getting colored certain area (see the picture). NOTE: When mouse is on this area it act's like it's out of polygon so polygon is not clickable there, but is still colored.
Data are under the picture.

var coord_region1 = [
{lat: 37, lng: 12},
{lat: 37, lng: 13},
{lat: 37, lng: 14},
{lat: 37, lng: 15},
{lat: 37, lng: 16},
{lat: 38, lng: 16},
{lat: 38, lng: 17},
{lat: 39, lng: 17},
{lat: 39, lng: 18},
{lat: 40, lng: 18},
{lat: 40, lng: 19},
{lat: 41, lng: 19},
{lat: 41, lng: 18},
{lat: 41, lng: 17},
{lat: 42, lng: 17},
{lat: 42, lng: 16},
{lat: 42, lng: 15},
{lat: 43, lng: 15},
{lat: 43, lng: 14},
{lat: 44, lng: 14},
{lat: 44, lng: 13},
{lat: 45, lng: 13},
{lat: 45, lng: 14},
{lat: 46, lng: 14},
{lat: 46, lng: 15},
{lat: 47, lng: 15},
{lat: 47, lng: 14},
{lat: 47, lng: 13},
{lat: 47, lng: 12},
{lat: 47, lng: 11},
{lat: 47, lng: 10},
{lat: 47, lng: 9},
{lat: 47, lng: 8},
{lat: 47, lng: 7},
{lat: 46, lng: 7},
{lat: 46, lng: 6},
{lat: 45, lng: 6},
{lat: 44, lng: 6},
{lat: 44, lng: 7},
{lat: 43, lng: 7},
{lat: 43, lng: 8},
{lat: 43, lng: 9},
{lat: 43, lng: 10},
{lat: 44, lng: 10},
{lat: 44, lng: 9},
{lat: 44, lng: 8},
{lat: 43, lng: 8},
{lat: 42, lng: 8},
{lat: 41, lng: 8},
{lat: 40, lng: 8},
{lat: 39, lng: 8},
{lat: 39, lng: 9},
{lat: 39, lng: 10},
{lat: 40, lng: 10},
{lat: 41, lng: 10},
{lat: 42, lng: 10},
{lat: 42, lng: 11},
{lat: 42, lng: 12},
{lat: 41, lng: 12},
{lat: 41, lng: 13},
{lat: 41, lng: 14},
{lat: 40, lng: 14},
{lat: 40, lng: 15},
{lat: 39, lng: 15},
{lat: 38, lng: 15},
{lat: 38, lng: 14},
{lat: 39, lng: 14},
{lat: 39, lng: 13},
{lat: 39, lng: 12},
{lat: 38, lng: 12},
{lat: 37, lng: 12},
];

A: I figure it out. The problem is for a polygon "hole" you need to define data like [path_outer, path_inner]. Important part is to have defined points in opposite direction than the outer path.
Like google documentation says:
    // Define the LatLng coordinates for the polygon's  outer path.
    var outerCoords = [
      {lat: 25.774, lng: -80.190},
      {lat: 18.466, lng: -66.118},
      {lat: 32.321, lng: -64.757}
    ];

    // Define the LatLng coordinates for the polygon's inner path.
    // Note that the points forming the inner path are wound in the
    // opposite direction to those in the outer path, to form the hole.
    var innerCoords = [
      {lat: 28.745, lng: -70.579},
      {lat: 29.570, lng: -67.514},
      {lat: 27.339, lng: -66.668}
    ];

https://developers.google.com/maps/documentation/javascript/examples/polygon-hole


text:
Q: SHM - Finding amplitude given 2 speed/distance pairs.
The head of a piston moves with SHM about a centre $O$. When $1$ metre from $O$ its speed is $7.2 \, \text{ms}^{-1}$, and when $2.4$ metres from $O$ its speed is $3 \,\text{ms}^{-1}$.  Find the amplitude of the motion.

To solve this, I set up a pair of simultaneous equations using the result $v^2 = \omega^2(a^2-x^2)$:
$$ w^2(a^2-1) = 7.2^2$$
$$w^2(a^2 - 2.4^2) = 3^2$$
Which gives $a = 2.6$ when solved, the correct answer.
However the solutions simply give the working: $a^2 = 2.4^2 + 1 \implies a =2.6$. This seems like some much easier 'shortcut' method to get to the answer. I can see that $2.4$ and $1$ are the distances involved, but I can't understand why this works and why the relevant velocities don't seem to be needed at all.
Is there a standard result or much easier method to solve this?

A: It just happens to be a coincidence in this example that $$\frac{7.2^2}{3^2}=2.4^2$$
One would usually divide the two equations to eliminate $w^2$ and rearrange to get $a^2$, so on this occasion this leads to $$a^2-1=2.4^2(a^2-2.4^2)$$
Hence $$a^2(2.4^2-1)=2.4^4-1=(2.4^2+1)(2.4^2-1)$$
and hence the result.
There is no special short-cut in general


text:
Q: Getting error on building a app on Xcode 6.1? I "m building an app on Xcode 6.1  and iam facing a problem when i click on build in Xcode
getting an error like below:
  CodeSign error: code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 8.1'

I google and get some similar links related to this issue but all are for SDK 5.1 or 6.0.
Could anyone help me how i can solve this issue.
Help is appreciated!

A:
Remove any blue check in [ProductName]Tests so it will be uncheck then try running.

A: I'm not sure,i think provisioning profile in the build settings for the test target was set to "Don't code sign". select provisioning profile manually. May be it will solve your issue.
for change provisioning profile identity
select your project title and the right side view
Go to Build settings->Code signing-> Code signing identity->(if its in Don't code sign )then select your provisioning profile.


text:
Q: Unable to include rapidjson library in VS2017 I am trying to include the rapidjson library in my VS community 2017 project.
On creating a new project, I tried including/adding the directory rapidjson-master\include\rapidjsonat the following places :

*

*Properties -> Configuration Properties -> C/C++ -> General -> Additional Include Directories.

*Properties -> Configuration Properties -> VC++ Directories -> Include Directories.
Either way, when I try to include a rapidjson related file, VS tells me that it cannot find the source file.
So, when i give this :
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

I get the following errors :

Error (active)    E1696   cannot open source file "rapidjson/document.h"
Error (active)    E1696   cannot open source file "rapidjson/writer.h"
Error (active)    E1696   cannot open source file "rapidjson/stringbuffer.h"

VS Info :

Microsoft Visual Studio Community 2017
Version 15.6.3

Let me know if you know the right way to use rapidjson in Visual Studio.
EDIT :
The rapidjson documentation advises us to "just copy the include/rapidjson folder to system or project's include path".

A: It looks like the include path should be just rapidjson-master\include, but let's start from the beginning.

*

*Clone the rapidjson repository; do the following in a command window:
mkdir C:/ThirdParty
cd C:/ThirdParty
git clone https://github.com/Tencent/rapidjson.git

Substitute a convenient directory for C:/ThirdParty.

*In Visual Studio, open the solution and in Solution Explorer, select the project that is using rapidjson and either use the main menu PROJECT Properties function, or right-click on the project and select Properties from the option menu. This will display the Properties dialog.

*Select C/C++ General in list on the left side of the dialog.

*Now on the right side of the dialog, the first line should be "Additional Include Directories". Edit that line, adding C:/ThirdParty/rapidjson/includeat the end of the list.

A: After spending some time trying to figure out why it wasn't including the external libraries, I finally found my solution.
When I was adding the path to my additional include directories, I was doing it under the following configuration :

Configuration : Debug
Platform : x64.

However, in my VS2017, every time I create a new project, the default configuration that is set for compilation/run is as follows :

Configuration : Debug
Platform : x86

The main reason behind my problem was the mismatch of platforms between configuring the project and compiling the project. So, I guess it's always better to check if the platform and configuration is the same in such cases.
Additional Info : ( regarding the comments and the other answer to this question )
It doesn't matter if the directory included is rapidjson-master\include\rapidjson or rapidjson-master\include\. In the former we include the files as #include "document.h" and in the latter it would be #include "rapidjson/document.h".

A: For those that still have this problem, I realized after a while of debugging that the reason that the error occurs is because the file can't be found within the remote project directory - even if it exists and is included properly in your local Windows project.
In order for the remote project to compile properly with the 3rd party headers, they have to be copied over from your Windows directory.
I solved the problem like this:

*

*First, I added the rapidjson header files to my project in the Solution Explorer window. It seems that they have to be explicitly included there in order for Visual Studio to copy the files to your remote project directory. In order to maintain the directory structure of the rapidjson include directory, I added the headers in their appropriate "filters" (the folder icons) - see screenshot below (project name censored due to it being a company project):

*

*Then, I changed how I wrote the #include statement from #include "rapidjson\document.h" to "rapidjson/document.h" (i.e. use the Linux file path syntax).

*Finally, I rebuilt the project. It successfully copied the header files to the remote project and my source files can "find" them now.


text:
Q: python - get part of string from query results I have a small script which download me a results from query and export it to .csv
yy = raw_input("Enter year: ")
mm = raw_input("Enter month: ")

try:

    conn = psycopg2.connect("dbname='xxx' user='xxx' host='xxx' password='xxx'")
    cur=conn.cursor()

 query1 = """SELECT name FROM xxx where name like '%{0}_{1}%' """.format(yy,mm)
        cur.execute(query1)
        results = cur.fetchall()
        for row in results:
        print row

csv_file = open('errors.csv','wb')# wb - query importing line by line
myFile = csv.writer(csv_file)
myFile.writerows(results)
csv_file.close()

What i need is a part of string from query results. Atm my results looks like this:
1-GRB-804_2016_02_03__08_42_12
1-GRB-804_2016_02_05__11_04_47
1-GRB-804_2016_02_06__08_20_15
1-GRB-804_2016_02_08__08_06_13
1-GRB-804_2016_02_08__08_30_58

And what i want is to get first line untill it meet sign '_'.
So results will be :
1-GRB-804
1-GRB-804
1-GRB-804
1-GRB-804
1-GRB-804

Regards

A: You want to keep everything until the first "_", you can simply use string.split:
>>> s = '1-GRB-804_2016_02_03__08_42_12'
>>> s.split('_')
['1-GRB-804', '2016', '02', '03', '', '08', '42', '12']
>>> s = s.split('_')[0]
>>>> s
'1-GRB-804'

So in your case, you would need to do:
for row in results:
    print row.split('_')[0]


text:
Q: Why isn't my Gravatar image updating? I updated the image in my Gravatar but my old picture still shows up.
Is this a cache issue?
Do I need to log out and then log back in?

A: I've had problems where my browser (Safari) refused to update my Gravatar before, no matter how many times I refreshed. If you haven't, I suggest closing your browser, restarting it, and reloading your profile. If it still doesn't change, try flushing your cache, restarting, etc.
If that doesn't do it, I don't know what will, but it's definitely not StackOverflow's fault. I'd suggest filing a bug report with Gravatar.

A: All you have to do is:

*

*Go to your profile eg: https://meta.stackoverflow.com/users/149813/organicpanda

*Right click on your Gravatar and open the image in a new tab / window, for example: http://www.gravatar.com/avatar/a5128cde1e044a1cc9d4e8adee191f5a?s=128&d=identicon&r=PG

*Force a refresh (in Firefox CTRL + F5)

*You should see your new Gravatar. Go back to your profile and refresh.

This works because Gravatars are not stored on the website you're using - they're stored on Gravatar so you need to refresh your cache there and you're done.

A: There are multiple sources for this problem:

*

*One is using a different email address. (And note that though for Gmail addresses like johndoe@gmail, john.doe@gmail and john.doe+whatever@gmail are all the same, they are different addresses with different avatars for Gravatar.)

*Regular caching, in which Gravatar tells the browser to cache for 5 minutes. Just wait.

*Caching at Gravatar. Wait a bit more. (Some say one needs to log off too?)

*You might have set some explicit rating, or no rating at all, while Stack Exchange requests PG.

*Issues with the Gravatar CDN, which (like in July 2012) for some parts of the world might serve images that were actually changed weeks ago. Also, as Stack Exchange uses different formats (profile 128×128, user card 32×32, expanded user card 64×64), some sizes might then be okay, while others are not. Even problems like these might be solved by waiting a bit longer, or maybe uploading some new image might trigger a new synchronization. Regardless if that helps or not: I guess you'll need to contact their service desk, giving the details about the server you're using.
Some technical insight in CDN issues:
Peeking into the Server header in the HTTP response (using something like Chrome's Developer Tools or Firebug in Firefox) will reveal which server you're using.
Like using the Frankfurt EdgeCast server, a two week old 64×64 image might be just fine:
Cache-Control: max-age=300
Content-Disposition: inline; filename="a80f263bea9df760a7d8932cd415ce3e.jpeg"
Content-Type: image/jpeg
Date: Fri, 13 Jul 2012 12:23:04 GMT
Expires: Fri, 13 Jul 2012 12:28:04 GMT
Last-Modified: Fri, 29 Jun 2012 08:10:29 GMT
Server: ECS (fra/5950)

Here, Last-Modified: Fri, 29 Jun 2012 08:10:29 GMT is the date the avatar was changed. (For some time, it would use the subscription date, but that was solved.) But for the very same image, the 128×128 version might show a default avatar:
Cache-Control: max-age=300
Content-Type: image/png
Date: Fri, 13 Jul 2012 12:20:34 GMT
Expires: Fri, 13 Jul 2012 12:25:34 GMT
Last-Modified: Wed, 11 Jan 1984 08:00:00 GMT
Server: ECS (fra/5950)

Above, Last-Modified: Wed, 11 Jan 1984 08:00:00 GMT indicates it's a default, generated avatar. But for that very same image, the Amsterdam EdgeCast server might give the expected image:
curl --compressed --head \
  http://www.gravatar.com/avatar/a80f263bea9df760a7d8932cd415ce3e?s=128&d=identicon&r=PG

Cache-Control: max-age=300
Content-Disposition: inline; filename="a80f263bea9df760a7d8932cd415ce3e.jpeg"
Content-Type: image/jpeg
Date: Fri, 13 Jul 2012 12:34:32 GMT
Expires: Fri, 13 Jul 2012 12:39:32 GMT
Last-Modified: Fri, 29 Jun 2012 08:10:29 GMT
Server: ECS (ams/49DF)

Also, for the very same image but without the rating r=PG, the Frankfurt server might serve the expected image too:
Cache-Control: max-age=300
Content-Disposition: inline; filename="a80f263bea9df760a7d8932cd415ce3e.jpeg"
Content-Type: image/jpeg
Date: Fri, 13 Jul 2012 12:40:29 GMT
Expires: Fri, 13 Jul 2012 12:45:29 GMT
Last-Modified: Fri, 29 Jun 2012 08:10:29 GMT
Server: ECS (fra/5950)

Like said: report CDN problems to Gravatar.

A: You need to log out of Gravatar.
Gravatar doesn't seem to invalidate its cache until you are logged out. Either by doing so manually, or waiting for the session to expire (on their end).

I have actually prevented the cache from being invalidated, by continuing to visit http://gravatar.com everyday. I didn't realize at the time it was preventing the site from invalidating the cache.

A: You need to follow up with gravatar.com , not us.
That said, usually you just need to wait a few days.

A: The problem for me was that Safari was caching my profile image. It had already updated on Gravatar's site, but even when I reloaded my user profile my image didn't change. I ended up emptying the cache and restarting my browser, and that solved it.

A: Jeff Atwood has stated that gravatar images are cached, so if it hasn't been very long, wait and it should change eventually. I do not believe logging in and out would influence this at all, since your gravatar is shown to everyone, not just you. Your logging in and out (of Stack Overflow) should have no affect.
Interesting note: your user page has not been updated, however the image for this question and on the questions page has been. I'm sure the user page will catch up, I just thought it was interesting.

A: I'm one of the Happiness Engineers working with Gravatar right now. Someone kindly pointed us in the direction of this thread, so I thought I would stop in and just point out a few things.
First, you can always check your Gravatar for any email address at:
http://gravatar.com/site/check/
Enter your email address into the form and you can see how your Grav will appear to a site that requests it, including ratings.
We are currently investigating a caching problem that occurs when a default Gravatar is specified in the querystring of the image request ("d="). We know this is happening and hope to have it fixed soon.
In the meantime, if you need a forced refresh of your Gravatar cache please file a support request and we can do that for you.
If you have any other questions feel free to leave me a message or contact us at Gravatar.