问:
Java reading nth line
I am trying to read a specific line from a text file, however I don't want to load the file into memory (it can get really big).

I have been looking but every example i have found requires either to read every line (this would slow my code down as there are over 100,000 lines) or load the whole thing into an array and get the correct element (file will have alot of lines to input).

An example of what I want to do:

```<code>String line = File.getLine(5);
</code>```

"code is not actual code, it is made up to show the principle of what i want"

Is there a way to do this?

-----Edit-----

I have just realized this file will be written too in between reading lines (adding to the end of the file).

答:
Here is a snippet of some code I had which will read a file and write every 10th line including the first line to a new file (writer.) You can always replace the try section with whatever you want to do.  To change the number of lines to read just change the 0 in the if statement "lc.endsWith("0")" to whatever line you want to read.  But if the file is being written to as you read it, this code will only work with the data that is contained inside the file when you run this code.</p>

```<code>            LineNumberReader  lnr = new LineNumberReader(new FileReader(new File(file)));
            lnr.skip(Long.MAX_VALUE);
            int linecount=lnr.getLineNumber();
            lnr.close();

        for (int i=0; i<=linecount; i++){

            //read lines
            String line = bufferedReader.readLine();
            String lc = String.valueOf(i);

            if (lc.endsWith("0")){

                try{

                    writer.append(line+"\n");
                    writer.flush();

                    }catch(Exception ee){
                }
            }
        }
</code>```

Title: Java reading nth line

Body:
I am trying to read a specific line from a text file, however I don't want to load the file into memory (it can get really big).

I have been looking but every example i have found requires either to read every line (this would slow my code down as there are over 100,000 lines) or load the whole thing into an array and get the correct element (file will have alot of lines to input).

An example of what I want to do:

String line = File.getLine(5);

"code is not actual code, it is made up to show the principle of what i want"

Is there a way to do this?

-----Edit-----

I have just realized this file will be written too in between reading lines (adding to the end of the file).

Body:
Here is a snippet of some code I had which will read a file and write every 10th line including the first line to a new file (writer.) You can always replace the try section with whatever you want to do.  To change the number of lines to read just change the 0 in the if statement "lc.endsWith("0")" to whatever line you want to read.  But if the file is being written to as you read it, this code will only work with the data that is contained inside the file when you run this code.

            LineNumberReader  lnr = new LineNumberReader(new FileReader(new File(file)));
            lnr.skip(Long.MAX_VALUE);
            int linecount=lnr.getLineNumber();
            lnr.close();

        for (int i=0; i<=linecount; i++){

            //read lines
            String line = bufferedReader.readLine();
            String lc = String.valueOf(i);

            if (lc.endsWith("0")){

                try{

                    writer.append(line+"\n");
                    writer.flush();

                    }catch(Exception ee){
                }
            }
        }


来源: stackexchange

问:
python binary search tree size
im trying to implement a binary search tree and im having trouble with my size() method, which counts the number of nodes in the tree.

```<code>class BSTNode:
def __init__(self, item):

    self._element = item
    self._leftchild = None
    self._rightchild = None
    self._parent = None
</code>```

this is what my size funtion looks like:

```<code>def size(self):

    size = 0
    if self != None:
        size += 1
        if self._leftchild != None:
            size += 1 + self._leftchild.size()
        if self._rightchild != None:
            size += 1 + self._rightchild.size()
    return size
</code>```

it overcounts the number of nodes that are actually in the tree and i dont know why, maybe because its recursive but im not  sure.

答:
You are counting the nodes twice. You should only be counting each node once.</p>

```<code>def size(self):

    size = 0
    if self != None:
        size += 1
        if self._leftchild != None:
            size += self._leftchild.size()
        if self._rightchild != None:
            size += self._rightchild.size()
    return size
</code>```

ContentLicense: CC BY-SA 3.0

Title: python binary search tree size

Body:
im trying to implement a binary search tree and im having trouble with my size() method, which counts the number of nodes in the tree.

class BSTNode:
def __init__(self, item):

    self._element = item
    self._leftchild = None
    self._rightchild = None
    self._parent = None

this is what my size funtion looks like:

def size(self):

    size = 0
    if self != None:
        size += 1
        if self._leftchild != None:
            size += 1 + self._leftchild.size()
        if self._rightchild != None:
            size += 1 + self._rightchild.size()
    return size

it overcounts the number of nodes that are actually in the tree and i dont know why, maybe because its recursive but im not  sure.

Body:
You are counting the nodes twice. You should only be counting each node once.

def size(self):

    size = 0
    if self != None:
        size += 1
        if self._leftchild != None:
            size += self._leftchild.size()
        if self._rightchild != None:
            size += self._rightchild.size()
    return size


问:
Fixed header above scrollable table
I am trying to have a table header, in a seperate div stay in place while a div undernearth is able to scroll al arge list of records. Both divs are in a div named Layer 3. Hereis the css file I am using:

#Layer3
{
    position:absolute;
    width: 89%;
    height: 40%;
    left: 10%;
    top: 56%;
    background-color: #f1ffff;
}

#Layer3 h1 {
    font-size: medium;
    color: #000033;
    text-decoration: none;
    text-align: center;
}

.tableheader {
}

.tablecontent {
    overflow: auto;
}
```

<p>and part of the php code I am using to generate the html:</p>

```echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";
echo "Start Date	" . "\n";
echo "Description	" . "\n";

echo "
\n";

// printing table rows

foreach ($rows as $row)
{
    $pk = $row['ARTICLE_NO'];
    echo '
' . "\n";

    // table contens generated in here

    echo '
' . "\n";
}
}

echo "
";
```

I am not sure what I have missed, but tableheader does not seem to be stationary, or even separate from tablecontent.

答:
div name does not equal div id.  #Layer3 is referencing an element with an id of Layer3.  Only one element is allowed to have a given id; all ids must be unique.

Don't forget to close your tags (table).

If div#Layer3 is scrolling everything inside it then it has some overflow set.  Redefine it to overflow:hidden in the #Layer3 style.  You may need to try playing with margins and floats to get things positioned right, but ill leave that to you.

Title: Fixed header above scrollable table

Body:
I am trying to have a table header, in a seperate div stay in place while a div undernearth is able to scroll al arge list of records. Both divs are in a div named Layer 3. Hereis the css file I am using:

#Layer3
{
    position:absolute;
    width: 89%;
    height: 40%;
    left: 10%;
    top: 56%;
    background-color: #f1ffff;
}

#Layer3 h1 {
    font-size: medium;
    color: #000033;
    text-decoration: none;
    text-align: center;
}

.tableheader {
}

.tablecontent {
    overflow: auto;
}

and part of the php code I am using to generate the html:

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";
echo "Start Date	" . "\n";
echo "Description	" . "\n";

echo "
\n";

// printing table rows

foreach ($rows as $row)
{
    $pk = $row['ARTICLE_NO'];
    echo '
' . "\n";

    // table contens generated in here

    echo '
' . "\n";
}
}

echo "
";

I am not sure what I have missed, but tableheader does not seem to be stationary, or even separate from tablecontent.

ContentLicense: CC BY-SA 2.5


问:
Adding dll's to the project and making functions work
I have to do one project and I was given dll and a header file with implemented functions needed for the project. I was told just to add the header file to the project but this way i get unresolve externals error if i try to use functions referenced in header. So what needs to be done to make everything work? Visual Studio 2010.
Here are the files i have: http://www.ipix.lt/images/33871682.png
And this is header file:

```<code>#ifndef __BIM482_RADAR__
#define __BIM482_RADAR__

int BIM482OpenRadar();
int BIM482AddPlane(double x, double y);
int BIM482SetPlaneColor(int planeidx, int coloridx);
int BIM482SetPlanePos(int planeidx, double x, double y);
void BIM482UpdateRadar();

#endif // __BIM482_RADAR__
</code>```

I need to initiate gui with OpenRadar and pass information with those functions. How to start this thing?

答:
You'll need to export the function from dll, while import the function from your exe. Like:

```<code>#if defined(XYZLIBRARY_EXPORT) // inside DLL
#define XYZAPI   __declspec(dllexport)
#else // outside DLL
#define XYZAPI   __declspec(dllimport)
#endif  // XYZLIBRARY_EXPORT

int XYZAPI BIM482OpenRadar();
int XYZAPI BIM482AddPlane(double x, double y);
int XYZAPI BIM482SetPlaneColor(int planeidx, int coloridx);
int XYZAPI BIM482SetPlanePos(int planeidx, double x, double y);
void XYZAPI BIM482UpdateRadar();
</code>```

In DLL, i suggest to add a macro, and add XYZLIBRARY_EXPORT in pre-processor

It will export all of your function.

In EXE, import the function, without adding pre-processor, as it will import the function by default.

Body:
I have to do one project and I was given dll and a header file with implemented functions needed for the project. I was told just to add the header file to the project but this way i get unresolve externals error if i try to use functions referenced in header. So what needs to be done to make everything work? Visual Studio 2010.
Here are the files i have: http://www.ipix.lt/images/33871682.png
And this is header file:

#ifndef __BIM482_RADAR__
#define __BIM482_RADAR__

int BIM482OpenRadar();
int BIM482AddPlane(double x, double y);
int BIM482SetPlaneColor(int planeidx, int coloridx);
int BIM482SetPlanePos(int planeidx, double x, double y);
void BIM482UpdateRadar();

#endif // __BIM482_RADAR__

I need to initiate gui with OpenRadar and pass information with those functions. How to start this thing?

Body:
You'll need to export the function from dll, while import the function from your exe. Like:

#if defined(XYZLIBRARY_EXPORT) // inside DLL
#define XYZAPI   __declspec(dllexport)
#else // outside DLL
#define XYZAPI   __declspec(dllimport)
#endif  // XYZLIBRARY_EXPORT

int XYZAPI BIM482OpenRadar();
int XYZAPI BIM482AddPlane(double x, double y);
int XYZAPI BIM482SetPlaneColor(int planeidx, int coloridx);
int XYZAPI BIM482SetPlanePos(int planeidx, double x, double y);
void XYZAPI BIM482UpdateRadar();

In DLL, i suggest to add a macro, and add XYZLIBRARY_EXPORT in pre-processor

It will export all of your function.

In EXE, import the function, without adding pre-processor, as it will import the function by default.


问:
Unexpected result after converting uint64_t to double
In the following code:

```<code>#include <iostream>

...

uint64_t t1 = 1510763846;
uint64_t t2 = 1510763847;
double d1 = (double)t1;
double d2 = (double)t2;
// d1 == t2 => evaluates to true somehow?
// t1 == d2 => evaluates to true somehow?
// d1 == d2 => evaluates to true somehow?
// t1 == t2 => evaluates to false, of course.
std::cout << std::fixed <<
        "uint64_t: " << t1 << ", " << t2 << ", " <<
        "double: " << d1 << ", " << d2 << ", " << (d2+1) << std::endl;
</code>```

I get this output:

```<code>uint64_t: 1510763846, 1510763847, double: 1510763904.000000, 1510763904.000000, 1510763905.000000
</code>```

And I don't understand why. This answer: biggest integer that can be stored in a double says that an integral number up to 2^53 (9007199254740992) can be stored in a double without losing precision.

I actually get errors when I start doing calculations with the doubles, so it's not only a printing issue. (e.g. 1510763846 and 1510763847 both give 1510763904)

It's also very weird that the double can just be added to and then come out correct (d2+1 == 1510763905.000000)

Rationale: I'm converting these numbers to doubles because I need to work with them in Lua, which only supports floating point numbers. I'm sure I'm compiling the Lua lib with double as the lua_Number type, not float.

```<code>std::cout << sizeof(t1) << ", " << sizeof(d2) << std::endl;
</code>```

Outputs

```<code>8, 8
</code>```

I'm using VS 2012 with target MachineX86, toolkit v110_xp. Floating point model "Precise (/fp:precise)"

Addendum

With the help of people who replied and this article Why are doubles added incorrectly in a specific Visual Studio 2008 project?, I've been able to pinpoint the problem. A library is using a function like _set_controlfp, _control87, _controlfp or __control87_2 to change the precision of my executable to "single". That is why a uint64_t conversion to a double behaves as if it's a float.

When doing a file search for the above function names and "MCW_PC", which is used for Precision Control, I found the following libraries that might have set it:

Android NDK

boost::math

boost::numeric

DirectX (We're using June 2010)

FMod (non-EX)

Pyro particle engine

Now I'd like to rephrase my question:

How do I make sure converting from a uint64_t to a double goes correctly every time, without:

having to call _fpreset() each and every time a possible conversion occurs (think about the function parameters)

having to worry about a library's thread changing the floating point precision in between my _fpreset() and the conversion?

Naive code would be something like this:

```<code>double toDouble(uint64_t i)
{
    double d;
    do {
        _fpreset();
        d = i;
        _fpreset();
    } while (d != i);
    return d;
}

double toDouble(int64_t i)
{
    double d;
    do {
        _fpreset();
        d = i;
        _fpreset();
    } while (d != i);
    return d;
}
</code>```

This solution assumes the odds of a thread messing with the Floating Point Precision twice are astronomically small. Problem is, the values I'm working with, are timers that represent real-world value. So I shouldn't be taking any chances. Is there a silver bullet for this problem?

答:
From ieee754 floating point conversion it looks like your implementation of double is actually float, which is of course allowed by the standard, that mandates that sizeof double >= sizeof float.

The most accurate representation of 1510763846 is 1.510763904E9.

Body:
In the following code:

#include <iostream>

...

uint64_t t1 = 1510763846;
uint64_t t2 = 1510763847;
double d1 = (double)t1;
double d2 = (double)t2;
// d1 == t2 => evaluates to true somehow?
// t1 == d2 => evaluates to true somehow?
// d1 == d2 => evaluates to true somehow?
// t1 == t2 => evaluates to false, of course.
std::cout << std::fixed <<
        "uint64_t: " << t1 << ", " << t2 << ", " <<
        "double: " << d1 << ", " << d2 << ", " << (d2+1) << std::endl;

I get this output:

uint64_t: 1510763846, 1510763847, double: 1510763904.000000, 1510763904.000000, 1510763905.000000

And I don't understand why. This answer: biggest integer that can be stored in a double says that an integral number up to 2^53 (9007199254740992) can be stored in a double without losing precision.

I actually get errors when I start doing calculations with the doubles, so it's not only a printing issue. (e.g. 1510763846 and 1510763847 both give 1510763904)

It's also very weird that the double can just be added to and then come out correct (d2+1 == 1510763905.000000)

Rationale: I'm converting these numbers to doubles because I need to work with them in Lua, which only supports floating point numbers. I'm sure I'm compiling the Lua lib with double as the lua_Number type, not float.

std::cout << sizeof(t1) << ", " << sizeof(d2) << std::endl;

Outputs

8, 8

I'm using VS 2012 with target MachineX86, toolkit v110_xp. Floating point model "Precise (/fp:precise)"

Addendum

With the help of people who replied and this article Why are doubles added incorrectly in a specific Visual Studio 2008 project?, I've been able to pinpoint the problem. A library is using a function like _set_controlfp, _control87, _controlfp or __control87_2 to change the precision of my executable to "single". That is why a uint64_t conversion to a double behaves as if it's a float.

When doing a file search for the above function names and "MCW_PC", which is used for Precision Control, I found the following libraries that might have set it:

Android NDK

boost::math

boost::numeric

DirectX (We're using June 2010)

FMod (non-EX)

Pyro particle engine

Now I'd like to rephrase my question:

How do I make sure converting from a uint64_t to a double goes correctly every time, without:

having to call _fpreset() each and every time a possible conversion occurs (think about the function parameters)

having to worry about a library's thread changing the floating point precision in between my _fpreset() and the conversion?

Naive code would be something like this:

double toDouble(uint64_t i)
{
    double d;
    do {
        _fpreset();
        d = i;
        _fpreset();
    } while (d != i);
    return d;
}

double toDouble(int64_t i)
{
    double d;
    do {
        _fpreset();
        d = i;
        _fpreset();
    } while (d != i);
    return d;
}

This solution assumes the odds of a thread messing with the Floating Point Precision twice are astronomically small. Problem is, the values I'm working with, are timers that represent real-world value. So I shouldn't be taking any chances. Is there a silver bullet for this problem?


问:
Change record field in each loop iteration
I have to generate a report which shows sales for each country, per year. (Fixed amount of years)

I managed to create this query:

```<code>SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = 'Australia' and dwdimdate.calenderyear = 2009;
        v_dwreport(1) := v_dwrecord;
</code>```

This query works perfectly to gather the amount of sales for the year 2009 in Australia. However, I want to use this query for each year and each country. I can iterate the countries, but I can't seem to iterate the years.

My record and table is declared as:

```<code>TYPE t_DWRECORD IS RECORD(
    COUNTRY     dwdimcustomer.country%TYPE,
    "2009"      NUMBER,
    "2010"      NUMBER,
    "2011"      NUMBER,
    "2012"      NUMBER,
    "2013"      NUMBER,
    "2014"      NUMBER,
    TOTAL       NUMBER
    );
TYPE t_DWTABLE IS TABLE OF t_DWRECORD INDEX BY BINARY_INTEGER;
</code>```

I created the following snippet:

```<code>v_count := 0;
FOR country_rec IN (SELECT DISTINCT country FROM dwdimcustomer order by country asc) LOOP
    FOR year_rec IN (SELECT DISTINCT calenderyear FROM dwdimdate order by calenderyear asc) LOOP
        SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = country_rec.country and dwdimdate.calenderyear = year_rec.calenderyear;
        v_dwreport(v_count) := v_dwrecord;
        v_count := v_count+1;
    END LOOP;
END LOOP;
</code>```

As you can see there's still the part INTO v_dwrecord."2009", I want to change it to the year_rec.calenderyear in each iteration. How can I do this? I tried using the EXECUTE IMMEDIATE with a VARCHAR2(500) variable, which contained a dynamic query. It looked like this: INTO v_dwrecord." || year_rec.calenderyear ||".

Working with the EXECUTE IMMEDIATE gave me the following errors:

00000 -  "SQL command not properly ended"
  *Cause:

  *Action:

00000 -  "%s: invalid identifier"
  *Cause:

  *Action:

ORA-00911: invalid character

Everything seems to break when I try out creating a dynamic query. How do I tackle this problem? Should I continue with dynamic queries or is there an easier way to change v_dwrecord."2009"?

Sample output:

答:
I think that you can do it with bulk collect and pivot, like here:

Sample data:

```<code>create table sales as (
  select 'Australia' country, 2009 year, 150 amount from dual union all
  select 'Brasil'    country, 2009 year, 927 amount from dual union all
  select 'Australia' country, 2010 year, 456 amount from dual );
</code>```

PLSQL block:

```<code>declare
    type t is record(
        country  sales.country%type,
        s2009    number,
        s2010    number,
        total    number);
    type tt is table of t index by binary_integer;

    vtt tt;
begin
    select country, s2009, s2010, nvl(s2009, 0) + nvl(s2010, 0) total
        bulk collect into vtt
        from sales
        pivot (sum(amount) for year in (2009 as s2009, 2010 as s2010));

    -- now you have your collection ready in variable vtt, show some data
    for i in 1..vtt.count loop
        dbms_output.put_line(i);
        dbms_output.put_line(vtt(i).country);
        dbms_output.put_line(' 2009: '||vtt(i).s2009);
        dbms_output.put_line(' 2010: '||vtt(i).s2010);
        dbms_output.put_line('Total: '||vtt(i).total);
    end loop;
end;
</code>```

Result:

```<code>1
Brasil
 2009: 927
 2010:
Total: 927
2
Australia
 2009: 150
 2010: 456
Total: 606
</code>```

Body:
I have to generate a report which shows sales for each country, per year. (Fixed amount of years)

I managed to create this query:

SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = 'Australia' and dwdimdate.calenderyear = 2009;
        v_dwreport(1) := v_dwrecord;

This query works perfectly to gather the amount of sales for the year 2009 in Australia. However, I want to use this query for each year and each country. I can iterate the countries, but I can't seem to iterate the years.

My record and table is declared as:

TYPE t_DWRECORD IS RECORD(
    COUNTRY     dwdimcustomer.country%TYPE,
    "2009"      NUMBER,
    "2010"      NUMBER,
    "2011"      NUMBER,
    "2012"      NUMBER,
    "2013"      NUMBER,
    "2014"      NUMBER,
    TOTAL       NUMBER
    );
TYPE t_DWTABLE IS TABLE OF t_DWRECORD INDEX BY BINARY_INTEGER;

I created the following snippet:

v_count := 0;
FOR country_rec IN (SELECT DISTINCT country FROM dwdimcustomer order by country asc) LOOP
    FOR year_rec IN (SELECT DISTINCT calenderyear FROM dwdimdate order by calenderyear asc) LOOP
        SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = country_rec.country and dwdimdate.calenderyear = year_rec.calenderyear;
        v_dwreport(v_count) := v_dwrecord;
        v_count := v_count+1;
    END LOOP;
END LOOP;

As you can see there's still the part INTO v_dwrecord."2009", I want to change it to the year_rec.calenderyear in each iteration. How can I do this? I tried using the EXECUTE IMMEDIATE with a VARCHAR2(500) variable, which contained a dynamic query. It looked like this: INTO v_dwrecord." || year_rec.calenderyear ||".

Working with the EXECUTE IMMEDIATE gave me the following errors:

00000 -  "SQL command not properly ended"
  *Cause:

  *Action:

00000 -  "%s: invalid identifier"
  *Cause:

  *Action:

ORA-00911: invalid character

Everything seems to break when I try out creating a dynamic query. How do I tackle this problem? Should I continue with dynamic queries or is there an easier way to change v_dwrecord."2009"?

Sample output:

Body:
I think that you can do it with bulk collect and pivot, like here:

Sample data:

create table sales as (
  select 'Australia' country, 2009 year, 150 amount from dual union all
  select 'Brasil'    country, 2009 year, 927 amount from dual union all
  select 'Australia' country, 2010 year, 456 amount from dual );

PLSQL block:

declare
    type t is record(
        country  sales.country%type,
        s2009    number,
        s2010    number,
        total    number);
    type tt is table of t index by binary_integer;

    vtt tt;
begin
    select country, s2009, s2010, nvl(s2009, 0) + nvl(s2010, 0) total
        bulk collect into vtt
        from sales
        pivot (sum(amount) for year in (2009 as s2009, 2010 as s2010));

    -- now you have your collection ready in variable vtt, show some data
    for i in 1..vtt.count loop
        dbms_output.put_line(i);
        dbms_output.put_line(vtt(i).country);
        dbms_output.put_line(' 2009: '||vtt(i).s2009);
        dbms_output.put_line(' 2010: '||vtt(i).s2010);
        dbms_output.put_line('Total: '||vtt(i).total);
    end loop;
end;

Result:

1
Brasil
 2009: 927
 2010:
Total: 927
2
Australia
 2009: 150
 2010: 456
Total: 606


问:
How to attach an existing sqlite database to the .apk project?
What I want is attach the database it inside the .apk. I would not like to copy it physically to the mobile device either. What I am doing now is create the database with sql scripts...Thanks</p>

答: Put it in the assets folder.  Then at runtime, copy it from the assets directory to the filesystem if you haven't already.</p>


问:
GSheets- Automate reminder e-mail to client 1-2 days prior to appointment
I'm looking for a way (google app script, add-on, or otherwise) that will automate an appointment reminder e-mail using cell values in my google spreadsheet. Currently, my work flow is like this:

I fill out my client ID and appointment date google form.

Mail merge sends a confirmation e-mail to client that informs them of their appointment date and time.

I'd like for the 3rd step to be that an e-mail is automatically sent 1-2 days prior to the appointment date and maybe a 4th step to send the e-mail on the appointment date to remind them.

Here is my sheet with dummy data and without mail merge formatting:

Although I've looked on these forums and stack exchange, I cannot find a solution to my problem. I've found that people are trying to achieve similar, but mostly want e-mails routed to a static e-mail/e-mails. My needs are more dynamic. Please help.

Here's what what I'm working with:

```<code>function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;  // First row of data to process
var numRows = sheet.getLastRow()-1;   // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data)

for (i in data) {
  var row = data[i];
  var date = new Date();
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  //Logger.log(date);
  var sheetDate = new Date(row[9]);
 //Logger.log(sheetDate);
  var Sdate = Utilities.formatDate(date,'GMT-0600','MM:dd:yyyy')
  var SsheetDate = Utilities.formatDate(sheetDate,'GMT-0600', 'MM:dd:yyyy')
     Logger.log(Sdate+' =? '+SsheetDate)
        if (Sdate == SsheetDate){
          var emailAddress = row[8]; // Patient Email
          var message = row[6];row[7];       // Date and Time
          var subject = "Your appointment is in 1 day!." +message;
          MailApp.sendEmail(emailAddress, subject, message);
          //Logger.log('SENT :'+emailAddress+'  '+subject+'  '+message)
            }
   }
  }
</code>```

What I've referred to and tried to make work for me:

Referencing by date/day- Google Forums:

Emails sent based on date- Google Forums:

Emails sent based on date - Stack Overflow:

Due Date Reminders - Stack Overflow

答:
Create a calendar event with a default set of notifications

Here's a function that creates an event on your calendar with default notifications of 1 day, 2 days and 1 hour.  You supply with an array that contains
Client Name, Appointment Date and Appointment Time as follows:
['Client Name','11/31/2017','1:30:00 PM']

```<code>function testCreateEventWithReminders()
{
  createEventWithReminders(['Harry Dog','11/20/2017','1:30:00 PM'])
}
//eA=[clientName,date,time]
function createEventWithReminders(eA)
{
  var minute=60*1000;
  var hour=60*minute;
  var day=24*hour;
  var cal=CalendarApp.getCalendarById('CalendarID');//You need to supply your calendarID
  var now=new Date().valueOf()
  var start=new Date(eA[1] + ' ' + eA[2]);
  var endValue=start.valueOf() + (hour);
  var end=new Date(endValue);
  var event=cal.createEvent(eA[0], start, end);
  event.addEmailReminder(24*60);//reminders in minutes
  event.addEmailReminder(2*24*60);
  event.addEmailReminder(60);
}
</code>```

Above you will need to insert your calendar ID.  If you run displayCalendarInfo you should be able to determine what the calendar names and id's are.

```<code>function displayCalendarInfo()//Use this function to determine calendar names and ids.
{
  var cals=CalendarApp.getAllCalendars();
  var s='Calendar Information';
  for(var i=0;i<cals.length;i++)
  {
    s+=Utilities.formatString('<br />Name: %s Id: %s', cals[i].getName(),cals[i].getId());
  }
  s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
  var ui=HtmlService.createHtmlOutput(s).setWidth(1200).setHeight(450);
  SpreadsheetApp.getUi().showModelessDialog(ui, 'Calendar Data');
}
</code>```

If you want to create your own non default reminders you can add more elements to the input array

Additional Instructions:

The input to the function createEventWithReminders(eA) is an array in the form ['client name','mm/dd/yyyy','hh:mm:ss AM'] where the date and time are for the appointment.

I'm assuming that you can integrate this function into your spreadsheet some how. Personally, I would probably would have made it into a contained webapp because I like to use Siri to do a lot of my data entry thus eliminating the need to type on my mobile device and providing me the opportunity to enter reminders as I proceed through the day without my laptop.

Body:
I'm looking for a way (google app script, add-on, or otherwise) that will automate an appointment reminder e-mail using cell values in my google spreadsheet. Currently, my work flow is like this:

I fill out my client ID and appointment date google form.

Mail merge sends a confirmation e-mail to client that informs them of their appointment date and time.

I'd like for the 3rd step to be that an e-mail is automatically sent 1-2 days prior to the appointment date and maybe a 4th step to send the e-mail on the appointment date to remind them.

Here is my sheet with dummy data and without mail merge formatting:

Although I've looked on these forums and stack exchange, I cannot find a solution to my problem. I've found that people are trying to achieve similar, but mostly want e-mails routed to a static e-mail/e-mails. My needs are more dynamic. Please help.

Here's what what I'm working with:

function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;  // First row of data to process
var numRows = sheet.getLastRow()-1;   // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data)

for (i in data) {
  var row = data[i];
  var date = new Date();
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  //Logger.log(date);
  var sheetDate = new Date(row[9]);
 //Logger.log(sheetDate);
  var Sdate = Utilities.formatDate(date,'GMT-0600','MM:dd:yyyy')
  var SsheetDate = Utilities.formatDate(sheetDate,'GMT-0600', 'MM:dd:yyyy')
     Logger.log(Sdate+' =? '+SsheetDate)
        if (Sdate == SsheetDate){
          var emailAddress = row[8]; // Patient Email
          var message = row[6];row[7];       // Date and Time
          var subject = "Your appointment is in 1 day!." +message;
          MailApp.sendEmail(emailAddress, subject, message);
          //Logger.log('SENT :'+emailAddress+'  '+subject+'  '+message)
            }
   }
  }

What I've referred to and tried to make work for me:

Referencing by date/day- Google Forums:

Emails sent based on date- Google Forums:

Emails sent based on date - Stack Overflow:

Due Date Reminders - Stack Overflow

Body:
Create a calendar event with a default set of notifications

Here's a function that creates an event on your calendar with default notifications of 1 day, 2 days and 1 hour.  You supply with an array that contains
Client Name, Appointment Date and Appointment Time as follows:
['Client Name','11/31/2017','1:30:00 PM']

function testCreateEventWithReminders()
{
  createEventWithReminders(['Harry Dog','11/20/2017','1:30:00 PM'])
}
//eA=[clientName,date,time]
function createEventWithReminders(eA)
{
  var minute=60*1000;
  var hour=60*minute;
  var day=24*hour;
  var cal=CalendarApp.getCalendarById('CalendarID');//You need to supply your calendarID
  var now=new Date().valueOf()
  var start=new Date(eA[1] + ' ' + eA[2]);
  var endValue=start.valueOf() + (hour);
  var end=new Date(endValue);
  var event=cal.createEvent(eA[0], start, end);
  event.addEmailReminder(24*60);//reminders in minutes
  event.addEmailReminder(2*24*60);
  event.addEmailReminder(60);
}

Above you will need to insert your calendar ID.  If you run displayCalendarInfo you should be able to determine what the calendar names and id's are.

function displayCalendarInfo()//Use this function to determine calendar names and ids.
{
  var cals=CalendarApp.getAllCalendars();
  var s='Calendar Information';
  for(var i=0;i<cals.length;i++)
  {
    s+=Utilities.formatString('<br />Name: %s Id: %s', cals[i].getName(),cals[i].getId());
  }
  s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
  var ui=HtmlService.createHtmlOutput(s).setWidth(1200).setHeight(450);
  SpreadsheetApp.getUi().showModelessDialog(ui, 'Calendar Data');
}

If you want to create your own non default reminders you can add more elements to the input array

Additional Instructions:

The input to the function createEventWithReminders(eA) is an array in the form ['client name','mm/dd/yyyy','hh:mm:ss AM'] where the date and time are for the appointment.

I'm assuming that you can integrate this function into your spreadsheet some how. Personally, I would probably would have made it into a contained webapp because I like to use Siri to do a lot of my data entry thus eliminating the need to type on my mobile device and providing me the opportunity to enter reminders as I proceed through the day without my laptop.


问:
Why can't a class member's name be the same as one of its nested classes?
Or why is the following impossible:

```<code>class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}
</code>```

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

答:
Because the nested class Keys is a member of Material as is the property Keys.  You've got two members called Keys.

In the same way you can't have two properties called the same thing:

```<code>public class Bar
{
    private bool Foo { get; set; }
    private string Foo { get; set; }
}
</code>```

When you access Foo which one are you trying to access?

```<code>public class Material : Keys
{

    private Keys K { get; set; }
}

public class Keys
{

}
</code>```

Works fine, but is probably not what you're after.

Body:
Or why is the following impossible:

class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

Body:
Because the nested class Keys is a member of Material as is the property Keys.  You've got two members called Keys.

In the same way you can't have two properties called the same thing:

public class Bar
{
    private bool Foo { get; set; }
    private string Foo { get; set; }
}

When you access Foo which one are you trying to access?

public class Material : Keys
{

    private Keys K { get; set; }
}

public class Keys
{

}

Works fine, but is probably not what you're after.


问:
How to read a sequence of integers from Standard-input with Stdin?
I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.

The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.

Input and Output example on Command line:

```<code>$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1
</code>```

I've tried to convert the Integers to an array

```<code>int[] n = StdIn.readAllInts();
</code>```

but it doesn't work when tried to print it out.
can anybody give me some tips?

答:
A possible solution could be:

```<code>    int testNum;
    Set<Integer> set = new HashSet<Integer>();
    Scanner in = new Scanner(System.in);

    System.out.println("number of elements to be inserted");
    testNum = in.nextInt();

    //Add items
    for ( int i = 0; i<testNum; i++)
    {
          set.add(in.nextInt());
    }

    //Print all element
    Iterator it = set.iterator();
    while(it.hasNext()){
           System.out.println(it.next());
    }
</code>```

I hope to have helped you

Body:
I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.

The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.

Input and Output example on Command line:

$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1

I've tried to convert the Integers to an array

int[] n = StdIn.readAllInts();

but it doesn't work when tried to print it out.
can anybody give me some tips?

Body:
A possible solution could be:

    int testNum;
    Set<Integer> set = new HashSet<Integer>();
    Scanner in = new Scanner(System.in);

    System.out.println("number of elements to be inserted");
    testNum = in.nextInt();

    //Add items
    for ( int i = 0; i<testNum; i++)
    {
          set.add(in.nextInt());
    }

    //Print all element
    Iterator it = set.iterator();
    while(it.hasNext()){
           System.out.println(it.next());
    }

I hope to have helped you


问:
Python array/list resetting inside loop
```<code>from collections import deque
import itertools
lfsr = deque([])
taps = []
i=0
x=0
y=0
test=''

for i in itertools.product([0,1],repeat=15):
    lfsr = deque(i)
    #print(lfsr)
    while x < len(lfsr):
        while y < len(lfsr):
            taps = [x, y]
            #print (lfsr)
            y+=1
        x+=1
</code>```

Sorry for repost.

I have a simplified version of my code above with the same problem. I am trying to set the lfsr list equal to a binary number, once this is being set i want to use this value within the nested loops. The lfsr is being set correctly i believe as when i uncomment out the first #print, it prints as it should, however when i try to print it during the nested loop, all it outputs is 0's.

What is causing the array/list to be set to 0 and changing from when its initially set?
Thanks

答:
It isn't getting reset.  The problem is your loop control.  Since you never reset x and y to 0, the only time you enter your while loops is when the dequeue is all 0s.

```<code>from collections import deque
import itertools
lfsr = deque([])
taps = []
i=0
test=''

for i in itertools.product([0,1],repeat=4):
    # reduced length to 4, to see the effects more easily

    lfsr = deque(i)
    print("TOP", lfsr)
    limit = len(lfsr)
    x=0
    while x < limit:
        y=0
        while y < limit:
            taps = [x, y]
            print ("MID", lfsr)
            y+=1
        x+=1
</code>```

Convert to for loops (which are the proper structure) to make this easier.

```<code>for i in itertools.product([0,1],repeat=4):
    lfsr = deque(i)
    print("TOP", lfsr)
    limit = len(lfsr)

    for x in range(limit):
        for y in range(limit):
            taps = [x, y]
            print ("MID", lfsr)
</code>```

Title: Python array/list resetting inside loop

Body:
from collections import deque
import itertools
lfsr = deque([])
taps = []
i=0
x=0
y=0
test=''

for i in itertools.product([0,1],repeat=15):
    lfsr = deque(i)
    #print(lfsr)
    while x < len(lfsr):
        while y < len(lfsr):
            taps = [x, y]
            #print (lfsr)
            y+=1
        x+=1

Sorry for repost.

I have a simplified version of my code above with the same problem. I am trying to set the lfsr list equal to a binary number, once this is being set i want to use this value within the nested loops. The lfsr is being set correctly i believe as when i uncomment out the first #print, it prints as it should, however when i try to print it during the nested loop, all it outputs is 0's.

What is causing the array/list to be set to 0 and changing from when its initially set?
Thanks

Body:
It isn't getting reset.  The problem is your loop control.  Since you never reset x and y to 0, the only time you enter your while loops is when the dequeue is all 0s.

from collections import deque
import itertools
lfsr = deque([])
taps = []
i=0
test=''

for i in itertools.product([0,1],repeat=4):
    # reduced length to 4, to see the effects more easily

    lfsr = deque(i)
    print("TOP", lfsr)
    limit = len(lfsr)
    x=0
    while x < limit:
        y=0
        while y < limit:
            taps = [x, y]
            print ("MID", lfsr)
            y+=1
        x+=1

Convert to for loops (which are the proper structure) to make this easier.

for i in itertools.product([0,1],repeat=4):
    lfsr = deque(i)
    print("TOP", lfsr)
    limit = len(lfsr)

    for x in range(limit):
        for y in range(limit):
            taps = [x, y]
            print ("MID", lfsr)


问:
c# automapper lookup value from source model
I have a model which has a generic properties property looking something like this:

```<code>public class GenericProperty
{
    public string Name { get; set; }
    public object Value { get; set; }
}
</code>```

Next to that I have a object that has a list with GenericProperties like this:

```<code>public class GenericEntity
{
    public string Name { get; set; }
    public List<GenericProperty> Properties { get; set; }
}
</code>```

Now im calling a API that deserialize the json to the model above. Next i want to use AutoMapper to construct an actual good looking model so i did the following:

```<code>Mapper.Initialize(x =>
{
x.CreateMap<GenericEntity, MyModel>()
    .ForMember(d => d.ManagerId, o => o.MapFrom(s => s.Properties.Where(n => n.Name == "ManagerId" ).Select(v => v.Value)))
});
</code>```

Problem is that this returns the property type and not the actual value:
System.Linq.Enumerable+WhereListIterator`1[MyProject.Models.GenericProperty]

How can i lookup the value of within the model?

答:
By using Where you are selecting all the properties with the name ManagerId. You should instead use Single like in this unit test:

```<code>public class TestClass
{
    [Test]
    public void TestMapper()
    {
        Mapper.Initialize(x =>
        {
            x.CreateMap<GenericEntity, MyModel>()
                .ForMember(d => d.ManagerId,
                           o => o.MapFrom(s => s.Properties.Single(n => n.Name == "ManagerId").Value));
        });

        var ge = new GenericEntity
        {
            Properties = new List<GenericProperty>
            {
                new GenericProperty {Name = "ManagerId", Value = "Great"}
            }
        };

        var myModel = Mapper.Map<MyModel>(ge);

        Assert.AreEqual("Great", myModel.ManagerId);
    }
}
</code>```

If you can not guarantee that there will be a property with the name ManagerId, you should use SingleOrDefault, and handle the null case.

IMHO, you should limit this kind of AutoMapper configurations to simple cases, since it quickly gets difficult to debug and maintain.

For more complex mappings like this one, I would recommend you to make an explicit mapping method instead, which you can call like an extension method. Another option worth considering if you want to use Automapper are Custom value resolvers.

Body:
I have a model which has a generic properties property looking something like this:

public class GenericProperty
{
    public string Name { get; set; }
    public object Value { get; set; }
}

Next to that I have a object that has a list with GenericProperties like this:

public class GenericEntity
{
    public string Name { get; set; }
    public List<GenericProperty> Properties { get; set; }
}

Now im calling a API that deserialize the json to the model above. Next i want to use AutoMapper to construct an actual good looking model so i did the following:

Mapper.Initialize(x =>
{
x.CreateMap<GenericEntity, MyModel>()
    .ForMember(d => d.ManagerId, o => o.MapFrom(s => s.Properties.Where(n => n.Name == "ManagerId" ).Select(v => v.Value)))
});

Problem is that this returns the property type and not the actual value:
System.Linq.Enumerable+WhereListIterator`1[MyProject.Models.GenericProperty]

How can i lookup the value of within the model?

Body:
By using Where you are selecting all the properties with the name ManagerId. You should instead use Single like in this unit test:

public class TestClass
{
    [Test]
    public void TestMapper()
    {
        Mapper.Initialize(x =>
        {
            x.CreateMap<GenericEntity, MyModel>()
                .ForMember(d => d.ManagerId,
                           o => o.MapFrom(s => s.Properties.Single(n => n.Name == "ManagerId").Value));
        });

        var ge = new GenericEntity
        {
            Properties = new List<GenericProperty>
            {
                new GenericProperty {Name = "ManagerId", Value = "Great"}
            }
        };

        var myModel = Mapper.Map<MyModel>(ge);

        Assert.AreEqual("Great", myModel.ManagerId);
    }
}

If you can not guarantee that there will be a property with the name ManagerId, you should use SingleOrDefault, and handle the null case.

IMHO, you should limit this kind of AutoMapper configurations to simple cases, since it quickly gets difficult to debug and maintain.

For more complex mappings like this one, I would recommend you to make an explicit mapping method instead, which you can call like an extension method. Another option worth considering if you want to use Automapper are Custom value resolvers.


问:
How to manage Unity3D Instances/singletons
Note: I have many years of development experience, but I'm a total beginner in Unity.

I was wondering what is the best practice for managing your GameObjects across scenes?

As you may know, each Scene has an Hierarchy tree with actual instances, lets say that I have a ScoreManager game object that I want to instantiate only one time, but I want to avoid the singleton pattern. (As it's a bad practice). Let's also say that the ScoreManager requires an instance of LevelsManager and so on...

One solution that I'm familiar with is Dependency Injection, but I did find any tutorial that uses it. All the tutorials that I see instantiate GameObjects in the Hierarchy tree, links other GameObjects via a public propery... which can count as a way to do Dependency Injection, but only for the current scene...

So, do you have a good practice that you use and love?

Thanks!

Edit:

@Shogunivar suggested DontDestroyOnLoad, the problem with that is that you should put only one GameObject in the first scene hierarchy, for example WelcomeScene, it will persist in all the future scene that were loaded.

The problem with that is that you might want to test (Press Play) say on Level01Scene that requires this GameObject to exist, but it's not there, you must first load the WelcomeScene that has this GameObject in the Heirarchy.

Putting the same GameObject also on Level01Scene will cause it to get duplicated, and will never destroy...

To solve this duplication, the only solution (That I know of) is to use Singleton. It's not "the-end-of-the-world", but this is the purpose of this question. Any other best-practice to handle this issue (In Unity)?

答:
Zenject is really powerful. There is some great documentation on their Github page as well that explains a lot. This is a great way to manage global bindings.

However, if you want something far simpler, you could inherit from a singleton class. Most people will advise against it, but it does work and it is super easy.

```<code>public class SingletonController : MonoBehaviour {
 public static SingletonController Instance;

 private void Awake() {
  if (Instance != null) {
   Destroy(gameObject);
  } else {
   Instance = this;
  }
 }
}
</code>```

Body:
Zenject is really powerful. There is some great documentation on their Github page as well that explains a lot. This is a great way to manage global bindings.

However, if you want something far simpler, you could inherit from a singleton class. Most people will advise against it, but it does work and it is super easy.

public class SingletonController : MonoBehaviour {
 public static SingletonController Instance;

 private void Awake() {
  if (Instance != null) {
   Destroy(gameObject);
  } else {
   Instance = this;
  }
 }
}


问:
How to use Power BI Embedded?
After reading the Power BI Embedded documentation, I have a Bunch of Questions.

How should a Front End Developer,who has very little knowledge in Backend Technologies but has knowledge of Power BI approach power BI embedded?

What should I do with the code generated in the Embed code sample?

If I have the Embed Id,Report ID and Embed URL,Can this Embedding be done without any Back End?

I'm trying to embed a report in a website where users do not require a Power BI account to view them.

答:
I agree with the person who asked the question. Recently, I spent a few weeks to get an embedded solution to work as I wanted to. There's a lot of documentation but it really isn't that clear on some things.

The easiest way to present your report on a web page is Publish to web as described here: https://powerbi.microsoft.com/en-us/documentation/powerbi-service-publish-to-web/

There are some disadvantages though, as described in the link. The main thing is, there's no real security with Publish to web. If someone knows the URL of the report, they are able to see it without any credentials.

The second way is to use the embedded APIs and all the things related to it, as described in the link you posted. And yes, you might need some backend code as well.

To sum up, you need an Azure AD tenant and one account in the tenant with Power BI Pro subscription.
First, you register a PowerBI app to Azure and write down the client id you get from that (https://dev.powerbi.com/apps). This is just to make the authentication work correctly.

Then you'll need to login to Azure portal and update the permission settings of the app you registered (https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-register-app/#apply-permissions-to-your-application-within-azure-ad).

Now you can publish the report to Power BI service. You should write down the report, workspace and dataset GUIDs after you have published the report. These GUIDs are visible in the URL when you click on the report and the report dataset.

After all of this, you're able to use the examples provided. You should have all the settings and id's that examples need. The backend stuff might be needed, if you'd like to use a single master account in the authentication.

ContentLicense: CC BY-SA 4.0

Title: How to use Power BI Embedded?


答: In addition to including header files, you need to link your program with the corresponding libraries. From your screenshot, you seem to have .a files, which are indeed libraries, but unfortunately they are meant for use with the GCC toolchain and will not work with Visual Studio. You either need to get .lib files if you must use Visual Studio, or otherwise switch to a GCC port such as MinGW.

Title: Adding dll's to the project and making functions work


问:
Including std::vector in header file results in template instantiation errors
I have a code that compiled just fine in Visual Studio 2017 until today, but now I keep getting template instantiation errors from std::vector which are provided at the end of the post. I should add that not a single line of code has been changed between then(when code compiled ok) and now.

When I isolated the problem, it strangely boiled down to whether or not std::vector is included in one of the header files. The following code reproduces the errors:

(Note that the code does not make much sense as it is.)

CDataUnit_ALB.h:

```<code>#pragma once

#include "DataUnit\CDataUnit.h"

// #include <vector> // <== UnREM'ing this results in compile errors

class CDataUnit_ALB :
    public CDataUnit
{
public:
    friend
    void swap(CDataUnit_ALB& lhs, CDataUnit_ALB& rhs) {
        using Base_t = CDataUnit;

        using std::swap;
        swap(static_cast<Base_t&>(lhs), static_cast<Base_t&>(rhs));
    }
};
</code>```

CDataUnit.h

```<code>#pragma once

#include <memory>

template<typename Tp_Alloc = std::allocator<char>>
class basic_CDataUnit
{
public:
    using allocator_type =
        typename std::allocator_traits<Tp_Alloc>::template rebind_alloc<char>;

    struct Representation :
        public allocator_type
    {
        char* data;

        friend
        void swap(Representation& lhs, Representation& rhs) noexcept {
            using std::swap;
            swap<allocator_type>(lhs, rhs); // swap base members
            swap(lhs.data, rhs.data);
        }
    };

    Representation m_r;

    friend
    void swap(basic_CDataUnit& lhs, basic_CDataUnit& rhs) noexcept {
        using std::swap;
        swap(lhs.m_r, rhs.m_r);
    }
};

using CDataUnit = basic_CDataUnit<>;
</code>```

main.cpp

```<code>#include "DataUnit\CDataUnit_ALB.h"

int main() {
    return 0;
}
</code>```

Here is the compile errors I am getting:

```<code>1>------ Build started: Project: test, Configuration: Debug Win32 ------
1>CDataUnit_ALB.cpp
1>c:\[path_to_msvc]\14.11.25503\include\vector(2131): error C2039: '_Alloc': is not a member of 'std::allocator<char>'
1>c:\[path_to_msvc]\14.11.25503\include\iosfwd(628): note: see declaration of 'std::allocator<char>'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2179): note: see reference to class template instantiation 'std::_Vb_iter_base<_Alvbase_wrapped>' being compiled
1>        with
1>        [
1>            _Alvbase_wrapped=std::allocator<char>
1>        ]
1>c:\[path_to_project]\cdataunit.h(20): note: see reference to class template instantiation 'std::_Vb_reference<std::allocator<char>>' being compiled
1>c:\[path_to_project]\cdataunit.h(18): note: while compiling class template member function 'void swap(basic_CDataUnit<std::allocator<char>>::Representation &,basic_CDataUnit<std::allocator<char>>::Representation &) noexcept'
1>c:\[path_to_project]\cdataunit.h(25): note: see reference to class template instantiation 'basic_CDataUnit<std::allocator<char>>::Representation' being compiled
1>c:\[path_to_project]\cdataunit_alb.h(10): note: see reference to class template instantiation 'basic_CDataUnit<std::allocator<char>>' being compiled
1>c:\[path_to_msvc]\14.11.25503\include\vector(2131): error C2061: syntax error: identifier '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2131): error C2238: unexpected token(s) preceding ';'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2065: '_Alvbase': undeclared identifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2923: 'std::allocator_traits': '_Alvbase' is not a valid template type argument for parameter '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2955: 'std::allocator_traits': use of class template requires template argument list
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(878): note: see declaration of 'std::allocator_traits'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2039: 'size_type': is not a member of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(196): note: see declaration of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2061: syntax error: identifier 'size_type'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2238: unexpected token(s) preceding ';'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2065: '_Alvbase': undeclared identifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2923: 'std::allocator_traits': '_Alvbase' is not a valid template type argument for parameter '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2955: 'std::allocator_traits': use of class template requires template argument list
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(878): note: see declaration of 'std::allocator_traits'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2039: 'difference_type': is not a member of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(196): note: see declaration of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2061: syntax error: identifier 'difference_type'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2238: unexpected token(s) preceding ';'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2134): error C2065: '_Alvbase': undeclared identifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2134): error C2923: 'std::_Rebind_alloc_t': '_Alvbase' is not a valid template type argument for parameter '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2141): error C2061: syntax error: identifier '_Sizet'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2148): error C2061: syntax error: identifier '_Sizet'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2155): error C2061: syntax error: identifier '_Sizet'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2172): error C3646: '_Myoff': unknown override specifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2172): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
</code>```

Strange Observations:

1- The first error(i.e. error C2039: '_Alloc': is not a member of 'std::allocator<char>') originates from the typedef using _Alvbase = typename _Alvbase_wrapped::_Alloc; in class _Vb_iter_base which, it seems, has to do with bool specialization of std::vector and that specialization is not used anywhere in the code.

2- Replacing swap<allocator_type>(lhs, rhs); in friend void swap(Representation& lhs, Representation& rhs) in CDataUnit.h with swap(static_cast<allocator_type&>(lhs), static_cast<allocator_type&>(rhs)); seems to fix the problem.

I appreciate any ideas on why this is happening.

答:
Consider this:

```<code>template<class T> struct foo : T { };
template<class T> void swap(foo<T>, foo<T>);
template<class T> void swap(T&, T&);

int i = 1, j = 2;
swap<int>(i, j);
</code>```

What do you think happens?

```<code>main.cpp:1:36: error: base specifier must name a class
    template<class T> struct foo : T { };
                                   ^
main.cpp:6:15: note: in instantiation of template class 'foo<int>' requested here
    swap<int>(i, j);
              ^
</code>```

Because you specified an explicit template argument, it's substituted into the signature of every function template in the overload set, which means that you can cause the instantiation of class templates with types they are never meant to be used with if the class template is used in the signature of one of the overloads.

In the above example, that substitution triggers the instantiation of foo<int>, which triggers a hard error. In your code, it's std::_Vb_reference<std::allocator<char>>.

Just...don't do it.

Body:
I have a code that compiled just fine in Visual Studio 2017 until today, but now I keep getting template instantiation errors from std::vector which are provided at the end of the post. I should add that not a single line of code has been changed between then(when code compiled ok) and now.

When I isolated the problem, it strangely boiled down to whether or not std::vector is included in one of the header files. The following code reproduces the errors:

(Note that the code does not make much sense as it is.)

CDataUnit_ALB.h:

#pragma once

#include "DataUnit\CDataUnit.h"

// #include <vector> // <== UnREM'ing this results in compile errors

class CDataUnit_ALB :
    public CDataUnit
{
public:
    friend
    void swap(CDataUnit_ALB& lhs, CDataUnit_ALB& rhs) {
        using Base_t = CDataUnit;

        using std::swap;
        swap(static_cast<Base_t&>(lhs), static_cast<Base_t&>(rhs));
    }
};

CDataUnit.h

#pragma once

#include <memory>

template<typename Tp_Alloc = std::allocator<char>>
class basic_CDataUnit
{
public:
    using allocator_type =
        typename std::allocator_traits<Tp_Alloc>::template rebind_alloc<char>;

    struct Representation :
        public allocator_type
    {
        char* data;

        friend
        void swap(Representation& lhs, Representation& rhs) noexcept {
            using std::swap;
            swap<allocator_type>(lhs, rhs); // swap base members
            swap(lhs.data, rhs.data);
        }
    };

    Representation m_r;

    friend
    void swap(basic_CDataUnit& lhs, basic_CDataUnit& rhs) noexcept {
        using std::swap;
        swap(lhs.m_r, rhs.m_r);
    }
};

using CDataUnit = basic_CDataUnit<>;

main.cpp

#include "DataUnit\CDataUnit_ALB.h"

int main() {
    return 0;
}

Here is the compile errors I am getting:

1>------ Build started: Project: test, Configuration: Debug Win32 ------
1>CDataUnit_ALB.cpp
1>c:\[path_to_msvc]\14.11.25503\include\vector(2131): error C2039: '_Alloc': is not a member of 'std::allocator<char>'
1>c:\[path_to_msvc]\14.11.25503\include\iosfwd(628): note: see declaration of 'std::allocator<char>'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2179): note: see reference to class template instantiation 'std::_Vb_iter_base<_Alvbase_wrapped>' being compiled
1>        with
1>        [
1>            _Alvbase_wrapped=std::allocator<char>
1>        ]
1>c:\[path_to_project]\cdataunit.h(20): note: see reference to class template instantiation 'std::_Vb_reference<std::allocator<char>>' being compiled
1>c:\[path_to_project]\cdataunit.h(18): note: while compiling class template member function 'void swap(basic_CDataUnit<std::allocator<char>>::Representation &,basic_CDataUnit<std::allocator<char>>::Representation &) noexcept'
1>c:\[path_to_project]\cdataunit.h(25): note: see reference to class template instantiation 'basic_CDataUnit<std::allocator<char>>::Representation' being compiled
1>c:\[path_to_project]\cdataunit_alb.h(10): note: see reference to class template instantiation 'basic_CDataUnit<std::allocator<char>>' being compiled
1>c:\[path_to_msvc]\14.11.25503\include\vector(2131): error C2061: syntax error: identifier '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2131): error C2238: unexpected token(s) preceding ';'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2065: '_Alvbase': undeclared identifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2923: 'std::allocator_traits': '_Alvbase' is not a valid template type argument for parameter '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2955: 'std::allocator_traits': use of class template requires template argument list
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(878): note: see declaration of 'std::allocator_traits'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2039: 'size_type': is not a member of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(196): note: see declaration of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2061: syntax error: identifier 'size_type'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2132): error C2238: unexpected token(s) preceding ';'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2065: '_Alvbase': undeclared identifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2923: 'std::allocator_traits': '_Alvbase' is not a valid template type argument for parameter '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2955: 'std::allocator_traits': use of class template requires template argument list
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(878): note: see declaration of 'std::allocator_traits'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2039: 'difference_type': is not a member of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\xmemory0(196): note: see declaration of 'std::allocator_traits<_Alloc>'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2061: syntax error: identifier 'difference_type'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2133): error C2238: unexpected token(s) preceding ';'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2134): error C2065: '_Alvbase': undeclared identifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2134): error C2923: 'std::_Rebind_alloc_t': '_Alvbase' is not a valid template type argument for parameter '_Alloc'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2141): error C2061: syntax error: identifier '_Sizet'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2148): error C2061: syntax error: identifier '_Sizet'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2155): error C2061: syntax error: identifier '_Sizet'
1>c:\[path_to_msvc]\14.11.25503\include\vector(2172): error C3646: '_Myoff': unknown override specifier
1>c:\[path_to_msvc]\14.11.25503\include\vector(2172): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Strange Observations:

1- The first error(i.e. error C2039: '_Alloc': is not a member of 'std::allocator<char>') originates from the typedef using _Alvbase = typename _Alvbase_wrapped::_Alloc; in class _Vb_iter_base which, it seems, has to do with bool specialization of std::vector and that specialization is not used anywhere in the code.

2- Replacing swap<allocator_type>(lhs, rhs); in friend void swap(Representation& lhs, Representation& rhs) in CDataUnit.h with swap(static_cast<allocator_type&>(lhs), static_cast<allocator_type&>(rhs)); seems to fix the problem.

I appreciate any ideas on why this is happening.

Body:
Consider this:

template<class T> struct foo : T { };
template<class T> void swap(foo<T>, foo<T>);
template<class T> void swap(T&, T&);

int i = 1, j = 2;
swap<int>(i, j);

What do you think happens?

main.cpp:1:36: error: base specifier must name a class
    template<class T> struct foo : T { };
                                   ^
main.cpp:6:15: note: in instantiation of template class 'foo<int>' requested here
    swap<int>(i, j);
              ^

Because you specified an explicit template argument, it's substituted into the signature of every function template in the overload set, which means that you can cause the instantiation of class templates with types they are never meant to be used with if the class template is used in the signature of one of the overloads.

In the above example, that substitution triggers the instantiation of foo<int>, which triggers a hard error. In your code, it's std::_Vb_reference<std::allocator<char>>.

Just...don't do it.


问:
Validate database schema programmatically in hibernate throws MySQLNonTransientConnectionException
Trying to validate schema programmatically

```<code>@Autowired
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean;
</code>```

// code for getting hibernate configuration

```<code>private Configuration getHibernateConfiguration() {
        final PersistenceUnitInfo persistenceUnitInfo = localContainerEntityManagerFactoryBean.getPersistenceUnitInfo();
        final Map<String, Object> jpaPropertyMap = localContainerEntityManagerFactoryBean.getJpaPropertyMap();
        EntityManagerFactoryBuilderImpl builder = new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), jpaPropertyMap) {
            @Override
            public Configuration buildHibernateConfiguration(ServiceRegistry serviceRegistry) {
                Configuration configuration = super.buildHibernateConfiguration(serviceRegistry);
                if (persistenceUnitInfo instanceof SmartPersistenceUnitInfo) {
                    for (String managedPackage : ((SmartPersistenceUnitInfo) persistenceUnitInfo).getManagedPackages()) {
                        configuration.addPackage(managedPackage);
                    }
                }
                return configuration;
            }
        };
        serviceRegistry = builder.buildServiceRegistry();

        return builder.buildHibernateConfiguration(serviceRegistry);
    }
</code>```

This method tries to call the schemaValidator method from  Configuration class.

```<code>public void getSchemaValidationService(DataSource dataSource) {
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.dialect", hibernateDialect);
        Dialect dialect = Dialect.getDialect(hibernateProperties);
        Configuration configuration = getHibernateConfiguration(dataSource);
        Connection connection = null;
        try {
            connection = dataSource().getConnection();
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect, configuration);
            configuration.validateSchema(dialect, metadata);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (connection != null) {
                try {
                    new SqlExceptionHelper().logAndClearWarnings( connection );
                    connection.setAutoCommit( false );
                    connection.close();
                    logger.error("Connection Closed : "+connection.isClosed() );
                    connection = null;
                    StandardServiceRegistryBuilder.destroy(serviceRegistry);

                } catch (SQLException e) {
                    logger.error("Datasource connection failed to close");
                }
            }
        }

    }
</code>```

Using hibernate in multi-tenancy mode so trying to validate schema programmatically.

Schema validation works perfect, but after few minutes it tries to throw

MySQLNonTransientConnectionException in case if validation fails.

Any valuable suggestions please.

答: Yes, the issue was dataSource was not closed when schema validation fails</p>

Body:
Trying to validate schema programmatically

@Autowired
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean;

// code for getting hibernate configuration

private Configuration getHibernateConfiguration() {
        final PersistenceUnitInfo persistenceUnitInfo = localContainerEntityManagerFactoryBean.getPersistenceUnitInfo();
        final Map<String, Object> jpaPropertyMap = localContainerEntityManagerFactoryBean.getJpaPropertyMap();
        EntityManagerFactoryBuilderImpl builder = new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), jpaPropertyMap) {
            @Override
            public Configuration buildHibernateConfiguration(ServiceRegistry serviceRegistry) {
                Configuration configuration = super.buildHibernateConfiguration(serviceRegistry);
                if (persistenceUnitInfo instanceof SmartPersistenceUnitInfo) {
                    for (String managedPackage : ((SmartPersistenceUnitInfo) persistenceUnitInfo).getManagedPackages()) {
                        configuration.addPackage(managedPackage);
                    }
                }
                return configuration;
            }
        };
        serviceRegistry = builder.buildServiceRegistry();

        return builder.buildHibernateConfiguration(serviceRegistry);
    }

This method tries to call the schemaValidator method from  Configuration class.

public void getSchemaValidationService(DataSource dataSource) {
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.dialect", hibernateDialect);
        Dialect dialect = Dialect.getDialect(hibernateProperties);
        Configuration configuration = getHibernateConfiguration(dataSource);
        Connection connection = null;
        try {
            connection = dataSource().getConnection();
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect, configuration);
            configuration.validateSchema(dialect, metadata);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (connection != null) {
                try {
                    new SqlExceptionHelper().logAndClearWarnings( connection );
                    connection.setAutoCommit( false );
                    connection.close();
                    logger.error("Connection Closed : "+connection.isClosed() );
                    connection = null;
                    StandardServiceRegistryBuilder.destroy(serviceRegistry);

                } catch (SQLException e) {
                    logger.error("Datasource connection failed to close");
                }
            }
        }

    }

Using hibernate in multi-tenancy mode so trying to validate schema programmatically.

Schema validation works perfect, but after few minutes it tries to throw

MySQLNonTransientConnectionException in case if validation fails.

Any valuable suggestions please.


问:
Owl carousel not following z-index in Wordpress theme
I've implemented Owl Carousel in the header of my Wordpress theme. It is a basic slider with each item containing a background image and an overlay div that will eventually feature information about my blog posts. I also have a fixed navigation bar at the top of my blog. No matter how I style the elements, the Owl Carousel continues to disobey the z-index parameters and scroll on top of my fixed navigation.

Here's the styling of my navigation:

```<code>.topbar {
  width:100%;
  color: #fff;
  position:fixed;
  font-family:'Abril Fatface';
  z-index:1;
}
</code>```

And the styling for my carousel:

```<code>.carousel-wrap {
   max-width: 1200px;
   width: 100%;
   height: 475px!important;
   margin:auto;
   margin-bottom:50px;
   position: relative;
   z-index:100;
}

/* fix blank or flashing items on carousel */
.owl-carousel .item {
  position: relative;
  -webkit-backface-visibility: hidden;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 37%;
  height: 450px;
}

/* end fix */
.owl-nav > div {
  margin-top: -26px;
  position: absolute;
  top: 50%;
  color: #cdcbcd;
}

.owl-nav i {
  font-size: 52px;
}

.owl-nav .owl-prev {
  left: -30px;
}

.owl-nav .owl-next {
  right: -30px;
}
.caroverlay {
   padding:40px;
   text-align: center;
   background: rgba(255, 255, 255, 0.5);
   max-width:300px;
   display: block;
   position: relative;
   top:175px;
   left: 40px;
   color:#000;
}
</code>```

Here is the HTML which in placed in my theme's header:

```<code><div class="carousel-wrapper">
  <div class="owl-carousel">

    <div class="item" style="background-image: url('https://hdwallsource.com/img/2016/6/zoe-kravitz-celebrity-wide-wallpaper-55692-57437-hd-wallpapers.jpg')">
    <div class="caroverlay">This is some text.</div>
    </div>

    <div class="item" style="background-image: url('http://pixel.nymag.com/imgs/fashion/daily/2017/04/08/08-zoekravitz.w710.h473.2x.jpeg')">
    <div class="caroverlay">This is some text.</div>
    </div>

  </div>
</div>
</code>```

Lastly, here is the JS that I placed in my theme's footer:

```<code><script>
$('.owl-carousel').owlCarousel({
  loop: true,
  margin: 10,
  nav: true,
  autoplay: true,
  items: 1,
    singleItem: true,
    itemsScaleUp : true,
})
</script>
</code>```

I've tried everything I can think of and nothing is working. My last attempt was wrapping all of the divs in a container that was set with a low z-index, but that also did not work. Here is a screenshot. Any help would be greatly appreciated. Thanks!

答:
You need the z-index of your topbar navigation to be higher than your carousel's z-index (100).</p>

```<code>.topbar {
  z-index:999;
}
</code>```

Body:
I've implemented Owl Carousel in the header of my Wordpress theme. It is a basic slider with each item containing a background image and an overlay div that will eventually feature information about my blog posts. I also have a fixed navigation bar at the top of my blog. No matter how I style the elements, the Owl Carousel continues to disobey the z-index parameters and scroll on top of my fixed navigation.

Here's the styling of my navigation:

.topbar {
  width:100%;
  color: #fff;
  position:fixed;
  font-family:'Abril Fatface';
  z-index:1;
}

And the styling for my carousel:

.carousel-wrap {
   max-width: 1200px;
   width: 100%;
   height: 475px!important;
   margin:auto;
   margin-bottom:50px;
   position: relative;
   z-index:100;
}

/* fix blank or flashing items on carousel */
.owl-carousel .item {
  position: relative;
  -webkit-backface-visibility: hidden;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 37%;
  height: 450px;
}

/* end fix */
.owl-nav > div {
  margin-top: -26px;
  position: absolute;
  top: 50%;
  color: #cdcbcd;
}

.owl-nav i {
  font-size: 52px;
}

.owl-nav .owl-prev {
  left: -30px;
}

.owl-nav .owl-next {
  right: -30px;
}
.caroverlay {
   padding:40px;
   text-align: center;
   background: rgba(255, 255, 255, 0.5);
   max-width:300px;
   display: block;
   position: relative;
   top:175px;
   left: 40px;
   color:#000;
}

Here is the HTML which in placed in my theme's header:

This is some text.

This is some text.

Lastly, here is the JS that I placed in my theme's footer:

I've tried everything I can think of and nothing is working. My last attempt was wrapping all of the divs in a container that was set with a low z-index, but that also did not work. Here is a screenshot. Any help would be greatly appreciated. Thanks!

Body:
You need the z-index of your topbar navigation to be higher than your carousel's z-index (100).

.topbar {
  z-index:999;
}


问:
BigQuery - can you add a value via ALLOW_FIELD_ADDITION?
I'm trying to add a new column while loading data into BigQuery with a repeated / static value that isn't in my source file/data.

I have managed to add a nullable column to my table on load with the ALLOW_FIELD_ADDITION option, but this just adds a column with null for values.

How would I go about setting a static value for each row in this new column?

My load config looks like this:

```<code>config= {
  'configuration'=> {
      'load'=> {
        'sourceUris'=> files_array,
        'schema'=> {
          'fields'=> fields_array
          },
        'schemaUpdateOptions' => [{ 'ALLOW_FIELD_ADDITION'=> true}],
        'destinationTable'=> {
          'projectId'=> my_project,
          'datasetId'=> 'my_dataset',
          'tableId'=> my_table
        },
        'sourceFormat' => 'NEWLINE_DELIMITED_JSON',
        'createDisposition' => 'CREATE_IF_NEEDED',
        'writeDisposition' => 'WRITE_TRUNCATE',
        'maxBadRecords'=> 10,
      }
    },
  }
</code>```

Thanks in advance!

答:
You'll have to do this in 2 steps:

Step 1: Load your data with the existing columns.

Step 2: SELECT *, 3 AS new_column FROM ..., and save the results of this query as a table.

Body:
I'm trying to add a new column while loading data into BigQuery with a repeated / static value that isn't in my source file/data.

I have managed to add a nullable column to my table on load with the ALLOW_FIELD_ADDITION option, but this just adds a column with null for values.

How would I go about setting a static value for each row in this new column?

My load config looks like this:

config= {
  'configuration'=> {
      'load'=> {
        'sourceUris'=> files_array,
        'schema'=> {
          'fields'=> fields_array
          },
        'schemaUpdateOptions' => [{ 'ALLOW_FIELD_ADDITION'=> true}],
        'destinationTable'=> {
          'projectId'=> my_project,
          'datasetId'=> 'my_dataset',
          'tableId'=> my_table
        },
        'sourceFormat' => 'NEWLINE_DELIMITED_JSON',
        'createDisposition' => 'CREATE_IF_NEEDED',
        'writeDisposition' => 'WRITE_TRUNCATE',
        'maxBadRecords'=> 10,
      }
    },
  }

Thanks in advance!


问:
Keeping track of points in simple console game
I'm having a hard time wrapping my mind around this. Every time the player makes a wrong guess, it should subtract his/her bet from the initial balance.
Since it is in a loop, it always takes the initial balance from the beginning spits out the same balance every time. (obviously)
I've tried assigning different variables and just can't seem to figure it out.

I've omitted the medium and hard difficulty methods as they are of no use right now, until I figure out this one.

My Main() only calls the setDifficulty(). Nothing else.

```<code>class Control
{
    int selectedNumber = 0;
    Random num = new Random();
    bool playAgain = true;
    int difficulty = 0;
    int bet = 0;
    int initialBalance = 20;
    int runningCredits = 0;
    int credits = 0;

    public Control()
    { }

    //sets game difficulty
    public void SetDifficulty()
    {

        Console.Clear();
        Console.WriteLine("Please select level of difficulty between 1 - 100");
        difficulty = int.Parse(Console.ReadLine());

        if (difficulty >= 1 && difficulty <= 20)
            LetsPlayEasy();

        else if (difficulty >= 21 && difficulty <= 50)
            LetsPlayMedium();

        else if (difficulty >= 51 && difficulty <= 100)
            LetsPlayHard();

        else
        {
            SetDifficulty();
        }

    }

    //easy level method
    public void LetsPlayEasy()
    {
        //variables
        int userGuess;
        int numGuesses = 0;
        selectedNumber = num.Next(1, 101);

        Console.BackgroundColor = ConsoleColor.DarkYellow;
        Console.Clear();
        Console.ForegroundColor = ConsoleColor.White;

        Console.WriteLine("Difficulty level = EASY");

        Console.WriteLine("\nBeggining credit balance = " + initialBalance);
        Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
        bet = int.Parse(Console.ReadLine());

        do
        {
            Console.WriteLine("\nGuess a number between 1 and 100.");
            userGuess = Convert.ToInt32(Console.ReadLine());
            numGuesses++;

            UI output = new UI();
            output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);

            runningCredits = (initialBalance - bet);
            Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");

        } while (playAgain == true);
    }
</code>```

```<code>class UI
{
    Random num = new Random();
    int keepGoing;

    public UI()
    { }

    //compare user's guess to selected number
    public void CompareNumbers(int userGuess, ref int selectedNumber, ref bool playAgain, ref int numGuesses)
    {
        Control difficulty = new Control();
        Admin say = new Admin();

        if (userGuess > selectedNumber)
        {
            Console.Beep(600, 300);
            Console.WriteLine("\nToo High! Guess Again!");

        }

        else if (userGuess < selectedNumber)
        {
            Console.Beep(300, 300);
            Console.WriteLine("\nToo Low! Guess Again!");

        }
        else
        {
            Console.Beep(350, 300);
            Console.Beep(380, 200);
            Console.Beep(380, 100);
            Console.Beep(500, 1100);
            Console.WriteLine("\n\nCongrats! It took you " + numGuesses + " guesses to win.");
            numGuesses = 0;
            Console.WriteLine("Press 1 to play again or 2 to quit.");
            keepGoing = int.Parse(Console.ReadLine());

            while (keepGoing != 1 && keepGoing != 2)
            {
                Console.WriteLine("\n\nPlease type either 1 or 2 only!");
                keepGoing = int.Parse(Console.ReadLine());
            }

            if (keepGoing == 2)
            {
                playAgain = false;
                say.Goodbye();
            }

            else
            {
                Console.Clear();
                difficulty.SetDifficulty();
            }

        }

    }
}
</code>```

}

答:
Initialise runningBalance to initialBalance and only use this value for calculations. If you only need initialBalance once, you can also do it by simply switching runningBalance to initialBalance without initializing runningBalance.</p>

```<code> Console.WriteLine("\nBeggining credit balance = " + initialBalance);
 Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
 bet = int.Parse(Console.ReadLine());
 runningBalance = initialBalance
 do
 {
     Console.WriteLine("\nGuess a number between 1 and 100.");
     userGuess = Convert.ToInt32(Console.ReadLine());
     numGuesses++;

     UI output = new UI();
     output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);

     runningCredits -= bet;
     Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");

 } while (playAgain == true);
</code>```

Body:
I'm having a hard time wrapping my mind around this. Every time the player makes a wrong guess, it should subtract his/her bet from the initial balance.
Since it is in a loop, it always takes the initial balance from the beginning spits out the same balance every time. (obviously)
I've tried assigning different variables and just can't seem to figure it out.

I've omitted the medium and hard difficulty methods as they are of no use right now, until I figure out this one.

My Main() only calls the setDifficulty(). Nothing else.

class Control
{
    int selectedNumber = 0;
    Random num = new Random();
    bool playAgain = true;
    int difficulty = 0;
    int bet = 0;
    int initialBalance = 20;
    int runningCredits = 0;
    int credits = 0;

    public Control()
    { }

    //sets game difficulty
    public void SetDifficulty()
    {

        Console.Clear();
        Console.WriteLine("Please select level of difficulty between 1 - 100");
        difficulty = int.Parse(Console.ReadLine());

        if (difficulty >= 1 && difficulty <= 20)
            LetsPlayEasy();

        else if (difficulty >= 21 && difficulty <= 50)
            LetsPlayMedium();

        else if (difficulty >= 51 && difficulty <= 100)
            LetsPlayHard();

        else
        {
            SetDifficulty();
        }

    }

    //easy level method
    public void LetsPlayEasy()
    {
        //variables
        int userGuess;
        int numGuesses = 0;
        selectedNumber = num.Next(1, 101);

        Console.BackgroundColor = ConsoleColor.DarkYellow;
        Console.Clear();
        Console.ForegroundColor = ConsoleColor.White;

        Console.WriteLine("Difficulty level = EASY");

        Console.WriteLine("\nBeggining credit balance = " + initialBalance);
        Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
        bet = int.Parse(Console.ReadLine());

        do
        {
            Console.WriteLine("\nGuess a number between 1 and 100.");
            userGuess = Convert.ToInt32(Console.ReadLine());
            numGuesses++;

            UI output = new UI();
            output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);

            runningCredits = (initialBalance - bet);
            Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");

        } while (playAgain == true);
    }

class UI
{
    Random num = new Random();
    int keepGoing;

    public UI()
    { }

    //compare user's guess to selected number
    public void CompareNumbers(int userGuess, ref int selectedNumber, ref bool playAgain, ref int numGuesses)
    {
        Control difficulty = new Control();
        Admin say = new Admin();

        if (userGuess > selectedNumber)
        {
            Console.Beep(600, 300);
            Console.WriteLine("\nToo High! Guess Again!");

        }

        else if (userGuess < selectedNumber)
        {
            Console.Beep(300, 300);
            Console.WriteLine("\nToo Low! Guess Again!");

        }
        else
        {
            Console.Beep(350, 300);
            Console.Beep(380, 200);
            Console.Beep(380, 100);
            Console.Beep(500, 1100);
            Console.WriteLine("\n\nCongrats! It took you " + numGuesses + " guesses to win.");
            numGuesses = 0;
            Console.WriteLine("Press 1 to play again or 2 to quit.");
            keepGoing = int.Parse(Console.ReadLine());

            while (keepGoing != 1 && keepGoing != 2)
            {
                Console.WriteLine("\n\nPlease type either 1 or 2 only!");
                keepGoing = int.Parse(Console.ReadLine());
            }

            if (keepGoing == 2)
            {
                playAgain = false;
                say.Goodbye();
            }

            else
            {
                Console.Clear();
                difficulty.SetDifficulty();
            }

        }

    }
}

}

Body:
Initialise runningBalance to initialBalance and only use this value for calculations. If you only need initialBalance once, you can also do it by simply switching runningBalance to initialBalance without initializing runningBalance.

 Console.WriteLine("\nBeggining credit balance = " + initialBalance);
 Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
 bet = int.Parse(Console.ReadLine());
 runningBalance = initialBalance
 do
 {
     Console.WriteLine("\nGuess a number between 1 and 100.");
     userGuess = Convert.ToInt32(Console.ReadLine());
     numGuesses++;

     UI output = new UI();
     output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);

     runningCredits -= bet;
     Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");

 } while (playAgain == true);


问:
how to add guest to google calendar link
I am adding a google calendar link to my website as below

```<code> <a href="https://calendar.google.com/calendar/render?
    action=TEMPLATE&
    text={{ticket.subject}}&
    dates=20170127T210000Z/20170127T220000Z&
    details=For+details,+link+here:+https://www.example.com/&
    location=Hyderabad,+Telangana,+India&sf=true&
    output=xml#eventpage_6"
    target="_blank" rel="nofollow">Add to calender</a>
</code>```

With the above Url, I can set the event title, event timing, event location

But now I want to add guest email like(dany@gmail.com) to the calendar event in the above link, was that possible?

答:
```<code>Example: add=dany%40gmail.com
Format:  add=guest email addresses
</code>```

Full list of parameters is available here: Google Calendar render action Template parameter documentation

Body:
I am adding a google calendar link to my website as below

 Add to calender

With the above Url, I can set the event title, event timing, event location

But now I want to add guest email like(dany@gmail.com) to the calendar event in the above link, was that possible?

Body:
Example: add=dany%40gmail.com
Format:  add=guest email addresses

Full list of parameters is available here: Google Calendar render action Template parameter documentation