text:
Q: How to use RequiredFieldValidator and ValidationSummary with Bootstrap I am new to ASP.Net and have a simple question about ValidationSummary or Validator in general. The problem is that even if there are no validation errors my alert div is still showing. ASP.Net generates code for clientside validation so how am I going to display the alert div only when an error occurs, is this even possible? I thought that ValidationSummary may help in this situation but I am not sure, hope someone can help me.
Current page:
<asp:Login ID="LoginForm" runat="server" ViewStateMode="Disabled" RenderOuterTable="False" OnAuthenticate="LoginForm_Authenticate">
    <LayoutTemplate>

<asp:RequiredFieldValidator ID="RequiredFieldValidatorUserName" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="UserName" Display="Dynamic"></asp:RequiredFieldValidator>

<asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="Password" Display="Dynamic"></asp:RequiredFieldValidator>

                <asp:TextBox runat="server" CssClass="form-control" ID="UserName" />
                <asp:TextBox runat="server" CssClass="form-control" ID="Password" TextMode="Password"/>

            <asp:Button runat="server" ID="Login" CommandName="Login" CssClass="btn btn-default btn-primary" Text="Login" />
    </LayoutTemplate>
</asp:Login>

A: RequiredFieldValidator should be under or above each TextBox with SetFocusOnError="True"
If you want, you can use ValidationSummary with alert alert-danger style to show consolidate validate messages of all validators.

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

Login

        <asp:ValidationSummary runat="server" ID="ValidationSummary1"
            DisplayMode="BulletList"
            ShowMessageBox="False" ShowSummary="True" CssClass="alert alert-danger" />

                Useranme

                <asp:TextBox runat="server" CssClass="form-control" ID="UserName" />
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorUserName"
                    runat="server"
                    ErrorMessage="Please enter username." ControlToValidate="UserName"
                    Display="Dynamic" SetFocusOnError="True" CssClass="alert-text" />

                Password

                <asp:TextBox runat="server" CssClass="form-control" ID="Password"
                    TextMode="Password" />
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword"
                    runat="server"
                    ErrorMessage="Please enter password." ControlToValidate="Password"
                    Display="Dynamic" SetFocusOnError="True" CssClass="alert-text" />

                <asp:Button runat="server" ID="Login" CommandName="Login"
                    CssClass="btn btn-default btn-primary" Text="Login" />

A: This is a life saver! but if you use CssClass="alert-text" bootstrap will not recognize it. Use CssClass="text-danger"in the required validators. But as for the rest, works like a charm!

A: create a <asp:ValidationSummary ID="Valid" runat="server" ValidationGroup="1" CssClass="validationsColor" DisplayMode="BulletList" />
then set the <asp:RequiredFieldValidator ID="RequiredFieldValidatorUserName" runat="server" ErrorMessage="RequiredFieldValidator" ValidationGroup="1" ControlToValidate="UserName" Display="Dynamic"></asp:RequiredFieldValidator>
Try that and see.


text:
Q: Reading Copied Integer Values from Excel to .txt file in Java I want to read an integer value from a text file to an array. The code works fine if type the numbers in the .txt file. Afterwards i tried to copy integer values from excel to the text file and tried to read it. In this case i get the following error code.
[989    1042    1059    1067    1087    1098    1103    1110    1114    1131]
Exception in thread "main" java.lang.NumberFormatException: For input string:
"989    1042    1059    1067    1087    1098    1103    1110    1114    1131"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at readparetoapprox.readapproxset(readparetoapprox.java:83)
at DomSortepsilon.main(DomSortepsilon.java:11)

File fileText = new File(FileName);
Scanner sc = new Scanner(new BufferedReader(new FileReader(fileText)));

Scanner sc1 = new Scanner(new BufferedReader(new FileReader(fileText)));
String[] line1 = sc1.nextLine().trim().split(" ");

int rows = 2;
int columns = line1.length;
int [][] intarray= new int[rows][columns];

int x=0;
while(x<1) {
   for (int i=0; i<intarray.length; i++) {
      String[] line = sc.nextLine().trim().split(" ");
      System.out.println(Arrays.toString(line));
      for (int j=0; j<line.length; j++) {
          paretofront[i][j] = Integer.parseInt(line[j]);
      }
   }
x++;
}
System.out.println(Arrays.deepToString(intarray));

I really have no idea why I receive the NumberFormatException error.
I´m really thankful for your help.
Greetings,
Martin

redpajama_set_name: RedPajamaStackExchange


text:
Q: Verb describing chainsaw making that bursting sound when you push the throttle trigger With the positive meaning, if it possible, just so I didn't have to use adverbs like happily. The only thing I came up- buzzed. Thank you.

A: Two-cycle, or four?  Anyhow, consider brattle, a verb that means "To rattle; to make a scampering noise", with etymology "Apparently imitative, probably under influence of break + rattle".  I don't know what a scampering noise is, but believe brattle suggests the right sort of sound.
To rev up an engine is "To increase the speed of an engine", so revving up may be appropriate too, along with the less-well-known poppity-popping.

A: How about roared?  It connotes power more strongly than buzzed does, but is still a word in common usage.

A: How about growled or ripped???


text:
Q: Prove that $\angle{BEC}=\angle{DAC}$. A convex quadrilateral $\quad{ABCD}$ has $AD=CD$ and$\angle{DAB}=\angle{ABC}<90$. The line through $D$ and the midpoint of $BC$ meets line $AB$ in $E$. Prove that $\angle{BEC}=\angle{DAC}$.
I have to approaches: Either we can prove that $EB.EA=EC^2$ or we can prove that line $AD$ is the tangent to the circumcircle of $\triangle{ACE}$ as shown, but I am not getting how to prove them. Pure geometrical method is preferred.

A:
Let $F$ be the intersection of line $AD$ and line $BC$. Since $\angle BDA = \angle ABC$, $AF=FB$.
Let $O$ be the center of the circumcircle of $\triangle ABC$ and let $G$, $I$ be the projections of $O$ onto $AF$ and $CD$. Then

*

*$OG = OM$ because $O$ and $F$ lie on the perpendicular bisector of $AB$.

*$OG = OI$ because $O$ and $D$ lie on the perpendicular bisector of $AC$.

It follows that $OM=OI$ and that $CO$ is the angle bisector of $\angle DCB$.
Next, consider $\triangle ABF$ with $D$, $M$, and $E$ colinear. Menelaus' theorem implies that
$$\frac{EA}{EB}\cdot\frac{MB}{MF}\cdot\frac{DF}{DA}=1.$$
Similarly, $\triangle ABF$ with $H$, $C$, and $E$ colinear. Menelaus' theorem gives us
$$\frac{EA}{EB}\cdot\frac{CB}{CF}\cdot\frac{HF}{HA} = 1.$$
Thus we have
$$\frac{MB}{MF}\cdot\frac{DF}{DA} = \frac{CB}{CF}\cdot\frac{HF}{HA},$$
or
$$\begin{aligned}\frac{HF}{HA} &= \frac{\color{blue}{MB}}{MF}\cdot\frac{DF}{DA}\cdot\frac{CF}{\color{blue}{CB}}\\
&=\frac{DF}{DA}\cdot\frac{CF}{2MF}
\end{aligned}$$
Since $AD = CD$ and $2MF = DF+CD+CF$, we have
$$\frac{HF}{HA}=\frac{DF\cdot CF}{CD\cdot(DF+CD+CF)}.$$
So
$$\frac{HF}{HF+HA}=\frac{DF\cdot CF}{CD(DF+CD+CF)+DF\cdot CF},$$
or
$$\frac{HF}{HA} = \frac{DF\cdot CF}{(CD+DF)(CD+CF)}.$$
Since $HA = DA+DF = CD+DF$, we have
$$HF = \frac{DF\cdot CF}{CD+DF}.$$
So $CH$ is the angle bisector of $\angle CDF$. Thus $CO\perp CH$, equivalently $EC$ is tangent to the circumcircle of $\triangle ABC$ at $C$.
It follows that $\angle BCE = \angle BAC$, and so $\angle DAC=\angle BEC$.

A: I have an Angle Chasing based approach to this problem. It is as follows;
Let $M$ be the midpoint of Line Segment $\overline{BC}$, we construct a line parallel to $BC$ through $D$, and let it intersect $AB$ and $EC$ at $F$ and $G$.

We know that $\angle AFD=\angle ABC=\angle BAD=\angle FAD$. Hence, $\triangle ADF$ is isosceles, and we must have $DA=DF$. We let $DA=DF=DC=x$.
We know by the Basic Proportionality Theorem that;
$$\frac{FD}{DG}=\frac{BM}{MC}=1$$
$$\implies FD=DG.$$
Since $FD=x$, we must have $DG=x$, as well. Now, we know that $DA=DF=DC=DF=x$, and thus $AFCG$ is a lies on a circle centered at $D.$ Hence, $AFCG$ is a Cyclic Quadrilateral.
Consider $\angle ACG$ and $\angle AFG$, since the two angles are inscribed in the same arc ${AG}$  of circle $AFCG,$ we know that $\angle ACG=\angle AFG.$
Hence, we know that;
$$180^{\circ}-\angle ACG = 180^{\circ}-\angle AFG$$
$$\implies \angle ACE= \angle GFE=\angle CBE$$
$$\implies \angle ACE=\angle CBE.$$
Consider triangles $\triangle ACE$ and $\triangle CBE,$ we know that they share an angle at $E,$ and $\angle ACE=\angle CBE.$ Hence, the two triangles are similar by $\text{AA Similarity}$ and we thus have;
$$\frac{EB}{EC}=\frac{EC}{EA}$$
$$\implies EB\cdot EA=EC^2,$$
which is what you needed. But just to continue, we know by similarity that $\angle BCE=\angle CAE,$ let this angle be $y.$
We know that $\angle BAD=\angle ABC,$ but since $\angle BAD=\angle BAC+\angle CAD,$ and $\angle ABC=\angle BCE+\angle BEC,$ we must have;
$$\angle BAC+\angle CAD=\angle BCE+\angle BEC$$
$$\implies y+\angle CAD=y+\angle BEC$$
$$\implies \angle CAD=\angle BEC$$
as required.

A: A shorter approach using symmedians:
It suffices to show that if $\angle BEC = \angle DAC$, then $ED$ passes through the midpoint of $BC$.
From $\angle BEC = \angle DAC$ we obtain that $DA$ (and hence also $DC$) is tangent to the circle through $A$, $C$ and $E$. It follows that $ED$ is the $E$-symmedian in triangle $ACE$. Because $\angle BCE = \angle BAC$, the line $BC$ is an antiparallel in triangle $ACE$, so its midpoint lies on the symmedian.

(The $A$-symmedian in triangle $ABC$ is the reflection of the median through $A$ in the angle bisector of angle $\angle BAC$. I used the known facts that the $A$-symmedian passes through the pole of $BC$ with respect to the circumcircle (i.e., the point of the intersection of the tangents at $B$ and $C$) and that the $A$-symmedian pases through the midpoint of every antiparallel (i.e. a line segment $XY$ with $X$ on $B$ and $Y$ on $AC$ so that $B$, $C$, $X$, $Y$ are concyclic).


text:
Q: How add List middle UITableViewRow I have full screen UITableView and i need set List from Resource  in MIDDLE UITableViewRow. I attach file which show what i need. For example how i do it in Android.
View cell = inflater.inflate(parent, R.layout.cell, false);
for(int = 0; i < resource.length; i++) {
 cell.findViewById(R.layout.cell).addView(inflater.inflate(parent, R.layout.list_item, false))
}

return cell;

Thank you

A: Here is a way to do it.
Add a StackView which would contain your List Items.
Now your stack view's top would be to bottom of the data row at top
And your stack view's bottom would be the top of data row at bottom.
As you keep adding labels to your stackview, it would keep growing.

Second way to do it, in case if your itemview is going to be very dynamic and would have lots of items.
Make the item view as a table view. And disable the scrolling of the item table view.
The constraints would be same as stack view.
And you would set tableview's height = tableview's content size.
Hope that helps


text:
Q: Converting timestamp(string) to date(dddd-mm-yy) in presto I have a timestamp value in a varchar column. the value looks like below.
2020-10-31T23:36:03.000+0000
I want to convert this to below for using it in my query filter.
2020-10-31
I tried using date_parse and split_part:
SELECT date_parse('2020-06-30T17:17:35.000+0000','%Y-%m-%d %H:%i:%s:%f') as xy
and
where cast(split_part('2020-06-30T17:17:35.000+0000', ' ', 1) as date) >= date '2020-06-30'
Both return error saying:
presto error: Invalid format: "2020-06-30T17:17:35.000+0000" is malformed at "T17:17:35.000+0000"
Can someone point me in the right direction?

A: Using this solved my problem
cast(from_iso8601_timestamp('2020-06-30T17:17:35.000+0000') as DATE)  >= date '2020-06-30'


text:
Q: Identify sequence of events based on certain rules I need help on identifying a sequence of events in SQL Server 2008 R2 rows please:
This is the sample data with SQLFiddle:
   ID   EventTime       TypeID             EventNr
    1   06:34:51        1
    2   06:35:51        3
    3   06:36:51        40
    4   06:37:51        10
    5   06:48:51        1
    6   06:49:51        2
    7   06:50:51        4
    8   06:51:51        40
    9   06:52:51        5
    10  06:53:51        10

I need help on identifying Event Nrs please -
Rules that I must follow:

*

*An event starts start with TypeID 1 (@StartTypeID).

*An event ends with TypeID 10 (@EndTypeID).

*An event has a different TypeID after @StartTypeID, and before @EndTypeID.

*And there must be more than 5 minutes between EventNrs.
This is the explected result for the above example:
 ID EventTime   TypeID  Notes                                               EventNr
1   06:34:51    1       Starts with TypeID @StartID 1     (OK)                     1
2   06:35:51    3       Has different TypeID in sequence before @EndID reached(OK) 1
3   06:36:51    40                                                                 1
4   06:37:51    10      Ends with @EndID 10 + >5min before next Event(OK EventEnd) 1

5   06:48:51    1       Starts with TypeID @StartID 1                              2
6   06:49:51    2       Has different TypeID in sequence before @EndID reached     2
7   06:50:51    4                                                                  2
8   06:51:51    40                                                                 2
9   06:52:51    5       Has different TypeID in sequence before  @EndID reached    2
10  06:53:51    10      Ends with @EndID 10                                        2

SQL for creating the data sample:
declare @FirstTypeID int = 1

declare @LastTypeID int = 10

create table #T (ID int identity , EventTime datetime, TypeID int)
insert into #T(EventTime,TypeID)
values
 (DATEADD(minute,-30,getdate()),1)
 ,(DATEADD(minute,-29,getdate()),3)
 ,(DATEADD(minute,-28,getdate()),40)
 ,(DATEADD(minute,-27,getdate()),10)
 ,(DATEADD(minute,-16,getdate()),1)
 ,(DATEADD(minute,-15,getdate()),2)
 ,(DATEADD(minute,-14,getdate()),4)
 ,(DATEADD(minute,-13,getdate()),40)
 ,(DATEADD(minute,-12,getdate()),5)
 ,(DATEADD(minute,-11,getdate()),10)

select * from #T

drop table #T

A: This query gives the correct output:
With ord as (
    Select first, last
        , EventNr = ROW_NUMBER() Over(order by first)
    From (
        Select first = t1.EventTime, last = t2.EventTime
            , rn = ROW_NUMBER() Over(partition by t1.ID order by t2.eventTime)
        From #T t1
        Inner Join #T t2 On t2.EventTime > t1.EventTime  and t2.TypeID = @LastTypeID
        Where t1.TypeID = @FirstTypeID
    ) ids
    Where rn = 1
)
Select t.ID, t.EventTime, t.TypeID, o.EventNr From #T t
Inner Join ord o On t.EventTime >= o.first and t.EventTime <= o.last
Order By o.EventNr, t.EventTime

I didn't use Column ID for ordering because it seems to be specific to your samplte.


text:
Q: Пару вопросов по pyTelegramApi (telebot) У меня есть два вопроса которые я не знаю как реализовать.
Первый вопрос - я добавил своего бота в чат, как получить список участников (через какой метод, если такой имеется).
Второй вопрос как после отправки сообщения боту, он разрешал нажимать на ту же самую кнопку уже на следующий день, то-есть кнопка работает один раз в день для всех участников.
Вот макет кода:
@bot.message_handler(content_types=['text'])
def ohh(message):
    chat_id = message.chat.id
    if message.text == ' Кликуха дня?' or message.text.lower() == 'кликуха дня' or message.text.lower() == 'кликуха':
    time.sleep(1)
    bot.send_message(message.chat.id, '` Подключаем базу ...`',parse_mode='Markdown')
    time.sleep(3)
    bot.send_message(message.chat.id, '`Ваня лашпед ...`',parse_mode='Markdown')


text:
Q: HistogramList with logarithmic bins? HistogramList gives the possibility to bin the elements in a list. Is it possible to have a logarithmic spacing? In an histogram I would do something like:
Histogram[data, "Log"]

I cannot find anything in the documentation...

A: As you found in the documentation
HistogramList[data, "Log"]

gives you a logarithmic spacing.  But if you're going to create a histogram figure, you'll also need to adjust the heights of the histogram bars so that the area sums to 1 or sums to the sample size depending on the objective.  Here's an example:
(* Generate some data *)
data = RandomVariate[LogNormalDistribution[0, 0.5], 1000];

(* Histogram based on the log of the data *)
h = HistogramList[Log[data]];

(* Convert back to original units *)
h[[1]] = Exp[h[[1]]];

(* Generate histogram boxes *)
n = Length[data];
logH=Table[{{h[[1,i]],0},{h[[1,i]],(h[[2,i]]/n)/(h[[1,i+1]]-h[[1,i]])},
{h[[1,i+1]],(h[[2,i]]/n)/(h[[1,i+1]]-h[[1,i]])},{h[[1,i+1]],0}},{i, Length[h[[2]]]}];

(* Plot histogram and true density *)
Show[ListLinePlot[logH, PlotStyle -> {{Thin, Black}}],
 Plot[PDF[LogNormalDistribution[0, 0.5], x], {x, 0, 4}]]

A: EDIT
HistogramList[data, "Log", "Probability"]

or for the counts:
HistogramList[data, "Log", "Count"]

ListPlot[Last@%]

Original answer
data = RandomVariate[NormalDistribution[0, 1], 200];
Histogram[data]

Histogram[data, ScalingFunctions -> {"Log", "Log"}]

Histogram[data, {"Log", "Sturges"}]


text:
Q: Cannot convert GeoJSON file to topo I have a GeoJSON file that represents the local government areas for NSW (state in Australia). It looks something like this:-
{
"LocalGovernmentArea" : {
    "type" : "FeatureCollection",
    "features" : [
        {
            "type" : "Feature",
            "geometry" : {
                "type" : "Polygon",
                "coordinates" : [
                    [
                        // Lots of coordinates
                    ]
                ]
            },
            "properties" : {
                "rid" : 63,
                "startdate" : "20160115133054",
                "enddate" : "30000101000000",
                "lastupdate" : "20160115133106.993000",
                "msoid" : 74,
                "centroidid" : null,
                "shapeuuid" : "70e041ba-bd11-30c2-b86f-8b89eb516afa",
                "changetype" : "M",
                "processstate" : null,
                "urbanity" : "U",
                "Shape__Length" : 622956.5638272235,
                "Shape__Area" : 8579520431.758272,
                "cadid" : 108012460,
                "createdate" : "20040729132211",
                "modifieddate" : "20160115132957",
                "lganame" : "WALCHA",
                "councilname" : "WALCHA COUNCIL",
                "abscode" : 7850,
                "ltocode" : 6520,
                "vgcode" : 252,
                "wbcode" : null
            }
        },

Each LGA is represented like this. The JSON is valid, but when I try to convert using geo2topo I get this:-
> geo2topo LocalGovernmentArea=lgas_minified.json
  {"type":"Topology","objects":{"LocalGovernmentArea":{}},"arcs":[]}

What am I doing wrong? Is my input not GeoJSON or am I using geo2json incorrectly?

A: Worked out the problem was that I had this in the JSON:-
"LocalGovernmentArea"
If you remove this element from the JSON and just flatten out the structure, everything works as expected.


text:
Q: how do i use expand on entrys while i can position them python 3 tkinter I want to make entrys move while resizing. an example is this code.
i didnt want to upload the 300 line code because it does not have to do anything with the design.
as you can see when you resize it horizontaly the entry2 is moving horizontaly how do i do the same for entry1?
i tried the pack(expand=True) on entry1 but then the entry2 is placed in the position of button.
im sorry if i cant make the problem clear this is my first time asking questions about programming...
import tkinter as tk

app = tk.Tk()

app.geometry("600x350")

Canvas = tk.Canvas(height=600, width=1000, bg="#343434")
Canvas.pack(fill="both", expand=True)

Frame = tk.Frame(Canvas, height=600, width=1000, bg="#1A1A1A")
Frame.pack(fill="both", expand=True)

large_font = ('Verdana', 17)
entry1 = tk.Entry(Frame, bg="#F7F5EB", font=large_font, width=25)
entry1.place(rely=0.3, relx=0.17)
entry1.configure(foreground="gray")

entry2 = tk.Entry(Frame, bg="#F7F5EB", width=22, font=("Verdana", 11))
entry2.pack(expand=True)
entry2.configure(foreground="gray")

generate_button_font = ('Arial', 12)
Generate_button = tk.Button(
Frame, bg="#f0f0f0", font=generate_button_font, foreground="#525252")
Generate_button.place(rely=0.7, relx=0.35, relwidth=0.31, relheight=0.12)
Generate_button.config(text="Generate")

help_button_font = ("Arial", 10)
help_button = tk.Button(Frame, bg="#F7F5EB", font=help_button_font, foreground="#525252")
help_button.place(rely=0.03, relx=0.88, relwidth=0.1, relheight=0.075)
help_button.config(text="Help")

about_button_font = ("Arial", 10)
about_button = tk.Button(Frame, bg="#F7F5EB", font=help_button_font, foreground="#525252")
about_button.place(rely=0.03, relx=0.02, relwidth=0.1, relheight=0.075)
about_button.config(text="About")

app.mainloop()

A: You can use the .place() geometry manager.
Read more about it here.
Place has 3 main paramaters which I think you need.
The first is relx. This places any widget at a certain position in a widget, relative to the widgets x legnth.
For example, if the relx = 0.5, then no matter how much you resize the widget, the widget stays in the middle.
The second parameter is rely, which works the same as relx, except it applies to the y axis.
The third paramater is anchor. Anchor basically tells the program which part of the widget should go to the specified coordinate. The default is "nw" or top left. You can put it as center, or anything else.
Hopefully this helps!!


text:
Q: Is this iter() redundant for the single line code in cs231n? This is the code for cs231n, I wonder in the return line of the __iter__ function , can we replace return iter((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B)) with return ((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B))? since ((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B)) is also a generator object. Actually I don't quite understand the function of iter() here, does it just call the function __iter__ of a generator object and just return itself? I am confuesd.
class Dataset(object):
def __init__(self, X, y, batch_size, shuffle=False):
    """
    Construct a Dataset object to iterate over data X and labels y

    Inputs:
    - X: Numpy array of data, of any shape
    - y: Numpy array of labels, of any shape but with y.shape[0] == X.shape[0]
    - batch_size: Integer giving number of elements per minibatch
    - shuffle: (optional) Boolean, whether to shuffle the data on each epoch
    """
    assert X.shape[0] == y.shape[0], 'Got different numbers of data and labels'
    self.X, self.y = X, y
    self.batch_size, self.shuffle = batch_size, shuffle

def __iter__(self):
    N, B = self.X.shape[0], self.batch_size
    idxs = np.arange(N)
    if self.shuffle:
        np.random.shuffle(idxs)
    return iter((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B))

train_dset = Dataset(X_train, y_train, batch_size=64, shuffle=True)
val_dset = Dataset(X_val, y_val, batch_size=64, shuffle=False)
test_dset = Dataset(X_test, y_test, batch_size=64)

A: Yes, calling iter is redundant. You can easily check that calling iter on a generator object just returns the generator object itself in a Python shell:
>>> gen = (x for x in [])
>>> gen is iter(gen)
True

More formally, from the Python glossary you can verify that generator expressions return iterators, and that all iterators return themselves when their __iter__ method is invoked:

Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted.


text:
Q: A pile of stones and two players take turns to get them to zero So we have $n$ stones and a set $S$ that has given positive natural numbers. Two players take stones from the $n$ stone pile and the one who takes the last stones wins the game. We need to find an algorithm that will tell us who wins it.
According to Wikipedia it says that the one who has the turn and $(n \text{ mod } (k+1) ) = 0$ holds has the winning strategy (where $k$ is a number from set $S$ if I understood correctly). However on this site https://open.kattis.com/problems/bachetsgame it is said that for some of the inputs where the above would hold, the contrary is the solution.
Can somebody explain where I am missing my understanding about the nim game.
My idea for this problem was that I would use the statement from Wikipedia to loop through the elements in the set $S$, if it would hold for any of them. If it would hold, then I could instantly stop the loop and say that the first player wins, because he has the winning strategy. If it would not hold for any of the elements in the set $S$, then that would mean that the player 2 has the winning strategy. However my thinking looks like it is not correct... (maybe somebody can correct me, where I did make a mistake)


text: Q: Magento 2 : Getting error - "Invalid state change requested" when placing order through my custom payment method I am getting error - "Invalid state change requested" when placing order through my custom payment method on checkout page.


text:
Q: Significance of random letter at the end of sub-query in FROM clause - SQL I have finally succeeded in summing the results of two sql sum queries.  One small step for this guy:)
My question relates to the last character in the code (Z):
SELECT SUM(hr)
FROM   (SELECT SUM(amount) AS hr
        FROM   Try_again.dbo.tuesday_practice_database
        WHERE  account_name LIKE 'concessions'
        UNION
        SELECT SUM(amount) AS hr
        FROM   Try_again.dbo.tuesday_practice_database
        WHERE  account_name LIKE 'salaries')Z

The code won't work unless there is something following the closing parenthesis).
I'm just curious why that is and why does there need to be a character following the ).
It seems that it doesn't matter what the character is, the code will work.  But the code breaks if I leave it blank.
Thank you

A: SELECT sum(hr)
FROM
(
   Select sum(amount) as hr
   from Try_again.dbo.tuesday_practice_database
   where account_name like 'concessions'
   union
   Select sum(amount) as hr
   from Try_again.dbo.tuesday_practice_database
   where account_name like 'salaries'
) z

To understand better, look at the above version of your query. It's the same code, just reformatted to help illustrate what is happening. If you notice, the parent FROM clause retrieves data from a sub-query. In this context, SQL requires the subquery to have a name of some kind, and so the z is added as an alias to meet that requirement. You could put anything you wanted there, but since the name doesn't matter to us a single-letter placeholder is fine.
Just like the following query :
select * from table1 as z

By the way, you didn't use wildcard in your LIKE clause! I think you should re-write the query like below :
select sum(hr) from
(
   Select sum(amount) as hr from Try_again.dbo.tuesday_practice_database
   where account_name like '%concessions&'
   union all
   Select sum(amount) as hr from Try_again.dbo.tuesday_practice_database
   where account_name like '%salaries%'
) AS z

If you don't want to use wildcard, then you should avoid using LIKE Use IN instead and re-write to this simple one :
Select sum(amount) from Try_again.dbo.tuesday_practice_database
where account_name in('concessions', 'salaries')

A: Just do this:
SELECT SUM(amount) as hr
FROM Try_again.dbo.tuesday_practice_database
WHERE account_name IN ('concessions', 'salaries')

The existing code has a bug, where it will consolidate your two SUM()s if they are both the same amount. You could also fix this with UNION ALL instead of just UNION, but since the LIKE conditions don't have any placeholders like % or _ we can do better and simplify this whole thing down to just one IN() condition, with no need for any subqueries.
Now, if you wanted to allow more variance in your matches ( ie LIKE '%concessions%' and LIKE '%salaries%'), then the UNION ALL is more helpful... just be warned that leading % placeholders in a LIKE condition are very bad for performance, and should be avoided when possible. Often this means changing the schema in some way, such as adding a table named something like AccountCategories that group each account into a specific category that you can target exactly in your query.
But all of that side-steps the actual question: what is that z character?
In this case, it's an alias. You're using a subquery to union the two smaller queries together. In certain contexts, the SQL language requires subqueries to have a name. This includes using the subquery (derived table) as the target of a FROM, JOIN, or APPLY expression. You can use any name you want — it doesn't matter to the functioning of the query, since it's never referenced again — and so a simple single-letter placeholder, like z, is good enough.


text:
Q: ASP.NET MVC viewmodel SQL query syntax I'm trying to convert basic models to model vİew and SQL queries. So what is wrong my queries or other files?
// GET: Cars
public ActionResult Index()
{
    List<CarsTrxViewModel> model = db.Database.SqlQuery<CarsTrxViewModel>(SqlCars.CarsTrxByID()).ToList();

    return View(model);
    // return View(db.Cars.ToList());
}

View model:
public class CarsTrxViewModel
{
    public int CarID { get; set; }
    public string CarBrand { get; set; }
    public string CarModel { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}")]
    public DateTime CreateDate { get; set; }
}

Query:
public static class SqlCars
{
    public static string CarsTrxByID()
    {
        return "select " + " * , " +
             "cars.CarID as CarID " +
            ",cars.CarBrand as CarBrand " +
            ",cars.CarModel as CarModel " +
            ",cars.CreateDate as CreateDate " +
            "from (SELECT * from [NagisOfflineDB].[dbo].[cars] )";
    }

    public static string GetCardholderByID()
    {
        return "SELECT TOP 1 * from [NagisOfflineDB].[dbo].[cars]";
    }
}

Model:
public class Cars
{
    [Key]
    public int CarID { get; set; }

    [StringLength(50)]
    [Required]
    public string CarBrand { get; set; }

    [StringLength(250)]
    [Required]
    public string CarModel { get; set; }

    public DateTime CreateDate { get; set; }
}

I'm not join or other operations I'm just select one column in one table and set alias rows so what is wrong my query?

Compiler say your query wrong its error System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'

Full version of error

Server Error in '/' Application.
  Incorrect syntax near ')'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ')'.
Source Error:
Line 20:
  Line 21:
  Line 22:             List model = db.Database.SqlQuery(SqlCars.CarsTrxByID()).ToList();

And the stack trace

[SqlException (0x80131904): Incorrect syntax near ')'.]
  System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2552942
  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5952492
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
     System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
     System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
     System.Data.SqlClient.SqlDataReader.get_MetaData() +89
     System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) +430
     System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2598
     System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +1483
     System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
     System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
     System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
     System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
     System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +14
     System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
     System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
     System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
     System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
     System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +266
     System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__68() +44
     System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
     System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__67() +167
     System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +190
     System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +462
     System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery(String commandText, ExecutionOptions executionOptions, Object[] parameters) +60
     System.Data.Entity.Internal.<>c__DisplayClass141.<ExecuteSqlQuery>b__13() +130
     System.Data.Entity.Internal.LazyEnumerator1.MoveNext() +45
     System.Collections.Generic.List1..ctor(IEnumerable1 collection) +387
     System.Linq.Enumerable.ToList(IEnumerable1 source) +58
     NgsOfflineDev.Controllers.CarsController.Index() in C:\Dev\NagisDevOffline\NgsOfflineDev\NgsOfflineDev\Controllers\CarsController.cs:22
     lambda_method(Closure , ControllerBase , Object[] ) +61
     System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
     System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
     System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
     System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
     System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
     System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +58
     System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
     System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
     System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
     System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +35
     System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100
     System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
     System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
     System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
     System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
     System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
     System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
     System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
     System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
     System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
     System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
     System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
     System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
     System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
     System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9874329
     System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
     System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

Version Information:

*

*Microsoft .NET Framework Version: 4.0.30319

*ASP.NET Version: 4.7.3062.0


text:
Q: How do you correct a corrupted index in Oracle? I have this ORA error in our logs:
Caused by: java.sql.BatchUpdateException: ORA-01578: ORACLE data block corrupted (file # 8, block # 22921) ORA-01110: data file 8: '/data/app/oracle/oradata/MYSRVR/datafile/o1_mf_mysrvr_88m82mdj.dbf'
I tried running this in sqlplus:
select segment_name,segment_type,tablespace_name, owner from sys.dba_extents where file_id=8 and 22921 between block_id and block_id + blocks -1;
output is:
SEGMENT_NAME             SEGMENT_TYPE   TABLESPACE_NAME     OWNER
-----------------------    ------------     ----------------    ---------------
PK_ZXCATSET_CATID      INDEX            MYSRVR_IDX_TB    MYSRVR

Now I am stuck on which index is that actual segment name. (I think :/ ) I tried doing this to rebuild that index:
SQL> alter index PK_ZXCATSET_CATID rebuild tablespace MYSRVR_IDX_TB;

*

*ERROR at line 1: ORA-01418: specified index does not exist

Even though if I do "select index_name from dba_indexes", that index name shows up. What am I doing wrong? This is a 10.2 Oracle server.
Thanks in advance!
EDIT If I do MYSRVR.PK_ZXCATSET_CATID  the alter completes... but I still don't think my problem is fixed!

A: Seems like you have media corruption. I would consult Automatic Diagnostic Repository (ADR) contents if there are open failures in your database. You can do that via Enterprise Manager or using RMAN command-line utility:

[oracle@oca ~]$ rman target=/

RMAN> list faliure;

If there are failures with status OPEN listed, you can ask Data Recovery Advisor (DRA) to analyze them and recommend you the solution to repair the failures:
RMAN> advise failure;

Since you have block corruption, DRA will probably suggest you to recover the corrupted blocks and will create the appropriate script which you can run manually or in the same flow with RMAN:
RMAN> repair failure;

After failures are repaired they're automatically closed by DRA. You can check if all failures are closed with one more list failure command in RMAN, and if not you can get another advice from DRA.
EDIT:
Since the recovery you performed didn't last long (elapsed time: 00:00:00), I infer that the datafile wasn't written to by RMAN, and maybe even checked. Thus I would recommend you to proactively validate the database; to do that, just issue validate database in RMAN and analyze the output. RMAN will check all datafiles (including control file and spfile) and show you if there are any corrupted blocks.
In your comment, you said that RMAN returns the message "Block Media Recovery requires Enterprise Edition" in response to one of your commands, and based on the response from RMAN to validate database command I suspect this feature is also not available in your software edition. If your database is running in ARCHIVELOG mode (check with select log_mode from v$database) you could just completely restore and recover your database without loss of committed transaction, but before doing this I would make sure that your media (hard disk) is not damaged.

A: Ok, the "RMAN> list failure;" thing didn't work, but it did lead me in the right direction.  To get things going again I did this:
$  rman target sys/myuser@mytargetsrvr

RMAN> recover datafile 8

// Which gave this
ORA-00283: recovery session canceled due to errors
ORA-01124: cannot recover data file 8 - file is in use or recovery

// instead I did this first
RMAN> sql 'alter tablespace MYSRVR_IDX_TB offline';

sql statement: alter tablespace MYSRVR_IDX_TB offline

RMAN> recover datafile 8;

Starting recover at 25-APR-13
using channel ORA_DISK_1

starting media recovery
media recovery complete, elapsed time: 00:00:00

Finished recover at 25-APR-13

RMAN> sql 'alter tablespace  MYSRVR_IDX_TB online';

sql statement: alter tablespace  MYSRVR_IDX_TB online

Big thanks to Yasir Arsanukaev!

A: alter index "MYSRVR"."PK_ZXCATSET_CATID" rebuild tablespace MYSRVR_IDX_TB;
or alter index MYSRVR.PK_ZXCATSET_CATID rebuild tablespace MYSRVR_IDX_TB;


text:
Q: Lock chrome extensions Is it possible to lock extensions on chrome (make them inaccessible) preferably on registry or on the computer level. I want to use some productivity tools but they are so easy to bypass i know you can prevent uninstallation in the windows registry, but is it possible to prevent accessing them? Thanks in advance

A: Depending on what you mean by "lock" the extensions, this can mostly be done using file system permissions / ACLs. Each extension installs into a known location on the file system, based on the extension's unique ID.
You can block specific extensions from being installed by creating the subdirectories they would install into, and then denying users the rights to delete those subdirectories or to write files into them. If you instead want to block most (or all) extensions, you can edit the permissions of the parent directory (the location where extension subdirectories get created) to disallow the user creating or editing subdirectories within it, and then either leave it as is (blocking all extension installation) or use elevated privileges to install specific extensions. Users would still be able to turn extensions on and off (unless you block writes to the location where that's configured), but they wouldn't be able to install arbitrary ones.
However, there's a lot of caveats here. First of all, this obviously doesn't work if your users have access to admin/root privileges, otherwise they can just override the ACLs. Second, Chrome is (mostly) open source and can be installed and run without needing admin privileges; a user could easily install a modified version (and it wouldn't take much effort for a programmer to produce one) that uses a different extension directory. Indeed, there's already a "portable" build of Chrome that is designed to run from a flashdrive, but can be run from anywhere, and has its own extensions directory. Third, most Chrome extensions are also available as Firefox and/or Edge extensions - they all use near-identical extension models and APIs - so you'd have to do this for all browsers if you wanted to be sure.
Frankly, trying to lock down systems so that users can't run stuff they want to is a very difficult process, especially if keep the machine useful in general and don't want to create an enormous IT maintenance burden. This has been known to parents and school officials for decades, and determined adults are far more capable than the school-age children that people have been trying to restrict for decades.


text:
Q: Atomic superhero cartoon pilot from early 1990s This has been driving me crazy all day, yet I am embarrassed to ask it.
I am trying to remember the name of a kids' animated cartoon I watched obsessively, produced around 1992+-2 years, for the US market.  I believe my copy of it came on a promotional VHS from Burger King.
It involved a group of superheroes who gained their powers from some sort of atomic science project.  I believe "city" was in the name - "heroes of mega city", or "atomic city heroes". Something like that.
One of the main male heroes was a cyborg who rode around on a buzzsaw-like wheel instead of legs, I think.  He may have been blue or silver.
I believe this was a pilot episode of a series, as I never saw another episode.

A: I knew this would happen - posting the question jogged my memory almost immediately.  The cartoon is 1992's "Defenders of Dynatron City".
The cyborg mentioned above is actually a misremembered version of the character Buzzsaw Girl - a humanoid who moves around on a buzzsaw-like monowheel lower body.


text:
Q: Creating a search bar that filters through nested details tag I am trying to create a search bar that filters through nested details tag elements.
I have a nested details tag like this:

    SD

            172.17.42.26

3033343857383498

3038373857383498

3647595959343498

374d343857383498

4253595959343498

4758343857383498

5139343857383498

5837553546353498

              172.17.42.24
5336594e58343498

56344f4330393498

5a4a444133393498

      HinduKush

          172.17.42.25

48314b4e58343498

4f32353857383498

4f58585959343498

56365a5959343498

I have a class name search for every Item I need to search. But, how do I loop through every tag and child nodes to filter? I need a search bar that autocompletes.

A: Are you trying to control the display of the child nodes depending on a search value?
Hope this will be helpful.

const searchbar = document.getElementById('search-bar');
searchbar.addEventListener('keyup', (event) => {
  const searchKey = event.target.value;
  const nodes = document.querySelectorAll('.search');
  nodes.forEach(node => {
    node.style.display = (node.textContent.indexOf(searchKey) > -1) ? 'block' : 'none';
  })
})
<input type="text" id="search-bar" placeholder="Enter the search key" />

    SD

        172.17.42.26

3033343857383498

3038373857383498

3647595959343498

374d343857383498

4253595959343498

4758343857383498

5139343857383498

5837553546353498

        172.17.42.24

5336594e58343498

56344f4330393498

5a4a444133393498

    HinduKush

        172.17.42.25

48314b4e58343498

4f32353857383498

4f58585959343498

56365a5959343498

A: I don't know exactly what your question is, but if you want to get every element you can do that in JS via the document.getElementsByClassName method. This would be an example use:

classes = document.getElementsByClassName("search");

for (let i = 0; i < classes.length; i++){
  document.getElementById("search-result").innerHTML += classes[i].innerText +"
"
}

    SD

            172.17.42.26

3033343857383498

3038373857383498

3647595959343498

374d343857383498

4253595959343498

4758343857383498

5139343857383498

5837553546353498

              172.17.42.24
5336594e58343498

56344f4330393498

5a4a444133393498

      HinduKush

          172.17.42.25

48314b4e58343498

4f32353857383498

4f58585959343498

56365a5959343498

This is how you would get all the elements you mentioned.


text:
Q: Calling viewDidLoad on a View Controller presented Modally I've noticed by viewDidLoad method is never called when I present a view controller modally.
I.E:
InfoViewController *v = [[Global get] infoVC];
[self presentModalViewController: v animated: true];

Is there anyway I can get it to call this?
I've put my viewDidLoad code in ViewDidAppear, I'm worried those items will be drawn twice in the view? If it's opened twice? Or does it get removed from memory?

A: viewDidLoad will only get called when the controller is created. So if your:
[[Global get] infoVC]
is not allocating and returning the controller (returning an already created controller) viewDidLoad will not be called.
In viewDidAppear it is safe to adjust the views related to your controller. If you created them in viewDidLoad they will already exist.
Or if you want viewDidLoad called create a new controller.
infoViewController *v = [[InfoViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController: v animated: true];
[v release];

A: If you are just adding items to your view in viewDidLoad, you could put that code in loadView instead.


text:
Q: Printing where the last inserted array position I would like to print an array where it states where the "placedPosition", or the parameter's location in the array. This position is the location that the latest number was inserted into the sorted part of the array.It is the same for the "currPosition", but I can figure that out if I get help on the placed. "i" is the placedPosition, and "c" is the "currPosition". It should look something like this:

I'm really not sure how to go about this, here is the code I have thus far:
public static void displaySort(int[] items, int currPosition, int placedPosition) {
    System.out.println("Iteration #"+currPosition);
    String[][] arr = new String[currPosition][currPosition];
    String i="i";
    String c="c";
    String ic="ic";
    System.out.println(arr[placedPosition][placedPosition]=i);
    System.out.println(arr[currPosition][currPosition]=c);
    System.out.println(Arrays.toString(items));
}

Sorting:
public static void insertionSort(int[] items) {
    int currentPosition;  // the number of items sorted so far
    int currentItem;   // the value being inserted
    int backwardMovingIndex; // used to find where the current value gets inserted.

    //displaySort(items, 0, 0); // use this call to display the list before the first iteration (iteration 0)

    for (currentPosition = 1; currentPosition < items.length; currentPosition++) // Start with 1 (not 0)
    {
        currentItem = items[currentPosition];
        for (backwardMovingIndex = currentPosition - 1; (backwardMovingIndex >= 0) && (items[backwardMovingIndex] > currentItem); backwardMovingIndex--) // Larger values are moving up
        {
            items[backwardMovingIndex + 1] = items[backwardMovingIndex];
        }
        items[backwardMovingIndex + 1] = currentItem;    // Put the current value in its proper location
        displaySort(items, currentPosition, backwardMovingIndex + 1); // use this call to display the list for all other iterations
    }
}

A: For starters, you need to make sure the numbers are printed out with a fixed number of digits, so instead of System.out.println(Arrays.toString(items)); try using code like
    for (int item : items) {
        System.out.printf("%5d", item);
    }
    System.out.println();

To place a an "i" in column i use code like
    int i = 1;
    for (int x = 0; x<items.length; x++) {
        if (x == i) {
            System.out.printf("%5s", "i");
        }
        else {
            System.out.printf("%5s", "");
        }
    }
    System.out.println();

The key is using the same value (in this example, 5) for the format specifier controlling the column width in all branches of the loop. If these are arbitrary integers, you might need to use a larger value, such as 10. If you want to get fancy, you can figure out how wide you need to make the columns by looking at the base 10 logrithm of the largest absoulte value in the array. You can then convert an integer into a string of exactly n characters with something like
String.format("%"+n+"d", item)
To complete your problem add more branches to the if/else structure to check for
 (x == c) and (i == c) && (x == i)


text:
Q: Can we find uncountably many disjoint dense measurable uncountable subsets of $[0,1]$? Can we find uncountably many disjoint dense measurable uncountable subsets of $[0,1]$? Obviously we may as well assume all the subsets have measure $0$. If I didn't specify the subsets were uncountable, we could easily find uncountably many dense disjoint measurable subsets $X_\alpha$ (all countable) by taking a Hamel basis $H$ of $\mathbb{R}$ as a vector space over $\mathbb{Q}$, where $H$ contains a non-zero rational number, and then set $X_\alpha = (\mathbb{Q} + \alpha) \cap [0,1]$ for every $\alpha \in H$.
But what about if we want uncountable measurable dense subsets? I think it should still be that there are uncountably many that can be found that are disjoint, according to my intuition, but I don't know an "easy" way to show it like I can in the case of countable dense subsets.

A: Sure.
Let $f:[0, 1] \to [0, 1]$ be such that $$f(0. b_1 b_2 b_3\ldots) = \liminf_{N\to \infty} \frac{1}{N}\sum_{n=1}^N b_n$$ where $\{b_n\}$ is the usual binary representation of a number in that interval. We have that $f$ is well defined, measurable and integrable and the Birkhoff ergodic theorem implies that $\lambda(f^{-1}(1/2)) = 1$. For all other values $t\in [0, 1]$, $A_t = f^{-1}(t)$ has measure $0$.
Furthermore $A_s\cap A_t =\emptyset$ for $s\neq t$, and for any $N$ and $0\leq n < 2^N$, $A_t \cap [\frac{n}{2^N}, \frac{n+1}{2^N}] \neq \emptyset$ (the initial part of the expansion doesn't really matter, so $A_t$ has elements in every interval), and so is dense in $[0, 1]$ for all $t$.
The collection $\{A_t\}_{t\in[0, 1] \setminus 1/2}$ is what you were looking for.

I just read your comment to the other answer. I'm not sure that the sets I have here are Borel. Let me think about that for a bit.

As mentioned in the comments, we have the $\liminf$ of Borel functions so we have a Borel function and it's preimages of singletons are therefore also Borel. I'm satisfied that this is all correct, but I don't have a specific reference, sorry.
Regarding uncountability, there are at least two arguments that come to mind. The first, which I had in mind as I wrote, relates to a class of measures on $\prod_{n\in \mathbb{N}} \{0, 1\}$, namely those measures that correspond to an infinite product of the measure where $\mu(\{0\}) = 1-t$ and $\mu(\{1\}) = t$. This is a non-atomic (for $t\neq 0\text{ or }1$) standard probability space, and so a set with measure $1$, which $A_t$ corresponds after a natural map, must be uncountable. (I really like this argument because it highlights that having measure $1$ is more about conforming to the expectations of a measure than being large).
More directly, assume that we have $A_t = \{a_1, a_2, a_3, \dots\}.$ For some $t$, and that $a_i = 0. b_{i, 1} b_{i, 2} b_{i, 3}\ldots$ where this is the usual binary representation of $a_i$. Using a standard diagonalisation argument would be problematic as we would lose control of the assymptotic density of $1$s in its representation. However, if we form the number $a$ which is such that $a= 0.b_1 b_2 b_3\ldots$ where $$b_i = \begin{cases} 1-b_{n,n^2} &\text{if } i = n^2 \text{ for some } n\in\mathbb{N} \\
b_{1, i}& \text{otherwise.} \end{cases}$$ then I claim that $f(a) = f(a_1)$ as the assymptotic density of the squares is $0$, so $a\in A_t$ but $a\neq a_n$ for all $n$ as their binary representations differ at the $n^2$ place. So $A_t$'s elements cannot be listed and $A_t$ is uncountable.

A: The following, which is related to the answer user24142 gave, is taken from this 21 January 2003 sci.math post:
[. . .] here's a collection of $c$-many pairwise disjoint sets with cardinality $c$ in every open interval. In fact, each of these sets will have a positive Hausdorff dimension intersection with every open interval and they are not very complicated from a descriptive set theoretic point of view (they're all $F_{\sigma \delta}$ sets, I believe), and thus are very low in the Borel hierarchy of sets.
For each real number $r$ between $0$ and $1$ (inclusive), let $P_r$ be the set of irrational numbers whose decimal expansions have $r$ for their limiting proportion of $5$'s. That is, if $N(x,5,n)$ is the number of appearances of the digit $5$ to the right of the decimal point in the first $n$ digits of the decimal expansion of the real number $x,$ then $P_r$ is the set of real numbers $x$ such that $\lim_\limits{n \to \infty}{N(x,5,n)}$ exists and is equal to $r.$
Then it is known that each $P_r$ is a Borel set (in fact, $F_{\sigma \delta}$ I think) with positive Hausdorff dimension in every open interval (see these sci.math posts: 16 June 2001 and 19 February 2003), which is quite a bit more than simply saying that each open interval has $c$-many numbers belonging to each of the $P_r$ sets.
On the other hand, these sets are small in a couple of other ways. All of them except for $P_{\frac{1}{10}}$ have measure zero, and all of them, including $P_{\frac{1}{10}},$ are first (Baire) category sets. Incidentally, the union of all the $P_r$ sets doesn't include all the real numbers. If you let $Q$ be the remaining real numbers, then $Q$ is a measure zero set with a first category complement. Hence, $Q$ is co-meager in every open interval, and so it too will have $c$-many elements in every open interval.

A: It's enough to do this for $\mathbb R,$ since $(0,1)$ and $\mathbb R$ are homeomorphic. Let $c$ denote the cardinality of $\mathbb R.$
Claim: There are $c$ many disjoint countable dense subsets of $\mathbb R.$
Proof: Let $K$ be the classical Cantor set. By "a Cantor set" I'll mean any set of the form $a+bK,$ where $a\in \mathbb R$ and $b>0.$
Let $I_1,I_2,\dots$ be the open intervals with rational end points. Then we can inductively choose disjoint Cantor sets $K_n\subset I_n$ for $n=1,2,\dots.$ (This is  pretty straightforward. I'll leave it for now; ask questions if you like.)
For each $n,$ write $K_n = a_n + b_nK,$ and let  $f_n: K \to K_n$ be the map $t\to a_n +b_nt.$ For $t\in K,$ define the sets $D_t = \{f_n(t): n=1,2,\dots \}.$ Then the sets $D_t$ are disjoint. Each $D_t$ is dense in $\mathbb R,$ simply because $D_t$ contains a point in each of the intervals $I_n.$ Because $K$ has cardinality $c,$ the claim follows.
To prove the full result, observe that there is a continuous surjective map $g:K\to [0,1]\times [0,1].$ (For example $g =P\circ C,$ where $P$ is the Peano space filling curve, and $C$ is the Cantor function.) For $t\in K,$ let $K_t = \{t\} \times [0,1].$ Then $\{ g^{-1}(K_t): t \in K\}$ is a disjoint collection of $c$ many sets, each of which is compact and of cardinality $c.$
Finally, consider the sets $D_t\cap (\mathbb R\setminus K) \cup g^{-1}(K_t)$ for $t\in K.$ These sets are disjoint, and each such set is dense in $\mathbb R$ and has cardinality $c.$ Since there are $c$ many such sets, we're done.

A: I found a construction based on this idea.
We need the following lemma:
If $M$ is an uncountable set, then there is an uncountable family of pairwise disjoint uncountable subsets of $M$.
To prove this assertion, observe that $|M \times M| = |M|$ and let $f$ be a bijection between the two sets. The family $\{f(\{x\} \times M) \;|\; x \in M\}$ satisfies the conditions of our lemma.
Now we only apply this lemma to the Cantor set to get an uncountable family of disjoint uncountable subsets. Since the Cantor set is a nullset, every subset is a nullset and therefore Lebesgue-measurable. Now we only need to join every set with one of the sets $X_\alpha$ from the starting post to get an uncountable family of uncountable disjoint dense subsets of $[0, 1]$.
Edit: I think the sets can be chosen Borel with the help of Zorn's Lemma, but I can't quite finish the proof. Let $B$ be the set of all uncountable Borel-nullsets and define
$$S = \{M \in \mathcal{P}(B) \;|\; \text{the sets in $M$ are pairwise disjoint}\}.$$
$S$ is obviously nonempty and we can define a partial order on $S$ via inclusion. Now every chain in S has an upper bound, namely the union of all elements in the chain. Therefore by Zorn's lemma there is a maximal element $T \in S$. We are done if we can prove that $T$ is uncountable.
Let's assume that $T$ is countable and that $N$ is the union of all sets in $T$. Then $N$ is Borel-measurable and a nullset. We now only need to prove that there is an uncountable Borel-nullset in $[0, 1] \setminus N$, but I can't find an argument to prove this assertion.


text:
Q: Using cosine similarity for classifying documents I have a set of files for five different categories and most of them are not labelled correctly.Objective is to predict the correct category of the file whenever the same is uploaded.I used cosine similarity along with tf -idf to predict the class of the document with which cosine similarity is the maximum as of now i am getting good results but really not sure how well this will work down the road. Also why isnt cosine similarity used in building document classifiers instead of machine learning models when the categories of files are labelled correctly?Would really appreciate your feedback on my approach as well as your answer to the question.

A: Cosine similarity is used for calculating the angle between two n-dimensional vectors. These vectors are mostly produced by Embeddings. They are pretrained models which produce word embeddings or fixed size vectors.

Cosine similarity is mostly used with vectors produced by word
  embeddings. If you are using something like Doc2Vec, then you get a
  vector for the whole document. These vectors could be categorized by
  using cosine similarity.

In your case, you should try a LSTM text classifier using Embedding layers. 1D Convolution layers can also be useful.
Also, referring to TF-IDF, it is useful for text classification which is dependent on certain words in the corpus. The words with higher term frequency and less document frequency have a higher TF-IDF score. The model learns to classify texts based on such scores.

In most cases, RNNs are the best to classify texts. The use of pretrained embeddings makes the model efficient.

Also, not the least, you can give Bayes text classification a try. It has been super useful in spam classification.
Tip:
You can implement the above methods with each other, creating a text classification system. Following the process like,

*

*Generate embeddings from Doc2Vec.

*Comparing the similarity of the input with other texts and thereby determine its class.

*Using the embedding in a  LSTM network to produce class probabilities.

*Apply Bayes text classification.

The steps 2 , 3 , 4 give three predictions. If the majority prediction was CLASS1, then we can make the output of the system as CLASS1!.


text:
Q: Java HashMap containsKey I have the following code
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Person {
  private String name;
  private long birthTime;

  @Override
  public int hashCode() {
    return Objects.hash(name, birthTime);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof Person)) {
      return false;
    }
    Person other = (Person) obj;
    return Objects.equals(name, other.name)
        && birthTime == other.birthTime;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public long getBirthTime() {
    return birthTime;
  }

  public void setBirthTime(long birthTime) {
    this.birthTime = birthTime;
  }

  public static Person person(String name, long time) {
    Person p = new Person();
    p.setName(name);
    p.setBirthTime(time);
    return p;
  }

  public static void main(String[] args) {
    Map<Person, Person> map = new HashMap<>();
    Person p = person("alice", 3);
    System.out.println("1. " + map.containsKey(p));

    map.put(p, p);
    System.out.println("2. " + map.containsKey(p));

    p.setName("charlie");
    System.out.println("3. " + map.containsKey(p));

    Person p2 = person("alice", 3);
    System.out.println("4. " + map.containsKey(p2));

    Person p3 = person("charlie", 3);
    System.out.println("5. " + map.containsKey(p3));
  }
}

I am expecting the output to be false, true, true, false and true.
However, the output is false, true, false, false, false.
I am looking for how the output is false for the 3rd and 5th case. What is the behavior of HashMap containsKey?
Why is the output false even though the Key object is there in the Map. The equals and hashcode methods are both overridden for the Person class.

A: The following statement breaks your Map:
p.setName("charlie");

It causes the key referenced by the variable p to no longer be positioned in the bin that matches its hashCode(), since you are changing its hashCode().
You should never change the state of a key that is already in the Map if that change affects the result of hashCode() or equals().
p.setName("charlie");
System.out.println("3. " + map.containsKey(p));

Returns false since a Person instance whose name is "charlie" is not mapped to the same bin as a Person instance whose name is "alice". Therefore containsKey() searches for p in the bin matching the name "charlie", and doesn't find it there.
Person p2 = person("alice", 3);
System.out.println("4. " + map.containsKey(p2));

Returns false since p2 is not equal to p (they have different names).
Person p3 = person("charlie", 3);
System.out.println("5. " + map.containsKey(p3));

Returns false since the key p is located in the bin that matches the name "alice", even though its current name is "charlie", so containsKey() searches for it in the wrong bin, and doesn't find it.

A: You're modifying the object after adding it as a key in the HashMap, in a way that changes the hash code. That's like giving someone your contact details, moving house, and then still expecting them to be able to find you.
When you add a key to the map, it stores the hash code. When you try to find a key, the map asks for the hash code of the key you're trying to find, and efficiently finds any entries with the same stored hash code. As the "new" hash code doesn't match the "old" hash code, it can't find any candidates to check with equals.
Basically, you shouldn't modify anything that affects the hash code or equality after using the object as a key in the map.

A: To put more information about Eran answer. I have checked some the source of HashMap.
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    ...
        tab[i] = newNode(hash, key, value, null);
    ...
}

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

In you 3rd case, the hash value of the key in "node" stay the same even you changed its' name to "Charlie". That's why it return false. It seems that you should NEVER change the object key given the fact that it would break the map for the mismatch of hash(key)


text:
Q: Change Language of Facebook "Send Request" button I integrate the facebook in my website which is in Danish Language, and I want to send facebook request to friends from account. Then the button after selecting friends and then pressing continue says: Send request, How to change language of button "Send Request"

A: I think it's not possible to do so. The language would depend on the user's choice, not yours. So the button should be in his chosen language.


text:
Q: How to handle a long if statement to read input that has many common parts? I am writing a simple Java program that interacts a lot with the user (through command line).
Consider that there is a unique code in order to do each possible action. However, each action requires further input. The problem is that many different actions require similar input. Therefore, I end up with something like this:
int input = scanner.nextInt();
String commonInputA, commonInputB, commonInputC, commonInputD;
if (input == 1) {
    //receive required input for action 1
    commonInputA = scanner.next();
    commonInputB = scanner.next();
} else if (input == 2) {
    //receive required input for action 2
    commonInputB = scanner.next();
    commonInputD = scanner.next();
} else if (input == 3) {
    //receive required input for action 3
    commonInputA = scanner.next();
    commonInputC = scanner.next();
} else if (input == 4) {
    //receive required input for action 4
    commonInputA = scanner.next();
    commonInputB = scanner.next();
    commonInputC = scanner.next();
    commonInputD = scanner.next();
} else if (input == 5) {
    //no extra input required to perform action 5
}

Of course, those commonInputs are used as constructor parameters to initialise objects. Is there a way to write the above input receiver in a cleaner way?

A: You can try something like below
int input = scanner.nextInt();
String commonInputA, commonInputB, commonInputC, commonInputD;

if(input!=2)
commonInputA = scanner.next();
if(input!=3)
commonInputB = scanner.next();
if(input!=1&&input!=2)
commonInputC = scanner.next();

if (input == 1) {
//perform input 1 action
}
else if (input == 2) {
    commonInputD = scanner.next();
} else if (input == 3) {
//perform input 3 action

} else if (input == 4) {
    commonInputD = scanner.next();
}

A: One of the way to accept common input.
import java.util.Arrays;
import java.util.Scanner;

public class SimpleClass {

    public static void main(String[] args) {
        Scanner scanner      = new Scanner(System.in);
        int[][] map          = {{0, 1}, {1, 3}, {0, 2}, {0, 1, 2, 3}, {}};
        int input            = scanner.nextInt();
        String[] commonInput = readCommonInput(input, map, scanner);

        System.out.println(Arrays.toString(commonInput));

        //Calling your constructor
        //commonInputA is stored at commonInput[0]
        //commonInputB is stored at commonInput[1]
        //commonInputC is stored at commonInput[2]
        //commonInputD is stored at commonInput[3]
        //CommonInputProcessor p = new CommonInputProcessor(commonInput[0], commonInput[1], commonInput[2], commonInput[3]);
    }

    public static String[] readCommonInput(int input, int[][] map, Scanner scanner)
    {
        String[] commonInput = new String[4];

        for(int i : map[input - 1])
        {
            commonInput[i] = scanner.next();
        }

        return commonInput;
    }
}


text:
Q: Why angularjs value do not change in app.run method I created some value named information and tried to edit it.
How ever it is not effect in controller.
Then, example in below not working.

(function () {
    var app = angular.module('app', []);

    app.value('information', []);

    app.run(['information', function (information) {
        information = [1, 2, 3, 4];
    }]);

    app.controller('myController', [
    '$scope', 'information', function ($scope, information) {
        $scope.inf = information;
    }]);
})();
<!DOCTYPE html>

    <title></title>
 <meta charset="utf-8" />

            {{ i }}

A: Because when you inject information, it is a reference to the information object which is stored in Angular cache.
I do not recommend to modify the value from the controllers (although you can: JSFiddle).
You'd better use factory:
app.factory('information', function () {
    var info = [];
    return {
        get: function () {
            return info;
        },
        set: function (newInfo) {
            info = newInfo;
        }
    };
});

And inside your controller, use information.get() and information.set() to do the trick.

A: You can use
Angular
(function () {
    var app = angular.module('app', []);

    app.value('information', []);

    app.run(['information', function (information) {
        information.push(1,2,3,4); //use this
    }]);

    app.controller('myController', [
    '$scope', 'information', function ($scope, information) {
        $scope.inf = information;
    }]);
})();

Refer plunker


text:
Q: Does MLE exist for an uniform distribution on an open interval? I am wondering if the Maximum Likelihood Estimate exists for a uniform distribution on $[0, \theta)$ (open interval on $\theta$). Choosing $\theta_{MLE}$ as $max\{\bar x\}$ would mean that the $\Pr(\bar x|\theta_{MLE}) = 0$, which obviously isn't the maximum of $\Pr(\bar{x})$.
I found many websites loosely interchanging the open and closed interval during the solution itself so I am not sure if people tend to give any attention to this.


text:
Q: updating text position on pie chart update I've been trying to adapt this design into a dynamic pie chart.
Everything has gone reasonably well aside from getting the text to reposition on update.
In the example below, I am first removing the text label and then redrawing, I don't think this is the best way to do it, I was trying to approach it with the code that is commented out just underneath but have been unsuccessful.
Plunk
Offending code;
function updatePath() {

    g = svg.datum(donutData).selectAll(".arc")
      .data(pie)
    g.select("path")
      .transition()
      .duration(750)
      .attrTween("d", arcTween) // redraw the arcs

    svg.selectAll(".donutText").remove()

    pieTextLabel()

}

// Attempt 1 Below

    /*

        svg.selectAll(".donutText")
        .style("opacity", 0)
          .attr("dy", 18)
          .append("textPath")
          .attr("startOffset", "50%")
          .style("text-anchor", "middle")
          .attr("xlink:href", function(d, i) {
            return "#donutArc" + i;
          })
          .text(function(d) {
            return d.value;
          })
          .transition()
          .duration(1000)
          .style("opacity", 1);

      */

  function pieTextLabel() {
    var selectText = svg.selectAll(".donutText")
      .data(donutData)

    selectText
      .enter().append("text")
      .attr("class", "donutText")
      .attr("dy", 18)
      .append("textPath")
      .attr("startOffset", "50%")
      .style("text-anchor", "middle")
      .attr("xlink:href", function(d, i) {
        return "#donutArc" + i;
      })
      .text(function(d) {
        return d.value;
      });

    selectText.exit().remove()

  }

  function drawPie() {
    var g = svg.selectAll(".donutArcSlices")
      .data(pie(donutData))
      .enter().append("g")
      .attr("class", "arc");

    var path = g.append("path")
      .attr("d", arc)
      .style("fill", function(d) {
        return color(d.data.label);
      })
      .each(function(d, i) {
        this._current = d;

        var firstArcSection = /(^.+?)L/;
        var newArc = firstArcSection.exec(d3.select(this).attr("d"))[1];
        newArc = newArc.replace(/,/g, " ");

        svg.append("path")
          .attr("class", "hiddenDonutArcs")
          .attr("id", "donutArc" + i)
          .attr("d", newArc)
          .style("fill", "none");
      })

  }

Having trouble cracking this - any help/advice is much appreciated!
Thanks

A: It's because you didn't update the path
First delete the old path
svg.selectAll("path").remove()

Then recreate it
var path = g.append("path")
  .attr("d", arc)
  .style("fill", function(d) {
    return color(d.data.label);
  })
  .each(function(d, i) {
    this._current = d;

    var firstArcSection = /(^.+?)L/;
    var newArc = firstArcSection.exec(d3.select(this).attr("d"))[1];
    newArc = newArc.replace(/,/g, " ");

    svg.append("path")
      .attr("class", "hiddenDonutArcs")
      .attr("id", "donutArc" + i)
      .attr("d", newArc)
      .style("fill", "none");
  })

see http://plnkr.co/edit/WTuX38GCgIFLFfc1QPVv?p=preview


text:
Q: PHP: DOMNode::appendChild to an array of Elements I am using DOMDocument to parse an XML file. I loop through the different Elements and see if any of them is missing and I fill an array with a createElement, with the error message. At the end I'm trying to appendChild that array but I always get the same error message:
Uncaught exception 'DOMException' with message 'Wrong Document Error'
DOMNode->appendChild(Object(DOMElement))
1 {main}
thrown in /xxx/xxx.php on line 235
PHP Fatal error: Call to undefined method DOMElement::item() in /xxx/xxx.php on line 235.

the code is as follow:
$SMQuery = new DOMDocument();
$SMQuery->loadXML($params);
$response = $SMQuery->createElement('SMreply');
$errors = array();
if (!$reqtyp = $SMQuery->getElementsByTagName("tag1"))
{$errors[] = $SMQuery->createElement('error', 'tag1 Element is missing');}
if (!$reqtyp = $SMQuery->getElementsByTagName("tag2"))
{$errors[] = $SMQuery->createElement('error', 'tag2 Element is missing');}
......

if(!empty($errors))
{
 foreach($errors as $error) {
  $response->appendChild($error); <==== this line is causing the error !!!
 }
}

Any help is much appreciated.
Cheers,
Riki.

A: You don't show where $response is being defined, but if it's the result of another new DOMDocument(), then that explains you error - you can't add nodes from one DOM object to another directly. It has to be imported first via ->importNode(). Only after that can you actually append it.


text:
Q: What's the best way to identify subdomains by PHP dynamically? I have configured the wildcard DNS of *.mydomain.com and it's all working properly. My question is which of these should I rely on identifying client subdomain requests?

*

*$_SERVER["HTTP_HOST"]

*$_SERVER["SERVER_NAME"]

*$_SERVER["SCRIPT_URI"]

They all seem to contain the subdomain part I want but after reading this article by Chris: http://shiflett.org/blog/2006/mar/server-name-versus-http-host, I'm lost at sea and there appears to be no safe way to do this?
Any idea on accomplishing this task securely? Which approach would you prefer?
Update: sorry, I meant this post: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

A: HTTP_HOST comes directly from the HOST header.  Apache does not clean it up in any way.  Even for non-wildcard setups, your first virtualhost in your config will receive a request for a HOST header that doesn't match any of your configured vhosts, so you have to be careful with it.  Treat it like any other user data.  Filter it appropriately before using it.

A: I'd suggest that you get the current page url, then use a regular expression to check. Be sure to ignore things link www, www2, etc.

A: $subdomain = explode('.', $_SERVER['HTTP_HOST'], -2);

Returns an array always, and can be empty if there is no sub domain. You should also make sure to notice that this could return www as an array value and that would link to your root domain anyway.

A: You can use any but most use HTTP_HOST.
You don't have to worry about 'security' here since you allow a wildcard for your subdomains. You won't be able to stop a user from entering a 'threatening' subdomain and sending a request to your server.
If you want to disallow certain subdomains then you have several options but thats a different question.

A: Too much talk of such a little problem.
Everyone says its dangerous but noone bother to write a solution, as simple as
$mydomain='example.com';
$subdomain="";
$matches=array();

$pat='!([a-z0-9_]+)\.'.preg_quote($mydomain).'$!i';
if (preg_match($pat,$_SERVER['HTTP_HOST'],$matches)) $subdomain=$matches[1];


text:
Q: Vue config for multiple html files By default Vue will build src/main.js and inject build script to public/index.html.
Is there any way to support for multiple html files?
Example: I have public/index.html and public/not-support.html and I also have 2 script files for each html, src/main.js for and src/not-support.js for public/not-support.html
After building, we will have dist/index.html and dist/not-support.html with separate script file injected.

A: if you use vue-cli, you can set config in vue.config.js file to support for multiple html files:
 const config = {
    devServer: {
        open: true,
        disableHostCheck: true,
    },
    pages: {
        index: {
            entry: 'src/index.js',
            template: 'public/index.html',
            filename: 'index.html',
        },
        support: {
            entry: 'src/support.js',
            template: 'public/support.html',
            filename: 'support.html',
        },
    },
    // ...config code
}
module.exports = config

refer to link, Build the app in multi-page mode
thanks.


text:
Q: Sum of product of certain binomial coefficients: $\sum\limits_{m = 0}^k \sum\limits_{n = 0}^m \binom{k}{m} \binom mn$
Given a nonnegative integer $k$. What is the value of the following sum:
  $$\sum_{m = 0}^k \sum_{n = 0}^m \binom{k}{m} \binom{m}{n}$$

I need this in order to simplify some of my work. I tried to expand it using binomial formula but didn't lead anywhere. I am simplifying weyl denominator formula for certain Kac-Moody algebras and I end up with this sum.

A: $${k\choose m}{m \choose n} = {k!\over m!(k-m)!}{m!\over n!(m-n)!}={k\choose k-m,n,m-n}$$ so we have $$\sum_{m=0}^k\sum_{n=0}^m{k\choose k-m,n,m-n}=3^k,$$ the number of ways to distribute $k$ objects in $3$ piles.

A: The  sum $$S=\sum_{m=0}^{k} \sum_{n=0}^{m} {k \choose m}{m \choose n}=\sum_{m=0}^{k} {k  \choose m}\sum_{n=0}^{m} {m \choose n}= \sum_{m=0}^{k} 2^m {k \choose m}=3^k.$$

A: The answer given by @saulspatz is correct. I would like to give an alternative way to get to the result that helps understanding what is actually going on.

The binomial coefficient $\binom{k}{m}$ is the number of ways in which we can choose $m$ elements out of a set of $k$ elements. In other words, it is the number of elements of the set
$$\{f:\{x_1,\ldots,x_k\}\to\{1,2\}\mid \#f^{-1}(2)=m\}.$$
Of course, we have a similar interpretation for $\binom{m}{n}$. Thus,
\begin{align}
\binom{k}{m}\binom{m}{n} ={}& \#\{f:\{x_1,\ldots,x_k\}\to\{0,1\}\mid \#f^{-1}(0)=m\}\cdot\#\{g:f^{-1}(0)\to\{2,3\}\mid \#g^{-1}(3)=n\}\\
={}&\#\{(f,g)\mid\#f^{-1}(0)=m,\ \#g^{-1}(3)=n\}
\end{align}
(I've omitted the domains and codomains of the maps in the last line). Now, given two such maps we can construct
$$h:\{x_1,\ldots,x_k\}\longrightarrow\{1,2,3\}$$
as the map given by $f$ on $f^{-1}(1)$ and $g\circ f$ otherwise, thus giving
$$\binom{k}{m}\binom{m}{n}=\#\{h:\{x_1,\ldots,x_k\}\to\{1,2,3\}\mid h^{-1}(3)=n,\ h^{-1}(2)=m-n\}\ .$$
Taking the sum over $m$ and $n$ is given by taking the union on the sets we are counting, which eliminates the conditions giving
$$\sum_{m=0}^k\sum_{n=0}^m\binom{k}{m}\binom{m}{n} = \#\{h:\{x_1,\ldots,x_k\}\to\{1,2,3\}\} = 3^k.$$


text:
Q: Cannot change the colour of HTML element with JavaScript It's a very simple line of code:
document.getElementsByClassName("header-2014 clearfix")[0].backgroundColor = "#FF0000"

I'm trying to use it here:
http://www.roblox.com/Chess-place?id=95041893
I'm using the JavaScript console (could that have anything to do with it?)
I'm expecting a very simple answer, so help would be appreciated, it's probably just some simple syntax error that a newbie to JavaScript (like me) would have.

A: You obviously want to change the style of the element, so don't forget to mention it in the code:
... [0].style.backgroundColor = "#FF0000";


text:
Q: A question about CLT for infinite variance This is an example from Durrett (Page 131, 5th edition, Durrett). Suppose $X_1,X_2,..$ are i.i.d. and have $P(X_1>x) = P(X_1<x)$ and $P(|X_1|>x)=x^{-2}$ for $x\geq 1.$ $E|X_1|^2 = \infty$ but $S_n = X_1+..X_n$ suitably normalized converges to a normal dist.
In the proof, I have one question.
Let $Y_{n,m} = X_m 1_{(|X_m|\leq n^{1/2}\log\log{n})}$ and $c_n = n^{1/2}\log\log{n}$. To show $EY_{n,m}^2 \geq \log{n}$, it says
$P(|Y_{n,m}|>x) = P(|X_1|>x)-P(|X_1|>c_n)$ $\geq (1-(\log\log{n})^{-2})P(|X_1|>x)$ when $x\leq \sqrt{n}$ which I don't understand why because that means $P(|X_1|>c_n) \leq (\log\log{n})^{-2}P(|X_1|>x)$ which I don't know why is true?
Thanks.

A: Assuming that $n$ is large enough in order to ensure that $c_n\geq 1$, we have
$$
\Pr(\lvert X_1\rvert>c_n)=c_n^{-2}= \frac 1n \frac 1{(\log\log n)^2}
$$
and since $x\leq \sqrt n$, then $n\geq x^2$ hence
$$
\Pr(\lvert X_1\rvert>c_n) \leq  \frac 1{x^2} \frac 1{(\log\log n)^2}
$$
which is exactly what we want.


text:
Q: Symfony2 Console and clipboard I am using Symfony2 Console as a stand alone component and I am looking for a way to copy some text on clipboard with a command. It must be for all Operating Systems.
For example:
php cli/console smth:copy

And when the command is run it must copy some text to user clipboard.
I've have google it and didn't found anything.
Is that possible an if is it how can i accomplish this task?


text:
Q: Login to a website using VBA Im a fresher to Excel Macros (VBA) and looking for a way to automate IE to login to a website and proceed to a certain page.
website URL : https://www.mast-technicalservices.com/ecp/index2.jsp and need to fill the login details and click continue.
Sub WebsiteLogIn()

Dim nURL As String
Dim UNElementID As String
Dim UserName As String
Dim PWElementID As String
Dim Password As String
Dim SIElementID As String

Set LoginData = ThisWorkbook.Sheets("Sheet1")
Set nURL = "https://www.mast-technicalservices.com/ecp/index2.jsp"
Set UNElementID = "ecp_param_userId"
Set UserName = LoginData.Cells(1, "B").Value
Set PWElementID = "ecp_param_password"
Set Password = LoginData.Cells(2, "B").Value
Set SIElementID = "imageField2"

Dim IE              As Object
Dim IEPage          As Object
Dim IEPageElement   As Object

    'Create a new Internet Explorer instance, make it visible and maximize its window and navigate to url.
    On Error Resume Next
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    ShowWindow IE.hwnd, SW_MAXIMIZE

    IE.navigate URL

    Set IEPage = IE.document

    'setthe UserName text box using the element ID.
    Set IEPageElement = IEPage.getElementById(UNElementID)

    'set the Password text box using the element ID.
    Set IEPageElement = IEPage.getElementById(PWElementID)

    'set the Continue button using the element ID.
    Set IEPageElement = IEPage.getElementById(SIElementID)

End Sub

A: This works:
Sub login()

    Const Url$ = "https://www.mast-technicalservices.com/ecp/index2.jsp"

    Dim UserName As String, Password As String, LoginData As Worksheet
    Set LoginData = ThisWorkbook.Worksheets("Sheet1")
    UserName = LoginData.Cells(1, "B").Value
    Password = LoginData.Cells(2, "B").Value

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    With ie

        .navigate Url
        ieBusy ie
        .Visible = True

        Dim oLogin As Object, oPassword As Object
        Set oLogin = .document.getElementsByName("ecp_param_userId")(0)
        Set oPassword = .document.getElementsByName("ecp_param_password")(0)

        oLogin.Value = UserName
        oPassword.Value = Password
        .document.forms(0).submit

    End With

End Sub

Sub ieBusy(ie As Object)
    Do While ie.Busy Or ie.readyState < 4
        DoEvents
    Loop
End Sub

The other sub: ieBusy will ensure the webpage is fully loaded prior to you attempting to manipulate it.


text:
Q: Google Analytics PDF Download Tracking I found this script that tracks more than just PDF downloads.  I updated it to work with analytics.js the latest version of Google Analytics (GA).  But, the events aren't being recorded in GA.  I stepped through the code and put console.log at each ga('send'...)  I know it's getting to the correct line of code, but the ga('send') isn't being recorded in GA.  Any ideas?
if (typeof jQuery != 'undefined') {
    jQuery(document).ready(function($) {
        var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
        var baseHref = '';
        if (jQuery('base').attr('href') != undefined)
            baseHref = jQuery('base').attr('href');
        jQuery('a').each(function() {
            var href = jQuery(this).attr('href');
            if (href && (href.match(/^https?\:/i)) && (!href.match(document.domain))) {
                jQuery(this).click(function() {
                    var extLink = href.replace(/^https?\:\/\//i, '');
                    ga('send','event','External Link','click',extLink);
                    if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
                        setTimeout(function() { location.href = href; }, 200);
                        return false;
                    }
                });
            }
            else if (href && href.match(/^mailto\:/i)) {
                jQuery(this).click(function() {
                    var mailLink = href.replace(/^mailto\:/i, '');
                    ga('send','event','Email Link','click',mailLink);
                });
            }
            else if (href && href.match(filetypes)) {
                jQuery(this).click(function() {
                    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                    var filePath = href;
                    ga('send','event','Download Link','click-' + extension,filePath);
                    if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
                        setTimeout(function() { location.href = baseHref + href; }, 200);
                        return false;
                    }
                });
            }
        });
    });
}


text:
Q: Best and concise resources/links for learning SEO techniques? Can you suggest any quick and concise resources for learning SEO techniques?

A: Beyond John's comment - which is TRUE, here is a list I have compiled (see the rest at http://www.qnq.com.au/resources/online-seo-link-repository/)
In no particular order and with no favour:

*

*http://www.google.com/webmasters/docs/search-engine-optimization-starter-guide.pdf

*https://docs.google.com/Present?docid=dc3qhbxg_1217d9mwjwg3

*http://www.bruceclay.com/web_rank.htm

*http://www.websitepublisher.net/seo-guide/

*http://www.highrankings.com/tentips

*http://www.hobo-web.co.uk/seo/

*http://sethgodin.typepad.com/seths_blog/2007/10/how-to-create-1.html

*http://www.webconfs.com/15-minute-seo.php

*http://www.seomoz.org/blog/the-web-developers-seo-cheat-sheet

*http://www.conversationmarketing.com/2010/07/on-page-seo-cheatsheet.htm

*http://www.seo-theory.com/wordpress/2008/09/22/nine-lessons-in-search-engine-optimization/

*http://searchengineland.com/25-super-common-seo-mistakes-51888

*http://www.seobook.com/archives/001792.shtml

*http://www.seobook.com/seo-strategy

*http://www.bing.com/community/blogs/webmaster/archive/2009/06/26/site-architecture-and-seo-file-page-issues-sem-101.aspx

*http://www.searchenginejournal.com/bing-rankings-cheat-sheet/29847/

*http://blog.vkistudios.com/index.cfm/2009/9/2/Server-Status-Codes-and-SEO

*http://sixrevisions.com/content-strategy/user-friendly-seo/

*http://www.youtube.com/watch?v=ecI_hCBGEIM – great 1hr long
presentation from Google

Make it through that list, and you'll be well on your way.
Remember - "Knowing is not enough; we must apply!" – Goethe


text:
Q: Formulario reactivo no devuelve valores Buen día, estoy tratando de crear un formulario reactivo en angular 10 pero a la hora de leer los datos, es como si el evento que asigna el valor a las variables no se ejecutara.
el punto es que aunque los campos del formulario estén llenos el objeto que arroja el formulario reactivo siempre esta vacío
Este es el componente .ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {

  formLogin: FormGroup;

  constructor(
    private readonly router: Router,
    private _builder: FormBuilder
  ) {
    this.formLogin = this._builder.group({
      user: ["", Validators.compose([Validators.email, Validators.required, Validators.maxLength(50)])],
      passwd: ["", Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(50)])]
    });
  }

  ngOnInit(): void {
  }

  sendData(value: any) {
    console.log(this.formLogin.value);
  }
  onSubmitData(value: any) {
    console.log(this.formLogin.value);
  }

  /**
   * Este método no se puede modificar
   * */
  public redirectUsers(): void {
    this.router.navigateByUrl('/users/list');
  }

}

El html es este:

  <form class="formLogin" [formGroup]="formLogin" (onSubmit) ="onSubmitData()">

Inicio de sesión

      Correo electrónico
      <input formControlName="user" type="email" name="login__email" id="login__email">

      Contraseña
      <input formControlName="passwd" type="password" name="login__password" id="login__password">

    <button class="btn-login" id="login__btn-login" [disabled]="!formLogin.invalid" type="button"
      (click)="sendData(formLogin.value)">Iniciar sesión</button>

{{formLogin.valid}}

  </form>

Este es el resultado en consola
aunque el formulario esta así

Gracias por la atención prestada


text:
Q: How can I match and filter a dataset using another one? I really dont know how to ask about this so let me give an example.
I have a dataset which has over 50k+ entries including adresses. Like this
streets <- c("st1","st2","st3","st4","st10000","st50000")

I need to match this street names to cities they are belonged to. When it sees "st1" it should add CityX. I didnt have a dataset so I've created one like this.
cities <- data.table(
  city1 <- c("st1","st2","st3"),
  city2 <- c("st4","st5","st6"),
  city3 <- c("st50","st10000","st50000")
  )

setnames(cities,"V1","NY")
setnames(cities,"V2","LA")
setnames(cities,"V3","DC")

Now I want to match this datasets if cities include street names it should create a new column in "streets" and add city name to there. Should be seen like this:
streets2 <- data.table(streets <- c("st1","st2","st3","st4","st10000","st50000"),
c("NY","NY","NY", "LA","DC","DC"))

I should mention that I cant use dpylr for this only data.table is allowed. I think I need to use for loop and lapply but idk how. Thank you.

A: Here is an option:
teams <- c("barcelona","rmadrid","liverpool")
DT <- rbindlist(lapply(mget(teams), function(x) data.table(Player=trimws(strsplit(x,",")[[1L]]))),
    idcol="Team")

data.table(Player=strsplit(players, ",")[[1L]])[DT, on=.(Player), Team := Team][]

output:
     Player      Team
 1:    Xavi barcelona
 2:   Puyol barcelona
 3: Iniesta barcelona
 4:   Messi barcelona
 5: Gerrard liverpool
 6:   Salah liverpool
 7:    Mane liverpool
 8: Ronaldo   rmadrid
 9:   Ramos   rmadrid
10:  Hazard   rmadrid

Hasn't Xavi, Puyol and Gerrard retired? And Ronaldo is still at Real Madrid?
data:
players <- "Xavi,Puyol,Iniesta,Messi,Gerrard,Salah,Mane,Ronaldo,Ramos, Hazard"
barcelona <- "Xavi,Puyol,Iniesta,Messi"
rmadrid <- "Ronaldo,Ramos,Hazard"
liverpool <- "Gerrard,Salah,Mane"


text:
Q: MFMailComposeViewController slow to render emails with attachments on iOS9 Opening a MFMailComposeViewController with attachment data takes a very long time to render the email on iOS9. The MFMailComposeViewController appears quickly, but its fields and contents (except Subject) are blank for a long time (e.g. 45s for an email with 10 attachments on an iPhone6). There appears to be no issue with the time it takes for the addAttachmentData method to run, the delay occurs at the view rendering stage.
Other people have experienced the same issue and it appears to be a bug in iOS9: https://forums.developer.apple.com/thread/17124
My question is whether anyone has discovered a workaround allowing emails with attachments to render in an acceptable time? (Issue is still present in iOS 9.0.2)


text:
Q: Data privacy and Access Modifiers java I am currently in the middle of a project, and I have a slight dilemma. Say I have a class called A. In class A, there is a private nested class called B. Then I created another class called C which inherits A. Do I need to make B protected so that C can access it? or is there another way to keep B private and still let C access that class.
In general, is it better to use protected or use private and create getters and setters?
Which one is better for variable / method privacy>

A: No , that's why private is for .
You don't want even class that inherit from you are able to access to it.
You can have a protected method which always return a new instance of B or return singleton of B, if you really need to access from your class child.
And for your last question , are you asking about variable inside classes?