text:
Q: Compare groups with same number of occurances of items in each group I am trying to solve a problem of matching a group of values to another group of values. What I want to do is to ensure that if a value is in first group is matched with a value in the other group, then that pair is sort of marked and we dont use those values again in comparing the groups. So for example,

So there are 4 groups in total. A-B, B-A, C-D, and D-C.
In each group there are multiple items.
What I want to do is compare groups A-B and B-A (just the opposite direction) and see if the values match exactly once in both the groups. So ID1 in group A-B has value 1000 which matches with ID5 in group B-A, similarly for ID2 in A-B matches with ID4 in B-A.
So both groups match.
Now if we consider Group C-D and D-C there is a problem, they do not match because although the values 666 and 777 can be found in each groups, but we need to use a value in comparison only if that value has not been matched before. So in this case

*

*ID7 in C-D is matched with ID11 in D-C,

*ID8 in C-D is matched with ID10 in D-C,

*ID9 in C-D Should NOT Matched (ID11 is already matched earlier).

Putting it in other words, sequence of match does not matter but the occurance of values does matter in each group.
I am expecting output like this

I am trying to do it in Excel and Power Query, but have no idea how to do it. Index columns or grouping might be helpful but I am not sure how to go about this problem.
The data has around 10000 rows and probably 2000 groups. The number of lines in each group are not fixed can range anywhere between 1-8. And the reverse groups also sometimes do not exist.

A: This seems to work.  Can be pasted into PQ with Home ... Advanced Editor...
Assumes 3 columns with headers ID, Group, Value in range Table1
Duplicates Group column then splits the duplicate Group into two separate columns
Group the data by the 3 items -- Group.1, Group.2, and Value; then adds an Index, thus creating a cumulative count of each Value for that Group combination
Merges entire table on itself, but with Group.1 matching Group.2, and Group.2 matching Group.1
Expands. Anything without a match is ... unmatched and returns a null
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Duplicated Column" = Table.DuplicateColumn(Source, "Group", "Groupx"),
#"Split Column by Delimiter" = Table.SplitColumn(#"Duplicated Column", "Groupx", Splitter.SplitTextByEachDelimiter({"-"}, QuoteStyle.Csv, false), {"Group.1", "Group.2"}),
#"Grouped Rows" = Table.Group(#"Split Column by Delimiter", {"Group.1", "Group.2","Value"}, {{"Count", each Table.AddIndexColumn(_, "Index",1,1), type table}}),
#"Expanded Count" = Table.ExpandTableColumn(#"Grouped Rows", "Count", {"Group", "ID", "Index"}, {"Group", "ID", "Index"}),
#"Merged Queries" = Table.NestedJoin(#"Expanded Count",{"Group.1", "Group.2", "Value", "Index"},#"Expanded Count",{"Group.2", "Group.1", "Value", "Index"},"Expanded Count",JoinKind.LeftOuter),
#"Expanded Expanded Count" = Table.ExpandTableColumn(#"Merged Queries", "Expanded Count", {"Index"}, {"Match"}),
#"Removed Columns" = Table.RemoveColumns(#"Expanded Expanded Count",{"Group.1", "Group.2", "Index"}),
#"Sorted Rows" = Table.Sort(#"Removed Columns",{{"ID", Order.Ascending}})
in #"Sorted Rows"


text:
Q: Displaying multiple trellis plots (from lattice) using grid.arrange nicely I am working with the gridExtra and lattice packages and wish to display multiple plots in the same plot window. I am working in an RMarkdown file and am testing my code by simply running the chunk.
library(lattice)
library(gridExtra)
p1 = dotplot(mpg ~ cyl, data = mtcars)
grid.arrange(p1,p1,p1,p1)

As you can see, the plots are very difficult to read. I am having an awful time trying to figure out how to do this. How can I make these plots more readable? Adjusting the heights and widths argument in grid.arrange does not seem to do the trick:
I'm not sure if the correct solution lies in the grid.arrange function, the dotplot function, or the underlying trellis options (from trellis.par.get), or if there is something that can be done to the plot window within my markdown file. I apologize as I am a beginner in visualizations with R, but I would appreciate any help on this!

A: I believe you would have to dig deeper into the grid engine to refine the positions on the plot. As an alternative, perhaps you can use the plot.trellis method that is available with the lattice package. The position argument allows you to specific the x and y extent of each grob. One simple way to get rid of excess white space is to overlap the plots slightly. The code below uses the variables xd and yd to provide the extent of overlap for the x and y directions, respectively.
# needed for plot.trellis() method
  library(lattice)

# midpoints and excess on either side of the midpoint
# these need to be adjusted for device size as well as plot details
  m <- 0.5 # midpoint of plot panel
  xd <- 0.04 # extra added or removed in X direction from midpoint 'm'
  yd <- 0.05 # extra added or removed in Y direction

# This could be coded as single loop but may be more apparent like this
  plot(p1, position = c(xmin=0, ymin=0, xmax=m + xd, ymax=m + yd), more = TRUE)
  plot(p1, position = c(m - xd, 0, 1, m + yd), more = TRUE)
  plot(p1, position = c(0, m - yd, m + xd, 1), more = TRUE)
  plot(p1, position = c(m - xd, m - yd, 1, 1), more = FALSE)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to drop duplicate multiindex column in Pandas Been searching the net, but I cannot find any resource on deleting duplicate multiindex column name.
Given a multiindex as below
      level1
      level2
           A   B   C   B   A   C
ONE       11  12  13  11  12  13
TWO       21  22  23  21  22  23
THREE     31  32  33  31  32  33

Drop duplicated B and C
Expected output
      level1
      level2
           A   B   C   A
ONE       11  12  13  11
TWO       21  22  23  21
THREE     31  32  33  31

Code
import pandas as pd
df = pd.DataFrame({'A': [11, 21, 31],
               'B': [12, 22, 32],
               'C': [13, 23, 33]},
              index=['ONE', 'TWO', 'THREE'])

df2 = pd.DataFrame({'B': [11, 21, 31],
               'A': [12, 22, 32],
               'C': [13, 23, 33]},
              index=['ONE', 'TWO', 'THREE'])

df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])
df2.columns = pd.MultiIndex.from_product([['level1'],['level2'],df2.columns ])
df=pd.concat([df,df2],axis=1)

-Drop by index not working

A: You can try:
mask=(df.T.duplicated() | (df.columns.get_level_values(2).isin(['A','D'])))

Finally:
df=df.loc[:, mask]
#OR
#df=df.T.loc[mask].T

A: Adaptation to df.T.drop_duplicates().T by Anurag Dabas.
Select only  unique column and its value
drop_col=['B','C']
drop_single=[df.loc [:, (slice ( None ), slice ( None ), DCOL)].T.drop_duplicates().T for DCOL in drop_col]

Drop the columns from the df
df=df.drop ( drop_col, axis=1, level=2 )

Combine everything to get the intended output
df=pd.concat([df,*drop_single],axis=1)

Complete solution
import pandas as pd
df = pd.DataFrame({'A': [11, 21, 31],
               'B': [12, 22, 32],
               'C': [13, 23, 33]},
              index=['ONE', 'TWO', 'THREE'])

df2 = pd.DataFrame({'B': [11, 21, 31],
               'A': [12, 22, 32],
               'C': [13, 23, 33]},
              index=['ONE', 'TWO', 'THREE'])

df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])
df2.columns = pd.MultiIndex.from_product([['level1'],['level2'],df2.columns ])
df=pd.concat([df,df2],axis=1)
drop_col=['B','C']
drop_single=[df.loc [:, (slice ( None ), slice ( None ), DCOL)].iloc [:, 1] for DCOL in drop_col]

df=df.drop ( drop_col, axis=1, level=2 )
df_unique=pd.concat(drop_single,axis=1)
df=pd.concat([df,df_unique],axis=1)
print(df)

A: You can try this:
# Drop last 2 columns of dataframe
df.drop(columns=df.columns[-2:],
        axis=1,
        inplace=True)


text:
Q: Horizontal Scrollview with snap effect I need a widget that functions as a horizontal scrollview, but snaps to the nearest value when scrolled (it should snap from value to value, and not be possible to stop the scrolling in between values). Theoretically I would solve this with a viewpager with negative margins - so that all the views are simultaneously visible, but it also "snaps". But I have a problem - if I use a viewpager then only the "foreground" (i.e. currentView) view is "clickable", and I need all onscreen visible views to be clickable at any given time. So - is there any way of having a "snapping" horizontal scroll widget where all visible views are clickable?
For example, the screen might look like this:
A B C D E
where scrolling right reveals F, G, H..
initial state should allow clicking on any of A,B,C,D,E and not just on A (if it was the "currentview")

A: You can use Snap ScrollView library. It supports both horizontal and vertical snap scrolling. You can add views directly. Click on this SnapScrollView library
And regarding click, you can implement onClick listener for each view and call correspondingly.


text:
Q: Can't make a shallow copy of a list in Python3 I'm trying to implement a simple TicTacToe game, but i'm unable to make a shallow copy of a certain list.
Here's a minimal extract from my script, that presents my problem:
SIZE = 3 # size of game board
PLAYERS = (PLAYER, COMPUTER) = "X", "O"

class TicTacToe(list):
    """ Class handling game board """
    def __init__(self, size=SIZE, players=PLAYERS):
        """ Board size defaults to 3 """
        super().__init__([[" " for idx in range(size)] for jdx in range(size)])
        self._size = size

    def winner_move(self, letter, range_):
        """ Determine winner move - range_ members are tuples """
        for tile in range_:
            sim = self[:] # shallow copy of game board for simulation
            sim[tile[0]][tile[1]] = letter
            print("Current board:")
            print(self)
            # code makes some decisions here and continues

    def get_empty(self):
        """ Return empty places on board as a set of (row, col) """
        return {(row, col) for row in range(self._size)\
                for col in range(self._size) if self[row][col] == " "}

board = TicTacToe()
board.winner_move(PLAYER, board.get_empty())

Although i assign new value only to sim, the change is reflected in the "main" board. I also tried
sim = list(self)

and
sim = [item for item in self]

but both give the same result.
Any suggestion what i'm doing wrong?

A: Arpegius' comment is right. You have a nested list. With sim = self[:], sim = list(self) or sim = [item for item in self] you get a new outer list, but it will be a list of the same references to the inner lists.
sim = [lst[:] for lst in self]

or
sim = [list(lst) for lst in self]

would have worked, but
from copy import deepcopy
# ...
sim = deepcopy(self)

is more elegant and its purpose is easier to comprehend. See its documentation.


text:
Q: Line scanning openCV below is a very simple code segment, but I am not able to understand why it is cribbing, can you please tell me what the error means:

CvSize iSize;
iSize= cvGetSize(I1);
CvLineIterator *iter ;
CvPoint p1,p2;
long *arrH = new long[iSize.height + 1];
long *arrV = new long [iSize.width + 1];

for( int i=0; i<=iSize.height;i++)
{

    p1.y = i; p2.y=i;
    p1.x = 0; p2.x=iSize.width;

    arrH[i] =0;
    int l = cvInitLineIterator(I1,p1,p2,iter,4,0);
    for( int j=0;j<l;j++)
    {
        arrH[i]+=iter.ptr;
        CV_NEXT_LINE_POINT(iter);

    }

    fprintf(f1,"%d \n",arrH[i]);

}

Errors of the form:
left of '.ptr' must have class/struct/union
how do I tackle them ?

A: I think this:
CvLineIterator *iter ;

Should be:
CvLineIterator iter ;

And this:
cvInitLineIterator(I1,p1,p2,iter,4,0);

Should be:
cvInitLineIterator(I1,p1,p2,&iter,4,0);


text:
Q: is it possible that I can set the website so that it autosizes? I am creating a website that is 800x800. i want to code the website so that when a user visits my website, the window automatically scales down to 800x800. is this possible by using dreamweaver (css)?

A: You can use the resizeTo method. Check out the implementation here:
http://www.javascripter.net/faq/resizing.htm
But I don't think what you are doing is good practice in the sense that you are resizing the users' window without they doing it on their own.
With following bit of CSS, you can create 800x800 layout instead:
#container{
  width:800px;
  margin:auto;
}

Where #container is assumed to be the main container tag for your site.

A: Don't do this. It's blocked in most modern browsers because resizing the browser window is a major nuisance for the user.
Create your web site in a way that works in a normal window instead, e.g. by defining a 800 x 800 pixels large container that is centered in the browser window.
Alternatively, you can use window.open to open a 800 x 800 pixel popup, but it will contain the address bar, and will be blocked by pop-up blockers.


text:
Q: How to gracefully stop a Quickbooks connector incoming request with PHP? I have a system that uses keith-palmers PHP Integration framework.
Periodically I need to perform maintenance on the system that uses it. The QB Server with the web connector dials in automatically every 30 minutes and the server system automatically queues new orders for import - how might I send a graceful "Nothing to do" response to the quickbooks web connector to halt the request without causing any errors?
Something like a 503 - Try Later header is what I was thinking but knowing the wonders of qbXML that would probably cause all sorts of headaches!
I have looked at a response of saying "100" - which I assume means that the queue is 100 percent complete? Would sending that cause the connection to shutdown without errors?

A: Quoted from the author of the framework, Keith Palmer!

Hi Ben,
The easiest way to do this is to set up your own authentication function, and then when you put the site in maintenance mode have that function return false so that the login from the Web Connector fails.
http://wiki.consolibyte.com/wiki/doku.php/quickbooks_integration_php_consolibyte_webconnector#custom_authentication_functions

So easy a child could have thought of it - simply short circuit your authentication system and return a 'false' to void the connection attempt.
Tried and Tested: Works!


text:
Q: Windows 10 reset couldn't delete my personal files - so where are they? I just used Windows 10's Reset option to clear out my PC and start over. I chose to delete everything, including my personal files etc.
At the end of the process, it told me it couldn't delete my personal files.
Well, I don't see any of the Users, and I don't see any of my old files. So my question is: what are those personal files Windows supposedly couldn't delete? Why did that happen?

A: I found some of my files here C:\$SysReset\OldOS


text:
Q: C++ lambda lexical closure over local variables Summary
In C++, when I return a lambda from a function that's captured a variable local to that function, what specifically happens, and why? The compiler (g++) seems to allow it, but it gives me different results than I was expecting, so I'm not sure if this is technically safe/supported.
Details
In some languages (Swift, Lisp, etc.) you can capture local variables in a closure/lambda, and they stay valid and in scope as long as the closure is in scope (I've heard it called "lambda over let over lambda" in a Lisp context). For example, in Swift, the example code for what I'm trying to do is:
func counter(initial: Int) -> (() -> Int) {
    var count = initial
    return { count += 1; return count }
}

let c = counter(initial: 0)
c() // returns 1
c() // returns 2
c() // returns 3

I tried to write a C++ equivalent of this like the following:
auto counter(int initial)
{
    int count = initial;
    return [&count] () -> int {
        count = count + 1;
        return count;
    };
}

However, the result I get is:
auto c = counter(0);
std::cout << c() << std::endl; // prints 1
std::cout << c() << std::endl; // prints 1
std::cout << c() << std::endl; // prints 1

If I capture a variable that's still in scope, it works as I'd expect. For example, if I do all of the following in a single function:
int count = 0;
auto c = [&count] () -> int {
    count = count + 1;
    return count;
};
std::cout << c() << std::endl; // prints 1
std::cout << c() << std::endl; // prints 2
std::cout << c() << std::endl; // prints 3

So I guess my question is, in the first C++ example above, what is actually getting captured? And is it defined behavior, or do I just have a reference to some random memory on the stack?

A:     return [&count] () -> int {

This is a capture by reference. The lambda captures a reference to this object.
The object in question, count, is in the function's local scope, so when the function returns, count gets destroyed, and this becomes a reference to an object that went out of scope and gets destroyed. Using this reference becomes undefined behavior.
Capturing by value seems to solve this problem:
    return [count] () -> int {

But your obvious intent is so that each invocation of this lambda returns a monotonically-increasing counter value. And merely capturing the object by value is not enough. You also need to use a mutable lambda:
 return [count] () mutable -> int
 {
    return ++count;
 };

But the pedantical answer to your question "what happens" is that a lambda is essentially an anonymous class, and what a lambda captures are really class members. Your lambda is equivalent to:
class SomeAnonymousClassName {

     int &count;

public:
     SomeAnonymousClassName(int &count) : count(count)
     {}

     int operator()
     {
          // Whatever you stick in your lambda goes here.
     }
};

Capturing something by reference translates to a class member that's a reference. Capturing something by value translates to a class member that's not a reference, and the act of capturing lambda variables translates to passing them to the lambda class's constructor, which is what happens when you create a lambda. A lambda is really an instance of an anonymous class, with a defined operator().
In a regular lambda, the operator() is actually a const operator method. In a mutable lambda, the operator() is a non-const, a mutable operator method.

A: In the first case, you are capturing a reference to a local variable. The reference becomes a dangling reference after the function returns. Hence, your program is subject to undefined behavior.


text:
Q: Getting HttpWebRequest to use ISO-8859-1 encoding for urlencoding I'm having a problem getting HttpWebRequest to use ISO-8859-1 encoding for parametres in a webrequest, the problem is related to both POSTs and GETs.
The problem in a nutshell is that any request parametres that contain non-ascii characters like Ö and æ, gets converted to their UTF-8 % representations rather than their ISO-8859-1 representations.
Ö gets converted to %c3%96 instead of %d6.
My current idea for a solution is to convert the request-string to an ISO-8859-1 byte array, and then convert the bytearray back to UTF-8, char for char, while catching any bytes > 127 and converting those to their %hex values instead.
Is there a better way of solving this issue?

A: Create your own URL-encoding algorithm as follows; the WebRequest method will use the URI you provide with your custom encoding.
string input = "http://www.example.com/q?Ö=æ";

StringBuilder sb = new StringBuilder();
foreach (byte by in Encoding.GetEncoding("ISO-8859-1").GetBytes(input))
{
    // NOTE: This is very simplistic; a robust solution would probably really need
    // to handle all non-alphanum and non-reserved characters, as specified by
    // http://www.ietf.org/rfc/rfc2396.txt
    if (by <= 0x7F)
        sb.Append((char) by);
    else
        sb.Append(string.Format("%{0:X2}", by));
}

Uri uri = new Uri(sb.ToString());
// uri.AbsoluteUri == "http://www.example.com/q?%D6=%E6"

WebRequest request = WebRequest.Create(uri);
using (request.GetResponse())
{
    // ...
}

A: I would rather try and fix "the other side of the pipe" and make it accept utf-8.
UTF-8 is the way to go if you want to be "future proof"


text:
Q: Not able to redirect domain … I have taken domain www.exampledomoain.com and www.sampledomain.com on Debian server server. on first domain [www.exampledomoain.com] i am running one application on port 80 now i i have install new second app for witch i want to use second domain [www.sampledomain.com] ,now second app is running on port 8080 so current URL will be www.sampledomain.com:8080
Now Problems: 1.) i am not able to make www.sampledomain.com:8080 to www.sampledomain.com only how to do that i don't have idea. 2.) Now i want to create dynamic host name like [www.username.sampledomain.com , www.username2.sampledomain.com] which should be redirect to www.sampledomain.com only is their any configuration file is their or i have to install some app.
Thanks in Advance

A: If your domain registrar allows them in the DNS settings, I think you should be able to do this using a SRV record.  I have used SRV records with no-ip.com to do the same thing with a home-hosted site.

A: 1) The basic redirect setup is this:
<VirtualHost *:8080>
  <Location />
    RedirectMatch 302 /(.*)$ http://www.sampledomain.com/$1
  </Location>
</VirtualHost>

You may need to add other configuration around it. Make sure apache is configured to listen on port 8080, but it sounds like you've got that part covered already. The above config will preserve the request in full when redirecting; so:
http://www.sampledomain.com:8080/page.html  => http://www.sampledomain.com/page.html

2) You can use wildcard ServerAlias directives to catch these. Inside your VirtualHost configuration for sampledomain.com:
ServerName www.sampledomain.com
ServerAlias *.sampledomain.com

Your script/app can then grab the HTTP_HOST variable, if it needs to know what was specified.


text:
Q: chromatic polynomial of G - Join graph Given a connected graph $G$ with $n$ vertices and given set of $\{m_1,m_2,...,m_n\}$ $n$ integers, we form a new graph $G^{\wedge} $  by considering the complete graph $K_{m_i}$ for each vertex i and 'join' (in the sense of graph theory) two of such complete graphs if the corresponding vertices are adjacent in $G$. Is there name for this graph $G^{\wedge }$ associated to the Graph $G$?
I think this is known as G-join graph. if any body can tell me the name this notion, I can look back in literature also.
By joining of two graphs $G_1$ and $G_2$, I mean introducing edges from all the vertices of $G_1$ to all the vertices of $G_2$ and vice versa, keeping the original edges as is.
My question is what is the chromatic polynomial of $G^{\wedge}$ (may be interms of the chromatic polynomial of $G$) ?
Thanks for your valuable time.
Thanks a lot

A: To me it seems hard to me describe $\chi(G^{\wedge})$ in general, but in the case of chordal graphs we can say something. For a chordal graph $G$ we have a perfect elimination order on the vertices which means we can order the vertices $v_1 < v_2 < \cdots < v_n$ such that for each $i$ the neighbors of $v_i$ occurring before $v_i$ form a clique. The perfect elimination order allows us to describe $\chi(G^{\wedge})$ in terms on $\chi(G)$ and $\{m_1, \dots, m_n\}$. The chromatic polynomials of a chordal graph factors in linear factors and can be computed by visiting vertices in the the order specified by a perfect elimination order. We can computed the chromatic polynomial of $G^{\wedge}$ by visiting the cliques in the order specified by the partial elimination order. The linear factors of $\chi(G)$ will be replaced by falling factorials in $\chi(G^{\wedge})$ (see example at end). Note if $G$ is chordal the a perfect elimination order and $\chi(G)$ can both be found efficiently.
As an example let's look at trees. Let $T$ be a tree on $n$ vertices and assume $m_i = m$ for for $1 \leq i \leq n$. Then I claim
$$\chi(T^{\wedge}) = (t)_m (t-m)_m^{n-1}$$
where $(t)_m = t(t-1) \cdots (t-m+1)$ is the falling factorial. We induct on $n$ similar to how we would prove $\chi(T) = t(t-1)^{n-1}$. If $n=1$, then $T^{\wedge} = K_m$ and the result holds. If $n > 1$, then $T$ must have leaf. Let $T'$ be $T$ with the leaf removed. By Induction $\chi((T')^{\wedge}) = (t)_m (t-m)_m^{n-2}$. Consider coloring $T^{\wedge}$ with $t$ colors by first coloring $(T')^{\wedge}$ in $(t)_m (t-m)_m^{n-2}$ possible ways and then coloring the $K_m$ associated to the leaf vertex in $(t-m)_m$ possible ways.
For arbitrary $m_i$ for any tree it will matter which $m_i$ is connected to which $m_j$, that is we need to first find a perfect elimination order. For example if $P$ is the path on $n$ vertices and we have $\{m_1, \dots, m_n\}$ we get
$$\chi(P^{\wedge}) = (t)_{m_{1}} (t-m_1)_{m_{2}} \cdots (t-{m_{n-1}})_{m_n}.$$
Also we can compute for $K_{n}$ since $K_n^{\wedge} = K_{m_1 + \cdots + m_n}$. We can express the chromatic polynomials as
$$\chi(K_n) = t(t-1)\cdots(t-n+1) = (t)_n$$
$$\chi(K_n^{\wedge}) = (t)_{m_1} (t-m_1)_{m_2} \cdots (t-m_1 -\cdots - m_{n-1})_{m_n} = (t)_{m_1 + \cdots + m_n}$$
and see that linear factors get replaced falling factorials.
This example is easy because of the symmetry of a complete graph. For the complete graph any ordering of the vertices is a perfect elimination ordering.
Update: Here is an example of computing $\chi(G)$ and $\chi(G^{\wedge})$ from a perfect elimination order on a graph. Let $G$ be the graph pictured below.
$$\chi(G) = t(t-1)(t-2)(t-1)$$
$$\chi(G^{\wedge}) = (t)_{m_1}(t-m_1)_{m_2}(t-m_1-m_2)_{m_3}(t-m_1)_{m_4}$$
$\hskip 2.5in$


text:
Q: Regex weird behavior, won't match what I need I have three different inputs.
<inverse content="HelloWorlD"/>
<reverse content="helloworld"/>
<repeat value="2" content="helloworld"/>

In the first input, I need to inverse the chars in the string which is in the content.
On the second one, I need to do the same, but reverse them.
At the third one I need to repeat the string which is in the content X number times when X is the value number.
I am using Regex to match the input.
It matches everything perfectly.

It works perfectly for the inverse and the reverse command, but when I try to match the repeat line it puts them in two different matches which doesn't work for me.

string line = Console.ReadLine();
Regex pattern = new Regex("(\\w+) \\w+=\"(\\w+)\"| \\w+=\"(\\w+)\"");

List<string> list = new List<string>();

while (line != "stop")
{
    MatchCollection matcher = pattern.Matches(line);

    foreach (Match match in matcher)
    {
        string command = match.Groups[1].ToString();
        string content;
        int value;

        switch (command)
        {
            case "inverse":
                content = match.Groups[2].ToString();
                list.Add(InverseContent(content));
                break;
            case "reverse":
                content = match.Groups[2].ToString();
                list.Add(ReverseContent(content));
                break;
            case "repeat":
                value = int.Parse(match.Groups[2].ToString());
                content = match.Groups[3].Value;
                for (int i = 0; i < value; i++)
                {
                    list.Add(content);
                }
                break;
        }
    }
    line = Console.ReadLine();
}

A: Make the second value optional with ?:
"(\\w+) \\w+=\"(\\w+)\"(\\s+\\w+=\"(\\w+)\")?"

For the "repeat" case it will yield the values in group #2 and #4.

A: try this regex :
(\w+) \w+="(\d+){0,1}" \w+="(\w+)"

A: This may be overkill, but I'm going to post it anyway.
Since your data appears to be well formed XML - we can use an XML parser to get a structured list of commands. This will make your solution easier to test and able to handle more complex situations. It will handle situations where the input is formed like <inverse content="HelloWorld"></inverse> as well as reordering the attributes <repeat content="x" value="3" /> instead of <repeat value="3" content="x" />. It can also support any random input inside the value (not just word characters).
If your input is surrounded by a root element (which you could insert yourself if you don't get it that way) - the input is well-formed xml. Example:
//file: input.xml
<input>
  <inverse content="HelloWorld" />
  <reverse content="helloworld" />
  <repeat value="2" content="helloworld" />
</input>

We could then construct a class to represent your list of input commands as follows:
[XmlRoot("input")] //indicate that this class represents the xml file
public class CommandList
{
    // tell the XmlSerializer which <element> belongs to which class.
    [XmlElement("repeat", typeof(Repeat))]
    [XmlElement("reverse", typeof(Reverse))]
    [XmlElement("inverse", typeof(Inverse))]
    public List<Command> Commands { get; } = new List<Command>();
}

The Command class is abstract, and has three different implementations, depending on the element:
public abstract class Command
{
    [XmlAttribute("content")]
    public string Content { get; set; }
    public abstract void Process(List<string> output);
}

After defining the abstract class, we can create the different commands as separate classes:
public class Inverse : Command
{
    public override void Process(List<string> output)
    {
        var inverseContent = this.Content; //todo: process
        output.Add(inverseContent);
    }
}
public class Reverse : Command
{
    public override void Process(List<string> output)
    {
        var reverseContent = this.Content; //todo: process
        output.Add(reverseContent);
    }
}

For the Repeat class, there is one extra attribute, the value.
public class Repeat : Command
{
    [XmlAttribute("value")]
    public int Value { get; set; }
    public override void Process(List<string> output)
    {
        for (int i = 0; i < this.Value; i++)
        {
            output.Add(this.Content);
        }
    }
}

Then, to run your solution:
using System.IO;
using System.Xml.Serialization;

var serializer = new XmlSerializer(typeof(CommandList));
var result = (CommandList)serializer.Deserialize(File.OpenRead("input.xml"));
var output = new List<string>();
foreach (var command in result.Commands)
{
    command.Process(output);
}


text:
Q: How to put PHP code into JavaScript? I'm trying to define a value by PHP echo with data received from MySQL.
How to put PHP echo code into JavaScript?
Example:
document.addEventListener("DOMContentLoaded", function(event) {
    var gg1 = new JustGage({
        id: "gg1",
        value: <?php echo 'Hello World!' ?>
        min: 0,
        max: 100,
        title: "Target",

A: You just missed the quotation around the <?php & semi-colon before ?>,
document.addEventListener("DOMContentLoaded", function(event) {
    var gg1 = new JustGage({
        id: "gg1",
        value: "<?php echo 'Hello World!'; ?>", // This line is edited
        min: 0,
        max: 100,
        title: "Target",

A: In order to use Php varibale inside Javascript or JQuery call them like this..
var example ="<?php echo date();?>";


text:
Q: Php, PDO, Sql, Try Catch ,Connection When i am using try catch block for example:
try{
     require_once('../php/connect.php');
     $dbh = db::getInstance();
     // What i am trying to understand should i close the connection here before the header?
     header("Location: x.php");
   }
} catch(PDOException $e){
   require_once('err.php');
 }
 $dbh = null; // Or should i close the connection here?

Is the "interpreter" even get after line "5", Thank you all and have a nice day.

A: Since you are not using exit after header() (which is recommended), your code will continue to execute.
As such, it does not matter if you put in on line 4 or 10. Furthermore, as pointed out by prodigitalson, you do no need to explicitly close the database connection.

A: You dont need to close the connection at all. It will be closed when php exits. However, you arent calling exit after header...
Your code doesnt make sesne though, If the db connection is successful why would you redirect without doing anything???? If using header at all i would think you would call it to redirect to an error page (ie. in your catch block).


text:
Q: We found a problem with some content in 'filename.xls' after editing file with openxml I have written a piece of code that grabs data from a database and then I try to sort it by region and have it export to an excel file. Each sheet within the excel has the data of each region. I keep getting this error:

We found a problem with some content in 'filename.xls'. Do you want us to try and recover as much as we can?

I can't seem to figure out where I have coded something wrong within here to cause this. Here is my code:
private void AddSheet(SpreadsheetDocument document, WorkbookPart workbookPart, Sheets sheets, string sheetName, UInt32 sheetNumber, List<RentalFeeReportingRecord> currentRecordList)
{
    Dictionary<int, string> listofCoreBankingIds = new Dictionary<int, string>();
    listofCoreBankingIds = currentRecordList.Select(x => new { id = x.CoreBankingId, regionName = x.RegionName }).Distinct().ToDictionary(y => y.id, y => y.regionName);
    foreach (var coreBankingId in listofCoreBankingIds.OrderBy(x => x.Value))
    {
        WorksheetPart worksheetPart1 = workbookPart.AddNewPart<WorksheetPart>();
        string previousCurrency = null;
        string previousRegionName = null;
        int recordCounter = 1;
        double previousTotal = 0;

        Worksheet worksheet1 = new Worksheet();
        SheetData sheetData1 = new SheetData();

        Row rowInSheet1 = new Row();
        Row firstRow = new Row();
        Row lastRow = new Row();

        rowInSheet1.Append(
          excelController.ConstructCell("Region", CellValues.String, 3), excelController.ConstructCell("Merchant - Terminal", CellValues.String, 3),
          excelController.ConstructCell("Fee Charged", CellValues.String, 3),
          excelController.ConstructCell("Currency", CellValues.String, 3),
          excelController.ConstructCell("Processing Date", CellValues.String, 3),
          excelController.ConstructCell("Description", CellValues.String, 3)
        );

        sheetData1.Append(rowInSheet1);

        foreach (var currentRecord in currentRecordList.OrderBy(x => x.RegionName).ThenBy(z => z.Currency).ThenBy(y => y.DateProcessed))
        {
            if (coreBankingId.Key == currentRecord.CoreBankingId)
            {

                string regionName = currentRecord.RegionName;

                string currentCurrency = currentRecord.Currency;

                double currentTotal = currentRecord.TotalFeeAmount;
                string EmptySpace = string.Empty;

                string merchant = currentRecord.MerchantRecord.MerchantID + " - " + currentRecord.MerchantTerminalRecord.terminalID;

                if (currentRecord.IsPinPad)
                {
                    merchant = merchant + " - PIN Pad";
                }

                string description = currentRecord.TerminalRecord.description;
                if (currentRecord.IsProRated)
                {
                    int days = DateTime.DaysInMonth(currentRecord.DeployedDate.Year, currentRecord.DeployedDate.Month);

                    description = currentRecord.TerminalRecord.description + " (" + currentRecord.MonthlyFee + " Fee \\ " + days.ToString() + " Days) * " + currentRecord.DaysActive.ToString() + " Days Active";
                }

                rowInSheet1 = new Row();
                firstRow = new Row();
                lastRow = new Row();

                if (recordCounter == currentRecordList.Count() && previousRegionName == regionName)
                {
                    firstRow.Append(
                      excelController.ConstructCell(regionName, CellValues.String, 2),
                      excelController.ConstructCell(merchant, CellValues.String, 2),
                      excelController.ConstructCell(currentRecord.TotalFee.ToString("N2"), CellValues.String, 1),
                      excelController.ConstructCell(currentRecord.Currency, CellValues.String, 2),
                      excelController.ConstructCell(currentRecord.DateProcessed.ToString("MMM dd, yyyy"), CellValues.String, 2),
                      excelController.ConstructCell(description, CellValues.String, 2)
                    );
                    sheetData1.Append(firstRow);

                    rowInSheet1.Append(
                      excelController.ConstructCell("TOTALS", CellValues.String, 6),
                      excelController.ConstructCell(" ", CellValues.String, 2),
                      excelController.ConstructCell(currentRecord.TotalFeeAmount.ToString("N2"), CellValues.String, 6),
                      excelController.ConstructCell(currentRecord.Currency, CellValues.String, 6),
                      excelController.ConstructCell(" ", CellValues.String, 2),
                      excelController.ConstructCell(" ", CellValues.String, 2)

                    );
                    sheetData1.Append(rowInSheet1);

                }
                else if (recordCounter == currentRecordList.Count())
                {
                    rowInSheet1.Append(
                      excelController.ConstructCell(regionName, CellValues.String, 2),
                      excelController.ConstructCell(merchant, CellValues.String, 2),
                      excelController.ConstructCell(currentRecord.TotalFee.ToString("N2"), CellValues.String, 1),
                      excelController.ConstructCell(currentRecord.Currency, CellValues.String, 2),
                      excelController.ConstructCell(currentRecord.DateProcessed.ToString("MMM dd, yyyy"), CellValues.String, 2),
                      excelController.ConstructCell(description, CellValues.String, 2)
                    );

                    sheetData1.Append(rowInSheet1);

                    lastRow.Append(
                      excelController.ConstructCell("TOTALS", CellValues.String, 6),
                      excelController.ConstructCell(" ", CellValues.String, 2),
                      excelController.ConstructCell(currentRecord.TotalFeeAmount.ToString("N2"), CellValues.String, 6),
                      excelController.ConstructCell(currentRecord.Currency, CellValues.String, 6),
                      excelController.ConstructCell(" ", CellValues.String, 2),
                      excelController.ConstructCell(" ", CellValues.String, 2)

                    );
                    sheetData1.Append(lastRow);

                }
                else
                {
                    if ((previousCurrency == null && previousRegionName == null) || (previousCurrency == currentCurrency && previousRegionName == regionName))
                    {
                        rowInSheet1.Append(
                          excelController.ConstructCell(regionName, CellValues.String, 2),
                          excelController.ConstructCell(merchant, CellValues.String, 2),
                          excelController.ConstructCell(currentRecord.TotalFee.ToString("N2"), CellValues.String, 1),
                          excelController.ConstructCell(currentRecord.Currency, CellValues.String, 2),
                          excelController.ConstructCell(currentRecord.DateProcessed.ToString("MMM dd, yyyy"), CellValues.String, 2),
                          excelController.ConstructCell(description, CellValues.String, 2)
                        );
                        sheetData1.Append(rowInSheet1);
                        previousCurrency = currentCurrency;
                        previousTotal = currentTotal;
                        previousRegionName = regionName;

                    }
                    else
                    {
                        rowInSheet1.Append(
                          excelController.ConstructCell("TOTALS", CellValues.String, 6),
                          excelController.ConstructCell(" ", CellValues.String, 2),
                          excelController.ConstructCell(previousTotal.ToString("N2"), CellValues.String, 6),
                          excelController.ConstructCell(previousCurrency, CellValues.String, 6),
                          excelController.ConstructCell(" ", CellValues.String, 2),
                          excelController.ConstructCell(" ", CellValues.String, 2)

                        );
                        sheetData1.Append(rowInSheet1);

                        Row emptyRow;
                        emptyRow = new Row();
                        emptyRow.Append(
                          excelController.ConstructCell(" ", CellValues.String, 2),
                          excelController.ConstructCell(" ", CellValues.String, 2),
                          excelController.ConstructCell(" ", CellValues.String, 2),
                          excelController.ConstructCell(" ", CellValues.String, 2),
                          excelController.ConstructCell(" ", CellValues.String, 2),
                          excelController.ConstructCell(" ", CellValues.String, 2)
                        );
                        sheetData1.Append(emptyRow);

                        Row row;
                        row = new Row();
                        row.Append(
                          excelController.ConstructCell(regionName, CellValues.String, 2),
                          excelController.ConstructCell(merchant, CellValues.String, 2),
                          excelController.ConstructCell(currentRecord.TotalFee.ToString("N2"), CellValues.String, 1),
                          excelController.ConstructCell(currentRecord.Currency, CellValues.String, 2),
                          excelController.ConstructCell(currentRecord.DateProcessed.ToString("MMM dd, yyyy"), CellValues.String, 2),
                          excelController.ConstructCell(description, CellValues.String, 2)
                        );
                        sheetData1.Append(row);

                        previousCurrency = currentCurrency;
                        previousTotal = currentTotal;
                        previousRegionName = regionName;
                    }
                    recordCounter++;
                }
            }

        }

        Columns columns = excelController.AutoSize(sheetData1);

        worksheet1.AppendChild(columns);
        worksheet1.AppendChild(sheetData1);
        worksheetPart1.Worksheet = worksheet1;

        Sheet sheet1 = new Sheet()
        {
            Id = document.WorkbookPart.GetIdOfPart(worksheetPart1),
            SheetId = sheetNumber,
            Name = previousRegionName
        };

        sheets.Append(sheet1);
    }
}

I have tried debugging as much as I can but can't seem to figure out where the problem lies.
Any help would be appreciated.

A: The issue lies with the sheetNumber It must be incremented or else Excel thinks all the sheets have the same sheetnumber. This was fixed by adding sheetNumber++ after appending every sheet.


text:
Q: How to create advanced search in ruby on rails 4 Is there any gem or method to do "Advanced Search" in rails 4.0.0 ?

A: Railscasts have an episode on Advanced Search Forms
The revised version is built for Rails 4 - though you'll need a Pro account ($9 a month) to watch it).

A: If you're looking to use an engine like Solr you could use the Sunspot gem.


text:
Q: Error importing QGIS modules in standalone script: from qgis._gui import * ImportError: The specified module could not be found I'm trying to run the following script (following Gary Sherman's PyQGIS Programmer's Guide). It is supposed to create a standalone PyQT window that displays a .shp in the QgsMapCanvas without opening QGIS.
from PyQt5.QtWidgets import QApplication, QFrame, QGridLayout, QMainWindow
from qgis.gui import QgsMapCanvas
from qgis.core import QgsApplication, QgsProject, QgsVectorLayer

app = QApplication([])
QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.22.7", True)
QgsApplication.initQgis()

main_win = QMainWindow()
frame = QFrame(main_win)
main_win.setCentralWidget(frame)
grid_layout = QGridLayout(frame)

map_canvas = QgsMapCanvas()
grid_layout.addWidget(map_canvas)

layer = QgsVectorLayer(
    'C:/data/alaska.shp',\
    'alaska', 'ogr')

prj = QgsProject()
prj.addMapLayer(layer)

map_canvas.setLayers([layer])
map_canvas.zoomToFullExtent()

main_win.show()

app.exec_()

However, when running the script I get the following error:

Line 25 in the gui_init_.py shows this:

Can anyone help me get past this obstacle and load up a basic standalone QGIS app?

A: You haven't said how you are running your standalone script, but my guess is that you need to set up your pyqgis environment, for which on Windows you can use a batch file. The batch file will depend on QGIS version and installation method, but the file below should work for you.
@echo off
SET OSGEO4W_ROOT=C:\Program Files\QGIS 3.22.7
call "%OSGEO4W_ROOT%"\bin\o4w_env.bat
@echo off
path %PATH%;%OSGEO4W_ROOT%\apps\qgis-ltr\bin
path %PATH%;C:\OSGeo4W\apps\Qt5\bin
path %PATH%;C:\OSGeo4W\apps\Python39\Scripts
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT:\=/%/apps/qgis-ltr
set GDAL_FILENAME_IS_UTF8=YES
rem Set VSI cache to be used as buffer, see #6448
set VSI_CACHE=TRUE
set VSI_CACHE_SIZE=1000000
set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\qgis-ltr\python
set PYTHONHOME=%OSGEO4W_ROOT%\apps\Python39
set QT_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\qgis-ltr\qtplugins;%OSGEO4W_ROOT%\apps\qt5\plugins

cmd.exe

This example is for an LTR standalone (not OSGeo4W) install. Be aware that if your version is not an LTR, you would need to replace qgis-ltr with qgis in the batch file paths.
If you save this batch file in the same location as your python script .py file, when you double click on the batch file, it will open a command prompt with pyqgis environment correctly set. You can then type 'python' followed by the name of your standalone script e.g. python scriptname.py to run your standalone script.


text:
Q: What is the c# equivalent of this c++ code? unsigned char setBit(unsigned char ch, int n)
{
    unsigned char mask = 1 << n;
    return ch | mask;
}

I want to change n-bit with 1 in c# but I can't do it. I have only c++ examples.

A: In C++ the char data type is one byte. In C# the equivalent type is byte.
In C# the char data type is a Unicode UTF-16 character (2 bytes).
byte setBit (byte b, int pos)
{
    return (byte)(b | 1 << pos - 1);
}


text:
Q: Upgrading to Visual Studio 2012/13 - test lists In upgrading a large application solution from VS2008 Developer to VS2012/13 Pro, I have a monumental problem - VS2012 onwards no longer supports test lists, and I have some 11,000 tests in various test lists so that they can be executed selectively.
Passing over the question of why on earth MS saw fit to drop this genuinely useful and easy to use feature in favour of the cumbersome TestCategory attribute approach, I have two questions:

*

*Is there a tool available that can be used to 'migrate' tests the are in one or other test list to the testcategory approach? (We could write one, but I'd rather not reinvent the wheel because we surely are not the first to be faced wiht this hurdle).

*Once tests have been taggged with one or more TestCategory attribute, how can you easily see in Visual Studio which tests belong to a particular TestCategory? In other words, how do you manage test categories?


text:
Q: Know if Backbone.Model.set changed/not-changed anything Is it possible to know if Backbone.Model.set() has changed/not-changed anything without events if possible? Reason being: if I use events it will look like:

*

*listen to change:something

*

*do something if value has changed

*model.set("something", "value")

But what if change does not happen? How do I know that? Also with event handlers, I need to remove them approperately. For example, if I do it this way, I need to remove the handler if a change does not happen

A: Here is a simple solution that hides Events, into a simple synchronous function that returns if set has an effect.
I choose to implement this in a different function name, but you can also override the default set behavior.
var M = Backbone.Model.extend({
  setThatLetsYouKnow: function(key, value){
    var thisSetHasEffect = { flag: false};
    this.listenToOnce(this, "change", function(){
      thisSetHasEffect.flag = true;
    });
    this.set(key, value);
    return thisSetHasEffect.flag;
  }
});

And the result is:
var m = new M();
m.setThatLetsYouKnow("key",2)// return true
m.setThatLetsYouKnow("key",2)// reutrn fasle

Of Course, you need to add support to all different kind of set argument, this is just the Idea.


text:
Q: Regex lambda doesn't iterate through df - prints first row's result for all def split_it(email):
    return re.findall(r"[^@]+@[^@]+(?:\.com|\.se|\.br|\.org)", s)

df['email_list'] = df['email'].apply(lambda x: split_it(x))

This code seems to work for the first row of the df, but then will print the result of the first row on all other rows.
Is it not iterating through all rows? Or does it print the result of row 1 on all rows?

A: You do not need to use apply here, use Series.str.findall directly:
df['email_list'] = df['email'].str.findall(r"[^@]+@[^@]+(?:\.com|\.se|\.br|\.org)")

If there are several emails per row, you can join the results:
df['email_list'] = df['email'].str.findall(r"[^@]+@[^@]+(?:\.com|\.se|\.br|\.org)").str.join(", ")

Note that the email pattern can be enhanced in many ways, but I would add \s into the negated character classes to exclude whitespace matching, and move \. outside the group to avoid repetition:
r"[^\s@]+@[^\s@]+\.(?:com|se|br|org)"


text:
Q: Vue.js render error with Firestore and vuefire I have a problem in my Vue.js application
Indeed, my component is working properly, however I have errors in the console because it seems to me that the component is rendered several times during its life cycle, and the first time, when it is rendered, it does not find not my races variable at the time of the display because the method db.collection ('courses') has not yet run. How to do?
thank you
My code on JsFiddle:
firestore() { }

https://jsfiddle.net/gf9qhsjr/1/
The Error :

vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot
  read property 'title' of undefined"


text:
Q: How to place Text and an Image next to each other in HTML? I want the text and the image to be next to each other but I want the image to be on the far left of the screen and I want the text to be on the far right of the screen. This is what I currently have....

The Art of Gaming

How can I do this?
Thanks

A: You want to use css float for this, you can put it directly in your code.

The Art of Gaming

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).
HTML:

The Art of Gaming

CSS:
.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

A: img {
    float:left;
}
h3 {
    float:right;
}

jsFiddle example
Note that you will probably want to use the style clear:both on whatever elements comes after the code you provided so that it doesn't slide up directly beneath the floated elements.

A: You can use vertical-align and floating.
In most cases you want to vertical-align: middle, the image.
Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align
vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;
For middle, the definition is: The element is placed in the middle of the parent element.
So you might want to apply that to all elements within the element.


text:
Q: How to estimate the probability of the periodicity of a time series signal I am trying to formulate a function to estimate the probability of a given 1-D vector which is a periodic signal.
For instance, a sine or a cosine wave could result in a probability of 1; a white noise signal should result in a probability close to 0.
Can anyone help me to come up with this function? Thanks in advance.


text:
Q: Getting jquery post value and checking it with php Briefly, i work on to create a Wordpress plugin. In this plugin, i need a progress bar that moving on according to background process. So, I determined a specific php file which contains my custom functions. Let's call this 'func.php' . Also, there is a file that acts as plugins main page file. We can call it 'main.php' .
So; I designed a concept in my head. On the main page, when I click begin button (named 'buttonbegin'), a jquery post being sent to func.php . I can control this POST value with these codes in func.php:
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'buttonbegin':
            func1();
            break;
        case 'otherbutton':
            func2();
            break;
    }
}

After it, func1 executes. In this function, i had these codes for testing:
function func1() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {

var itemnumber=0;
for (var i = 1; i <= 3000; i++) { //it should be execute 3000 times because of nature of process
    itemnumber++;
    if (itemnumber == 30) {
        var value = "mystring";
        var ajaxurl = 'fullurl+pluginsdirectory/main.php', //func.php and main.php are in same folder
        data =  {'action': value};
        $.post(ajaxurl, data, function (response) {
        });

        itemnumber=0;
        }
}
});
</script>
<?php
}

At this point in this func1, I wanna do another jquery post to make a trigger mechanism for progress bar on main.php . And finally, there is some javascript code to control this last jquery post and expand 1% progress bar. Here is the script codes in main.php :
<script type="text/javascript"> //below are for the first process i told
var width = 0;
var addition = 1;
jQuery(document).ready(function($) {
$('#buttonbegin').click(function(){
    var clickBtnValue = $(this).val();
    var ajaxurl = 'fullurl/func.php',
    data =  {'action': clickBtnValue};
    $.post(ajaxurl, data, function (response) {
    });
});
    //actual part starts here
    var continuous = setInterval(function() {
    var code = <?php echo !isset($_POST['action']) ?>; // the source of the problem
    if(!code) {
        var percent = $("#myBar").width() / $("#myBar").parent().width() * 100;
        if (percent == 100) {
            clearInterval(continuous);
        }
        var element = document.getElementById("myBar");
        element.style.width = (width+addition) + "%";
        element.innerHTML = (width+addition) * 1  + "%";
        width = width + addition;
    }
    }, 1000);
});
</script>

But it doesn't work. When i print the 'code' variable with console.log, I see NaN value. The php code inside script tags doesn't work properly. Is there any mistake? Or is there another simpler way to do whole process?
Note: Necessary jquery cdn links are included in main.php and func.php both. This is how its look like:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>


text:
Q: Send email to users who finished submitting a product review in WooCommerce I am using the following code which works fine.
function send_comment_email_notification( $comment_ID, $commentdata ) {
    $comment = get_comment( $comment_id );
    $postid = $comment->comment_post_ID;
    $master_email = 'email@gmail.com';
    var_dump($commentdata);
    if( isset( $master_email ) && is_email( $master_email ) ) {
        $message = 'New comment on ' .  get_the_title( $postid ) . '';
        add_filter( 'wp_mail_content_type', create_function( '', 'return "text/html";' ) );
        wp_mail( $master_email, 'New Comment', $message );
    }
}
add_action( 'comment_post', 'send_comment_email_notification', 11, 2 );

However, I would like to send an email to the user who just reviewed on a product page so I can offer them a coupon and a thank you for giving a review.
The problem is the $master_email variable, that is "hard coded". I need to capture the email entered by the user after he/she submitted the product review
Any advice?

A: To get the  email entered by the user after he/she submitted the product review, you can use $commentdata['comment_author_email']
So you get:
function action_comment_post( $comment_ID, $comment_approved, $commentdata ) {
    // Isset
    if ( isset ( $commentdata['comment_author_email'] ) ) {
        // Get author email
        $author_email = $commentdata['comment_author_email'];

        if ( is_email( $author_email ) ) {
            // Post ID
            $post_id = $commentdata['comment_post_ID'];

            // Send e-mail
            $to = $author_email;
            $subject = 'The subject';
            $body = sprintf( __(' Thank you for giving a review on %s', 'woocommerce' ), '' .  get_the_title( $post_id ) . '' );
            $headers = array( 'Content-Type: text/html; charset=UTF-8' );

            wp_mail( $to, $subject, $body, $headers );
        }
    }
}
add_action( 'comment_post', 'action_comment_post', 10, 3 );


text:
Q: SQL column taking "0" as value I have two tables. One is members table with columns member id, member first name, member last name. I have another table guest passes with columns guest pass id, member id and issue date.
I have a list view that will display guest passes details, like member name and issue date. I have two textboxes. Those are for entering member name and issue date.
Member name textbox is auto complete textbox that is working fine.
But the problem is when I am entering the name that is not in member table. At this time it will accept and display a blank field in list view in member name column and member id is stored as "0" in guest pass table.
I don't want to display the member name empty blank and I don't want to store "0" in guest pass table.
This is the insert statement:
sql2 = @"INSERT INTO guestpasses(member_Id,guestPass_IssueDate)";
sql2 += " VALUES(";
sql2 += "'" + tbCGuestPassesMemberId.Text + "'";
sql2 += ",'" + tbIssueDate.Text + "'";

guestpassmemberId = memberid

Is there any validation that needs to be done? Can anyone give suggestions on this please? This is the auto complete textbox statement:
sql = @"SELECT member_Id FROM members WHERE  concat(member_Firstname,'',member_Lastname) ='" + tbMemberName.Text+"'";
dt = GetData(sql, mf);
if (dt != null)
{
   if (dt.Rows.Count > 0)
   {
       tbCGuestPassesMemberId.Text  = Convert.ToInt32(dt.Rows[0]  ["member_Id"]).ToString();
   }
}

Can anyone help me on this? Is there any type of validation with SQL query?

A: You do not have to supply a value for memberID if that is an *auto_increment* field. MySql inserts that number for you. If, on the other hand, you require the value to be displayed prior to actually writing that member/guest data to the data store, then there are several ways to achieve that.

A: The problem you have is that tbCGuestPassesMemberId.Text is always going to have a value, whether it gets set or not. I would suggest putting the first section of code in an if statement as a hack around this, as I guess your member IDs start at 1 anyway?
if (tbCGuestPassesMemberId.Text != 0)
{
  sql2 = @"INSERT INTO guestpasses(member_Id,guestPass_IssueDate)";
  sql2 += " VALUES(";
  sql2 += "'" + tbCGuestPassesMemberId.Text + "'";
  sql2 += ",'" + tbIssueDate.Text + "'";
}


text:
Q: Parsing NSAttributedString to HTML on iOS 7 I have an NSAttributedString  (coming from HTML) that I set for a UITextView.
- (void)setHtml:(NSString *)html {

    NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];

    // Create the HTML string
    NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSError *error = nil;
    self.htmlString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];

    self.editorView.attributedText = self.htmlString;

}

I then let the user edit what they want, and I would like to then convert it out to HTML again, so I use an edited version of ULIKit htmlFromRange:. Here is the relevant method from that:
-(NSString*)    HTMLFromRange: (NSRange)range
{
    unsigned int                location = 0;
    NSRange                     effRange;
    NSMutableString*            str = [NSMutableString string];
    NSMutableString*            endStr = [NSMutableString string];
    NSDictionary*               attrs = nil;
    NSDictionary*               oldAttrs = nil;

    unsigned int    finalLen = range.location +range.length;

    // TODO: Use oldAttrs, add NSForegroundColorAttributeName and

    attrs = [self attributesAtIndex: location effectiveRange: &effRange];
    location = effRange.location +effRange.length;

    NSLog(@"attributed string: %@", self);

    // Font/color changed?
    UIFont* fnt = [attrs objectForKey: NSFontAttributeName];
    UIColor* tcol = [attrs objectForKey: NSForegroundColorAttributeName];
    if( fnt || tcol )
    {
        [str appendString: @""];
        [endStr insertString: @"" atIndex: 0];

        UIFontDescriptor *fontDescriptor = [fnt fontDescriptor];
        if( (fontDescriptor.symbolicTraits & UIFontDescriptorTraitItalic) == UIFontDescriptorTraitItalic )
        {
                [str appendString: @""];
                [endStr insertString: @"" atIndex: 0];
        }
        if( (fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold) == UIFontDescriptorTraitBold)
        {
            [str appendString: @""];
            [endStr insertString: @"" atIndex: 0];
        }
    }

    //Underline
    NSNumber *underline = [attrs objectForKey:NSUnderlineStyleAttributeName];
    if(underline && [underline intValue] > 0) {
        [str appendString:@""];
        [endStr insertString:@"" atIndex:0];
    }

    // Superscript changed?
    NSNumber* supers = [attrs objectForKey: (NSString*)kCTSuperscriptAttributeName];
    if( supers && supers != [oldAttrs objectForKey: (NSString*)kCTSuperscriptAttributeName] )
    {

        [str appendString: [supers intValue] > 0 ? @"" : @""];
        [endStr insertString: [supers intValue] > 0 ? @"" : @"" atIndex: 0];
    }

    // Actual text and closing tags:
    [str appendString: [[[self string] substringWithRange:effRange] stringByInsertingHTMLEntitiesAndLineBreaks: YES]];
    [str appendString: endStr];

    while( location < finalLen )
    {
        [endStr setString: @""];
        attrs = [self attributesAtIndex: location effectiveRange: &effRange];
        location = effRange.location +effRange.length;

        // Font/color changed?
        UIFont* fnt = [attrs objectForKey: NSFontAttributeName];
        UIColor* tcol = [attrs objectForKey: NSForegroundColorAttributeName];
        if( fnt || tcol )
        {
            [str appendString: @""];
            [endStr insertString: @"" atIndex: 0];

            UIFontDescriptor *fontDescriptor = [fnt fontDescriptor];
            if( (fontDescriptor.symbolicTraits & UIFontDescriptorTraitItalic) == UIFontDescriptorTraitItalic )
            {
                    [str appendString: @""];
                    [endStr insertString: @"" atIndex: 0];
            }
            if( (fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold) == UIFontDescriptorTraitBold )
            {
                [str appendString: @""];
                [endStr insertString: @"" atIndex: 0];
            }
        }

        //Underline
        NSNumber *underline = [attrs objectForKey:NSUnderlineStyleAttributeName];
        if(underline && [underline intValue] > 0) {
            [str appendString:@""];
            [endStr insertString:@"" atIndex:0];
        }

        // Superscript changed?
        NSNumber* supers = [attrs objectForKey: (NSString*)kCTSuperscriptAttributeName];
        if( supers && supers != [oldAttrs objectForKey: (NSString*)kCTSuperscriptAttributeName] )
        {

            [str appendString: [supers intValue] > 0 ? @"" : @""];
            [endStr insertString: [supers intValue] > 0 ? @"" : @"" atIndex: 0];
        }

        ///Lists.

        // Actual text and closing tags:
        [str appendString: [[[self string] substringWithRange:effRange] stringByInsertingHTMLEntitiesAndLineBreaks: YES]];
        [str appendString: endStr];
    }

    return str;
}

The problem comes from lists. Specifically the NSAttributedString method to parse from HTML parses lists ( and  tags) into NSTextLists from what I can see in logs.  NSTextList is private in UIKit.  Is there a way to parse that back into a list without using apple's default parser (by adding to my htmlFromRange method above)? (See this question:  from Nic Hubbard).
I understand how if the user CREATES a list in my textview to use a custom attribute to fake a NSTextList and then I can easily parse that into html, but can't figure out a way to get that going with a pre-made NSAttributedString.
Thanks. (I will note I put a bounty on the Nic Hubbard question that is very related if you want to answer in both places. )


text:
Q: Order the levels of multiple factors at once I have a dataset full of character variables, which I want to convert to ordered factor variables. I was able to convert all variables to factors at once, but my attempt to order them ("Stimme nicht zu", "Stimme eher nicht zu", "Stimme teilweise zu", "Stimme zu", "Stimme voll zu", "k. A.") was not successful. Do you have a solution for me?
Here are my code and my data:
MD4[,1:10] <- lapply(MD4[1:10], factor)
MD4[,1:10] <- lapply(MD4[1:10], ordered(MD4[1:10],c("Stimme nicht zu", "Stimme eher nicht zu", "Stimme teilweise zu", "Stimme zu", "Stimme voll zu", "k. A.")))

structure(list(veränderung_imap_austausch.verstärkt.akteuren = c("Stimme teilweise zu",
"Stimme zu", NA, NA, "Stimme teilweise zu", "Stimme zu", "Stimme zu",
"Stimme teilweise zu", NA, NA, NA, NA, NA, NA, NA, "Stimme teilweise zu",
NA, NA, NA, NA, NA, "Stimme zu", NA, NA, NA, NA, "Stimme teilweise zu",
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, "Stimme voll zu", NA, "Stimme zu",
NA, NA, NA, NA, NA, "Stimme voll zu", "Stimme zu", NA, NA, NA,
"Stimme zu", "Stimme teilweise zu", NA, NA, NA, NA, NA, NA, NA,
NA, "Stimme voll zu", "Stimme teilweise zu", "Stimme zu", NA,
NA, NA, "Stimme zu", "Stimme zu", NA, "Stimme nicht zu", "Stimme zu",
NA, "Stimme teilweise zu", "Stimme zu", "Stimme teilweise zu",
NA, NA, NA, "Stimme voll zu", "Stimme voll zu", "Stimme teilweise zu",
NA, NA, NA, "Stimme voll zu", NA, "Stimme nicht zu", "Stimme zu",
NA, "Stimme zu", NA, "Stimme zu", "Stimme zu", "Stimme zu", "Stimme teilweise zu",
"Stimme teilweise zu", "Stimme teilweise zu", NA, "Stimme teilweise zu",
"k. A.", "Stimme eher nicht zu"), veränderung_imap_austausch.verstärkt.ideen = c("Stimme voll zu",
"Stimme zu", NA, NA, "Stimme teilweise zu", "Stimme zu", "Stimme zu",
"Stimme eher nicht zu", NA, NA, NA, NA, NA, NA, NA, "Stimme zu",
NA, NA, NA, NA, NA, "Stimme zu", NA, NA, NA, NA, "Stimme zu",
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, "Stimme voll zu", NA, "Stimme zu",
NA, NA, NA, NA, NA, "Stimme zu", "Stimme zu", NA, NA, NA, "Stimme zu",
"Stimme teilweise zu", NA, NA, NA, NA, NA, NA, NA, NA, "Stimme voll zu",
"Stimme zu", "Stimme voll zu", NA, NA, NA, "Stimme zu", "Stimme zu",
NA, "Stimme teilweise zu", "Stimme zu", NA, "Stimme eher nicht zu",
"Stimme zu", "Stimme zu", NA, NA, NA, "Stimme voll zu", "Stimme voll zu",
"Stimme teilweise zu", NA, NA, NA, "Stimme voll zu", NA, "Stimme zu",
"Stimme zu", NA, "Stimme zu", NA, "Stimme teilweise zu", "Stimme voll zu",
"Stimme zu", "Stimme teilweise zu", "Stimme zu", "Stimme zu",
NA, "Stimme zu", "k. A.", "Stimme teilweise zu"), veränderung_imap_fortschritt.umsetzung = c("Stimme zu",
"Stimme zu", NA, NA, "Stimme teilweise zu", "Stimme zu", "k. A.",
"Stimme teilweise zu", NA, NA, NA, NA, NA, NA, NA, "Stimme zu",
NA, NA, NA, NA, NA, "Stimme zu", NA, NA, NA, NA, "Stimme zu",
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, "Stimme zu", NA, "Stimme zu", NA,
NA, NA, NA, NA, "Stimme voll zu", "Stimme teilweise zu", NA,
NA, NA, "Stimme zu", "Stimme teilweise zu", NA, NA, NA, NA, NA,
NA, NA, NA, "Stimme zu", "Stimme teilweise zu", "Stimme zu",
NA, NA, NA, "Stimme zu", "Stimme zu", NA, "Stimme teilweise zu",
"Stimme zu", NA, "Stimme teilweise zu", "Stimme teilweise zu",
"Stimme zu", NA, NA, NA, "Stimme voll zu", "Stimme voll zu",
"Stimme teilweise zu", NA, NA, NA, "Stimme voll zu", NA, "Stimme teilweise zu",
"Stimme teilweise zu", NA, "Stimme zu", NA, "Stimme teilweise zu",
"Stimme voll zu", "Stimme teilweise zu", "Stimme zu", "Stimme eher nicht zu",
"Stimme teilweise zu", NA, "Stimme teilweise zu", "k. A.", "Stimme teilweise zu"
), veränderung_imap_neue.strukturen = c("Stimme zu", "Stimme zu",
NA, NA, "Stimme teilweise zu", "Stimme zu", "Stimme zu", "Stimme teilweise zu",
NA, NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", NA, NA, NA,
NA, NA, "Stimme teilweise zu", NA, NA, NA, NA, "Stimme teilweise zu",
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", NA, "Stimme zu",
NA, NA, NA, NA, NA, "Stimme voll zu", "Stimme teilweise zu",
NA, NA, NA, "Stimme zu", "Stimme teilweise zu", NA, NA, NA, NA,
NA, NA, NA, NA, "Stimme zu", "Stimme zu", "Stimme teilweise zu",
NA, NA, NA, "Stimme zu", "Stimme zu", NA, "Stimme teilweise zu",
"Stimme zu", NA, "Stimme teilweise zu", "Stimme zu", "Stimme zu",
NA, NA, NA, "Stimme voll zu", "Stimme zu", "Stimme teilweise zu",
NA, NA, NA, "Stimme voll zu", NA, "Stimme voll zu", "Stimme teilweise zu",
NA, "Stimme voll zu", NA, "Stimme teilweise zu", "Stimme voll zu",
"Stimme teilweise zu", "Stimme eher nicht zu", "Stimme eher nicht zu",
"Stimme eher nicht zu", NA, "Stimme eher nicht zu", "k. A.",
"Stimme nicht zu"), veränderung_imap_zuständigkeiten.klarer = c("Stimme teilweise zu",
"Stimme teilweise zu", NA, NA, "Stimme teilweise zu", "Stimme zu",
"k. A.", "Stimme teilweise zu", NA, NA, NA, NA, NA, NA, NA, "Stimme eher nicht zu",
NA, NA, NA, NA, NA, "Stimme teilweise zu", NA, NA, NA, NA, "Stimme teilweise zu",
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", NA, "Stimme zu",
NA, NA, NA, NA, NA, "Stimme teilweise zu", "Stimme teilweise zu",
NA, NA, NA, "Stimme teilweise zu", "Stimme teilweise zu", NA,
NA, NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", "Stimme teilweise zu",
"Stimme zu", NA, NA, NA, "Stimme teilweise zu", "Stimme teilweise zu",
NA, "Stimme zu", "Stimme teilweise zu", NA, "Stimme teilweise zu",
"Stimme teilweise zu", "Stimme zu", NA, NA, NA, "Stimme voll zu",
"Stimme zu", "Stimme teilweise zu", NA, NA, NA, "Stimme voll zu",
NA, "Stimme eher nicht zu", "Stimme zu", NA, "Stimme teilweise zu",
NA, "Stimme teilweise zu", "Stimme teilweise zu", "Stimme teilweise zu",
"Stimme teilweise zu", "Stimme eher nicht zu", "Stimme eher nicht zu",
NA, "Stimme zu", "k. A.", "Stimme eher nicht zu"), veränderung_imap_rollen.klarer = c("Stimme teilweise zu",
"Stimme teilweise zu", NA, NA, "Stimme teilweise zu", "Stimme zu",
"k. A.", "Stimme eher nicht zu", NA, NA, NA, NA, NA, NA, NA,
"Stimme teilweise zu", NA, NA, NA, NA, NA, "Stimme teilweise zu",
NA, NA, NA, NA, "Stimme eher nicht zu", NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, "Stimme zu", NA, "Stimme zu", NA, NA, NA, NA, NA, "Stimme teilweise zu",
"Stimme nicht zu", NA, NA, NA, "Stimme teilweise zu", "Stimme teilweise zu",
NA, NA, NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", "Stimme teilweise zu",
"Stimme nicht zu", NA, NA, NA, "Stimme zu", "Stimme teilweise zu",
NA, "Stimme zu", "Stimme nicht zu", NA, "Stimme teilweise zu",
"Stimme zu", "Stimme zu", NA, NA, NA, "Stimme voll zu", "Stimme zu",
"Stimme teilweise zu", NA, NA, NA, "Stimme voll zu", NA, "Stimme eher nicht zu",
"Stimme teilweise zu", NA, "Stimme teilweise zu", NA, "Stimme teilweise zu",
"Stimme zu", "Stimme teilweise zu", "Stimme eher nicht zu", "Stimme teilweise zu",
"Stimme teilweise zu", NA, "Stimme zu", "k. A.", "Stimme zu"),
    veränderung_imap_digitale.lösungen = c("Stimme zu", "Stimme zu",
    NA, NA, "Stimme voll zu", "Stimme zu", "Stimme zu", "Stimme zu",
    NA, NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", NA, NA,
    NA, NA, NA, "Stimme zu", NA, NA, NA, NA, "k. A.", NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, "Stimme voll zu", NA, "Stimme zu",
    NA, NA, NA, NA, NA, "Stimme voll zu", "Stimme zu", NA, NA,
    NA, "Stimme zu", "Stimme teilweise zu", NA, NA, NA, NA, NA,
    NA, NA, NA, "Stimme nicht zu", "Stimme teilweise zu", "Stimme zu",
    NA, NA, NA, "Stimme voll zu", "Stimme voll zu", NA, "k. A.",
    "Stimme voll zu", NA, "Stimme zu", "Stimme zu", "Stimme zu",
    NA, NA, NA, "Stimme zu", "Stimme voll zu", "k. A.", NA, NA,
    NA, "Stimme zu", NA, "Stimme nicht zu", "Stimme voll zu",
    NA, "Stimme zu", NA, "Stimme zu", "Stimme voll zu", "Stimme voll zu",
    "Stimme zu", "Stimme zu", "Stimme zu", NA, "Stimme zu", "k. A.",
    "Stimme zu"), veränderung_imap_klarheit.prozesse = c("Stimme voll zu",
    "Stimme teilweise zu", NA, NA, "Stimme zu", NA, NA, "Stimme zu",
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Stimme zu",
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, "Stimme zu", NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Stimme zu",
    NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, "Stimme voll zu", NA, NA, "Stimme voll zu", "Stimme voll zu",
    "Stimme teilweise zu", "Stimme zu", "Stimme zu", NA, "Stimme teilweise zu",
    "k. A.", "Stimme zu"), veränderung_imap_weiterent.planung = c("Stimme voll zu",
    "Stimme teilweise zu", NA, NA, "Stimme teilweise zu", NA,
    NA, "Stimme teilweise zu", NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, "Stimme zu", NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    "Stimme voll zu", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, "Stimme zu", NA, NA, NA, NA, NA,
    NA, "Stimme teilweise zu", NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Stimme zu",
    NA, NA, "Stimme zu", "Stimme voll zu", "Stimme teilweise zu",
    "Stimme zu", "Stimme zu", NA, "Stimme teilweise zu", "k. A.",
    "Stimme zu"), veränderung_imap_arbeit.relfelktieren = c("Stimme zu",
    "Stimme teilweise zu", NA, NA, "Stimme zu", NA, NA, "Stimme zu",
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Stimme zu",
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, "Stimme voll zu", NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Stimme voll zu",
    NA, NA, NA, NA, NA, NA, "Stimme teilweise zu", NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, "Stimme zu", NA, NA, "Stimme teilweise zu", "Stimme voll zu",
    "Stimme teilweise zu", "Stimme zu", "Stimme zu", NA, "Stimme zu",
    "k. A.", "Stimme zu")), row.names = c(NA, -114L), class = c("tbl_df",
"tbl", "data.frame"))

A: The second line of code should be a lambda function
MD4[1:10] <- lapply(MD4[1:10], function(x)
   ordered(x,c("Stimme nicht zu", "Stimme eher nicht zu",
   "Stimme teilweise zu", "Stimme zu", "Stimme voll zu", "k. A.")))

Or can specify the levels as
lapply(MD4[1:10], ordered,
   c("Stimme nicht zu", "Stimme eher nicht zu",
  "Stimme teilweise zu", "Stimme zu", "Stimme voll zu", "k. A."))

A: Another possibility is using fct_relevel from forcats package (it is in tidyverse)
library(dpylr)
library(forcats)
df %>%
  mutate(across(starts_with("veränderung"), forcats::fct_relevel, "Stimme nicht zu", "Stimme eher nicht zu", "Stimme teilweise zu", "Stimme zu", "Stimme voll zu", "k. A."))

A: With the dplyr package, you can use mutate with across.
library(dplyr)

MD4 %>%
  mutate(across(1:10, ordered, levels = c("Stimme nicht zu", "Stimme eher nicht zu", "Stimme teilweise zu", "Stimme zu", "Stimme voll zu", "k. A.")))


text:
Q: Ionic iOS app: Xcode UIKit Crashes Ionic iOS app is on testflight and I have 3 crashes (see below). They all have to do with the UIKit.
Since it is an Ionic app and I have nothing to do or have no control over layers and this stuff (all I can edit is the HTML, CSS, and JS for my ios app), I have no idea what in my code might be causing this or even where to start looking?
Any help or even just how to understand how the UIKit relates to my ionic code or point me in the right direction to look, would be appreciated, I am really stuck.


text:
Q: convert sql to plsql Hello I have three codes in sql and you know you advice on how to rewrite them in pl / sql.I can not find an answer or program to transform
thanks for help
1
SELECT PATIENT.NAME ,
PATIENT.NAME_OF_DOCTOR,
PATIENT.ROOM_NUMBER
FROM PATIENT ;

2
SELECT WING.NAME ,
WING.SISTER_ON_WING,
WING.NURSES
FROM WING
oRDER BY WING.NAME,
WINGSISTER_ON_WING,
WING.NURSES;

3
SELECT COUNT (*) ,
CASE radiation_theraphy
WHEN '1' then 'Attendance'
WHEN '0' then 'Absence'
wHEN null then 'Null'
END radiation_theraphy
FROM patient
GROUP BY radiation_theraphy;

A: With SELECT clause you retrieve data from database. If you need to handle it in your PLSQL code, you have to put result into variable. For that you can use simple SELECT ... INTO clause (which works only for select always returning one row) or cursor together with looping over selected data, like this:
DECLARE
  CURSOR c_patient IS
    SELECT COUNT (*) ,
           CASE radiation_theraphy
             WHEN '1' then 'Attendance'
             WHEN '0' then 'Absence'
             wHEN null then 'Null'
           END radiation_theraphy
      FROM patient
      GROUP BY radiation_theraphy;
BEGIN
  for r in c_patient loop
    -- do something. you access values by r.<selected_column_name>,
    -- for example r.radiation_therapy
  end loop;
END;


text:
Q: Superkey consists of three attributes - how to cope with Hibernate? Consider a relation with a candidate key of three attributes:

I was wondering if someone could give me an example of a config file for Hibernate?

A: ...
<class name="Topic" table="topics">
    ...
    <set name="candidatures" table="Topic_has_Count_has_Date">
        <key column="TOPIC_ID"/>
        <composite-element class="TopicCountDate">
            <parent name="topic"/>
            <many-to-one name="count" class="Count" column="COUNT_ID"/>
            <many-to-one name="date" class="Date" column="DATE_ID"/>
        </composite-element>
    </set>
</class>
<class name="Date" table="dates">
    ...
    <set name="candidatures" table="Topic_has_Count_has_Date">
        <key column="DATE_ID"/>
        <composite-element class="TopicCountDate">
            <parent name="date"/>
            <many-to-one name="count" class="Count" column="COUNT_ID"/>
            <many-to-one name="topic" class="Topic" column="TOPIC_ID"/>
        </composite-element>
    </set>
</class>
<class name="Count" table="counts">
    ...
    <set name="candidatures" table="Topic_has_Count_has_Date">
        <key column="COUNT_ID"/>
        <composite-element class="TopicCountDate">
            <parent name="count"/>
            <many-to-one name="date" class="Date" column="DATE_ID"/>
            <many-to-one name="topic" class="Topic" column="TOPIC_ID"/>
        </composite-element>
    </set>
</class>


text:
Q: press q for quit and enter for continue I have a do-while loop, and I want if I press ENTER key, the progress will continue, but q will finish the program. It is not working as the program will end straight away and does not wait for the user to enter the key.
Code below is my main code.
void displayGrid() {
    bool progress = true;
    printf("%s", "input round for round mode, moves for move mode");
    scanf("%s", input);
    toLowerCase(input);
    if (strcmp(input, "round") == 0) {
        do {
            printf("Enter key ENTER to continue,Q for quit \n");
            bool qoc = quitOrContinue();
            if (qoc) {
            } else if (!qoc) {
                progress = false;
            }
        } while (progress);
    }
}

This is my code for checking enter and q key:
bool quitOrContinue() {
    if (kbhit()) {
        char click = fgetc(stdin);
        while (getchar() != '\n');
        if (click == 0x0A) {
            return true;
        } else if (click == 'q') {
            return false;
        }
    }
}

A: You do not need three functions to read a char from stdin.
Here's some psuedo-code to illustrate how to read one char. (I couldn't test it, so there may be some bugs in it).
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

static bool quitOrContinue(void)
{
    int click = fgetc(stdin);
    if (click == 0x0A) {
        return true;
    } else if (click == 'q') {
        return false;
    }
    /* Returns false in case of any other character */
    return false;
}

int main(void)
{
    bool condition = false;
    do {
        printf("Hello World\n");
        printf("Enter q to quit or ENTER to continue.\n");
        condition = quitOrContinue();
    } while (condition);

    return EXIT_SUCCESS;
}

You do not need the progress variable.
while (getchar() != '\n');
serves no purpose in your code, unless you're trying to flush stdin.
regarding:
printf("%s", "input round for round mode, moves for move mode");

You could use:
printf("input round for round mode, moves for move mode");

regarding:
scanf("%s", input);

What happens when one inputs more than size characters?
Limit length:
scanf("%6s", input);


text:
Q: Oracle Php Login Script i have created a login script in php using Mysql database but im trying to mimic the same script using Oracle 11g database,my problem is that i can not seem to login no errors are showing on my page or notices,im pretty sure the mistakes are from SQL statements here is what i have and i have been following this link PHP ORACLE MENU
my login scrip
<?php
                if(isset($_POST['login'])){
                    include 'includes/config.php';

                    $uname = $_POST['uname'];
                    $pass = $_POST['pass'];

                    $query = oci_parse($conn, "SELECT * FROM admin WHERE uname = '$uname' AND pass = '$pass'");
                    oci_execute($query);

                    $rs = $conn->query($query);
                    $num = $rs->num_rows;
                    $rows = $rs->oci_fetch_array();
                    if($num > 0){
                        session_start();
                        $_SESSION['uname'] = $rows['uname'];
                        $_SESSION['pass'] = $rows['pass'];
                        echo "<script type = \"text/javascript\">
                                    alert(\"Login Successful.................\");
                                    window.location = (\"admin/index.php\")
                                    </script>";
                    } else{
                        echo "<script type = \"text/javascript\">
                                    alert(\"Login Failed. Try Again................\");
                                    window.location = (\"login.php\")
                                    </script>";
                    }
                }
            ?>

i'm trying to learn the oracle php scripting and i need guidance on how  to sort this out thanks in advance.

A: Your statement looks ok to me.
If the connection string ($conn) is ok, following code should do the trick.
$query = oci_parse($conn, "SELECT * FROM admin WHERE uname = '$uname' AND pass = '$pass'");
oci_execute($query);
if( $rows = oci_fetch_array($query) ){
  //... set session variables, login, etc...
}

The line
if( $rows = oci_fetch_array($query)

would just return false if there are no results.


text:
Q: Backbone.js event doubts i have to create events using backbone.js.Below is my js code
var Trainee = Backbone.Model.extend();

            var TraineeColl = Backbone.Collection.extend({
                model: Trainee,
                url: 'name.json'
            });

            var TraineeView = Backbone.View.extend({
                el: "#area",

                template: _.template($('#areaTemplate').html()),

                render: function() {
                        this.model.each(function(good){
                        var areaTemplate = this.template(good.toJSON());
                        $('body').append(areaTemplate);
                    },this);

                    return this;
                }
            });

            var good = new TraineeColl();
            var traineeView = new TraineeView({model: good});
            good.fetch();

            good.bind('reset', function () {
            $('#myButtons').click(function() {
                traineeView.render();
                });
            });

<button class="firstbutton" id="newbutton">
   Display

</button>


text:
Q: TFS and clicking hyperlinks I have some buttons in my web (javascript based) application. And I can record consecutive steps which I use these button in. The problem appears when I want to click a hyperlink. TFS doesn't recognize it - everything seems to be fine while recording a step, but later in tests it points my hyperlink with the mouse cursor, but nothing happens (no click executed).
In HTML it looks like:

*
    Link 1

[edit]
I have noticed that the problem appears in Chrome, but in IE10 is OK...

A: You need to be using TFS 2012 update 2 or higher for this to work in Chrome.


text:
Q: Reset SKScene in Sprite Kit Game I am working on a game.
My 1st screen include 3 buttons : leaderboards, achievements and play.
When I tap on play, the Game Scene is showed.
let transition = SKTransition.doorsOpenHorizontal(withDuration: 1.0)
let next_scene = GameScene(fileNamed: "GameScene")
next_scene?.scaleMode = scaleMode
view?.presentScene(next_scene!, transition: transition)

When the user dies, I want to reset the game scene, that includes erasing everything and calling didMove function again. I want to erase game scene and create it again.
How can I do this?
I tried
self.view?.presentScene(nil)
let transition = SKTransition.doorsOpenHorizontal(withDuration: 1.0)
let next_scene = MainMenu(size: self.size)
next_scene.scaleMode = scaleMode
self.view?.presentScene(next_scene, transition: transition)

but made the scene blank with 0 nodes.

A: Try doing it this way: `
  let gameSceneTemp = sceneName(fileNamed: "fileName")
                gameSceneTemp?.scaleMode = self.scaleMode
                self.scene?.view?.presentScene(gameSceneTemp!, transition: SKTransition.doorsCloseHorizontal(withDuration: 0.0))`

I also sometimes create objects not in SKScenes files, and if you are using addChild, you shouldn't have any problems.


text:
Q: How to reset kafka to integrate it in a JUnit testing process? I am testing and debugging an event-sourcing (or stateful stream processing) application that runs in top of kafka and uses samza. I want to remove queues and topics in kafka so that samza jobs get an empty kafka installation at startup.
How can I do it??

Edit:
The question is quite more complex and specific that what I wrote at first.
As David states there is a solution to purge the topic, starting from kafka 0.8.2:
Purge Kafka Queue
What I am interested in is in setting up a testing environment that automatically loads zookeeper and kafka (which are bundled in my git repository as binary packages).
I am using gradle environment + eclipse and JUnit. I run integration tests from eclipse (as JUnit tests).
How could the loading be automated? Should I create a specific Test class to set up the environment and launch kafka and zookeeper? Is there any reference example/code? The idea would be to load the enviroment, run a few tests, and stop. If this process could be made in a few seconds, better.

A: There are different approaches to purging individual topics. All of them could be extended out to purging all of your topics. However, I think you are asking a larger question related to creating a baseline environment for Kafka -- something you would need for testing, perhaps. Or maybe you have a production process that starts from scratch each time. These are actually different scenarios.
For Testing
If you were talking testing, then I would do something brute force, on purpose. First, I would configure Kafka to be the way I would want it to look on startup. Then I would shut it down and back it up -- either using tar or possibly even making a disk image, if I am using a VM.
I'd use it and abuse it during testing, then throw it all away when I was done. "Resetting kafka" would just mean restoring either via untar or from a disk image or whatever (rsync even, or just cp from another directory).
For testing, I really do want a clean beginning, so I prefer brute force.
During Production
If this is part of your production processes -- and I question the wisdom of that on its face -- then I would try and not lose the data first. Either include a backup in your process, or don't actually reset the topics.
Topic rename doesn't exist yet -- but you can use the same approach that's going to be used. Don't deal directly with topic names -- have a dictionary to map virtual topic names to actual topic names.
Then, instead of "resetting" Kafka each time, create new versions of all of the topics, and update the dictionary to map the virtual topic name to the newly created topic versions.


text:
Q: Do Firebase preview channels use the same DB? I've looked around for answers to my question, but most are actively trying to do what I don't want which is why I'm asking.
An app I'm developing for the company I work for has gone live, and so to further develop I need to use Firebase preview channels.
I've looked over the documentation and it states that channels use the same resources, which I find a little unclear.
Does this mean that preview channels are UI only and using an app on a preview channel will still write to the live database (Firestore) that customers are currently using?

A: If you're talking about Firebase Hosting preview channels, the only difference between each channel is the web content (html, css, js, images) that you deploy to it.  The configurations for the other Firebase products (database, analytics, etc) don't change at all.  You can see this for yourself by printing the active Firebase configuration in JavaScript - you should see the all the same values.
If you want to build against a different database before you push updates to production, you should instead use completely different Firebase projects to keep them separate.  It's common for developers to keep multiple projects for multiple environments, such as development, staging, and production.  This is the formal recommendation.
Bottom line: A Firebase Hosting preview channel just lets you try out different web assets against the same backend services.  If you want different working environments to avoid disturbing customers in production, you should use different projects entirely.


text:
Q: Construction of a rhombus with given conditions
given two parallel lines $P$, $Q$ and two points $X$,$Y$ how to construct a rhombus $ABCD$ passing through $X$,$Y$  and opposite sides lie on $P$ and $Q$.
I solved a special case of this problem where one point $Y$ lies on the parallel line. any hints or ideas?
If $Y$ lies on line $q$, draw a circle with center $Y$ and radius $XY$. The circle will intersect line $p$ at point $Z$. If I draw a perpendicular bisector of $ZX$ it will intersect line $p$ at $B$. Then it is easy to construct the required rhombus.

A: In a rhombus the distance between one pair of parallel sides is same as distance between another pair of parallel opposite sides.
So first find perpendicular distance $AB$ between $p$ and $q$.

Next with $X$ as center and radius $AB$, draw a circle. From $Y$ drop tangents to this circle. Extend a suitable tangent to intersect $p,q$ in $Q$ and $R$.
Now construct a line through $X$ parallel to $QR$ to intersect $p,q$ in $P,S$. $PQRS$ is our desired rhombus.
We used the fact that $AB=XT$. For this construction, $X,Y$ need not lie between $p,q$.


text:
Q: Query to retrieve custom columns from select statement Let's say that within the customers table there are the following columns : customer_id and customer_name.
From a select statement that I am trying to perform, I need to add in a custom sysdate column that is not associated with the customer's table and give it a value. I tried using an inner query, but that only led to the creation of the current_date column but it has no value.
Example -
SELECT CUSTOMER_ID, CUSTOMER_NAME, (SELECT SYSDATE FROM DUAL) AS CURRENT_DATE
FROM customers

OUTPUT
CUSTOMER_ID || CUSTOMER_NAME || CURRENT_DATE
-----------    -------------    ------------
1              JOHN DOE
2              JANE DOE

The expected output I am trying to get is down below - Could anyone please provide me a solution to this problem?
OUTPUT
CUSTOMER_ID || CUSTOMER_NAME || CURRENT_DATE
-----------    -------------    ------------
1              JOHN DOE          08/07/2020
2              JANE DOE          08/07/2020

A: In my database, it is as simple as
SQL> select empno, ename, sysdate
  2  from emp
  3  where rownum < 4;

     EMPNO ENAME      SYSDATE
---------- ---------- -------------------
      7369 SMITH      07.08.2020 22:13:22
      7499 ALLEN      07.08.2020 22:13:22
      7521 WARD       07.08.2020 22:13:22

SQL>

Your query works as well (although, why making it more complex than it should be?):
SQL> select empno, ename, (select sysdate from dual) current_date
  2  from emp
  3  where rownum < 4;

     EMPNO ENAME      CURRENT_DATE
---------- ---------- -------------------
      7369 SMITH      07.08.2020 22:14:35
      7499 ALLEN      07.08.2020 22:14:35
      7521 WARD       07.08.2020 22:14:35

SQL>

Why didn't you get the result? No idea.

A: You can get the current date using SYSDATE, so you could do something like
SELECT
  CUSTOMER_ID,
  CUSTOMER_NAME,
  to_char(cast(SYSDATE as date), 'MM/DD/YYYY') AS cust_date
FROM
  customers

which should give you the output formatted how you want.


text:
Q: por que no me sube el archivo de imagen y no se visualiza? tengo el siguiente codigo fuente, el problema es que no se por que no se visualiza ni tampoco se suben las imagenes. me indica error de extencion de archivo. uso windows 7 con xampp php 5.3
   <?php
include_once "includes/mysql_conex.php";
$archivo = $_POST['archivo'];
if (isset($_POST['submit']))
{
        $useruid2 = mysqli_query($conexion, 'INSERT INTO usuarios_registro (foto_perfil) values(\''.$archivo.'\')');
        // if (mysqli_num_rows($useruid2) == 0)
        if ($useruid2 == 0)
            die('Dato 1.');
        else
        {
        $imagen_vista = mysqli_query($conexion, 'SELECT * FROM usuarios_registro ORDER BY RowID DESC  LIMIT 1');
        $RowID =(mysqli_fetch_array($imagen_vista));
        $id_insert = $RowID['0'];
        echo "
Entro el RowID ".$RowID['0']." con ese numero
";
        if($_FILES['archivo']['error']>0){
            die('No se subio archivo.');
        }else{
        //die('Entro 1');//test de entrada para descomentar
            $permitidos = array("image/jpg","image/png","image/gif");
            $limite_kb = 5120;
                if(in_array($_FILES["archivo"]["type"],$permitidos))
                {
                    if(in_array($_FILES['archivo']['type']['size'] < $limite_kb))
                    {
                        die('Entro 2');//test de entrada para descomentar
                        $ruta='./images/'.$id_insert.'/';
                        $archivo = $ruta.$_FILES['archivo']['name'];
                                if(!file_exists($ruta)){
                                // die('Entro 3');//test de entrada para descomentar
                                mkdir($ruta);
                                }
                                    if(!file_exists($archivo)){
                                    $resultado =@move_uploaded_file($_FILES['archivo']['tmp_name'],$archivo);
                                        if($resultado){
                                        // die('Entro 4');//test de entrada para descomentar
                                        echo"archivo guardado";
                                        }else{
                                        // die('Entro 5');//test de entrada para descomentar
                                        echo"Error al guardar archivo";
                                        }

                                    }else{
                                    die('el archivo ya existe');
                                    }
                    }else{
                    die('archivo pesado');
                    }
                }else{
                die('Extencion de archivo no permitido');
                }
        }

        }
}

        $imagen_vista_src = mysqli_query($conexion, 'SELECT * FROM usuarios_registro ORDER BY RowID DESC  LIMIT 1');
        $vita =(mysqli_fetch_array($imagen_vista_src));
echo    "images/".$vita['0']."/".$vita['foto_perfil'];
?>

<form action="<?php
echo $_SERVER['PHP_SELF'];
?>" method="POST">

<img src="<?php "images/".$vita['foto_perfil'];?>" width=100 height=100>

Subir Foto de Perfil
<input type="file" name="archivo" id="archivo"accept="image/*">

Name
<?php echo $namefirs; ?>

last Name
<?php echo $namefirs; ?>

Documento
<?php echo $namefirs; ?>

Wallet Bitcoin
<?php echo $namefirs; ?>

Wallet Etherium
<?php echo $namefirs; ?>

Wallet litecoin
<?php echo $namefirs; ?>

PayPal
<?php echo $namefirs; ?>

Uphold
<?php echo $namefirs; ?>

<input type="submit" value="Actualizar" name="submit" />

</form>

A: Ten cuidado, no es image/jpg es image/jpeg. Por tanto, debería de ser:
 $permitidos = array("image/jpeg","image/png","image/gif");

En cualquier caso, para poder ayudarte se necesita algo más de información. Por ejemplo, ¿ puedes añadirnos el resultado de la siguiente línea...
print_r($_FILES["archivo"]["type"]);

si la colocas antes del if de comprobación de la extensión ?.


text: Q: Javafx TextFlow text wrapping issue when using ImageView When I'm adding ImageView to the TextFlow element, the next Text element is starting at the bottom of an image. Is there a way to configure text wrapping so that text will start near the top and continue along the side while where is space?