text:
Q: SQL query to show all child record in 1 row? I have one to many relations. I want to show my child record in one row with parent record here is my query LIKE pivot table i want to show marks obtained by student in exams in 1 row depending on how many exams registered so in table 1 i have parent ID and in table 2 i have exam sub component like
parent exam viva and subcomponent viva 1 and viva 2
Now student query will have 2 columns exam1 marks and exam 2 marks that are marks of both viva in 1 exam So this will be in single line like
    student  | viva 1  | viva 2

I have ID of main exam that is 1 and component viva 1 and viva 2 ID is 21 , 22
Now marks save in marks table with  both ID's now i want to view them in single row that in exam viva marks is ?? and viva 2 marks???
SELECT DISTINCT
    A.S_RNo, A.S_SNo, C.S_SName, G.S_RID, A.Crs_SID, A. Enr_ID,
    0 AS M_ObtMarks
FROM
    tblAcdEnrol_Course A
INNER JOIN
    tblAcdStudent_Reg G ON A.S_RNo = G.S_RNo
INNER JOIN
    tblAcdStudent C ON A.S_SNo = C.S_SNo
LEFT OUTER JOIN
    tblAExPolicy_1 D ON A.ESec_T_ID = D.ESec_T_ID
LEFT OUTER JOIN
    tblAExPolicy_2 E ON D.AEx_ID = E.AEx_ID
CROSS APPLY
    (SELECT DISTINCT
         A.S_RNo, A.S_SNo, S_SName, S_RID, Crs_SID, B.AEx2_ID,
         C.ESec_T_ID, Enr_ID, ISNULL(M_ObtMarks, 0) AS M_ObtMarks
     FROM
         tblAExMarks_1 A
     INNER JOIN
         tblAExPolicy_2 B ON A.AEx2_ID = B.AEx2_ID
     INNER JOIN
         tblAExPolicy_1 C ON B.AEx_ID = C.AEx_ID
     INNER JOIN
         tblAcdStudent_Reg D ON A.S_RNo = D.S_RNo
     INNER JOIN
         tblAcdEnrol_Course E ON E.S_RNo = A.S_RNo
     INNER JOIN
         tblAcdStudent F ON F.S_SNo = A.S_SNo)V
     WHERE
         V.ESec_T_ID = 6
         AND V.Crs_SID <> 2
         AND V.AEx2_ID = 1

not working
currently
       1    21  5.0
       1    21  10.0
       1    21  10.0
       2    21  4.0
       2    21  10.0
       2    21   8.0

I want
       1    21  5.0 10.0 10.0
       2    21  4.0 10.0  8.0

picture
problem pic

A: You can use pivot on your output data as below:
;with cte as (
SELECT   DISTINCT    A.S_RNo , A.S_SNo, C.S_SName, G.S_RID,A.Crs_SID   , A. Enr_ID,0 AS M_ObtMarks,
RowN = Row_number() over (Partition by A.S_RNo, A.S_SNo order by A.S_RNo)
 FROM tblAcdEnrol_Course A
 INNER JOIN tblAcdStudent_Reg G ON A.S_RNo = G.S_RNo
 INNER JOIN tblAcdStudent C ON A.S_SNo = C.S_SNo
 LEFT OUTER JOIN tblAExPolicy_1 D ON A.ESec_T_ID = D.ESec_T_ID
 LEFT OUTER JOIN tblAExPolicy_2 E ON D.AEx_ID = E.AEx_ID

 CROSS APPLY (
 SELECT   DISTINCT    A.S_RNo , A.S_SNo, S_SName, S_RID, Crs_SID ,B. AEx2_ID , C.ESec_T_ID , Enr_ID,ISNULL(M_ObtMarks , 0) AS M_ObtMarks
 from tblAExMarks_1 A
 inner join tblAExPolicy_2 B on A.AEx2_ID = B.AEx2_ID
 inner join tblAExPolicy_1 C on B.AEx_ID = C.AEx_ID
 inner join tblAcdStudent_Reg D ON A.S_RNo = D.S_RNo
 INNER JOIN tblAcdEnrol_Course E ON E.S_RNo = A.S_RNo
 INNER JOIN   tblAcdStudent F ON F.S_SNo = A.S_SNo)V
  WHERE V.ESec_T_ID  =  6  AND V.Crs_SID <> 2   and  V.AEx2_ID = 1
)
select * from cte
pivot (max(M_ObtMarks) for RowN in ([1],[2],[3]) ) p


text:
Q: C - Open and read all files in specific folder to store text in variables I am having difficulty finding a way to open and read all files in a specific directory and also i don´t understand the relation between -> and pointers. I am able to easily operate with files when I know their name, but I haven't found a way to do it when I don't. As I said above what I want to do is read all the files (of a known directory) and store strings of those files in variables.
scan a directory to find files in c was referenced but my knowledge isn't enough to understand most of those commands, so if it is possible to do such a thing in a simpler way, please help
Bellow you can find the code I used to read a specific file.
    printf("Insert the name of the product to look for: ");
    char tmp_prodname4[50];
    scanf(" %[^\n]%*c",tmp_prodname4);
    char filenameProd4[50];
    char fullpathProd4[200];
    char cwdProd4[200];
    char pathProd4[200];

    if (getcwd(cwdProd4, sizeof(cwdProd4)) == NULL)
    {
        erro();
        produtos(tmpUsername,tmpPassword);
    }
    strcat(cwdProd4,"\\products\\");
    strcpy(pathProd4, cwdProd4);
    strcpy(filenameProd4, strcat(strlwr(tmp_prodname4), ".txt"));
    strcpy(fullpathProd4, strcat(pathProd4, filenameProd4));
    if( access( fullpathProd4, F_OK ) != 0 )
    {
        erro();
        produtos(tmpUsername,tmpPassword);
    }
    else //When i can access
    {
        clrscr();
        authFileProdC = fopen(fullpathProd4,"r");
        fscanf(authFileProdC, "Name: %s\n", p.nome);
        fscanf(authFileProdC, "Reference: %s\n", p.referencia);
        fscanf(authFileProdC, "Quantity in X: %d\n",&p.quantidade[1]);
        fscanf(authFileProdC, "Quantity in Y: %d\n",&p.quantidade[2]);
        fscanf(authFileProdC, "Quantity in Z: %d\n",&p.quantidade[3]);
        fscanf(authFileProdC, "Price: %fEUR.unid\n",&p.precoporunidade);
        fclose(authFileProdC);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to locate Spring NamespaceHandler i am creteing maven project and i got some error which im amntn below
Unable to locate Spring NamespaceHandler
org.springframework.web.context.ContextLoader initWebApplicationContext: Context initialization failed
        org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
        Offending resource: ServletContext resource [/WEB-INF/applicationContext.xml]

A: you need to add spring-security-config dependency into your pom.xml, you can find it below. and you can also refer 4.2.3.RELEASE but you need to use only version which match your other spring version, you can find it form below link:
https://mvnrepository.com/artifact/org.springframework.security/spring-security-config
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>3.0.1.RELEASE</version>
</dependency>


text:
Q: Finding classes tagged with a custom attribute doesn't work I've used the code from another answer to find classes in an assembly that are tagged with a specific custom attribute:
var allClasses = tpAssy.GetTypes();

var testClasses = from t in tpAssy.GetTypes()
                  let attributes = t.GetCustomAttributes(typeof(TestClassAttribute), true)
                  where attributes != null && attributes.Length > 0
                  select new { Type = t, Attributes = attributes.Cast<TestClassAttribute>() };

However, in my test-case assembly I can see that allClasses lists 4 classes, of which three are tagged with the custom attribute (TestClassAttribute) that I am interested in. but the second Linq query assigned to testClasses returns an empty enumeration.
Here's the code header for one such class:
[TestClass()]
public class BaseSessionTest
{...

This is VS2013 with .Net 4.5.
What gives?

A: It's a .Net framework issue. The assembly being loaded was compiled using Visual Studio 2008 (.Net 3.5) and the application that isn't working is .Net 4.6 in Visual Studio 2013. In the latter, reflection clearly doesn't work completely with .net assemblies compiled using earlier frameworks. Is that a bug or is there a secret trick you have to know?


text:
Q: Is there any way to get the 206px version of a photo via the Facebook Graph API? I'm trying to get version of a photo that FB uses as the background image for album layouts where one side is always exactly 206px and the other one at least the same, for example https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xpa1/v/t1.0-9/p206x206/10401476_409218399235620_1454525834273554679_n.jpg?oh=eda59fce63113796b35c46cc4bec162a&oe=55760EFD&gda=1433681435_6b4729404e05493108c271a50c753d7f I've scoured both the graph and SO, but am having absolutely no luck here. I'm aware that you can get 3 versions of a photo using type=album/thumbnail/normal ie https://graph.facebook.com/409218399235620/picture?type=album (you'd think this one would work, but they probably never updated it to redirect to the new size?). I've tried all kinds of variants of this knowing that the graph documentation is pretty crap, to no avail.
I've also used the Explorer to for example pull up ?fields=images, but it's never one of the listed images there. I've tried using widths, replacing parts of the URL etc. etc. I am running the checks with a valid access_token.
I've pretty much resigned myself to just resizing myself, but given the time I've spent on this, I thought I'd at least put it out there in case someone else has had the same problem, and come up with a solution.


text:
Q: Фокус в элементах при открытом Bootstrap Modal Есть демка, в которой показывается открытие одного модала поверх другого. В правом верхнем углу я добавил текстовое поле. Проблема с тем, что в это текстовое поле не ставится фокус (и каретка не появляется) по клику на него, если открыт модал.
Причем я заметил такую особенность. Сначала когда открываю первый модал - фокус не ставится. Когда открываю второй модал (кнопка "Open FG modal"), то фокус начинает ставится. После закрытия второго модала фокус продолжает ставится в поле.
Задача: сделать так, чтобы всегда можно было поставить фокус в текстовое поле, если открыт модал.
P.S. Спрашиваю не для любопытства, это смоделированная ситуация в моем приложении.
A: Причина такого поведения - tabindex="-1", но если его убрать, то не срабатывает закрытие по esc, в общем я смог починить только по click
$('.fixed').bind('click.$',function() {$(this).focus();});

демо


text:
Q: How to query mysql to select and group by multiple values I'm trying to select and group by all the contentid values of the table below where the match criteria can be several different values.
the contentid values actually represent cars, so I need to select [and group by] all the contentis where the values are 'GMC' and the values are 'sedan' and the value is 'automatic.
i.e. I'm trying to select all the GMC sedans with an automatic transmission.
a query like this fails [obviously]:
select * from modx_site_tmplvar_contentvalues WHERE
`value` = 'gmc' and
`value` = 'tacoma'
group by contentid

I have no idea how to create a query like that. Any suggestions?

A: You need to "pivot" these data on "tmplvarid", but unfortunately for you MySQL doesn't have a PIVOT statement like other RDBMS. However, you can pivot it yourself by joining in the table multiple times for each variable you care about:
SELECT
    contents.contentid,
    transmission.value as transmission,
    type.value as type,
    make.value as make
FROM
    (SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
LEFT JOIN
    modx_site_tmplvar_contentvalues AS transmission
        ON contents.contentid = transmission.contentid
        AND transmission.tmplvarid = 33 -- id for transmission
LEFT JOIN
    modx_site_tmplvar_contentvalues AS make
        ON contents.contentid = make.contentid
        AND make.tmplvarid = 13 -- id for make
LEFT JOIN
    modx_site_tmplvar_contentvalues AS type
        ON contents.contentid = type.contentid
        AND type.tmplvarid = 17 -- id for type
WHERE
    type.value = 'sedan'
    AND make.value = 'GMC'
    AND transmission.value = 'automatic'

You can expand this with additional joins for other criteria such as year (id 15) or mileage (id 16).
If you need to use the value only, you could try:
SELECT DISTINCT
    contents.contentid,
    transmission.value as transmission,
    type.value as type,
    make.value as make
FROM
    (SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
INNER JOIN
    modx_site_tmplvar_contentvalues AS transmission
        ON contents.contentid = transmission.contentid
        AND transmission.value = 'automatic'
INNER JOIN
    modx_site_tmplvar_contentvalues AS make
        ON contents.contentid = make.contentid
        AND make.value = 'GMC'
INNER JOIN
    modx_site_tmplvar_contentvalues AS type
        ON contents.contentid = type.contentid
        AND type.value = 'sedan'

In any case, make sure you have an index on the value column; these queries are going to get slow.

A: please try this:
SELECT *
FROM modx_site_tmplvar_contentvalues t1 INNER JOIN modx_site_tmplvar_contentvalues t2 ON t1.contentid = t2.content_id
WHERE
  t1.`value` = 'gmc'
  AND t2.`value` = 'tacoma';

A: This is always false:

`value` = 'gmc' and
  `value` = 'tacoma'

Instead, use OR:

`value` = 'gmc' OR
  `value` = 'tacoma'

In a condition "and" means "this and this is true at the same time". If you want all foos and all bars, then your condition is "foo OR bar".
EDIT:
To select groups containing your values, you can write subqueries:
SELECT DISTINCT name FROM table WHERE name IN (SELECT name FROM table WHERE value='value1') AND name IN (SELECT name FROM table WHERE value='value2')

A: You can do this with a group by.  This is the most flexible in terms of expressing the conditions.  In MySQL, multiple joins will often perform better:
select contentid
from modx_site_tmplvar_contentvalues
group by contentid
having sum(`value` = 'gmc') > 0 and
       sum(`value` = 'tacoma') > 0;


text:
Q: Integer programming problem. I do not know the integer programming problem. I am reading a paper (1 below) which makes the following claim for the problem P1. I have two questions regarding this claim which I will post after posting the problem from the paper.

Problem (P1) is a three-dimensional integer programing problem whose solution space is in the size of $2^{NM(K+2)}$.
My questions are:
1. Why is the problem P1 a 3D problem? P1 is given in the image with this post.
2. Why is the solution space $2^{NM(K+2)}$? I understand that without know N,M, or K no one can give me an answer about this solution space. But I want to know how is the size of the solution space found by the authors?
$[1]$ Multi-Server Multi-User Multi-Task Computation Offloading for Mobile Edge Computing Networks

A: *

*It's a 3D problem because $a_{nmk}$ has three subscripts, so that $a\in \lbrace 0,1 \rbrace^{N\times M\times K}$ where $N=|\mathcal{N}|$ etc.

*Assuming that everything other than the $a$ variables is a constant, I don't know where they get $2^{NM(K+2)}$ for the size of the solution space. Ignoring (13c), the size of the solution space would be $2^{NMK}$. Assuming that (13c) holds for all $m\in\mathcal{M}$ and $n\in\mathcal{N}$ (the presentation is mathematically sloppy), the feasible portion of the solution space would have size $K^{NM}$. (For each combination of $n$ and $m$, you would have $K$ ways to satisfy (13c), and choices for one $n,m$ pair would be independent of choices for other pairs.)


text:
Q: Not Getting Custom Nameservers Using Godaddy Api I used this api call to get DNS records and nameservers using domain name
https://api.godaddy.com/v1/domains/testsd34.com/records/NS
GetRecords here is the api call
For default godaddy nameservers its giving everything perfectly but whenever i am using custom nameservers for domain that time this api call not giving nameservers in response its giving empty array,
 anyone knows how to get custom nameservers using this api call?

A: Finally, I found a way to get and edit nameservers for domain.
(For custom nameservers, records are not set by GoDaddy, therefore you have to
query nameserver provider.)
Following is the API call for getting nameservers:
HTTP request:
GET https://api.godaddy.com/api/v1/domains/mydomain.com
HTTP headers:
Authorization -> sso-key my-key:my-secret
Content-Type  -> application/json

Response will contain JSON object which has key "nameservers"
with pair of nameservers that you have. Example:
"nameServers": [
    "ns1.mynameservers.com",
    "ns2.mynameservers.com"
]

To edit the nameservers via API call, you can use following API call:
HTTP request:
PATCH https://api.godaddy.com/api/v1/domains/mydomain.com
HTTP headers:
Authorization -> sso-key my-key:my-secret
Content-Type  -> application/json
HTTP body:
{
  "nameServers": [
     "ns3.mynameservers.com",
     "ns4.mynameservers.com"
  ]
}


text:
Q: How to invoke a web service from a stand alone Java client? I have an echo web service running on lets say http://localhost:8080/axis2/services/Service1. This service just echos back a string that is sent to it through the function echo(). Using the wsdl of the above mentioned service (Service.wsdl), I have generated (in eclipse) the ServiceStub.java and the ServiceCallbackHandler.java. With these two files, how can I write a client which will invoke echo(String some_word) and receive the response back? Thanks.

A: If you simply want to test/exercise your web service, I recommend SOAPUI - http://www.soapui.org/
Point it at your WSDL and it will allow you to call your Web Service methods.

A: Check Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2, starting from step 27.

A: Something like this:
(see also: Axis2 Web Service (Tomcat v6)
package com.gg.ws;

import java.rmi.RemoteException;

import com.gg.ws.ServiceStub.Echo;
import com.gg.ws.ServiceStub.EchoResponse;

public class WebServiceTest {

    public void callEcho() throws RemoteException {

        ServiceStub stub = new ServiceStub();

        Echo request = new Echo();
        request.setValue("Whatever");
        EchoResponse response = stub.echo(request);
        System.out.println(" echo call   response: " + response.get_return());
    }
}


text:
Q: Copy file names to another folder I need to copy file names from one folder to another. File contents are never changed. No files are overwritten, moved or copied. It's only about file names.
I have a folder A with files named:

*

*Show - S01E01 - Descriptive title.mkv

*Show - S01E02 - Another descriptive title?.mkv

*Show - S01E03 - Another complex name!.mkv

*...

I have a folder B with files named:

*

*show.s01e01.mkv

*show.s01e02.mkv

*show.s01e03.mkv

*...

I don't need the files in folder A anymore because the files in folder B have a better quality. But I don't want to manually rename all files in folder B to have the proper file name including the episode title. I would like to automatically transfer the proper file names from the files in folder A to the files in folder B. The alphabetical order is identical in both folders. So the nth file in folder B corresponds to the nth file in folder A. In the end folder B would contain exactly the same file names as in folder A but the files contents are different of course.
Example:
Before:
Folder A:

*

*Show - S01E01 - Green Apples.mkv

*Show - S01E02 - Peaches in the Sky.mkv

Folder B:

*

*show.s01e01.mkv

*show.s01e02.mkv

After:
Folder A:

*

*Show - S01E01 - Green Apples.mkv

*Show - S01E02 - Peaches in the Sky.mkv

Folder B:

*

*Show - S01E01 - Green Apples.mkv

*Show - S01E02 - Peaches in the Sky.mkv

How do i do this in Bash? (Or any other GNU/Linux tool, KDE OK too)

A: To do what you want would take some scripting.  Not too involved, but it is re-inventing the wheel a bit.
What I would suggest is installing tvnamer https://github.com/dbr/tvnamer
This will use a database to consistently rename all of your media.  If you run this across everything then both the low and high quality shows will have the same name, so you can just copy over the high quality ones over the low quality ones with cp.

A: You can try bash arrays. I am giving a skeletal solution below.
cd $DIR1
list1=( * )

cd $DIR2
i=0
for f in *
do
  mv $f ${list1[$i]}
  (( i += 1 ))
done

As you have mentioned in the question the assumption is that exact number of files are in both directories and alphabetically they are in order. More error checking and may be pattern matching can be done to make it robust.
list1 is an array with the filenames in that directory. ${list1[0]} is the first element in the array, etc. I am not sure if this will work with filenames with whitespaces, etc.


text:
Q: невозможно создать экземпляр абстрактного класса Задача:
Создать абстрактный базовый класс Pair с виртуальными арифметическими операциями. Реализовать
производные классы Complex и Rational
Моё примерное решение:
#pragma once
class Rational;
class Complex;
class Pair
{
public:
    virtual Rational& operator +=(const Rational& pr) = 0;
    virtual Rational& operator -=(const Rational& pr) = 0;
    virtual Rational& operator *=(const Rational& pr) = 0;
    virtual Rational& operator /=(const Rational& pr) = 0;

    virtual Complex& operator +=(const Complex& pr) = 0;
    virtual Complex& operator -=(const Complex& pr) = 0;
    virtual Complex& operator *=(const Complex& pr) = 0;
    virtual Complex& operator /=(const Complex& pr) = 0;
};

Rational.h
#include <iostream>
#include <numeric>
#include "Pair.h"

class Rational : public Pair
{
private:
    int numerator;
    unsigned int denominator;
    unsigned int gcd(int n1, int n2);
public:
    Rational()noexcept;
    Rational(const int &numerator, const unsigned int &denominator);
    Rational& operator +=(const Rational& rt)override;
    Rational& operator -=(const Rational& rt)override;
    Rational& operator *=(const Rational& rt)override;
    Rational& operator /=(const Rational& rt)override;
    friend Rational& operator + (const Rational& rt, const Rational& rt2);
    friend Rational& operator - (const Rational& rt, const Rational& rt2);
    friend Rational& operator * (const Rational& rt, const Rational& rt2);
    friend Rational& operator / (const Rational& rt, const Rational& rt2);
};

#include <iostream>
#include "Pair.h"
#include "Rational.h"

using namespace std;

int main()
{
    Rational rat;
             ^^^
    Rational f(15, 5);
             ^
    Rational s(16, 8);
             ^
}

Не абстрактный Rational вдруг стал абстрактным?

A: Возможно подразумевается такое решение.
template <class T>
class Pair
{
public:
    virtual Pair& operator +=(const T& pr) = 0;
    virtual Pair& operator -=(const T& pr) = 0;
    virtual Pair& operator *=(const T& pr) = 0;
    virtual Pair& operator /=(const T& pr) = 0;
};

class Rational : public Pair<Rational>
{
private:
    int numerator;
    unsigned int denominator;
    unsigned int gcd(int n1, int n2);
public:
    Rational()noexcept;
    Rational(const int &numerator, const unsigned int &denominator);
    Rational& operator +=(const Rational& rt) override;
    Rational& operator -=(const Rational& rt) override;
    Rational& operator *=(const Rational& rt) override;
    Rational& operator /=(const Rational& rt) override;
};

A: Например, для класса Rational вы не определили функции
virtual Complex& operator +=(const Complex& pr) = 0;
virtual Complex& operator -=(const Complex& pr) = 0;
virtual Complex& operator *=(const Complex& pr) = 0;
virtual Complex& operator /=(const Complex& pr) = 0;

Поэтому класс Rational по-прежнему остается абстрактным.
Аналогичная проблема имеет место для класса Complex, в котором не определены операторы для объектов класса Rational.
Абстрактный класс Pair не должен содержать ссылки на классы Rational и Complex. Вы должны в классе Pair объявить операторы для объектов ссылочных типов Pair. Также, как следует из названия самого класса, класс Pair должен содержать по крайней мере два члена данных, которые будут использоваться в классах Rational и Complex.
Классы могут выглядеть примерно следующим образом. как показано в демонстрационной программе ниже.
#include <iostream>

class Pair
{
public:
    Pair( int first, int second ) : first( first ), second( second )
    {
    }

    Pair() : Pair( 0, 0 )
    {
    }

    virtual Pair & operator +=( const Pair & ) = 0;
/*
    virtual Pair & operator -=( const Pair & ) = 0;
    virtual Pair & operator *=( const Pair & ) = 0;
    virtual Pair & operator /=( const Pair & ) = 0;
*/
protected:
    int first, second;
};

class Complex : public Pair
{
public:
    Complex( int real, int image ) : Pair( real, image )
    {
    }

    Complex() : Complex( 0, 0 )
    {
    }

    Complex & operator +=( const Pair &p ) override
    {
        const Complex &c = reinterpret_cast<const Complex &>( p );

        this->first += c.real();
        this->second += c.image();

        return *this;
    }
/*
    Complex & operator -=( const Pair & ) override;
    Complex & operator *=( const Pair & ) override;
    Complex & operator /=( const Pair & ) override;
*/
    int real() const { return this->first; }
    int image() const { return this->second; }
};

int main()
{
    Complex c( 10, 10 );

    c += Complex( 5, 5 );

    std::cout << "{ " << c.real() << ", " << c.image() << " }\n";

    return 0;
}

Вывод программы на консоль:
{ 15, 15 }

Если хотите объявить класс Pair, как класс, зависящий от шаблонного параметра, то определение класса Pair может выглядеть так, как показано в следующей демонстрационной программе.
#include <iostream>

template <class T>
class Pair
{
public:
    Pair( const T &first, const T &second ) : first( first ), second( second )
    {
    }

    Pair() : Pair( T(), T() )
    {
    }

    virtual Pair & operator +=( const Pair & ) = 0;
/*
    virtual Pair & operator -=( const Pair & ) = 0;
    virtual Pair & operator *=( const Pair & ) = 0;
    virtual Pair & operator /=( const Pair & ) = 0;
*/
protected:
    T first, second;
};

template <class T>
class Complex : public Pair<T>
{
public:
    Complex( const T &real, const T &image ) : Pair<T>( real, image )
    {
    }

    Complex() : Complex( T(), T() )
    {
    }

    Complex & operator +=( const Pair<T> &p ) override
    {
        const Complex &c = reinterpret_cast<const Complex &>( p );

        this->first += c.real();
        this->second += c.image();

        return *this;
    }
/*
    Complex & operator -=( const Pair<T> & ) override;
    Complex & operator *=( const Pair<T> & ) override;
    Complex & operator /=( const Pair<T> & ) override;
*/
    const T & real() const { return this->first; }
    const T & image() const { return this->second; }
};

int main()
{
    Complex<int> c( 10, 10 );

    c += Complex<int>( 5, 5 );

    std::cout << "{ " << c.real() << ", " << c.image() << " }\n";

    return 0;
}

A: В С++ если, ты не переопределяешь чисто виртуальные методы в производном классе, то он считается тоже абстрактным


text:
Q: How to solve this equation - $\sqrt{3-x}\geq 1+\sqrt{x}$ $$\sqrt{3-x}\geq 1+\sqrt{x}$$
The second square $(\sqrt{x})$ give me problems.
Solution must be:
$$0\leq x <\dfrac{3-\sqrt{5}}{2}$$

A: If we assume that $\sqrt{x}\,$ is the positive root of $x$, then we can square both sides of the inequality:
$$3 - x \geq 1 + 2 \sqrt{x} + x$$
Next we write $y = \sqrt{x}\,$, and rearrange this equation, which gives
$$y^2 + y - 1 \geq 0$$
We can use the quadratic equation to find the roots of $y^2 + y - 1 = 0$:
$$y = \frac{-1 \pm \sqrt{5}}{2}$$
But remember that $\sqrt{x}\,$ is positive, so we can only take the positive root. Thus
$$0 \leq \sqrt x \leq \frac{-1 + \sqrt 5}{2}$$
Now squaring throughout (which doesn't introduce spurious solutions, because everything is non-negative), we get
$$0 \leq x \leq \left(\frac{-1 + \sqrt 5}{2}\right)^2 = \frac{3-\sqrt 5}{2}$$
Note
The quoted form of your solution is incorrect (or at least, inconsistent with the stated inequality). If the original inequality is non-strict, then so is the final solution.
However, if the original inequality is strict; that is, if it takes the form
$$\sqrt{3-x} > 1 + \sqrt x$$
then we carry a strict inequality for the upper bound on $x$ throughout; the non-strict bound on zero comes because we need $x \geq 0$, or $\sqrt{x}\,$ doesn't make sense. (At least, not in the context of inequalities.)

A: $$\sqrt{3-x}\geq 1+\sqrt{x}\\
\implies 3-x\geq 1+x+2\sqrt{x}\\
\implies 2(\sqrt{x})^2+2\sqrt{x}-2\leq0\\
\implies (\sqrt{x})^2+\sqrt{x}-1\leq0$$
Use the quadratic formula.


text:
Q: Publishing Kafka message to Elastic search I have a process that is writing a JSON data object from Kafka and putting some of the fields from this object via the elastic API into elastic search index.
I have to write two separate messages - one for the data object and another for the Elastic search index which is a subset of the data object.
My question is this:
Can I augment the JSON metamodel so that I publish only one record format from Kafka, which contains both the full data object and the indexable fields, but only the indexable fields are loaded into Elastic search? Then I don't have to maintain two separate processes and keep them both synced up, I just have one process and JSON record.
I am not batch loading, so I cannot use the Bulk load API and 'index' field marker that this tool uses like this
JSON bulk load API example


text:
Q: R grouping data by numeric numbers in a column I am trying to group data by numbers in a column, I have tried different versions of
group_by, cut, group etc but I have not been able to get it.
I have a lot of data that looks like this:
  position variants

     3      snv
     5      snv
    12      snv
    17      mnv
    22 deletion
    27      snv
    33      snv
    35      snv
    42      snv
    46      mnv
    50      snv
    53 deletion
    60      snv
    62      snv
    65      snv
    70      snv

variants <- c(rep("snv", 3),rep("mnv", 1),rep("deletion", 1),rep("snv", 4), "mnv", rep("snv"), "deletion", rep("snv", 4))
variants
position = c(3, 5, 12, 17, 22, 27, 33, 35, 42, 46, 50, 53, 60, 62, 65, 70)
position
patient1 = data.frame(position, variants)
patient1

I would like to be able to group the data
something like this:
group  tally
1-10    2snv
11-20   1snv 1mnv
21-30   1deletion 1snv
31-40   2snv
etc

so that i can run further downstream analysis.
And be able to change it to
groups of 1-5 or 1-2 etc.
thank you very much

A: Here a pure R solution. Of course you can replace variables by their corresponding calls:
variants <- c(rep("snv", 3),rep("mnv", 1),rep("deletion", 1),rep("snv", 4), "mnv", rep("snv"), "deletion", rep("snv", 4))
position = c(3, 5, 12, 17, 22, 27, 33, 35, 42, 46, 50, 53, 60, 62, 65, 70)
patient1 = data.frame(position, variants)

labels = cut(position, seq(0, max(position), 10))
groups = split(patient1 , labels)
lapply(groups , function(x) {
  paste( table(x$variants), names(table(x$variants)), collapse = ", " )
      }
  )

A: We can use tidvyerse to do a group by operation.  Create a group of ranges with cut, summarise the frequency count based on the cut and the 'variants', then paste them together in summarise
library(dplyr)
patient1 %>%
   group_by(group = cut(position, breaks = c(-Inf, seq(1, 100,
       by = 10))), variants) %>%
   summarise(n = n()) %>%
   summarise(tally = paste(n, variants, collapse=' ', sep=""))

NOTE: Another option is findInterval which does similar option as cut but without the labels as it will output numeric index

A: In base R, you can create a group column using findInterval making groups of every 10 positions. We can then use aggregate and combine the count of variants with the variants to create one string for each group.
patient1$group <- with(patient1, findInterval(position, (seq(0, max(position), 10))))

aggregate(variants~group, patient1, function(x) {
  tb <- table(x)
  paste(tb, names(tb), collapse = ' ')
})

#  group         variants
#1     1            2 snv
#2     2      1 mnv 1 snv
#3     3 1 deletion 1 snv
#4     4            2 snv
#5     5      1 mnv 1 snv
#6     6 1 deletion 1 snv
#7     7            3 snv
#8     8            1 snv


text:
Q: How to check a string starts with numeric number? I have a string which contains alphanumeric character.
I need to check whether the string is started with number.
Thanks,

A: This should work:
String s = "123foo";
Character.isDigit(s.charAt(0));

A: Sorry I didn't see your Java tag, was reading question only. I'll leave my other answers here anyway since I've typed them out.
Java
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
    System.out.println("String begins with a digit");
}

C++:
string myString = "2Hello World!";

if (isdigit( myString[0]) )
{
    printf("String begins with a digit");
}

Regular expression:
\b[0-9]

Some proof my regex works: Unless my test data is wrong?

A: I think you ought to use a regex:

import java.util.regex.*;

public class Test {
  public static void main(String[] args) {
    String neg = "-123abc";
    String pos = "123abc";
    String non = "abc123";
        /* I'm not sure if this regex is too verbose, but it should be
         * clear. It checks that the string starts with either a series
         * of one or more digits... OR a negative sign followed by 1 or
         * more digits. Anything can follow the digits. Update as you need
         * for things that should not follow the digits or for floating
         * point numbers.
         */
    Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
    Matcher matcher = pattern.matcher(neg);
    if(matcher.matches()) {
        System.out.println("matches negative number");
    }
    matcher = pattern.matcher(pos);
    if (matcher.matches()) {
        System.out.println("positive matches");
    }
    matcher = pattern.matcher(non);
    if (!matcher.matches()) {
        System.out.println("letters don't match :-)!!!");
    }
  }
}

You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.

A: See the isDigit(char ch) method:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html
and pass it to the first character of the String using the String.charAt() method.
Character.isDigit(myString.charAt(0));

A: System.out.println(Character.isDigit(mystring.charAt(0));

EDIT: I searched for java docs, looked at methods on string class which can get me 1st character & looked at methods on Character class to see if it has any method to check such a thing.
I think, you could do the same before asking it.
EDI2: What I mean is, try to do things, read/find & if you can't find anything - ask.
I made a mistake when posting it for the first time. isDigit is a static method on Character class.

A: Use a regex like ^\d


text:
Q: returned array referencing the same memory spot but returning different values I'm setting up a basic dynamic web page to display EC2 instance data and I need to be checking and passing arrays with the data inside to display with D3. Im using multiprocess to run the collection in the background.
Running python3.7 and the newest version of Flask.
app.py Code
    @app.route('/experiment')
    def experiment():
        type = request.args.get('type')
        resource = request.args.get('resource')
        action = request.args.get('action')
        if 'test' not in session:
            thread = multiprocessing.Process(target=exp.transmitTest)
            session['test'] = 'started'
            thread.start()
        print(f"Looking for Data at {hex(id(exp.getData()))} found {exp.getData()}")
        return render_template('experiment.html',  data=exp.getData(), type=request.args.get('type'), resource=request.args.get('resource'), action=request.args.get('action'))

Backend Code
    def transmitTest(self):
        for i in range(5):
            self.data.append(random.randint(0,100))
            time.sleep(4)
            print(f"Data: {self.data} at {hex(id(self.data))}")

    def getData(self):
        return self.data

My JS scheduler runs '/experiment' every 5 seconds. The print statements show that the array im writing to and getting from the getter are at the same memory space, but one is empty and the other has the data. Can anyone help me understand this?

A: so I figured it out. When calling object methods in processes in flask python creates copies of the objects and then differentiates between the two copies even if they do take up the same memory space. I needed to add a backend queue through redisqueue (https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxii-background-jobs) so that I could make asynchronous calls to my backend without disrupting flask's routing.


text:
Q: AJAX keeps on calling the same page's URL instead of the API URL I'm using Symfony version 3.* and I am using tetranz/select2entity-bundle to have Select2 to select assets to be assigned to users.
For some reason, AJAX keeps on calling the same page URL when trying to get the JSON output from an API URL.
URL should be:

http://127.0.0.1:8000/asset/api/asset_list

But the URL used is:

http://127.0.0.1:8000/user/1?field_name=assets

/**
 * Lists all asset entities.
 *
 * @Route("/api/asset_list", name="api_asset_list")
 * @Method({"GET", "POST"})
 */
public function apiAssetListAction()
{
    $em = $this->getDoctrine()->getManager();
    $assets = $em->getRepository('AppBundle:Asset')->findAll();

    foreach($assets as $asset)
            $itemArray[] = array('id' => $asset->getId(),'text' => $asset->__toString(),);

    return new Response(json_encode($itemArray), 200, array('Content-Type' => 'application/json'));
}

$builder->add('assets', Select2EntityType::class, [
                    'multiple' => true,
                    'remote_route' => 'api_asset_list',
                    'class' => 'AppBundle::Asset',
                    // 'primary_key' => 'id',
                    'text_property' => 'code',
                    'minimum_input_length' => 2,
                    'page_limit' => 10,
                    'allow_clear' => true,
                    'delay' => 250,
                    'cache' => true,
                    'cache_timeout' => 60000, // if 'cache' is true
                    'language' => 'en',
                    'placeholder' => 'Select assigned assets',
                    // 'object_manager' => $objectManager, // inject a custom object / entity manager
                ]);

My Twig Code is as simple as this since I am using the Form Builder of Symfony to do the work for me:

Assign Assets

                {{form_start(assign_form)}}
                {{form_widget(assign_form)}}
                <input class = "btn btn-block btn-success" type="submit" value="Assign" />
                {{form_end(assign_form)}}

I also included this template in in my twig:form_themes configuration:

TetranzSelect2EntityBundle:Form:fields.html.twig

My list of JS Scripts used:

I hope you guys can help.


text: Q: Find all the properties of tetrahedron if the lengths of all the edges are known. The task here seems simple but is, in fact, something that I don't really know how to solve. Say, you have a tetrahedron with edges of 2, 3, 4, 5, 6 and 7. The easiest here would be to calculate the surface area by using Heron's formula. But then for the volume, you need to either somehow calculate the length of one of the heights, or find a formula similar to Heron's one, that would let you calculate the volume by either using edges or sides. Does anyone have an idea about how to do that?


text:
Q: ¿Problema con cubo olap? estoy realizando un cubo olap en visual studio 2017, pero al procesar el cubo me sale este error:

No se puede implementar el proyecto en el servidor 'localhost' debido a los siguientes problemas de conexión:
  'No se puede establecer una conexión. Asegúrese de que el servidor se esté ejecutando.'.
  Para comprobar o actualizar el nombre del servidor de destino, haga clic con el botón derecho del mouse (ratón) en el proyecto en el Explorador de soluciones, seleccione Propiedades del proyecto, haga clic en la pestaña Implementación y especifique el nombre del servidor.

¿Cómo puedo resolverlo?

hice todo lo que me sugirieron, pero me sigue saliendo error

A: Como el error indica, debes de comprobar o actualizar el nombre del servidor de destino
Para ello debes de hacer click derecho sobre tu proyecto e ir a las propiedades:

Una vez ahí, accede a la sección de  implementación, y verifica que el nombre de la base de datos y del servidor sea igual a las instancias de SQL Server:

Puntos a considerar: La instancia del servidor SQL a donde te conectas tiene que tener instalada la característica de SQL Server Analysis Services (SSAS), para ello la edicion de SQL Server debe de ser Standar o Enterprise.
Si ya cuentas con lo anterior,  tambien verifica que los siguientes servicios se encuentren ejecutando:
(Yo aqui tengo dos instancias de SQL Server: SQLEXPRESS Y MSSQLSERVER en la misma PC)


text:
Q: Weird issue, attribute value in catalog_product_entity_text but empty when I do an export Very strange issue, when I open a product I can see the value of my attribute (EAN), the value is also in the catalog_product_entity_text table.

But when I do an export I get this result
"sku","ean"
"002",""
The issue is getting more weird every second. What I now found out is that the field EAN is a textarea field, but when he hits the flat table it becomes a int(11) and he adds the max int 2147483647 in that field for every SKU

A: Magento stores textarea attributes as text not as varchar.
You can get the details by looking at the app/code/core/Mage/Eav/Model/Entity.php and see the getBackendTypeByInput function:
public function getBackendTypeByInput($type)
{
    $field = null;
    switch ($type) {
        case 'text':
        case 'gallery':
        case 'media_image':
        case 'multiselect':
            $field = 'varchar';
            break;

        case 'image':
        case 'textarea':
            $field = 'text';
            break;

        case 'date':
            $field = 'datetime';
            break;

        case 'select':
        case 'boolean':
            $field = 'int';
            break;

        case 'price':
            $field = 'decimal';
            break;
    }

    return $field;
}


text:
Q: Algolia not importing my records laravel scout I am using laravel scout to implement my text search. I followed all the configuration instructions and imported the records. When I do that i get this success message Imported [App\Thread] models up to ID: 8 but in algolia I can't see my records for the given index, it keeps saying I have 0 records. I am currently using my admin APIkey.
How do I fix that?

A: I used to have this problem. it is weird but after i did:
php artisan cache:clear
php artisan route:clear
php artisan config:cache
composer dumpautoload

I can do php artisan scout:import without any problem. But when i switched the driver, it didn't work again, and i had to do the 4 steps above again to fix it.

A: I used to have the same problem. I was using sqs for queue driver and i had to run queue worker to function the importing to algolia.

A: i had this problem with in my local , so i runned meilisearch without master key, and it fixed


text:
Q: One class calling another's method In an attempt to tidy up my (very basic) UI code i have split the button and text field into two seperate classes, with a main to create a frame and run. The button needs to affect the contents of the text field when clicked, so i have used a mouseEvent. However, i cannot call my textfield's method, as the textfield object is stored in main, so there is no object to use a method for. All methods are public and all attributes are private. All help is apprciated, thank you.
I have tried making the object public statiic to no avail, i'm not sure if there's something brightly obvious that I am missing here.
Fpor context, the mouseEvent needs to call the method rename(String) from the text field object, known as tf, in the class gui1
edit:
(main)
public interface gui1{
    public static void main(String[] args) {

        textfieldobj tf = new textfieldobj("You should press button 1",100,100, 150,20);
        buttonObject b = new buttonObject("new button!");

(in buttonObject class)
public class buttonObject extends JButton implements{
    JButton b;

    public buttonObject(String text){
        JButton b=new JButton(text);
        b.setBounds(100,100,60,60);
        b.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
                tf.setText("You Did It");//problem area
                b.setEnabled(false);

(in textfield class)
    public void setText(String newtext) {
        text = newtext;
        super.setText(newtext);
    }

A:
textfieldobj

buttonObject

Why are you reinventing all these wheels? JTextField and JButton are the classes to represent a text field and a button, you don't need to make do-nothing wrappers around these.

The button needs to affect the contents of the text field when clicked

That's bad design; you don't want your button to need to know about the textfield; if it does, there is no way to use said button for anything, except to modify that exact text field.

so i have used a mouseEvent.

Yup, that's what to use. But, just.. add the listener at the place that knows about both the button and the field. This can be main, but this gets us to another point:

public static void main(...

this is not the place to write code. Make an object, invoke some 'go' method on it, and that's the one line your main should have. You want to get away from static asap, that's how you do that.
So, something like:
public class MainApp {
    // frames, layout managers, whatever you need as well
    private final JButton switchTextButton;
    private final JTextField textField;

    public MainApp() {
        this.switchTextButton = new JButton("Switch it up!");
        this.textField = new JTextField();
        // add a panel, add these gui elements to it, etc.

        setupListeners();
    }

    private void setupListeners() {
        // hey, we have both the button and the textfield in scope here.
        switchTextButton.addActionListener(evt -> {
            textField.setText("Hello!");
        });
    }
}


text:
Q: How to resolve Groovy conflict with Apache Common Logging? This is my custom maven Groovy execution:
[...]
<plugin>
  <groupId>org.codehaus.groovy.maven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.0-rc-5-SNAPSHOT</version>
  <executions>
    <execution>
      <phase>prepare-package</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <classpath>
          <element>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
          </element
        </classpath>
        <source>
          import org.apache.commons.httpclient.HttpClient;
          // ...
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>
[...]

This is what Maven says:
[...]
[ERROR] Failed to execute goal org.codehaus.groovy.maven:gmaven-plugin:1.0-rc-5-SNAPSHOT:execute (...) on project XXX:
java.lang.ExceptionInInitializerError: org.apache.commons.logging.LogConfigurationException:
org.apache.commons.logging.LogConfigurationException:
Invalid class loader hierarchy.
You have more than one version of 'org.apache.commons.logging.Log' visible,
which is not allowed.
(Caused by org.apache.commons.logging.LogConfigurationException:
Invalid class loader hierarchy.
[...]

I think that I understand why it happens, but how can I solve it?

A: Its hard to say exactly how to fix this without seeing your entire pom.xml file, but I'd suggest looking into the  tag. You could exclude the extra dependency with something like the following:
<plugin>
    ...
    ...
    <dependencies>
        <dependency>
            <artifactId>...</artifactId>
            <groupId>...</groupId>
            <version>...</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                <exclusion>
            </exclusions>
        </dependency>
    </dependencies>
</plugin>

A: Upgrade to version 1.3 solved the problem.

A: Check who is importing that dependency with mvn dependency:tree and remove conflict.


text:
Q: WordPress widget to display more than one images in a frame or div Is there any word-press widget/plugin available which can switch images in a div or a frame automatically with a time interval. ?
My requirement is to have a div or a frame which can display images one at a time and move to the next image after a time interval automatically.
One of the similar example is the "Top News Section" in bbc website.(www.bbc.co.uk).
If there is no plugin from word-press, let me know whether this can be achieved by  java-script or i need to use some flash plugin for that?

A: If you need a plugin than please have a look here.
http://5wpthemes.com/we-recommend/
Also from your wordpress dasboard, go to Plugins - Add New and search for desired plugin.


text:
Q: Kinect depth pixel I am working on a kinect project using MS Kinect SDK1.7.
When I am trying the sample code about bridging with OPENCV.
I am not understanding about the code of calculation
    // Convert depth info into an intensity for display
            BYTE b = 255 - static_cast(256 * realDepth / 0x0fff);
And how can I get the pixels from Mat back to the depth distance?

A: I'm not that familiar with Kinect, but from that line I'm assuming that realDepth will be depth measured by their device inside Kinect, which is in some SI unit (since 0x0fff is 4096 I'm assuming mm). The line there
// Convert depth info into an intensity for display
BYTE b = 255 - static_cast(256 * realDepth / 0x0fff);

then converts the depth value in mm into the range (0 - 255) so it can be displayed on the monitor screen.
You don't need to get depth 'back', you can just use realDepth directly


text:
Q: How to pause the service while getting a incoming call and resume the service after call has ended? My app is has a simple service, i need to pause that service when user makes or receive a call and service has to resume after call has ended.
Here is my Main Activity looks like:-
public class MainActivity extends Activity {

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

    Intent intent = new Intent(getApplicationContext(), MyService.class);
    startService(intent);

    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    TelephonyMgr.listen(new TeleListener(),
            PhoneStateListener.LISTEN_CALL_STATE);
}

class TeleListener extends PhoneStateListener {
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);
        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
                        Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                Toast.makeText(getApplicationContext(), incomingNumber,
                        Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
                        Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }
}}

Here is my Service class file:-
public class MyService extends Service {
private static final String TAG = "MyService";

private boolean isRunning = false;

@Override
public void onCreate() {
    Log.i(TAG, "Service onCreate");

    isRunning = true;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(TAG, "Service onStartCommand");
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }

                if (isRunning) {
                    Log.i(TAG, "Service running");
                }
            }

            stopSelf();
        }
    }).start();

    return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    Log.i(TAG, "Service onBind");
    return null;
}

@Override
public void onDestroy() {

    isRunning = false;

    Log.i(TAG, "Service onDestroy");
}}

From the TeleListener class in MainActivity i'm able to fetch the phone state. My problem is when the TelephonyManager is equal to CALL_STATE_OFFHOOK i need to pause the MyService and when the TelephonyManager is equal to CALL_STATE_IDLE i need to resume the MyService

A: you need to use onCallStateChanged method.
put this lines in your onCreate() method,it will initialize object of TelephonyManager and will setup listener for you.
TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
ListenToPhoneState listener = new ListenToPhoneState()
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

class definition of innerclass ListenToPhoneState will be looking like this,
private class ListenToPhoneState extends PhoneStateListener {

    boolean callEnded=false;
    public void onCallStateChanged(int state, String incomingNumber) {

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            UTILS.Log_e("State changed: " , state+"Idle");

            if(callEnded)
            {
                //you will be here at **STEP 4**
                //you should stop service again over here
            }
              else
              {
                //you will be here at **STEP 1**
             //stop your service over here,
                //i.e. stopService (new Intent(`your_context`,`CallService.class`));
                //NOTE: `your_context` with appropriate context and `CallService.class` with appropriate class name of your service which you want to stop.

              }

            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            UTILS.Log_e("State changed: " , state+"Offhook");
                //you will be here at **STEP 3**
             // you will be here when you cut call
            callEnded=true;
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            UTILS.Log_e("State changed: " , state+"Ringing");
                //you will be here at **STEP 2**

            break;

        default:
            break;
        }
    }

}

Explaination: While the call,your listener will go through following states,
Step 1: TelephonyManager.CALL_STATE_IDLE
initially your call state will be idle that is why the variable callEnded will have the value false.
Step 2: TelephonyManager.CALL_STATE_RINGING
now you are waiting for the receiver person to receive your call
Step 3: TelephonyManager.CALL_STATE_OFFHOOK
you cut the call
Step 4: TelephonyManager.CALL_STATE_IDLE
idle again
NOTE: If you don't want to know when the call ends and what should be done after ending the call then just remove callEnded variable and stop the service whenever you enter in the block of TelephonyManager.CALL_STATE_IDLE
I hope it will be helpful !!

A: You cannot pause or resume a service, you can start your service again when call ends. Inside PhoneStateListener's TelephonyManager.CALL_STATE_OFFHOOK constant, start your service again! Using different states of PhoneStateListener as mentioned by @Tijo, you can decide when to start or stop your service.


text:
Q: Creating a random URL in NodeJS I'm playing around with socket.io and would like to make it so that when someone visits my app, they start out at a random URL (site.com/52436) and that url is the url that they would share with someone else that initiates a room and allows them to chat with each other. My question is, is how do I make it so when they visit site.com, it goes to site.com/56443 and initiates a room with the same id?
Edit: I'm using the meteor framework.

A: Here's an example I had available (this is coffeescript).  It requires iron router and cookie, but your logic would generate it randomly instead.  It happens on client.
Meteor.startup ->

  auto = Cookie.get('autosubscribe')
  if auto
    Router.go 'publicScreen',
      _id: auto

I also suggest that the meteor framework has socket built into it, and that you may want to look at the chat example.  They hide a lot from you, which can be a good thing.


text:
Q: Linking Tables using SQL Trying to figure out how to link two tables, specifically Medicine and Medication.
My script is as follows:
SELECT DISTINCT Physician.FirstName, Physician.LastName
FROM Physician, Consultation, Medication, Medicine
WHERE Physician.Specialty = 'Geriatrics'
AND Medicine.Name = 'Aspirine'
AND Consultation.PhysicianID = Physician.ID
AND Consultation.ConsultationID = Medication.ConsultationID

I presume that I would have to use INNER JOIN, but am not entirely sure as I am new to this. Query should populate physician name and specialty that prescribed Aspirine.

A: I think you are missing a link between consultations of Aspirine and consultations of Geriatrics. At the same time, the way you wrote the query is very inneficient when tables become large, because you are doing a full-join of four tables. The Access query optimizer most likely fixes the inefficiency, but I still think it is not good practice to write code in this way. What I believe you want is the code below. It may look large and cumbersome to you, but I can tell you it reflects much better the logic of what you are trying to do and will be easier to maintain. I am guessing that the table "medicine" has a field called "medicineID" (or something similar), and the table "consultation" has an equivalent field. As I indicated above, I think that you are missing the link between these two fields. The code would be:
SELECT DISTINCT Physician.FirstName, Physician.LastName
   (-- Cons_Ger produces all the consultations by Geriats
    SELECT Geriats.ID, FirstName, LastName, ConsultationID
    FROM
        (SELECT FirstName, LastName, ID
         FROM Physician
         WHERE Speciality = "Geriatrics"
        ) AS Geriats
    INNER JOIN
        (SELECT PhysicianID, ConsultationID
         FROM Consultation
         WHERE True -- I guess you need some condition here. If not, suppress this line
        ) AS Consult
    ON Geriats.ID = Consult.PhysicianID
   ) AS Cons_Ger
INNER JOIN
   (-- This produces all the consultations prescribing Aspirine
    SELECT Geriats.ID, FirstName, LastName, ConsultationID
    FROM
        (SELECT MedicineID, Name
         FROM Medicine
         WHERE Name = "Aspirine"
        ) AS Asp
    INNER JOIN
        (SELECT MedicineID, ConsultationID
         FROM Consultation
         WHERE True -- I guess you need some condition here. If not, suppress this line
        ) AS Consult
    ON Asp.MedicineID = Consult.MedicineID
   ) AS Cons_Asp
ON Cons_Ger.ConsultationID = Cons_Asp.ConsultationID

If this is not what you want, please clarify your question (list the fields of the tables "medicine" and "consultation") and I will try to provide additional support. More information at LightningGuide.net.


text:
Q: Will "apt-get dist-upgrade" update my Ubuntu to the next major release? I'm trying to cleanup the following error message:
pdf-reader /home/jseidel/ebilling_1393100.pdf
Traceback (most recent call last):
  File "/usr/lib/command-not-found", line 10, in <module>
    import CommandNotFound
ImportError: No module named CommandNotFound

which is apparently caused by a python problem (see http://ubuntuforums.org/showthread.php?t=1380441). I recently tried to upgrade to python7.2 because of a dependency from poppler. However, the instructions suggest doing a sudo apt-get dist-upgrade  but I don't want to upgrade my distribution - I'm on Kubuntu 10.04 and don't want to introduce and instability into my system.
I read on another post that dist-upgrade wouldn't automatically take you from and LTS version (10.04) to another release but since there are subsequent LTS distributions to 10.04, I'm hesitant to run that command (I've read the definition of dist-upgrade and it sure isn't clear to me).
Thanks...
Any suggestions?

A: As you'll see in the manual page, dist-upgrade doesn't necessarily mean distribution upgrade. Sometimes it just means remove some packages and install other ones to fix conflicts that prevent the system from upgrading completely:

dist-upgrade
dist-upgrade in addition to performing the function of upgrade,
    also intelligently handles changing dependencies with new versions
    of packages; apt-get has a "smart" conflict resolution system, and
    it will attempt to upgrade the most important packages at the
    expense of less important ones if necessary. So, dist-upgrade
    command may remove some packages. The /etc/apt/sources.list file
    contains a list of locations from which to retrieve desired package
    files. See also apt_preferences(5) for a mechanism for overriding
    the general settings for individual packages.

My advice would be to run the command and check what is going to be installed/removed. If agree on the chagnes, then press Y, otherwise press N. Even if you make a mistake and the distribution upgrade tool starts gathering information, you can click on the cancel button without actually making any change, so just running the command shouldn't cause any problem.


text:
Q: Hausdorff space - proof (trying to improme my proof writing skills) I'm working on the following problem from Munkres book on Topology:
"Show that X is Hausdorff if and only if the diagonal $\Delta$ = $\{x \times x  |  x \in X \}$ is closed in $X \times X$."
My question is: what does $x_1$ and $x_2$ mean? Are they equivalent to $p_1$ and $p_2$? I've written it in steps to make it more clear to my self.
1. step
Assume X is Hausdorff. Now prove that $(X \times X) \setminus \Delta$ is open.
2. step
Let $p_1, p_2 \in (X \times X)\setminus \Delta $ and therefore $p_1 \neq p_2$
3. step
Let $U_1$ and $U_2$ be disjoint open sets containing $p_1$ and $p_2$, respectively.
4. step
Then $U_1 \times U_2$ is an open set in $X \times X$ containing $p_1$ and $p_2$, such that $U_1 \times U_2 \cap \Delta = \emptyset$
5. step
Therefore, $(p_1, p_2) \in (U_1 \times U_2) \subset (X \times X) \setminus \Delta$. This implies that $(X \times X)\setminus \Delta$ is open.
6. step
Assume that $\Delta$ is closed (i.e. that $(X \times X) \setminus \Delta$ is open)
7. step
Since $(X \times X) \setminus \Delta$ is open, there is an open set $U \times V \in X \times X$ such that $(x_1, x_2) \in U \times V \subset (X \times X)\setminus \Delta$.
8. step
This implies $x_1 \in U$ and $x_2 \in V$, and $U$ and $V$ are disjoint, which shows that X is Hausdorff.
$\square$


text:
Q: CURL working, JSON not working I have a Json get request that works perfectly when I use CURL to send it over php , but when I try to do the same thing with getJSON (which is the requirement), all I get back is status is error when I use the code below.  How can I know exactly what the error is ?  I dont know if I am sending the request with wrong parameters of if its a time out, or what it could be.  Thanks
         $.getJSON(url, function(data,status,xhr) {
          if (status == "success"){
     alert ("got the data"+data);
}else if (status == "timeout"){
    alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
    alert("An error occured");
}else{
    alert("datatosend did not change");
}
         })

A:
How can I know exactly what the error is

An answer to that at least :
$.getJSON(url, function(data,status,xhr) {
    alert ("got the data"+data);
}).fail(function(a,b,c) {
    console.log(a,b,c);
});

I'm guessing CORS error and same-origin policy as it works with cURL, and if that's case and it's not your server there's not much you can do other than go back to using cURL, which to me sounds like a much better approach to begin with.

A: the answer was that although I was on the same domain I was not putting https on the url to get which is what my site was using.
thanks


text:
Q: ContentProvider Threading Just curious.
getContentResolver().query(...)

I know that Loaders run queries on background threads. Does this also apply to inserts, updates and deletes? Should I create AsyncTasks, Threads, etc... for these kinds of calls?
Large updates might block my application's main thread.
getContentResolver().insert(...)

Thanks!

A: from Content Provider Basics

Retrieving Data from the Provider
This section describes how to retrieve data from a provider, using the
  User Dictionary Provider as an example.
For the sake of clarity, the code snippets in this section call
  ContentResolver.query() on the "UI thread"". In actual code, however,
  you should do queries asynchronously on a separate thread. One way to
  do this is to use the CursorLoader class, which is described in more
  detail in the Loaders guide. Also, the lines of code are snippets
  only; they don't show a complete application.

A: The Loaders only works for queries, that is, loading data in Activities or Fragments, other than insert/update/delete.
Besides Loader, availabe since Android 3.0, android did provide a helper class AsyncQueryHandler, since API level 1, for async CRUD like operations with full CRUD callbacks supported.
The AsyncQueryHandler works inside with a HandlerThread for the async operations and delivers the results back to the main thread. Using AsyncTask or simple worker threads are also popular practices in terms of particular requirements.

A: When you say Loaders run queries on background threads, you need to understand that it is the implementations of the Loader class that perform the queries in the background thread.
The consequence of this is that you will want to use or extend and implement subclasses of the abstract Loader class and not use AsyncTask or Java threads. The reason is when you create a Loader, it expects you to return an instance of type Loader. A java thread or an AsyncTask cannot be used for this.
Subclasses of the Loader class do this by starting their own thread. The client class or the class that creates the Loader has only initializes the Loader. The actual Loader instance can do anything you want it to do. This can be anything - insert, update, delete, etc. The Android provided CursorLoader implementation queries data from tables in a background thread asynchronously and returns the result set. Android does not provide similar native implementations for inserting or updating data. What you do have is the option to extend from the AsyncTaskLoader (the same class that CursorLoader inherits from).
Also, keep in mind that Loaders are used to optimize database access and as such will provide post the result to the main thread only when they have completed their task and not before that (there is a hack like workaround to post updates to the UI thread but then this breaks the paradigm). Loaders are only concerned with completing their work and are not interested in providing any updates.
If you simply want to handle ContentProvider queries asynchronously, you might want to consider using the AsyncQueryHandler class supplied by Android.


text:
Q: Remove row if values in one column if found in another in Oracle SQL I have the table below where I have two columns per client.  I want to delete rows in Column B if it is in Column A per Client.  In this example we would remove rows with "123" in Column B for Tom since it is in Column A.
Sorry for the confusion.

Client
Column A
Column B

Tom
123
560

Tom
544
123

Bob
658
85

Tom
32
123

Sean
45
105

Output

Client
Column A
Column B

Tom
123
560

Bob
658
85

Sean
45
105

A: DELETE tableclients FROM tableclients
WHERE columnB IN (SELECT columnA from tableclients)

This should work out,
It's a simple and effective query hope you'll get your required results from it

A: You can use either not exists clause or not in clause to do that.
select t1.*
from Your_Table t1
where not exists (
  select null
  from Your_Table t2
  where t2.Client = t1.Client and t2.Column_A = t1.Column_B
  )
;

or
select t1.*
from Your_Table t1
where (t1.Client, t1.Column_B) not in (
  select t2.Client, t2.Column_A
  from Your_Table t2
)
;

demo

A: I hope this will help you.
this is the MySql procedure
CREATE PROCEDURE DBname.deleteRecord()
BEGIN

DROP TABLE IF EXISTS `temp`;
create table temp select    b.Column2  as Column2  from
clienttable  a  inner join
clienttable  b where  a.Column1  = b.Column2 AND a.client  =   b.client ;

delete   FROM  clienttable  WHERE  Column2 in (select  b.Column2
from  temp b );

SELECT * from  clienttable ;

END

Call
call DBname.deleteRecord()

A: You can try this:
declare @TableIntersect table(Name nvarchar(max))

insert into @TableIntersect(Name) SELECT Name
    FROM ColumnA
    INTERSECT
    SELECT Name
    FROM ColumnB

delete from YourTable where ColumnA in (select Name from @TableIntersect)
delete from YourTable where ColumnB in (select Name from @TableIntersect)


text:
Q: How to solve "ValueError: Supported target types are: ('binary', 'multiclass'). Got 'multiclass-multioutput' instead." error in pyton 3.7 I want to create a program to do emotion classification using TF-IDF and SVM. Before classify the data, I have to split a dataset into data training and testing using stratified KFold. I've used the numpy array to store the texts (X) and labels (Y)
But it ended up with this error:
ValueError: Supported target types are: ('binary', 'multiclass'). Got 'multiclass-multioutput' instead'

this code is running on python 3.7:
labels = []

with open(path, encoding='utf-8') as in_file:
    data = csv.reader(in_file)
    for line in data:
        labels.append(line[1])

label_np = np.array(labels)
lp = label_np.reshape(20,20)
# lp = label_np.transpose(0)
# print(lp)

result_preprocess_np = np.array(result_preprocess)
hp = result_preprocess_np.reshape(20,20)

model = LinearSVC(multi_class='crammer_singer')
total_svm = []

total_mat_svm = np.zeros((20,20))

kf = StratifiedKFold(n_splits=3)
kf.get_n_splits(hp, lp)

for train_index, test_index in kf.split(hp, lp):
    # print('Train : ', test_index, 'Test : ', test_index)
    x_train, x_test = hp[train_index], hp[test_index]
    y_train, y_test = lp[train_index], lp[test_index]

vectorizer = TfidfVectorizer(min_df=5,
                             max_df=0.8,
                             sublinear_tf=True,
                             use_idf=True)
train_vector = vectorizer.fit_transform(x_train)
test_vector = vectorizer.transform(x_test)

model.fit(x_train, y_train)
result_svm = model.score(x_test, y_test)
print(result_svm)

I expect the result is the accuracy of classification.


text:
Q: In need of a visually pleasing UML diagram tool I've been looking for different tools to create UML diagrams for my Java apps. My prof uses Omnigraffle, but this is only for Mac/iPad. I'm really looking for something as visually pleasing as Omni but for Linux or even Windows. Thanks for your help.

A: I use http://argouml.tigris.org/ it's free and OK to look at :)

A: or visual paradigm they have community edition for free

A: Try Sparx Enterprise Architect for Windows.  It is very reasonably priced.

A: JUDE has a community edition.  I used to think this was a terrific tool before they split it into community and paid editions.

A: There is also StarUML, I have also used Visual Paradigm community edition that @Milan mentioned before.

A: If you're just looking for a drawing tool (as opposed to a "modelling" tool) then take a look at YEd.  Conceptually v similar to omni.  Free, works on linux/mac/osx and looks great.  Also has very nice auto-layout.
hth.

A: Most minimalistic UML diagrams-editing tool (not modeling environment!) ever: UMLet.
Gives reasonable black-and-white results, exports vector graphics to PDF and EPS.  Up side: A small text pane speeds up editing.  Down side: A couple of end-cases (e.g., labels on vertical lines) do not give optimal results.

A: What does "visually pleasing" mean for you? I think it is a very subjective matter and should be the last thing considered when choosing a UML modeling tool.
However, I like how the Altova UModel diagrams look, except for the use case diagrams' actor element. I'm not such a fan of StarUML and Visual Paradigm.

A: I will recommend you to try Visio for creating UML diagrams. Visio has the feature of dynamic, data-driven visuals which makes it one of the best software for diagramming. I use it for my diagramming needs.


text:
Q: SQL Synapse, use dynamic/parameterized Azure Container in CREATE EXTERNAL TABLE We have a scenario where the source csv files are isolated by Customer i.e., each Customer will have a Container in the Azure Storage.
When creating External Table in SQL Synapse, is it possible to pass the Container name as parameter that way there are not multiple External Data Tables in SQL Synapse DB?
    CREATE EXTERNAL DATA SOURCE AzureBlobStorage with (
    TYPE = HADOOP,
    LOCATION ='wasbs://<**container100**>@<accountname>.blob.core.windows.net',
    CREDENTIAL = AzureStorageCredential
    );

    CREATE EXTERNAL TABLE [dbo].[res1_Data] (
    [ID] INT,
    [UniqueId] VARCHAR(50),
    [Status] VARCHAR(50) NULL,
    [JoinedDate] DATE
    )
    WITH (LOCATION='<**container2**>/<folder>/<file>.csv',
    DATA_SOURCE = AzureBlobStorage,
    FILE_FORMAT = CEFormat
    );

A: Unfortunately you can't use variables within DDL commands. However, you can build dynamic statements and then execute with sp_executesql to do this.
More information here.


text:
Q: How to avoid repeated istringstream construction when converting stream of string tokens I'm (intending to) use the code in this answer to read something from a CSV. Essentially I get an iterator to strings between consecutive , characters; but instead of putting them in a vector of strings, I want to parse these strings into elements of (arbitrary) type T, which comes from  template argument. So...
template <typename T>
void foo(const std::string& line)
{
    // ....
    std::vector<T> vec;
    using namespace boost;
    tokenizer<escaped_list_separator<char> > tk(
       line, escaped_list_separator<char>('\\', ',', '\"'));
    for (tokenizer<escaped_list_separator<char> >::iterator i(tk.begin());
       i!=tk.end();++i)
    {
       /* magic goes here */
    }

I could use an istringstream` (e.g. as suggested here):
std::istringstream iss(*i);
T t; iss >> t;
vec.push_back(t);

But that's overkill (and I might be constructing twice or even three times here). If C++ had an std::from_string() like its std::to_string, then I would just do
vec.emplace_back(std::from_string(*i));

but that doesn't exist. Perhaps boost::lexical_cast? I'd really rather using something standard.
What should I do instead?

A: make the istringstream static thread_local
T parse (const string& line){
  static thread_local istringstream stream;
  stream.str(""); //flush the stream
  //keep using stream
}

if your application is mono-threaded, you can discard the thread_local
other solution which does not involve keeping the stream static to a function is to wrap the stream with Parser object, and keep using that object, flushing it's inner buffer with str
class Parser{
  std::stringstream stream;
  public:
  void parse(const std::string& data){
     stream.str("");
     // the rest
  }

}

Parser parser;
parser.parse("my,data");
parser.parse("other,data");

EDIT:
In order to prevent instansiation for every T type, encapsulate the stream in diferent function,
make a helper function which constructs std::istringstream once form every thread:
namespace detail {
istringstream& getStream(){
      static thread_local istringstream stream;
      stream.str("");
      return stream;
}
} // namespace detail

template<class T>
void parse(){
   auto& stream = detail::getStream();
   //do soemthing with stream

}


text:
Q: LWC event target data attributes propagation not working in Lightning Experience? In a parent LWC component I am using a child LWC component like so
<c-comp key={stuff.id} data-name={stuff.name} parameters={stuff.parameters} onresultavailable={handleResultAvailable}/>

and from the child LWC component I am triggering a Custom Event like the following:
    this.dispatchEvent(
        new CustomEvent('resultavailable', {
          detail: {
            data: body,
            success: successful
          }
        })
    );

In the parent I can correctly access the event target data (for example event.target.dataset.name) fields when working in local dev server, but it doesn't work when running the component in the org. Should I configure the event in a different way, and if not, should I instead pass that element as field in the detail event (and how, then?)


text:
Q: How to access the methods from WADL file in Java? I have a REST service for which I have a WADL file. I want to refer this file and access the methods from it.  The content of the WADL file is as below:
<resource path="/loadPerson">
    <method id="loadPerson" name="GET">
        <request>
            <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="personId" style="query" type="xs:int"/>
        </request>
        <response>
            <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="person" mediaType="application/xml"/>
            <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="person" mediaType="application/json"/>
        </response>
    </method>
</resource>

Actually I am not getting how to approach towards it, as I never played with WADL files before. What should I be doing?

A: The <resource> identifies a URL (with respect to a base URL specified as a base attribute on an outer <resources> element that you don't show) that you would interact with in a RESTful manner. The <method> has a name attribute of GET, which means that to use that particular operation, you do a GET on the resource URL. The inner <request> has a <param> so we know to add a query parameter to the GET URL; in this case, it'll be personId=123 (or some other integer). The <response> tells us that we can get back the answer as either XML or JSON; we should use HTTP content negotiation to say which.
There's a minor bug in the WADL in that it is specifying the <resource> URL with a leading /; that will quite possibly cause problems with tooling as it tries to assemble a correct URL, but we can still say what the URL will be (from knowing how RESTful webapps tend to be implemented).
Assuming that the outer <resources> says that the base URL is http://example.org/foobar (and there's no intermediate <resource> elements; WADL allows that) then the WADL is saying that if you do a GET on http://example.org/foobar/loadPerson?personId=123 with your HTTP client configured to prefer XML, you'll get a <person> element back as the body of the HTTP response (or an error, e.g., if there's no match for such a personId or if you're not authorized to find out).


text:
Q: XSLT FO Horizontal alignment of inline container I'm trying to align an inline container horizontally, but I can't find the corresponding FO attribute like display-align for vertical alignment.
Here is some example code without any alignment:
<fo:inline-container background-color="white" border-style="solid" border-width="2mm" border-color="white">
    <fo:block font-family="Blablabla" text-align="center" font-size="54pt" space-after="6mm" text-indent="0mm" last-line-end-indent="0mm" alignment-baseline="central">
        ...
    </fo:block>
</fo:inline-container>

The whole thing is going to be processed with AntennaHouse 5.2.
Thanks in advance
Stavros

A: Add text-align="center" to the fo:block (or similar) that contains the fo:inline-container:
 <fo:block text-align="center">
    <fo:inline-container background-color="white" border-style="solid" border-width="2mm" border-color="white">
      <fo:block font-family="Blablabla" text-align="center" font-size="54pt" space-after="6mm" text-indent="0mm" last-line-end-indent="0mm">
          ...
       </fo:block>
    </fo:inline-container>
 </fo:block>

Also, your alignment-baseline="central" doesn't do anything since alignment-baseline doesn't apply to fo:block and is not inherited.  See https://www.w3.org/TR/xsl11/#alignment-baseline


text:
Q: Understanding grid system in bootstrap I am trying to learn web design and I am using Angular to do so. However, I am stuck with some of the concepts in bootstrap and I don't know what is right from wrong. I am a beginner so please bear with me. My questions are the following:

*

*When and where should I use containers? Some people say that I should only use one single fluid-container at the root component/index.html file and nothing else. But when I see some examples on Github I don't see many do that. Do I use a fluid-container for components that extends the whole viewport and continer for the other components? Should I use a container for every component? Should I have nested containers? What is best practices?

*Can I have cols directly nested in other cols? or is it best practices to use rows if I want to nest more cols in cols?
for example:

         some content

         some content

      some content

*When is it best to use rows and when is it not recommended?

*Can I have rows without a container/container-fluid?
Please help me understand and if possible refer to some document.

A: Combining Angular and Bootstrap can be quite a challenge. Since you're just mentioning the bootstrap grid system, I'll start off with that.
Bootstrap grid
Docs
The simplest grid is as follows

      <button class="btn btn-primary">Primary button</button>

      <button class="btn btn-secondary">Secondary button</button>

I'm using the .container, so respectively to the window width, the grid will keep a fixed size:

The bootstrap breakpoints are listed here

So if the window is wider than 1200px (XL), then the container will have a fixed width of 1200px.
.container-fluid indicates that you don't want gutters, but prefer the container to expand to full-width:

Columns
The bootstrap grid uses the 12-column grid system ideology. You can specify the width of each column (1 to 12), and alltogether they should come to 12 (or fewer).
Wrapping

 indicates that the cells of the grid will move below one another when the window is smaller than 768px. You may as well tell the browser that cells should wrap sooner (eg. col-xs-6) or later (eg. col-lg-6).
Nested grid
As you've indicated, you want to have subgrids too. @Sean already explained how to do this:

Cell 1

Cell 2

Cell 3

Cell 1

Cell 2

Cell 3

Spoiler
As I already mentioned, using bootstrap with angular is another challenge. In order to use the bootstrap grid in angular, you can add the bootstrap styles through angular.json (or off course only use _grid.scss...):
{
  "projects": {
    "example": {
      ...,
      "architect": {
        "build": {
          "options": {
            ...,
            "styles": [
              { "input": "node_modules/bootstrap/scss/bootstrap.scss", "bundleName": "style.css" },
              { "input": "src/styles.scss", "bundleName": "style.css" }
            ],
            "scripts": [
              ...
            ]
          }
        }
      }
    }
  }
}

However, doing the same for the scripts doesn't really work properly, and isn't recommended too. Scripts registered through angular.json aren't tree-shakable and will end up entirely in the main bundle.
So for advanced bootstrap components that require javascript, you have to arrange this by creating angular components for them. But this in turn poses a challenge as well. There are already multiple angular-bootstrap libraries out there:

*

*ng-bootstrap: only rewrites the typescript code, and the css is referenced globally, which increases the bundlesize with 180 kB

*ngx-bootstrap, also using global css

Writing your own ng-bootstrap library
I've been in the process of writing a library myself. The idea was to extract the styles into the specific components, in order to prevent styles from being bundled in the main bundle while you actually don't need them. Usually you would do the following:
:host ::ng-deep {
    // Configuration
    @import "~bootstrap/scss/functions";
    @import "~bootstrap/scss/variables";
    @import "~bootstrap/scss/mixins";

    // Layout & components
    @import "~bootstrap/scss/alert";

    // Custom SCSS
    .alert .btn {
        bottom: 0;
        display: inline-flex;
        align-items: center;
    }
}

However I found out that from the moment a selector contains ::ng-deep, angular will create a javascript chunk in the main bundle containing this style, even for :host ::ng-deep. I've created a github issue for this, hoping that they'll fix this...
Conclusion
If you don't care about your bundle size, you may use ng-bootstrap, ngx-bootstrap, or if there's no javascript magic to what you're writing, simply reference _bootstrap.scss from angular.json.
If bundle size matters to you, you'll probably have to wait until the angular team resolves this issue, and use or build a library like this one.


text:
Q: Android : Passing a value between activities In my Android application I have to use common string value for all activities. "commonValue" is the common string value that I want to use in all activities. Relevant code of the main activity like this :
public class TestActivity extends Activity {

 public String commonValue;//THE COMMON STRING FOR ALL ACTIVITIES

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    commonValue = "DemoValue";
  }
}

In my next activity I created an object of "TestActivity" class and tried to assign "testValue" string to another string named "str"
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testlist);

    TestActivity obj = new TestActivity();//OBJECT OF MAIN ACTIVITY
    String str = obj.commonValue;
 }

but the "str" value in second activity does not equal to the value assigned in my first activity. Why is that & How can I do this?
Thanks!

A: Put your value in string.xml
 <string name="common_value">DemoValue</string>

and use in any activity like this..
String common_value = getApplicationContext().getString(R.string.common_value);

A: Start using SharedPreferences in your app.
In your first activity you would do
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("commonValue", "DemoValue");
editor.commit();

In your second activity
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String str = settings.getString("commonValue", null);

A: If the value is always the same you can create a public static final variable and access it via TestActivity.COMMON_VALUE.
If you want to pass around a value between to Activities you should use Intents and add an extra with the value you want to pass.

A: Try this -
TestActivity.java
public class TestActivity extends Activity {

 public static String commonValue;//THE COMMON STRING FOR ALL ACTIVITIES

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    commonValue = "DemoValue";
  }
}

another activity
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testlist);

    String str = TestActivity.commonValue;
}

A: As Sana has suggested, use SharedPreferences.
Alternatively, use a global constant class. If you want to stick with what you have, then you could try:
String str = TestActivity.this.commonValue;
Your existing code is creating a new instance of the activity, so it's not going to have the value you had set.

A: To pass data between activities use Bundle. and methods,
intent.putExtra()

and If you want to set data to be global to your app, then create an application class, and save the data there.

A: We have an Application file for each app you can declare the variable there and as the Application file can get from any activity so using the public getter setter and can get/set that
there are vaious oter metjod you can sue as mention on  developer.android http://developer.android.com/resources/faq/framework.html
Singleton class
A public static field/method
A HashMap of WeakReferences to Objects (almost same as my above solution )
Persistent Objects

take a look on them as well

A: The reason why commonValue doesn't equal what you set in TestActivity onCreate method is because that function hasn't been called yet.
The solution for this is already mentioned by others. Like putting the value in a bundle.


text:
Q: Change label from Newrelic "MySQL (subquery) select" to custom label I have using Newrelic with Laravel application.
Whenever I use simple queries then newrelic shows table name with it.
But in case of sub-queries it shows MySQL (subquery) select

I am using Laravel Eloquent for queries.
Can you please help me how I can replace this label with custom table name like MySQL subquery_customer_table select
Thank You in advance!


text:
Q: с# как сделать так, чтобы одновременно показывалась только часть формы Допустим есть форма 1500 на 1200. Как сделать так, чтобы при движении курсора показывался только участок формы скажем 300 на 300 вокруг него?
protected override void OnLoad(EventArgs e)  // этот участок отвечает за черный круг
    {
        base.OnLoad(e);
        SetEventHandlers(this);
    }
    private void SetEventHandlers(Control ct)
    {
        ct.Paint += PaintControl;
        ct.MouseMove += (o, e) => Invalidate(true);
        foreach (Control item in ct.Controls)
        {
            SetEventHandlers(item);
        }
    }

    int Radius = 100;

    void PaintControl(object sender, PaintEventArgs e)
    {
        e.Graphics.SmoothingMode = SmoothingMode.None;

        Control ct = (Control)sender;
        Point ct_position = ct.PointToScreen(new Point(0, 0));
        Point client_position = this.PointToScreen(new Point(0, 0));
        int shiftX = ct_position.X - client_position.X;
        int shiftY = ct_position.Y - client_position.Y;
        Point p = PointToClient(MousePosition);
        p.Offset(-shiftX, -shiftY);
        using (GraphicsPath path = new GraphicsPath())
        {
            path.AddRectangle(new Rectangle(-shiftX, -shiftY, ClientSize.Width, ClientSize.Height));
            path.AddEllipse(p.X - Radius, p.Y - Radius, 2 * Radius, 2 * Radius);
            e.Graphics.FillPath(Brushes.Black, path);  // этот участок отвечает за черный круг
        }
    }

A: Могу предложить такое решение.
Размещаем на форме непрозрачную панель поверх всех контролов.
При движении мыши вырезаем в этой панели дырку-регион нужного размера и формы.
Единственная проблема - глобальное отслеживание движения мыши. Я сделал это с помощью таймера - костылик, да, зато просто.
public Form1()
{
    InitializeComponent();

    fogPanel = new Panel { Parent = this, BackColor = Color.Black, Size = this.DisplayRectangle.Size };
    fogPanel.BringToFront();

    var timer = new Timer();
    timer.Interval = 10;
    timer.Tick += Timer_Tick;
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
    var point = PointToClient(MousePosition);
    var rect = new Rectangle(point.X - 50, point.Y - 50, 100, 100);
    var region = new Region(fogPanel.DisplayRectangle);
    region.Exclude(rect);
    fogPanel.Region = region;
}

Работает без лагов, плавно, процессор не грузится.

A: Не знаю, как в WinForms, но в WPF сделать это очень просто с помощью CombinedGeometry в режиме Exclude.
Разметка:
<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Width="400" Height="300"
        MouseMove="Window_MouseMove">

    <Grid Margin="5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ListBox>
            <ListBoxItem>Элемент 1</ListBoxItem>
            <ListBoxItem>Элемент 2</ListBoxItem>
            <ListBoxItem>Элемент 3</ListBoxItem>
            <ListBoxItem>Элемент 4</ListBoxItem>
            <ListBoxItem>Элемент 5</ListBoxItem>
            <ListBoxItem>Элемент 6</ListBoxItem>
            <ListBoxItem>Элемент 7</ListBoxItem>
            <ListBoxItem>Элемент 8</ListBoxItem>
            <ListBoxItem>Элемент 9</ListBoxItem>
            <ListBoxItem>Элемент 10</ListBoxItem>
        </ListBox>

        <StackPanel Grid.Column="1">
            <Button>Кнопка 1</Button>
            <Button>Кнопка 2</Button>
            <Button>Кнопка 3</Button>
            <Button>Кнопка 4</Button>
            <Button>Кнопка 5</Button>
            <Button>Кнопка 6</Button>
            <Button>Кнопка 7</Button>
            <Button>Кнопка 8</Button>
            <Button>Кнопка 9</Button>
            <Button>Кнопка 10</Button>
        </StackPanel>

        <Path Grid.ColumnSpan="2" Fill="LightGray"
              Name="path">
            <Path.Data>
                <CombinedGeometry GeometryCombineMode="Exclude">
                    <CombinedGeometry.Geometry1>
                        <RectangleGeometry Rect="0 0 400 300"/>
                    </CombinedGeometry.Geometry1>
                    <CombinedGeometry.Geometry2>
                        <EllipseGeometry x:Name="el" Center="50 50" RadiusX="50" RadiusY="50"/>
                    </CombinedGeometry.Geometry2>
                </CombinedGeometry>
            </Path.Data>
        </Path>
    </Grid>
</Window>

Обработчик события:
private void Window_MouseMove(object sender, MouseEventArgs e)
{
    el.Center = e.GetPosition(path);
}


text:
Q: How to get external xml data to load before MovieClip loads with AS 3? I have an AS3 project (main.FLA) that loads my XML data via an .as file (called projectData.as) utilizing the URLLoader function and tests for Event.COMPLETE and it's successful.  The issue is that I have a startup screen MovieClip on the stage (associated with an external as file called startUp.as) with dynamic textBox that needs the data in order to populate the text field but startUp.as loads BEFORE the XML loading projectData.as file. So startUp.as traces out a "In Startup" before the projectData.as file can trace out an "XML Loaded".
How can I force the projectData.as file to load the xml data before the startup.as calls for it?  Or, get the startUp.as file to wait for the projectData.as file to load the data before asking it to pull the text it needs? It would be redundant I think to make it load twice, but is there a way to for an order of execution in Flash?


text:
Q: add class to nested div if class exists and to all if class doesn't? OK I have the following structure:

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

and this js:
$('.test').on('click', function () {
    $(this).addClass('checkin');
});

How do I add a class to all the nested .test divs in between the .checkin and .reserved and if in the case of .reserved not existing then add the class to all of the .test divs?
jsfiddle

A: Try this:
$('.test').on('click', function () {
    $(this).nextUntil('.reserved').andSelf().addClass('checkin');
});

http://api.jquery.com/nextUntil/
http://api.jquery.com/andSelf/

A: Try this
$('.test').on('click',function(){
$(this).addClass('checkin').nextUntil('.preserved').addClass('checkin');
    for (var i = 0; i < $(this).parent().nextAll('.class').length;i++){
        var $class=$(this).parent().nextAll('.class').eq(i);
        if($class.find('.reserved').length ==0){

        }else{
            $class.find('.test:first').nextUntil('.reserved').addClass('checkin');
        }
    }
});

DEMO

A: You need to use .hasclass()

Description: Determine whether any of the matched elements are
  assigned the given class.

$(this).hasClass('reserved') // retuns boolean value

A: You can use the jquery nextUntil() function : http://api.jquery.com/nextUntil/
This will work well for your exact question, but if you wan to tweak it a little bit, you should go back to the stupid brute method : take the array and loop on it with boolean.
$('.test').on('click', function(e){
    //add the class to your target
    $(e.target).addClass('checkin');

    //get an array of all the .test divs in the .class div you click
    var arTests = $(e.target).parent().find('div.test');
    //if you want to loop on all the .test of the page, just go like that :
    // var arTests = $('div.test');

    //boolean to check in the loop
    var boCheckinPased = false;
    var boReservedPassed = false;

    for(var i = 0; i < arTests.length; i++) {
        if($(arTests[i]).hasClass('checkin')) boCheckinPased = true;
        if($(arTests[i]).hasClass('reserved')) boReservedPassed = true;

        //if passed the first checkin and not yet the reserved, add the class
        if(boCheckinPased && !boReservedPassed) $(arTests[i]).addClass('checkin')
    }
});

I did update a jsfiddle here : http://jsfiddle.net/SvFAA/8/

A: Less code is better code:
$('.test').on('click', function(){
    var elements = $('.class .test');
    elements.each(function(key, value) {
        if (!$(elements[key]).hasClass('reserved')) {
            $(elements[key]).addClass('checkin');
        }
    });
});

elements: is a list of objects
key: is the position of a each element in the list of elements
value: is the object itself