text:
Q: Summing a column gives null in C#/ASP.NET I have the following sql statement that calculate the sum of the column:
 select coalesce(SUM(cdin_ActMortgageAmnt),0)
 from CDIndex,company
 where  comp_companyid=cdin_companyid and comp_idcust like '%10319%'
 and cdin_Deleted is null and cdin_startunstufdate is not null
 and cdin_Status='InProgress'

gives me the output like this:

I tried to convert it to LINQ like this:
var sumation = (from com in db.Companies
                join cd in db.CDIndexes on com.Comp_CompanyId equals cd.cdin_CompanyId
                where
                    cd.cdin_Status == "InProgress" &&
                    cd.cdin_startunstufdate == null &&
                    cd.cdin_Deleted == null
                select new {
                    sum = cd.cdin_ActMortgageAmnt
                }
               );

var summ = sumation.Sum(x => x.sum);

When I put tracePoint beside var summ in debug mode it gives me null when i point to it.
What is the problem?

A: On your case you are using coalesce(SUM(cdin_ActMortgageAmnt),0) because some values of cdin_ActMortgageAmnt can be null and you are giving the default value of 0, you need to do the same in your final query. Something like this when you do the select
cd.cdin_ActMortgageAmnt ?? 0

A: this query is appropriate your sql query
     var sumation =db.Companies.Join(db.CDIndexes,
                                        com=>com.Comp_CompanyId,
                                        cd=>cd.cdin_companyid,
                                        (com,cd)=>new {com,cd})
                                   .Where(x=>x.com.comp_idcust.Contains("10319") && x.cd.cdin_Status== "InProgress" &&
                                          cd.cdin_startunstufdate != null &&
                                          cd.cdin_Deleted == null)
                                   .Select(x=>new
                                   {
                                      sum=x.cd.cdin_ActMortgageAmnt ?? 0
                                   }).ToList()

A: Here is one way:
var summ = db.Companies.Join(
    db.CDIndexes,
    cd => cd.cdin_CompanyId,
    com => Comp_CompanyId,
    (com, cd) => new { com, cd })
  .Where(z=>z.com.comp_idcust.Contains("10319")) // Added "LIKE"
  .Where(z=>z.cd.cdin_Status == "InProgress")
  .Where(z=>z.cd.cdin_startunstufdate != null) // Reversed your condition
  .Where(z=>z.cd.cdin_Deleted == null)
  .Sum(z=>z.cd.cdin_ActMortgageAmnt);

You can also combine all the Wheres together, but I prefer not to in most cases like this:
var summ = db.Companies.Join(
    db.CDIndexes,
    cd => cd.cdin_CompanyId,
    com => Comp_CompanyId,
    (com, cd) => new { com, cd })
  .Where(z=>z.com.comp_idcust.Contains("10319") // Added "LIKE"
    && z.cd.cdin_Status == "InProgress"
    && z.cd.cdin_startunstufdate != null // Reversed your condition
    && z.cd.cdin_Deleted == null)
  .Sum(z=>z.cd.cdin_ActMortgageAmnt);


text:
Q: How to insert value to table using cursor in stored procedure without getting duplicate records? I am trying to insert records into existing but empty table based on from date and to date parameters using cursor in stored procedure. Please let me know what I am doing wrong in the below SQL?
When executing this procedure I am getting first row duplicated multiple times.
Error:

Maximum stored procedure, function, trigger or view nesting level exceeded (limit32)

Code:
ALTER proc [dbo].[spempmaster] (@date1 datetime,@date2 datetime)
as
Begin

    Set nocount on

    declare @doj datetime
    declare @empname nchar(10)
    declare @managername nchar(10)
    declare @dept varchar(50)
    declare emp_report15 cursor for

    select convert(varchar(10),convert(smalldatetime,emp.doj,120),103) DOJ,
    (emp.name + ' ' + emp.lastname)  Name,
    emp1.name Manager_Name, txtdepartment Department
    from empmaster emp
    left outer join tbljobtitles jt
        on emp.fkjobtitleid = jt.pkjobtitleid,
    tbldepartment td,
    tblteam t,
    empmaster emp1
    where
        jt.fkteamid = t.pkteamid
        and td.pkdeptid= t.fkdeptid
        and emp.reportingto = emp1.empno
        and emp.doj between @date1 and @date2
    order by doj

    open emp_report15

    fetch emp_report15 into @doj, @empname, @managername, @dept

    while @@fetch_status = 0
    begin
        insert into tblreport (DOJ,emp_name,manager_name,department)
        values(@doj,@empname,@managername,@dept)
    end

    fetch next from emp_report15 into @doj,@empname,@managername,@dept

    close emp_report15

    deallocate emp_report15

end

A: First of all - there's absolutely no need for a cursor in this situation. SQL Server is a set-based system - don't apply the procedural row-by-agonizing-row approach that works in procedural languages to this set-based system! Use a set-based approach instead!
Also: don't mix the proper ANSI join syntax with the old-style, deprecated comma-separated list of tables JOIN approach. That old style has been deprecated with the SQL-92 standard - more than 20 years ago! - about time to toss it out the window and use the proper ISO/ANSI standard JOIN syntax (INNER JOIN, LEFT OUTER JOIN) all the time.
So basically, in the end - your statement would be something like:
ALTER PROCEDURE [dbo].[spempmaster] (@date1 DATETIME, @date2 DATETIME)
AS
  INSERT INTO dbo.tblreport(DOJ, emp_name, manager_name, department)
      SELECT
          CONVERT(VARCHAR(10), CONVERT(SMALLDATETIME, emp.doj, 120), 103),
          (emp.name + ' ' + emp.lastname),
          emp1.name Manager_Name,
          txtDepartment
      FROM
          dbo.empmaster emp
      INNER JOIN
          dbo.empmaster emp1 ON emp.reportingto = emp1.empno
      LEFT OUTER JOIN
         dbo.tbljobtitles jt ON emp.fkjobtitleid = jt.pkjobtitleid
      LEFT OUTER JOIN
         dbo.tblteam t ON jt.fkteamid = t.pkteamid
      LEFT OUTER JOIN
         dbo.tbldepartment td ON td.pkdeptid = t.fkdeptid
      WHERE
          emp.doj BETWEEN @date1 AND @date2

As for avoiding duplicates: run your SELECT query separately, and see why you're getting duplicates. Just from this code alone, there's no way for outsiders to provide a meaningful answer here - it entirely depends on what data is stored in your tables.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spread our elements over parent width I'm trying to spread out 3 elements over the width of the screen. I've tried different methods but when I use inline-block the second element doesn't center. When I leave out inline-block the third element shows on the next line. Any suggestions?

A: You can use the below CSS3 to do this.

* {
            margin: 0px;
            padding: 0px;
        }
        .base {
            display: block;
            height: 200px;
            background-color: #eeeeee;
        }
        .container {
        }
        .shape {
            width: 100px;
            height: 100px;
            background-color: #ff0000;
        }
        .container {
        display:flex;
        justify-content:space-between;
        }

CSS Solution

* {
            margin: 0px;
            padding: 0px;
        }
        .base {
            display: block;
            height: 200px;
            background-color: #eeeeee;
        }
        .container {
        }
        .shape {
            width: 100px;
            height: 100px;
            background-color: #ff0000;
        }
        .container {
          display:block;
          text-align:center;
        }
        #left{
          float:left;
        }
        #right{
          float:right;
        }
        #center{
          display:inline-block;
        }

A: I would suggest you to use display:flex;


text:
Q: Excel: Get the days delayed from Start date to End date Using DatedIF? I have a sample data here that I want to get the days delayed.

As you can see,
The data shows the records for those users who did not submit their project, users who submitted on-time, and users who actually dont submit their project.
Currently,
I have this formula
=DATEDIF(A2,B2,"d")
for the first row to calculate the days delayed of first row.
Can I add in this formula that detects if the user dont submit their project and the delayed days continues counting for day delayed? Like for example the data on row 4. The column submitted_project is blank means the user still dont submit their project the days delayed will start counting after the deadline.

A: You don't need DateDif for that. (By the way it's Date-Dif for "date difference", not Dated-If)
You can simply subtract the two dates from each other and format the result as a number.
DateDif expects the earlier date as the first parameter, that's why it errors when the first parameter is the later date, i.e. when the project was submitted before the due date.
But with simple subtraction like =B2-A2 you can get the correct result. Better even, to check that both cells have dates before doing the calculation, to avoid misleading results, so
=if(count(A2:B2)=2,B2-A2,"")

Edit after comment:  Yes.
=IF(COUNT(A5:B5)=2,B5-A5,IF(B5="",TODAY()-A5))


text:
Q: Merging Shapes and Attaching Partial Drag/Drop in WPF I would like to draw two shapes in WPF and merge them together.  Then, I'd like to attach a drag/drop event to ONE of the original shapes.
So basically, you can only drag if you click on a certain part of the shape, but it will drag the entire shape with you.
Here is some code:
// Set up some basic properties for the two ellipses
Point centerPoint = new Point(100, 100);
SolidColorBrush ellipseColor_1 = new SolidColorBrush(Color.FromArgb(255, 0, 0, 255));
double width_1 = 10; double height_1 = 10;
SolidColorBrush ellipseColor_2 = new SolidColorBrush(Color.FromArgb(50, 255, 0, 0));
double width_2 = 200; double height_2 = 200;

// Create the first ellipse: A small blue dot
// Then position it in the correct location (centerPoint)
Ellipse ellipse_1 = new Ellipse() { Fill = ellipseColor_1, Width = width_1, Height = height_1 };
ellipse_1.RenderTransform = new TranslateTransform(point.X - width_1 / 2, point.Y - height_1 / 2);

// Create the second ellipse: A large red, semi-transparent circle
// Then position it in the correct location (centerPoint)
Ellipse ellipse_2 = new Ellipse() { Fill = ellipseColor_2, Width = width_2, Height = height_2 };
ellipse_2.RenderTransform = new TranslateTransform(point.X - width_2 / 2, point.Y - height_2 / 2);

// ???
// How should I merge these?
// ???

// Now apply drag drop behavior to ONLY ellipse_1
MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior();
dragBehavior.Attach(ellipse_1);  // This may change depending on the above

// ...
// Add new element to canvas

This code creates two circles (a big one and a small one).  I would like to only be able to drag if the small one is clicked, but I'd like to have them attached so they'll move together without having to manually add code that will take care of this.

A: If you put them both in a Grid (or Canvas, StackPanel, etc.), and set the drag behavior on the panel, they will be "merged".  If you set IsHitTestVisible to false on ellipse_2, it won't respond to any mouse events, so effectively it won't be draggable.


text:
Q: Can you do .End in excel if there are blank columns? I have code that builds a table row by row.
Once it puts the data in each cell in the row, it selects the entire row using
Range(Cells(2 + RowOffset, 2), Range(Cells(2 + RowOffset, 2), Cells(2 + RowOffset, 2)).End(xlToRight)).Interior.Color = vbBlack
and makes it black.
This was working great, until one of the table cells didn't have any data. At that point the code only selects the row up until the cell after the empty cell.
Is there a method to do .End to select the entire row, regardless of if there are blank cells in the middle? Obviously I still want to only select rows with data in.
Just to clarify, if X is data and 0 is blank:

X X X X X

X X O X X

X X X X O

The code would highlight the first row all 5 cells, highlight the second row all 5 cells, highlight the last row just 4 cells (because the O on the last row is no data)

A: From the First Cell to the Last Non-Empty Cell

*

*You have concluded yourself that the End property with its parameter set to xlToRight is not an option. Since you are fighting (in the comments) against an xlToLeft option, there is probably data to the right of the table or you just want to restrict the whole thing to only some (5) columns leaving the cells to the right intact. In any case, using the Find method is a better option.

An Example

*

*It is assumed that in each row you want to highlight the cells from column B to column F with the following condition:

*

*If any of the cells are not empty, highlight the cells from the first cell to the last non-empty cell (no matter if there are empty cells in between).

    Dim ws As Worksheet: Set ws = ActiveSheet ' change appropriately
    ' e.g.:
    'Dim ws As Worksheet: set ws = ThisWorkbook.Worksheets("Sheet1")
    Dim crg As Range: Set crg = ws.Columns("B:F") ' "B1:F1048576"
    ' Or any of the following:
    'Dim crg As Range: Set crg = ws.Columns("B").Resize(, 5) ' "B1:F1048576"
    'Dim crg As Range: Set crg = ws.Columns(2).Resize(, 5) ' "B1:F1048576"

    Dim rrg As Range
    Dim rlCell As Range

    ' Start loop e.g. 'For RowOffset = 1 to whatever'

    Set rrg = crg.Rows(2 + RowOffset)
    Set rlCell = rrg.Find("*", , xlFormulas, , , xlPrevious)
    If Not rlCell Is Nothing Then
        ws.Range(rrg.Cells(1), rlCell).Interior.Color = vbBlack
        Set rlCell = Nothing ' don't forget to reset since in a loop
    End If

    ' End loop e.g. 'Next RowOffset'


text:
Q: Random number generation Function explanation Can anyone explain these two lines of function??
 int getRandomNumber(int min, int max)
 {
    static const double fraction = 1.0 / (RAND_MAX + 1.0);
    return min + static_cast<int>((max - min + 1) * (rand() * fraction));
 }

A: Looks like it's constraining rand() function's output to fall inside a min and max.
a double type value fraction is calculated from 1.0 / (RAND_MAX + 1.0);
RAND_MAX is a pre-compiler value defined in cstdlib or other header file or library, it's a big positive integer that represents the largest signed int your program can use. A higher RAND_MAX will make fraction lower since 1/number is a reciprocal; the reciprocal of 4 is 1/4 or 0.25. 5 is 1/5 or 0.20
The 1.0's are to implicitly cast RAND_MAX into a floating point number aka decimal; this makes sure that the / division / operator doesn't do integer division (5 / 2 == 2; vs 5.0 / 2.0 == 2.5)
return min + static_cast<int>((max - min + 1) * (rand() * fraction));

Return the integer representation of the min/max spread reduced by a random factor, added to the original minimum.
This line uses the min parameter value as a 'floor'. static_cast<int>() rounds down the floating point value of ((max - min + 1) * (rand() * fraction)) into an integer aka a whole number with no decimal parts. This cast is important for returning an int, but it also ensures that max is not exceeded by rounding down.
(max - min + 1) is the spread between the max and min parameters + 1. So if max == min you would be multiplying (rand() * fraction) by 1 instead of zero.
rand() generates a semi-random integer (no decimal parts) between 0 and RAND_MAX
Since fraction is the reciprocal of RAND_MAX + 1, fraction will always be < 1, and rand()s output will be a random portion of the min/max spread. The key part of understanding this function beyond the mixed C and C++ code confusion is knowing that RAND_MAX is used by the fraction variable AND the rand() function.
Think of the (rand() * fraction) part as a portion of distance from min
I would try feeding this function multiple values, tweaking the min, max, and fraction values each time and see how the output changes, you could probably find a pattern.
By making fraction smaller than (1.0 / RAND_MAX + 1.0) you can cluster the return values closer to the minimum.
(look up math ceiling and floor, and walnut's comment about uniform distribution). This can be done to smooth output, or make something more predictable, or cluster return values around an input value. If the math is the confusing part for you then messing around with code and seeing what happens will likely help your understanding and intuition of math functions.
Welcome to Stack Overflow!


text:
Q: Twitter bootstrap .on calls Just a small question. If you trigger the following code from multiple locations, does the latter one replace the function of the previous one or does it append?
$('#myModal').on('hidden.bs.modal', function () {
  // do something…
})

For example when you do something like
$('.modal').on('hidden.bs.modal', function () {
  // do something…
})
//---
//and then using the modal id
//---
$('#myModal').on('hidden.bs.modal', function () {
  // do something…
})

A: Multiple calls to .on on the same element adds new events on top of the previous ones. They will get executed first in first out.


text:
Q: Subgroups of free groups question I am just reading Allufi chapter 0. I have a specific question in regards to a comment that the book made.
"By Proposition 6.9, every nontrivial subgroup of $\mathbb{Z}$ is in fact iso-morphic to $\mathbb{Z}$. Putting this a little strangely, it says that every subgroup of the free group on one generator is free."
I am not sure I understand this. Is it saying that subgroup of free groups on one generator is isomorphic to a subgroup of free groups of one generator ? I am guessing I am right in my understanding, because the second comment it is saying beware that free groups on two generators contain subgroups isomorphic to free group of arbitrary generators.

A: Yes, you understood it right. The only free group of one generator is $\mathbb{Z}$ up to isomorphism. So its non trivial subgroups are isomorphic to it. With free groups of more than one generator it becomes much more complicated.


text:
Q: using Tikz to create a maze I created this figure with microsoft powerpoint but I'd like to make a similar one using latex because I am writing my document in latex.

I already asked how I can make similar maze structure but in the response it is hard to remove some part of periphery to keep the red region without removing the whole circle. It would be even better structure if the extra light blue space between 2,3,4,5,7 steps will be removed and only the corresponding cells and middle region remain. I appreciate if someone suggest how I can modify the previous answer to get this image or with mentioned changes.
Thanks

A: I let the author of the previous answer modify his figure because I didn't follow the same way to build this figure.
As I didn't quite understand everything you want, here is a first approach.

*

*I use nodes, 3 in the form of a circle, 3 in the form of a pentagon. The latter are used to place the text at the top of these pentagons.

*The radii of the circles are set, by modifying these parameters, everything is calculated automatically.

*Not having recognized the font you used, I didn't write the text.
If you have any questions, I'm listening.

Translated with www.DeepL.com/Translator (free version)
Update

\documentclass[tikz,border=5mm]{standalone}
%\usepackage{tikz}
\usetikzlibrary{shapes.geometric,calc}
\begin{document}
\def\ultrad{60mm}
\def\bigrad{45mm}
\def\smallrad{30mm}

\def\pentasmall{20mm}

\begin{tikzpicture}
\node[name=cercle3,shape=circle,minimum width=\ultrad] {};%invisible circle
\node[name=cercle2,shape=circle,minimum width=\bigrad] {};
\node[name=cercle1,shape=circle,draw=cyan!30!violet,fill=cyan!60!violet!40,minimum width=\smallrad] {};
% 3 pentagon used to place text at their corner
\node[name=penta1, shape=regular polygon,rotate=108,draw=cyan!50!violet,
fill = blue!80!violet!20, inner sep=.5cm,minimum width=\pentasmall]
{};
\pgfmathtruncatemacro\pentamed{(\bigrad+\smallrad)/2}
\node[name=penta2, shape=regular polygon,inner sep=0pt,minimum width=\pentamed,rotate=108]{};
\pgfmathtruncatemacro\pentabig{(\bigrad+\ultrad)/2}
\node[name=penta3, shape=regular polygon,inner sep=0pt,minimum width=\pentabig,rotate=108]{};

\node[align=center] at (penta1){Start\\  1};
\foreach \i [evaluate=\i as \j using \i+24]in {-30,42,...,320}{
    \draw (cercle1.\i)--(cercle2.\i)arc[start angle=\i,end angle=\j,radius=\bigrad/2] (cercle1.\j)--(cercle2.\j);}
%\foreach \i/\j in {-90/2,-18/{R\\3},54/5,126/7,198/4}
%    \node[align=center] at ($(cercle1.\i)!.5!(cercle2.\i)$){\j};

\node[align=center,rotate=108] at (penta2.corner 1){J\\4};
\node[align=center] at (penta2.corner 2){2};
\node[align=center] at (penta2.corner 3){3};
\node at (penta2.corner 4){5};
\node at (penta2.corner 5){7};

% red
\draw[fill=red](cercle2.42)--(cercle3.42)arc[start angle=42,end angle=66,radius=\ultrad/2]--(cercle2.66)arc[start angle=66,end angle=42,radius=\bigrad/2];
\draw[fill=red](cercle2.114)--(cercle3.114)arc[start angle=114,delta angle=24,radius=\ultrad/2]--(cercle2.138)arc[start angle=138,delta angle=-24,radius=\bigrad/2];

\end{tikzpicture}

\end{document}

Old answer

\documentclass[tikz,border=5mm]{standalone}
%\usepackage{tikz}
\usetikzlibrary{shapes.geometric,calc}
\begin{document}
\def\ultrad{60mm}
\def\bigrad{45mm}
\def\smallrad{30mm}

\def\pentasmall{1cm}
\tikzset{
shape example/.style= {color = black!30,
draw=cyan!50!violet,
fill = blue!80!violet!20,
very thick,
inner xsep = 2.5cm,
inner ysep = 0.5cm,
rotate=108}
}
\begin{tikzpicture}
\node[name=cercle3,shape=circle,minimum width=\ultrad] {};%invisible circle
\node[name=cercle2,shape=circle,draw,fill=cyan!20,minimum width=\bigrad] {};
\node[name=cercle1,shape=circle,draw=cyan!30!violet,fill=cyan!60!violet!40,minimum width=\smallrad] {};
% 3 pentagon used to place text at their corner
\node[name=penta1, shape=regular polygon, shape example, inner sep=.5cm,minimum width=\pentasmall]
{};
\pgfmathtruncatemacro\pentamed{(\bigrad+\smallrad)/2}
\node[name=penta2, shape=regular polygon,inner sep=0pt,minimum width=\pentamed,rotate=108]{};
\pgfmathtruncatemacro\pentabig{(\bigrad+\ultrad)/2}
\node[name=penta3, shape=regular polygon,inner sep=0pt,minimum width=\pentabig,rotate=108]{};

\node[align=center] at (penta1){Start\\  1};
\foreach \i [evaluate=\i as \j using \i+24]in {-30,42,...,320}{
    \draw (cercle1.\i)--(cercle2.\i);
    \draw (cercle1.\j)--(cercle2.\j);}
%\foreach \i/\j in {-90/2,-18/{R\\3},54/5,126/7,198/4}
%    \node[align=center] at ($(cercle1.\i)!.5!(cercle2.\i)$){\j};

\node[align=center,rotate=108] at (penta2.corner 1){J\\4};
\node[align=center] at (penta2.corner 2){2};
\node[align=center] at (penta2.corner 3){3};
\node at (penta2.corner 4){5};
\node at (penta2.corner 5){7};

% red
\draw[fill=red](cercle2.42)--(cercle3.42)arc[start angle=42,end angle=66,radius=\ultrad/2]--(cercle2.66)arc[start angle=66,end angle=42,radius=\bigrad/2];
\draw[fill=red](cercle2.114)--(cercle3.114)arc[start angle=114,delta angle=24,radius=\ultrad/2]--(cercle2.138)arc[start angle=138,delta angle=-24,radius=\bigrad/2];

\end{tikzpicture}

\end{document}

A: Another option. In this case, outer segments are drawn with arcs. If you don't want the border, they could be drawn with just an arc with the correct line width.
As a first solution all angles are defined by hand, but it's not too difficult to define them automatically.
\documentclass[margin=3mm, tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric, intersections, decorations.text}
\begin{document}

\begin{tikzpicture}
    \node [circle, minimum size=6cm, draw, draw= blue!20!black,fill=blue!20] (a) {} ;
    \node [draw,minimum size=4cm,inner sep=0pt,regular polygon,regular polygon sides=5,shape border rotate=180, align=center, fill=blue!80] (b) {Start\\ 1};
    \foreach \i [evaluate=\i as \j using 30+\i] in {39,111,183,255,327}{
    \draw[fill=cyan] (\i:3) arc (\i:\j:3)--++(\j:1) arc(\j:\i:4)--cycle;
    \draw[fill=red] (\i:4) arc (\i:\j:4)--++(\j:1) arc(\j:\i:5)--cycle;
    }
    \foreach \i [count=\ni] in {54,126,...,342}{
        \node[rotate=\i-90] at (\i:3.5) {\ni};
        \node[rotate=\i-90] at (\i:4.5) {\ni};
    }

\end{tikzpicture}

\end{document}

Update:
\documentclass[margin=3mm, tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric, intersections, decorations.text}
\begin{document}

\begin{tikzpicture}
    \node [circle, minimum size=6cm, draw, draw= blue!20!black,fill=blue!20] (a) {} ;
    \node [draw,minimum size=4cm,inner sep=0pt,regular polygon,regular polygon sides=5,shape border rotate=180, align=center, fill=blue!80] (b) {Start\\ 1};

    \foreach \i [evaluate=\i as \j using 30+\i] in {39,111,183,255,327}
        \draw[fill=cyan] (\i:3) arc (\i:\j:3)--++(\j:1) arc(\j:\i:4)--cycle;
    \foreach \i [count=\ni] in {54,126,...,342}
        \node[rotate=\i-90, ] at (\i:3.5) {\ni};

    \foreach \i [evaluate=\i as \j using 30+\i] in {39,111}
        \draw[fill=red] (\i:4) arc (\i:\j:4)--++(\j:1) arc(\j:\i:5)--cycle;
    \foreach \i [count=\ni] in {54,126}
        \node[rotate=\i-90, ] at (\i:4.5) {\ni};

\end{tikzpicture}

\end{document}


text:
Q: Prevent scrolling when changing TextEditingController text flutter Iam using  TextEditingController control and when I set the control text to a new data by using control.text = 'hi';
in a function, the listview scroll to the widget which use this control because the data has been changed.
How to prevent scrolling the widget which use this control when I change the control text and stay in the same position in the screen?
Widget textbox_widget1(){
         return TextFormField(
          keyboardType: TextInputType.number,
          controller: control,
          autofocus: false,
        );
}

and here I added my listview in a scaffold in build function
     child: Scrollbar(
                controller: _scrollController,
                child: Padding(
                  padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom / 1.5), // fixade keyboard över title med padding, 1.5 ta bort vit padding
                  child: ListView(
                    controller: _scrollController,
                    shrinkWrap: true,
                    padding: EdgeInsets.only(left: 24.0, right: 24.0),
                    children: <Widget>[

                      SizedBox(height: 15.0),

                      textbox_widget1(),

                      SizedBox(height: 15.0),

                      textbox_widget2(),

                     SizedBox(height: 15.0),

                      textbox_widget3(),

            SizedBox(height: 15.0),

              textbox_widget4(),

            textbox_widget5(),
                      SizedBox(hight: 70,),

                    ],
                  ),
                ),
              ),

and the function is something like this
    void set_text(){control.text = 'new data';}

Thanks

A: I solved the problem by using TextEditingController
control = new TextEditingController(text: 'new value');


text:
Q: Why is my .htaccess code slowing down my site? I have a quick question about .htaccess. Why does my site load faster when using this URL:
http://www.phaidi.com/network/index.php?p=home&s=chaumyvn
Than by going straight to the chaumy.vn domain?
I think it has something to do with my .htaccess, but I have not been able to fix it. See my .htaccess file below:
Options +FollowSymlinks
RewriteEngine on
RewriteBase /

ReWriteCond %{HTTP_HOST} chaumy.vn
ReWriteCond %{REQUEST_URI} !network/
ReWriteRule ^(.*)$ /network/index.php?p=$1&s=chaumyvn [R=301]

<Files .htaccess>
order allow,deny
deny from all
</Files>

Any ideas?

A: I don't know if this will fix all the slowness, but a quick remark.
You are only excluding the network folder from the rewrite rule, however what about your static files (/css/, favicon etc.) They will all be rewriting to your network/index.php file as well.
Besides that for production environments (especially on high-traffic websites) I've heard it's better to put the 'htaccess' information straight into the apache/virtualhost configuration, as it saves Apache from having to scan for the htaccess and parse is for every request. But it shouldn't save 'that much' in this situation.


text:
Q: Regular Expressions How to exclude entering other URL's than domain URL Hello i wrote a regular expression to validate URL
jQuery.validator.addMethod("url_validation", function (value, element) {
    return this.optional(element) || /^([ \t+])?(([http|https|HTTPS|HTTP]+:\/\/))?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/i.test(value);
}, "error")

I could not find a way to prevent entering anything after entering the domain : for example : - "http://www.mydomain.uk/whateverthing.ext"  i want to stop entering the "whateverthing after entering the domain . I could not figure out a way to solve this issue . can anyone give me a help?"(this will include validating the URL as well)

A: OK, so you want two things:

*

*validate the hostname;

*validate that the part after the /, if / there is, is empty.

You can proceed as such:

*

*validate your input against ^https?://([a-z0-9-]+(?:\.[a-z0-9-]+)*)/?(.*);

*if the above does not match, you have an invalid URL;

*grab group 2: if non empty, it means a non empty path, invalid URL;

*grab group 1 and split it against \..

*verify whether all groups are of length <= 255 and match ^[a-z0-9]+(-[a-z0-9]+)*$: if one doesn't, invalid URL.

And that doesn't take IP addresses in the hostname part...
I am surprised anyhow that jQuery doesn't have methods to check for that. Have you looked?
Edit: it has: http://docs.jquery.com/Plugins/Validation/Methods/url


text:
Q: How to extract similar data from two sheets I have a two different list of data. In both list one column can match but the other column can be unique. How do I pull the the duplicated values with its respective partnering column? I have tried the unique, and tried match functions. I would like to only pull the same value that is duplicated in Col1 with its partnering data in Col2 list1
list2

A: Use a QUERY function... Assuming you want to pull specific items?
=QUERY({Sheet1!A1:B;Sheet2!A1:B},"Select * Where Col1 = 1234")
This example will show you the results that match with 1234 in Column A
If you want all the results not specific to anything use this:
=QUERY({Sheet1!A1:B;Sheet2!A1:B},"Select * Where Col1 IS NOT NULL")

A: try this if you want to list it:
=QUERY({list1!A2:B; list 2!A2:B};
 "where Col1 matches '"&TEXTJOIN("|"; 1; list2!A2:A)&"'")

if you want to sum it try:
=QUERY({list1!A2:B; list 2!A2:B};
 "select Col1,sum(Col2)
  where Col1 matches '"&TEXTJOIN("|"; 1; list2!A2:A)&"'
  group by Col1
  label sum(Col2)''")


text:
Q: Hello i want to copy a character to a 2D array, but the second char wipes the first i am making a hangman game and the only thing i have left to do is copy the letters which have been inputted into a 2d array or 1d.
I have tried both and i am getting nowhere, using strcpy, strncpy, memcpy.
 char letterAttempt[26]={0};
                cin >> letterAttempt;

                char letterGuessed[26];

                memcpy (&letterGuessed,letterAttempt,sizeof(letterAttempt));

cin >> letterAttempt;

                char letterGuessed[26];

                strcpy (letterGuessed,letterAttempt);

I have been trying loads of variations, i have been through the debugger and the initial value goes there as soon as i enter the next it deletes the first and replaces it with the second.
I am not sure what i am doing wrong.
Thanks for reading.

A: You need to store each guess in a different index in the array.
char letterAttempt;
char lettersGuessed[26];
int numberOfAttempts = 0;

// Loop round here
    cin >> letterAttempt;

    // Check for duplicate guesses here?

    // This places the new guess in the numberOfAttempts-th place in the array ...
    lettersGuessed[numberOfAttempts] = letterAttempt;
    // and increments the number of guesses counter, ready for the next guess.
    numberOfAttempts++;

//  Check for correct answer, etc.


text:
Q: @Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW) not working as expected I have a usecase as explained below which I am trying to accomplish using transaction in SERIALIZABLE or REPEATALBE READ ISOLATION.
It is a bookstore system. Simplest with no user management and price deduction constraint.  The book store count of copies with it.
For each order request, I need to check the count of copies available and deduct it by 1 if it is > 0.
For this, I tried to use transaction in which I
1. read the book object and get count
2. if count > 0 updates the count ( count -1 ) in db.
Both of these have to be done in a single transaction to confirm atomicity/ consistency.
I have written this method in my spring boot service :
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRES_NEW)
    @Override
    public Book updateBookQuantity(String isbn) {
        Book book = null;

        Optional<Book> bookRecord = bookRepository.findById(isbn);
        try {
            System.out.println("threadname on hold= " + Thread.currentThread().getId());
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("threadname resumed = " + Thread.currentThread().getId());

        if (bookRecord.isPresent()) {
            book = bookRecord.get();
            System.out.println("book count == " + Thread.currentThread().getId() + "  "+ book.getQuantity());

            if (book.getQuantity() > 0) {
                book = bookRecord.get();
                book.setQuantity(bookRecord.get().getQuantity() - 1);
                bookRepository.save(book);
            } else {
                throw new BookOutOfStockException(book.getTitle());
            }
        }
        return book;
    }

Now where am I going wrong with this as when tried to run it using Rest api ( hit 2 times simultaneously) . Both the threads run parallely, both read the count as 1  and updated it to 0.
Ideally one should have passed and other should have thrown the BookOutOfStockException exception.
I have not configured anything specific to transaction manager, its all handled by spring boot only.
Where is this code going wrong ? Are configuration the reason for this?
Note : using spring-data-jpa ,  database : mysql

A: Using InnoDB engine resolved the issue. To change the engine, use the correct dialect .
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
MyIASM does not support transactions. so that is the reason why no transactions are getting created in the above problem.
Innodb supports transaction and foreign key as well.


text:
Q: OpenCV4Android conversion from MatOfKeyPoint to MatOfPoint2f I am trying to use OpenCV for Android (OpenCV 2.4.3)
I am writing a program to track keypoints. I am trying to use FeatureDetector to detect keypoints and then Video.calcOpticalFlowPyrLK
to track them.
The question that has me stumped is that the FeatureDetector function returns a MatOfKeyPoint while calcOpticalFlowPyrLK takes a MatOfPoint2f.
Note that MatOfKeyPoint is different from MatOfPoint (Conversion from MatOfPoint to MatOfPont2f is straightforward).
Here is my code so far:
//Feature detector for LKT flow estimation
FeatureDetector cvFeatureDetector;
//Vector of keypoints
MatOfKeyPoint keypoints;

...
...

//intitialize detector
cvFeatureDetector = FeatureDetector.create(FeatureDetector.GFTT);

keypoints = new MatOfKeyPoint();

...
...

//mPrevImgMat is a grayscale image - previous frame
//mCurrentImgMat is a grayscale image - current frame

//Run feature detector in previous image
cvFeatureDetector.detect(mPrevImgMat, keypoints);

MatOfPoint2f keypointsFound = new MatOfPoint2f();
MatOfByte keypointsStatus = new MatOfByte();
MatOfFloat err = new MatOfFloat();
Size winSize = new Size(25,25);
int maxLevel = 3;

//Optical flow to find keypoints in current image
Video.calcOpticalFlowPyrLK(mPrevImgMat, mCurrentImgMat, keypoints,
            keypointsFound, keypointsStatus, err, winSize, maxLevel);

//Obviously "keypoints" in the line above does not work. How does one covert
//keypoints to MatOfPoint2f?

Things I have tried unsuccessfully so far:
(1) keypoints.convertTo()
(2) Creating a vector from keypoints and then trying to populate a vector of Point Vector pointList. Then typecast to MatOfPoint2f when calling flow funciton
 (MatOfPoint2f) pointList
(3) Trying to populate a MatOfPoint2f from scratch. Cant figure out how to do this
(4) Using fromArray method in MatOfPoint2f - Not sure what this method does. Documentation is blank for this method. Am I missing something obvious?

A: Answering my own question... I got the answer in another forum. The link to that discussion is below
http://www.answers.opencv.org/question/6206/opencv4android-conversion-from-matofkeypoint-to/


text:
Q: Birthday field doesn't work I need a birthday field with format "0000/00/00". I have one field with format "MM/DD/YYYY" but doesn't work in MySQL when I insert something.
There is the code:

    Date of Birth

       <input type="date" id="birthDate" class="form-control">

A: Your datetime format i.e. MM/DD/YYYY is different from the mysql default format. The default format is:
Y-m-d H:i:s

So change it to like:
date('Y-m-d',strtotime($yourDate));


text:
Q: How do I share user settings or files using the UserAppDataPath across builds? Right now when I release a new build of my .NET app, the UserAppDataPath path points to a new folder that includes the build number.

Documents and
  Settings\UserName\Application
  Data\Company\AssemblyName\1.0.0.0

I use this path as a convenient storage place for extended user UI setting files. Every time I release the user looses their previous UI settings.
Is it safe to trim off the \1.0.0.0 version number and use its root path? or is there a better way to store settings in a place that is always has write privileges?

A: AppSettings do support upgrades.  Have a look here.  Hopefully this points you in the right direction...

A: I am using the following code when retrieving custom data stored in potentially old folders from previous assembly versions:
    string suffix = "/MyUserSettings.dat";
    string folder = Application.UserAppDataPath;
    string filename = folder + suffix;

    if (!File.Exists(filename))
    {
        // Check whether an older folder from a previous version with appropriate user data exists
        DirectoryInfo[] directories = new DirectoryInfo(folder).Parent.GetDirectories("*", SearchOption.TopDirectoryOnly);
        for (int i = 0; i < directories.Length; i++)
        {
            if (File.Exists(directories[i].FullName + suffix))
            {
                filename = directories[i].FullName + suffix;
            }
        }
    }

    if (File.Exists(filename))
    {
        // load user settings from file
    }
    else
    {
        // use default settings
    }


text:
Q: How to enable a specific system audit policy in PowerShell in Windows 11? There doesn't seem to be a native PowerShell way to do this.
I want to enable this audit

I'm using PowerShell and sadly there is no auto-complete to help with it.
I've been searching and reading Auditpol documentation but can't figure out why i can't set this.
first I used this to get all the category and sub-category GUIDs
auditpol /list /subcategory:* /r

then tried this:
auditpol /set /category:{6997984A-797A-11D9-BED3-505054503030} /subcategory:{0CCE9225-69AE-11D9-BED3-505054503030} /failure:enable /success:enable

but it fails.
also tried this
auditpol /set /category:Object Access,{6997984A-797A-11D9-BED3-505054503030} /subcategory:{0CCE9225-69AE-11D9-BED3-505054503030} /failure:enable /success:enable

still fails.
so what is the correct syntax exactly? I have the names, I have the GUIDs, don't know why it's not working.
also how does the GUI work exactly? if i enable it successfully from command line, should I restart the system to see the effect in GUI? should I close and reopen it?
Oh and I want to set it for the entire system, not for a specific user.


text:
Q: Packaging Storyboards I am developing a WPF application which consists of a single window and many animations. These animations are split up into six of so different storyboards which work fine when placed in the  section. My problem is that I want to somehow take these storyboards and put them somewhere else, like in their own file. This produces less cluttered code and makes it reusable. I learned that storyboards can't reside in a ResourceDirectory but is there some other way of splitting storyboards that I don't know about?

A: You may consider creating a behavior to encapsulate these animations. What I normally do is, translate my storyboards into c# code, then put them into a behavior.
If you think translating these animations into c# is a bit of work you might also try putting your xaml code into a readonly string, something like this,
internal static readonly string MyStoryboard =
@"<Storyboard xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
    <DoubleAnimation Duration=""0"" To=""1"" Storyboard.TargetProperty=""(UIElement.Opacity)"" Storyboard.TargetName=""LayoutRoot"" />
</Storyboard>";

and then just use XmlReader.Load to load it. Something like this,
_storyboard = XamlReader.Load(Storyboards.MyStoryboard) as Storyboard;

Hope this helps. :)

A: Are we SURE Storyboards can't be in a ResourceDictionary?  I feel like I've done this myself.  Also, this.


text:
Q: Replacing strings in text files I'm trying to replace some text in a file. I need to change the number in the below string (spacing included):
 "2016101901   ; serial number"

This number may vary, but the format is always the same (so it may be 2015100101, etc.).
I'm not sure how to approach this using wildcards...  I've tried below and it doesn't work:
{$_ -replace "*   ; serial number", "2016101902   ; serial number"}

Any ideas how I'd do this?

A: The -replace method is using regex. So use this:
{$_ -replace '^\d{10}(\s*;\s*serial number)', '2016101902$1'}


text:
Q: Getting exception while trying to compare enum(converted to string) and a string value obtained from search Getting

System.InvalidOperationException: 'The LINQ expression 'DbSet Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable()

while trying to compare two values - an enum(by converting to string) and a string keyword which I get from a search form in .NET 3 API
 query = query.Where(it => it.EnumType.ToString().ToLower().StartsWith(keyword.ToLower());

Help is appreciated.

A: Instead of doing this
it => it.EnumType.ToString()

I would suggest you do it the other way around by try converting
keyword.ToLower()

to enum.
You can try something like this.
private static bool IsDefined<T>(string value)
{
    return Enum.IsDefined(typeof(T), value);
}
public static T GetEnumByString<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value);
}

and then write the expression like this:
if (IsDefined<YourEnum>(keyword))
{
    query = query.Where(it => it.EnumType == GetEnumByString<YourEnum>(keyword));
}


text:
Q: Change value based on frequency in a column in given dataframe_Python I have dataset containing 180000 wind speed which are discrete ranging from 0 to 30. I want to change those discrete integer values to specified decimals based on the frequencies.
So, I need a code that searches for wind speed==i (i is integer ranging from 0 to 30) and replaces the first n1 (given by frequency) by a new value, next n2 by another value, and so on.
It should do this for all wind speeds.
Input:

*

*Dataframe with one column containing wind speed ranging from 0 to 30 (unsorted).

*Frequency [0,1820,2459,2745,2925,....]
Frequency is such that it's split into 5 of a segment. Meaning for each integer wind speed, it is to be replaced by new dataset based on frequency.
Ex: 0 to be replaced by 0,0.2,0.4,0.6,0.8. The number of occurence depend on frequency.
1 to be replaced by 1,1.2,1.4,1.6,1.8 and so on

*New dataset=[0,0.2,0.4,0.6,0.8,1,1.2,...]
So, for wind speed==0, it should replace first 1820 (occurence of 0) by 0.2, next 2459 occurence by 0.4, next 2745 by 0.6, and final 2925 by 0.8.
For new dataset 1 to 1.8, replace wind speed==1 based on frequency specified.
For wind speed==1, it should take new dataset value>1. See attached image for further clarity.

Output:
Discrete wind speed integer 0 to 30 replaced by 0.2,0.4,... (0.2 increment) based on frequency.
Note: The dataframe is unsorted and I would like to keep it that way.
Dataset sample

A: This should work. It may not be very efficient in terms of computation, however it does the work.
import pandas as pd
import numpy as np
speeds=[0]*5 + [1]*5 + [2]*5 + [3]*5 + [4]*5 + [5]*5

#update the frequency with the actual frequencies
df=pd.DataFrame({'Speed': speeds ,  'v':np.r_[0:30]*0,
                'frequency': ([0, 1820, 2459, 2745, 2925] + [1]*25)})

#Need to update the keys of the dictionary below accordingly

dict={0: {0:0, 1820:0.2, 2459:0.4, 2745:0.6, 2925:0.8  },
      1: {5:1.0, 6:1.2, 7:1.4, 8:1.6, 9:1.8 }
}

for key1 in dict:
    for key2 in dict[key1].keys():
        df.loc[ (df['Speed']==key1) & (df['frequency']==key2), 'v']= dict[key1][key2]

print(df)


text:
Q: How to perform full index refresh in solrcloud I am evaluating SolrCloud and am wondering if anyone can comment or provide a link on how to perform full-indexing in SolrCloud. Due to dictionary changes and so on, I need to build the index from scratch periodically and it is not very clear to me how I can do that. Should I have multiple clusters?

A: My solution for now is to build a new cluster on the fly (I am using EC2) for full refresh and then swap with the cluster in action.

A: I don't think creating a new cluster periodically and swapping it up is a solution to this problem.I understand you can use ELB for this purpose but still it's not the way to go.
Why can't you reindex your data periodically on the same cluster.Just use a clean attribute alongside your regular indexing command.


text:
Q: Not able to detect Persistence.xml i have 3 days searching for a solution ,but nothing helpful,
i want to deploy an MAVEN Web project ,this Web project contains a dependency of an EJB maven project(i use the MAVEN POM EDITOR to add this dependency).. when i make a MAVEN INSATALL to both projects every thing is fine..
But when i try to deploy the WEB maven project ( i copy the WAR ,then i paste it into the stadlone deployement Folder of my Jboss 7.0.2)
i get an error relating to the Persistence.xml caused by
 Can't find a deployment unit named ModuleEjbPU at deployment "GestionReclamationWeb-1.0-SNAPSHOT.war

i tried to put the folder META-INF web.xml in the WEB content ,src,lib
i tried also to remove the EJB dependecy and put the jar (of the EJB project) into meta inf lib
i feel like the persistence.xml is not found on the war of my web project
if u want to me to provide code i readdy ..i need help..thank you

A: You should place the persistence.xml at the WEB-INF/classes/META-INF/persistence.xml as mentioning at Where to put persistence.xml in web app?
By using the Maven way, the persistence.xml should be placed at src/main/resources/META-INF/persistence.xml
I hope this may help.

A: Your persistence unit is configured for use in resource local mode, but you need to configure it for use in a container. In order to make it work:

*

*Configure a datasource in your container, see this.

*Change the persistence definition like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="ModuleEjbPU" transaction-type="JTA">
        <jta-data-source>name</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <!-- Indique a Hibernate de (re-)créer la BDD au lancement de l'application -->
        <property name="hibernate.hbm2ddl.auto" value="create" />
    </persistence-unit>
</persistence>

Where I have <jta-data-source>name</jta-data-source>, replace name with whatever JNDI name you come up with in 1.
Voila, assuming other problems won't come up.


text:
Q: stacking pages in SPA, good idea or bad? I've created a framework in javascript for my personal single page applications, and I'm trying to add the stacking page feature to it.
if you have ever worked with android, you have seen that every new activity or page that is created in android, pushes the previous one back in a stack that can be accessed once the user presses the back button, just like the history in a browser.
the only difference is that in android the page that has been pushed to stack, stays there until the OS runs out of ram or something, but in browser the page gets destroyed no matter what.
now, in my framework, I have come up with a very simple soloution to keep pages in memory so that when user presses the back button, instead of loading data from server, I just find the page in the stack and if it exists, I just bring it to the front and push the current page back to the stack.
but there are some issues with this method:

*

*if you keep the stacked page in a javascript variable or you keep it in the DOM and just make the display: none; style applied to it, bringing it to the front and make it visible requires painting the whole page again and if the page is too large, this means a lot of process and makes the transition between pages extremely slow, specially if you have some animation going on while page transition.

*and if the stacked page is visible, and just pushed back using z-index, then the scrolling will cause problem, as the scroll for the previous pages are still available. and if you make the pages overflow: hidden; then still if you stack multiple pages, the scrolling becomes very slow and choppy because the browser has to scroll over multiple layers of painted pages.
and so my question is, is it even a good idea to stack pages with these problems?
or is it just not meant to happen in browsers yet?

A: Depending on your SPA I don't think it is a good idea to keep all pages in the DOM and hide them with display: none; or a different z-index. What you could try to do is to keep the state / the information of the page in a variable and remove all related elements from the DOM. When the user is going back one page you recreated the elements with the information you previously stored in a variable. This way you prevent to load information from the server and you don't have any problems with going back to any state.
You might be able to optimize it even further by keeping the last page in the DOM and simply hide it and keep the state of the pages before in a variable.


text:
Q: Shell script to run Linux command on multiple servers command by command I have a scenario:
My system has 2 servers: server_A and server_B
On server_A I create a shell script to execute commands on server_A and server_B by this flow:

*

*Run command1 on server_A and wait for completion.

*Run command2 on server_B and wait for completion.

*Run command3 on server_A and wait for completion.

(etc.)
Is there any good solutions for this case?
Thank you a lot.

A: You can just make a script on server_A with :
command1

ssh server_B command2

command 3


text:
Q: Creating a proxy object on the array with data downloaded from api I don't know why after saving the data downloaded from api to the table, the table is closed in the proxy object.
data() {
    return {
      date: [],
  },

async dataToChart(code){
   try{
      const response = await fetch(`https://api.covid19api.com/total/country/${code}`);
      const data = await response.json();

      data.forEach((el, i) => {
      if(i > 250){
        this.date.push(el.Date)
      }
    });
    }catch(error){
       console.log(error);
    }
  },

and when I pass this table to a child component and display it there using console.log, the proxy object pops up:
Proxy {}
    [[Handler]]: Object
    [[Target]]: Array(49)
    [[IsRevoked]]: false

A: This is not with your code or API, This(Proxies) is how Vue3 observes the data properties. Mostly all properties are converted to Proxies As far I know. If you want to know why Proxies being used, you can watch this video, as Evan You(The creator of Vue) explains in a better way!! :-)
Proxies let's you intercept the object changes and do any actions accordingly.
To understand more about Proxies and stuff, you need to understand how Vue reactivity works.
As per MDN docs:

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.


text:
Q: PyQt: how to display a treeview or other complex widget as tooltip I'm working on a PyQt project. I have a map with points on it (The map is a QGraphicsScene and my points are QGraphicsEllipseItem).
I would like to display some informations on the points when they receive a hover event.
The information will be: a picture, some text and a treeview fill with data.
I don't want to open a new window, I want it to float over the map exactly how a tooltip will do.
I don't know how to do it, I can't find any widget who fill my needs.
Thank you for any help !

A: Create a new widget/window with windowflag Qt::ToolTip. According to the docs Qt's tooltips are nothing else. http://doc.qt.io/qt-5/qt.html#WindowType-enum


text:
Q: Migrating to NUnit from SpecRunner - Parallels Execution with Selenium I am migrating my test framework to NUnit from SpecRunner since SpecRunner is not longer maintained.
So far i am able to run the tests in parrallel by using the assembly code [assembly: Parallelizable(ParallelScope.Fixtures)]
However I am using Selenium to run my UI tests, currently when i run the tests only one browser instance in open (just testing on Chrome) for the two tests causing one of them to fail.
In SpecRunner I could specify the number of threads by specifying them in the default.srprofile file using the testThreadCount attribute.
<Execution stopAfterFailures="0" retryFor="Failing" testThreadCount="3" testSchedulingMode="Sequential" />

And that would open 3 instances of Chrome locally on my machine, and on the CI machine.
My question is : Can I do something similar in NUnit3 to run a chrome instance per thread?
UPDATE
GetWebDriver.cs
    public class GetWebDriver
    {
        private static TestContextModified context;

        public static string url;

        public static IWebDriver WebDriver(string browserName)
        {
            IWebDriver driver;
            context = TestContextModified.GetContextInstance();
            url = context.AppSetting["url"];
            var seleniumHubURL = context.AppSetting["seleniumGridServer"];

            switch (browserName)
            {
                case "IE":
                    try
                    {
                        if (context.AppSetting["REMOTE"] == "true")
                        {
                            InternetExplorerOptions options = new InternetExplorerOptions();

                            options.AddAdditionalCapability("ignoreProtectedModeSettings", true);

                            options.AddAdditionalCapability(CapabilityType.AcceptSslCertificates, true);

                            options.AddAdditionalCapability(CapabilityType.IsJavaScriptEnabled, true);

                            options.AddAdditionalCapability(CapabilityType.Platform,
                                new Platform(PlatformType.Windows));
                            driver = new RemoteWebDriver(
                                    new Uri(seleniumHubURL), options.ToCapabilities(), TimeSpan.FromSeconds(600))
                            { Url = url};
                        }
                        else
                        {
                            return new InternetExplorerDriver(new InternetExplorerOptions { IgnoreZoomLevel = true }) { Url = url};
                        }

                        return driver;
                    }
                    catch
                    {
                        string strCmdText;
                        strCmdText = @"/C cd bin\Debug&taskkill /im IEDriverServer.exe /f";
                        System.Diagnostics.Process.Start("CMD.exe", strCmdText);
                        Console.WriteLine("Deleted Chromedriver becouse Exception was raised");
                        return null;
                    }
                case "Chrome":
                    try
                    {
                        if (context.AppSetting["REMOTE"] == "true")
                        {
                            ChromeOptions options = new ChromeOptions();
                            options.AddArguments("--window-size=1920,1080");
                            options.AddArguments("--start-maximized");
                            options.AddArguments("--headless");
                            options.AddArgument("--disable-gpu");

                            driver = new RemoteWebDriver(
                                    new Uri(seleniumHubURL), options)
                            { Url = url};
                        }
                        else
                        {
                            return new ChromeDriver { Url = url};
                        }

                        return driver;
                    }
                    catch
                    {
                        string strCmdText;
                        strCmdText = @"/C cd bin\Debug&taskkill /im chromedriver.exe /f";
                        System.Diagnostics.Process.Start("CMD.exe", strCmdText);
                        Console.WriteLine("Deleted Chromedriver becouse Exception was raised");
                        return null;
                    }
                case "Firefox":
                    try
                    {
                        if (context.AppSetting["REMOTE"] == "true")
                        {
                            FirefoxOptions options = new FirefoxOptions();
                            driver = new RemoteWebDriver(
                                new Uri(seleniumHubURL), options);
                            return driver;
                        }
                        else
                        {
                            return new FirefoxDriver { Url = url};
                        }
                    }
                    catch
                    {
                        string strCmdText;
                        strCmdText = @"/C cd bin\Debug&taskkill /im geckodriver.exe /f";
                        System.Diagnostics.Process.Start("CMD.exe", strCmdText);
                        Console.WriteLine("Deleted Chromedriver becouse Exception was raised");
                        return null;
                    }

                case string browser: throw new NotSupportedException($"{browser} is not a supported browser");
                default: throw new NotSupportedException("not supported browser: <null>");
            }
        }
    }
}

IntiliazeWebdriver.cs
 public class IntializeWebdriver

{
    public static IWebDriver driver;
    public IntializeWebdriver()
    {

    }
    public static IWebDriver webDriver()
    {
        if (driver == null)
        {
            driver = GetWebDriver.WebDriver("Chrome");
            return driver;
        }
        else
        {
            return driver;
        }
    }
}

And then in my steps:
  public class Steps: IntializeWebdriver
    {
        public Steps stepsTest;
        private ScenarioContext scenarioContext;
        public Steps(ScenarioContext _scenarioContext)
        {
            scenarioContext = _scenarioContext;
            stepsTest= new Step(webDriver());
        }
...

A: Kumar's answer leads you in the right direction. The web driver cannot be static, because then multiple threads (hence multiple tests) share the same instance of web driver. Instead, each scenario needs to create its own web driver instance and register it with the dependency injection framework. Unfortunately with how your code is currently, this will involve a good amount of refactoring. Despite this being a moderate amount of work, it is worth the effort.

*

*Initialize web driver in a [BeforeScenario] hook (see SpecFlow docs):
[Binding]
public class SpecFlowHooks
{
    private readonly IObjectContainer container;

    public SpecFlowHooks(IObjectContainer container)
    {
        this.container = container;
    }

    [BeforeScenario]
    public void CreateWebDriver()
    {
        // Initialize whichever web driver you want to use, however
        // you want to initialize it
        var driver = new ChromeDriver(...);

        // Register the web driver with SpecFlow's dependency injection framework
        container.RegisterInstanceAs<IWebDriver>(driver);
    }
}

*Refactor step definition classes to accept an IWebDriver object as a constructor parameter:
[Binding]
public class YouStepDefinitions
{
    private readonly IWebDriver driver;

    public YouStepDefinitions(IWebDriver driver)
    {
        this.driver = driver;
    }

    [Given("...")]
    public void GivenX()
    {
        driver.FindElement(...)
    }
}

This ensures you initialize one web driver per scenario, which should allow your tests to run in parallel.
At the end of the test, you can use an [AfterScenario] hook to destroy the driver and even take a screenshot:
[Binding]
public class SpecFlowHooks
{
    private readonly IObjectContainer container;

    ...

    [AfterScenario]
    public void CreateWebDriver()
    {
        var driver = container.Resolve<IWebDriver>();
        var photographer = (ITakeScreenShot)driver;

        // take screenshot with 'photographer' variable

        driver.Quit();
        driver.Dispose();
    }
}

A: Looks like this line is causing issue :-
public static IWebDriver driver;

Can you try by not making this static? I remember that I faced issue in parallel execution via Nunit when the driver was static.


text:
Q: Accessing index using list comprehesion in Python Hello recently I am trying to figure out list comprehension. And it looks like I suck at this :/
Here is my code I am trying to remake using list comprehension
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(61)]
del date_list[0]
date_list.reverse()

weekend = []
dates = []
for idx, val in enumerate(date_list):
    dates.append(str(val)[0:10])
    dates.append(str(val)[0:10])
    case = val.isoweekday()
    if case == 6 or case == 7:
        weekend.append(str(val)[0:10])

I looked it out how to use enumerate using this method and i found this:
[val for idx, val in enumerate(date_list)]
But i don't know how to continue this idea.
I would really appreciate some help :)

A: This
dates = []
for idx, val in enumerate(date_list):
    dates.append(str(val)[0:10])
    dates.append(str(val)[0:10])

can be reworked into list comprehension but beware that you might end with low readibility.
Consider similar but simpler case:
digits = [1,2,3,4,5,6,7,8,9]
numbers = []
for val in digits:
    numbers.append(val)
    numbers.append(val)
print(numbers)

output
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]

First step is to rework code such that is there is exactly one .append, in this case replace for loop with
for val in digits:
    for _ in range(2):
        numbers.append(val)

As you might check output is same, final step is to rewrite that into list comprehension which in case of nested for is shallow-deep to left-right thus outcome is
digits = [1,2,3,4,5,6,7,8,9]
numbers = [val for val in digits for _ in range(2)]
print(numbers)

This approach might be also used if you have more levels of nesting.

A: For list comprehension with if condition it should look like this [function(x) if condition(x) else other_function(x) for x in list]
So for your case, I would say:
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(1,61)]
date_list.reverse()

weekend = [date.strftime("%m/%d/%Y, %H:%M:%S")  for date in date_list if (date.weekday()==5 or date.weekday()==6)]
dates=[]
for date in date_list:
    dates.extend([date.strftime("%m/%d/%Y, %H:%M:%S"),date.strftime("%m/%d/%Y, %H:%M:%S")])

It's better to use strftime to transform datetime in the format you want: https://docs.python.org/fr/3.6/library/datetime.html#strftime-and-strptime-behavior


text:
Q: Getting only the necessary row I am working on a query for a project and sometimes the results have multiple rows for the same entity. What I need to do is:
If the results look like this:
   Type        |   Entity
-----------------------------
   TypeA       |      B. Didly

   TypeA       |      J. Hendrix

   TypeC       |      G. VanFleet

   TypeA       |      M. Manson

   TypeB       |      M. Manson

   TypeC       |      M. Manson

Then I need to choose TypeB over TypeA or TypeC for M. Manson
My results need to look like this:
   Type        |   Entity
-----------------------------
   TypeA       |      B. Didly

   TypeA       |      J. Hendrix

   TypeC       |      G. VanFleet

   TypeB       |      M. Manson

I am struggling with using a cursor or finding another option.
Basically if an entity has all three types, I need to only get TypeB for that entity.
There are 10 possible "types" from what I have been told. And the client has given me their ranking of those types. I am thinking a case statement to set the rank.

A: Assuming you also only want B when an entity has two types, or if they have A and C you don't care which one you get:
;WITH x AS
(
  SELECT type, entity, rn = ROW_NUMBER() OVER
    (
     PARTITION BY entity
     ORDER BY CASE type WHEN 'B' THEN 1 ELSE 2 END
    )
  FROM dbo.tablename
)
SELECT type, entity
  FROM x
  WHERE rn = 1;

If you care about the order of A and C in the case where those are the only two (in this example A will be returned):
     ORDER BY CASE type WHEN 'B' THEN 1 WHEN 'A' THEN 2 ELSE 3 END

A: Complete re-edit of my answer based on my deleted comment, "And why does TypeA appear twice in your sample output?"
create table testx (type varchar(10), entity varchar(20)) ;

insert into testx (type, entity)
select 'A' , 'Didly' union all
select 'A' , 'Hendrix' union all
select 'C' , 'VanFleet' union all
select 'A' , 'Manson' union all
select 'B' , 'Manson' union all
select 'C' , 'Manson' ;

 select * from
 (
 select a.type, b.entity, b.ent_count,
 row_number() over (partition by b.entity order by b.entity) as rownum
 from testx a
 inner join
    (select entity, count(*) as ent_count
     from testx
     group by entity
    ) b
  on a.entity = b.entity
 )y
 where ent_count = 1 or rownum = 3 ;

---- Much simpler, this time using count(*) as an analytic function ---
 select * from
 (
  select a.type, entity,
 row_number() over (partition by entity order by entity) as rownum,
 count(*) over (partition by entity order by entity) as ent_count
 from testx a
 )x
 where ent_count = 1 or rownum = 3 ;


text:
Q: Setting function if cell contains string I had a function that worked fine - it checks the title of a cell for a ipy.datagrid and then sets the color of the cell based on the header
def header_bg_color(cell):
    if cell.value in ['Portfolio -30%','Change -30%']:
        return '#f3722c'
    elif cell.value in ['Portfolio -20%','Change -20%']:
        return '#f8961e'
    elif cell.value in ['Portfolio -10%','Change -10%']:
        return '#f9844a'

I have changed the name of my 'Portfolio -10%' column to 'Portfolio -10%' + igwd_change ...where igwd_change is a variable I define earlier.
I thought that simply changing the line from
elif cell.value in ['Portfolio -10%','Change -10%']:
    return '#f9844a'

to
elif cell.value in ['Portfolio -10%' + igwd_change,'Change -10%']:
    return '#f9844a'

Would work, but I get an error
Py2VegaNameError: name 'igwd_change' is not defined, available variables are ['cell', 'default_value', 'index'], note that only a subset of Python is supported
However igwd_change is defined (cell above this one has definitely been run) and I can call the variable in the cell after to check.
Edited to show cell working as desired (Portfolio -10%) yet cell Portfolio 0% (-3.2%) which is Portfolio 0% + igwd_change not having the required vega function applied

A: you need to pass igwd_change variable inside the header_bg_color function as a parameter
def header_bg_color(cell):

should be
def header_bg_color(cell, igwd_change):

Now when calling this function, make sure you pass the same variable
header_bg_color(cell, igwd_change)

or
header_bg_color(cell, "any custom parameter you want here")


text:
Q: When drag-copying formula cells to the right, table-references are changed I have a simple Excel table containing a formula that is referencing columns in another table, and is using the automatic table-range-names (not sure what they're correctly called)
=A1 + SUM(MyOtherTable[ColumnA]) * SUM(AnotherTable[AnotherA])

The problem is that when I copy that formula to the right, the column references all shift right too, so becoming:
=A1 + SUM(MyOtherTable[ColumnA]) * SUM(AnotherTable[AnotherA])
=B1 + SUM(MyOtherTable[ColumnB]) * SUM(AnotherTable[AnotherB])
=C1 + SUM(MyOtherTable[ColumnC]) * SUM(AnotherTable[AnotherC])

How can I stop this? I can't find an equivalent to the dollar-references like $A$A. Note that I do want the normal behaviour for the RC references.
The only alternative I can think of is to created named ranges for the columns in the other tables, although this seems to defeat the object to some extent of the table-ranges.

A: Instead of dragging, try copy-and-pasting.  That works in Excel 2007/2010.

A: The way to specify a whole column is with the reference
$A:$A

That will give you a fixed whole-column reference.
Personally, I find Excel much easier to work with when I switch to the R1C1 reference format (Tools/Options/General). Then you can refer to a fixed column as:
C1

Or a relative column as
C[1]
C[-5]

This mode makes it very easy to refer to the current row or column:
RC2

would be the cell on current row, column 2.

A: If you still need the answer modify your formula as below:
A1 + SUM(MyOtherTable[[ColumnA]: [ColumnA]]) * SUM(AnotherTable [[AnotherA]: [AnotherA]])


text:
Q: Wildfly 12 - EJB invocations from remote servers under domain controller (Elytron) I am following the instructions from this link: https://developer.jboss.org/people/fjuma/blog/2017/09/08/getting-started-with-ejbs-and-elytron-part-2
Trying to replicate those configurations under domain controller but without success.
I have two server groups, one is client of other. But the servers of server group "B" still unable to lookup the remote EJB from servers of server group "A"
I tried to configure the servers with jboss-cli.sh from domain controller. Applying the configurations at the corresponding profiles.
Ex:
From Domain Controller's jboss-cli.sh:
/profile=my-custom-profile-full-ha/subsystem=elytron/authentication-configuration=ejb-auth-config:add(authentication-name=ejb, credential-reference={clear-text="ejbejb"})

and so on...
The socket-binding-group is defined at domain.xml as well.
But my client server still getting errors when lookup the remote EJB.
Is there other configuration for servers running under domain controller to get remote invocations work?
The error:
javax.ejb.NoSuchEJBException: EJBCLIENT000079: Unable to discover destination for request for EJB StatelessEJBLocator for "/portal/SampleEJB", view is interface my.company.ejb.interfaces.SampleEJBRemote, affinity is None

Thanks!


text:
Q: How do I use CSS3 transitions to fade in on hover? I set this up: http://jsfiddle.net/yWHfK/
However, I can't get it to fade in on hover. Any ideas where I went wrong?

A: You've listed your transition element as color (which will transition the text color), did you mean to make it background-color?
ie
a { -moz-transition:background-color .2s ease-in;-o-transition:background-color .2s ease-in;-webkit-transition:background-color .2s ease-in;background-color:#31c3e7;text-decoration:none }
#post-list { color:#fff;text-align:center }
#post-list li { border-bottom:1px solid #4d4949 }
#post-list li a { color:#fff;display:block;font-size:16px;padding:20px 0 }
#post-list li a:hover, #post-list li.current a { background-color:#3c3636 }
#post-list li a:active {  }
#post-list li a span { font-size:12px }

That works for me in Chrome.

A: you ought to do this:
.class li a:hover{
    color: #fff;
}

you can change  the #fff to whatever colour you want.


text:
Q: better way to notify an inner(nested) recyclerview adapter? I have an Activity that has a RecyclerView and a RecyclerView.Adapter (let's call it adapter1). inside of this Adapter, I have another RecyclerView and another Adapter(adapter2). What I want to do is that there might be some info passed to onActivityResult and needs to be passed to the inner adapter2. What I'm doing is creating a method in both adapters and chain them up from activity all the way to adapter2. I feel this way is a bit stupid. Is there any other way to achieve this? I did try EventBus but looks like I'm not able to subscribe a method in an adapter.
Thanks!
Edited
everything works fine. I'm just looking for a better solution if there's any. the complete code will be too massive to post, so I'll just post some snippet here.
Activity A {
    Adapter adapter1;

    onActivityResult() {
        adapter1.onEvent();
    }
}

Adapter1 {
    Adapter adapter2;

    public void onEvent() {
        adapter2.onEvent();
    }
}

Adapter2 {
    public void onEvent() {
        notifyDataSetChanged();
    }
}

yes, info will update the lists.