text:
Q: string input issue c++ using character array getting runtime error on codeforces 1167a
http://codeforces.com/problemset/problem/1167/A
string input issue
int n;
int temp=0;
cin>>n;
//n++;

while(n--)
{
    int nn;
    cin>>nn;
    //cout<<n<<endl;

    if(nn<11)
    {
        cout<<"NO"<<endl;
        continue;
    }

    char* str = new char[nn+1];
    cin>>str;

    for(int i=0;i<=(nn-11)+1;++i)
    {
        if(str[i]=='8')
        {
            cout<<"YES"<<endl;
            temp=8;
            delete[] str;
            break;

        }

    }

    if(temp!=8)
    {
        cout<<"NO"<<endl;
    }

    temp=0;

}

input
15
11
88888888888
100
8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
100
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
100
1111111111111111111111111111811111111111111111111111111111111111111111111111111111111111111111111111
100
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111181111111111
100
111111111111111111111111111111111111111111111111111111111...
output
YES
YES
NO
YES
YES
YES
YES
YES
NO
runtime error

A: You are mixing things up.
There's two ways you could handle this, but you are doing half of one and half of the other.
You could use dynamic allocation
char* str = new char[nn+1];
...
delete[] str;

Or you could use a variable length array (VLA).
char str[nn+1];
...

Your code uses a VLA but then tries to delete it as if you are using dynamic allocation.
Of the two alternatives use dynamic allocation, VLAs are not legal C++, even though some compilers accept them.
A better C++ solution would be to use a std::string. Then the allocation will be handled for you.


text:
Q: How to debug maven surefire tests running in a docker container? I have a maven project that contains integration tests and I use the surefire plugin. I can run the tests with
mvn clean package

and that works fine. I can also remote debug the integration tests using intellij. To do so I execute
mvn clean package -Dmaven.surefire.debug

and in Intellij I create a Run/Debug Configuration of type "Remote" setting Host to localhost and Port to 5005. As soon as the console prints
Listening for transport dt_socket at address: 5005

I start the remote debugging in intellij and everything works fine.
The thing is I want to execute the integration tests inside a docker container and especially also debug them inside the container. I have created a docker image with java, maven and all the other stuff my application needs. In the Entrypoint I start my application and then I start the integration tests with
mvn clean package -Dmaven.surefire.debug

inside the docker container. I run the docker container with the option
-p 5005:5005

to open that port for remote debugging. When running the container, at some point I can see the console output
Listening for transport dt_socket at address: 5005

But when I start the remote debugger in intellij, it won't connect but instead gives me the following error message
Error running '...':
Unable to open debugger port (localhost:5005): java.net.SocketException "Connection reset"

and if I try again to start the debugger i get the error message
Unable to open debugger port (localhost:5005): java.net.IOException "handshake failed - connection prematurally closed"

But the port should be open, because executing
nc -zv localhost 5005

in the host (netcat) results in
Connection to localhost 5005 port [tcp/*] succeeded!

But if execute the same netcat command inside the docker container it results in
localhost [...] 5005 (?) : Connection refused

Can anybody tell me what I am doing wrong? I don't insist on debugging with intellij, but being able to debug the tests inside the docker container somehow would be amazing.

A: The answer actually can be found here: Remote debugging Java 9 in a docker container from IntelliJ IDEA
In my case this means, that running the tests with
mvn clean package -Dmaven.surefire.debug="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=*:5005"

solves the problem

redpajama_set_name: RedPajamaStackExchange


text:
Q: approaches to Apollonius circle problems I've been looking for solutions to finding the set of circles tangent to two other circles.  one circle can be inverted to a line, but two circles can be mapped to a line and a circle
or equivalently one circle tangent to three circles

has the Apollonius problems been approached from intersection theory. in this case CCC
Are they solvable from that perspective?  this looks like a very classical algebraic geometry problem about Mobius geometry.

A: Perhaps you are looking for a Steiner chain?

(Images (above & below) from Wikipedia.)

A: Two circles with different radii can also be mapped to two circles with the same radius by an inversion (or a möbius transformation in general). Then the family of tangent circles is easier to describe. Similarly one could send three circles of different radii to three circles of the same radii by an inversion (möbius also in general), as long as the circles are not too far apart from each other (this can be properly formulated).
In general the closest thing to what you are describing seems to me is the solution to the Appolonius problem via the methods of Lie sphere geometry (simply google it and you will find it). The idea is that the set of oriented circles (points being treated as circles of radius zero) lying in the two sphere form a 3 dimensional quadric in $\mathbb{P}(\mathbb{R}^{5,2})$ with a dot product of signature $+++--$. Two oriented circles are tangent when the dot product between their corresponding points in the model is zero (i.e. the vectors representing the points are orthogonal). Then three oriented circles if in general position form three points on the quadric, determining a projective two dimensional plane. The polar projective subspace to that plane with respect to the quadric (which is the orthogonal complement before projectivization) is a projective line. Depending on its signature, the line can intersect the Lie quadric in zero, one or two points, which are the solutions to the Appolonius' problem. Observe that the orientation of the circles is crucial. Möbius geometry is a sub geometry of Lie sphere geometry. I hope this helps.
Edit: Since you asked about the relation between the two nested circles (red and blue) and the number of black circles in the Steiner chain, here is a relation, if I have not made a mistake in my computations:
Let $R$ and $r$ be the radii of the larger circle and the smaller circle inside it respectively. Let $d$ be the distance between the centers of these two circles. Then one gets an $n$ chain that wraps around $m$ times whenever $$ \frac{R(d+r-x)}{(d+r)x-R^2} =\left( \sec\left(\frac{m}{n} \pi\right)+\tan\left(\frac{m}{n} \pi\right)\right)^2,$$
where $x$ is the larger solution of the quadratic equation
$$ (R^2-xd)(x-d)-r^2x=0. $$


text:
Q: Place Cursor at Mouse Position on Terminal with an Option+Click in terminal doesn't work In Ubuntu terminal I can see placing Cursor at Mouse Position on Terminal with an Option+Click works.
The same works in other linux terminal from Mac. For example reference : https://www.bollyinside.com/articles/place-cursor-at-mouse-position-on-terminal-with-an-optionclick/
Is there a way to achieve this in Ubuntu?

A: By the very nature of how terminals work, the cursor is "owned", controlled by the application that's running inside. The cursor denotes the next position where the application's output will be printed at.
Should you somehow forcefully modify this position in the terminal, unbeknownst to the application, most likely subsequent output printed by the application will corrupt the screen big time.
What a few terminal emulators do is that they try to guess what keypresses to synthesize towards the application, so that in response the application will end up moving the cursor to the location where you wish to.
Any such heuristic has obviously very limited use, and is likely to break pretty often. How would the terminal know which application is running? Using hacks like digging into /proc or equivalent, which stops working across an ssh, tmux or other similar layers? If it knows what application is running (e.g. a shell or a text editor), how would it know what state that application is in (e.g. is the shell running a command or waiting for you to type a command? If the latter, is it perhaps in some special mode of readline? If it's a text editor, are you editing a file or are you in some other mode (e.g. a command line, a dialog etc.)? Does it have split screen, and do you need to jump to a different panel?) Shall we begin to teach the behavior of some well-known applications to the terminal? Hopeless.
No wonder that only very few terminal emulators try to offer you this convenience feature. I haven't tried this feature yet in any of them, but I'm pretty sure I'd find a plethora of bugs in just a few minutes. It's impossible to reliably know which keypresses need to be emitted so that the applicaton's response will be to move the cursor to the spot you requested. Any work that any terminal offers you is necessarily a fragile guesswork.
I'm not sure what you mean by "Ubuntu terminal", but based on the tags of the question you probably mean GNOME Terminal. Like the majority of the terminals out there, GNOME Terminal doesn't attempt to address the impossible.
You should get familiar with the power features of the applications you're using. Does the application support mouse? Maybe you need to enable it, and then the application receives mouse clicks and most likely moves the cursor there. If not, are there any keyboard shortcuts that move the cursor in bigger steps? E.g. Ctrl+Left, Ctrl+Right to jump by words? Newer versions of bash and readline can jump up and down to the next visual row, which I've personally connected to Ctrl+Up, Ctrl+Down. Etc. There's no "one size fits all" solution for repositioning the cursor.

A: The terminal rxvt-unicode moves the cursor to the mouse position with Shift-Click.
This will behave exactly the same at Option-Click does in the Mac terminal.


text:
Q: Login Form header() shows blank page I created a login form that should direct the user to the page after sending the form but it just shows me a blank page
with a link of **http://localhost/Cisu/AccHolder/holderlogin.php
Login Form
<?php
session_start();
?>
<!DOCTYPE html>

            <title>Login</title>
            <link type="text/css" rel="stylesheet" href="css/login.css">

                <form method="" action="holderlogin.php">

                            <button class="profile__avatar" id="toggleProfile">

                            </button>

                                        <input type="text" id="user" name="user" class="input" required pattern=.*\S.* />
                                        Username

                                        <input type="password" id="pass" name="pass" class="input" required pattern=.*\S.* />
                                        Password

                                        <input id="Submit" name="Submit "type = "Submit" class="btn"/>

                </form>

holderlogin.php
<?php
ob_start();
session_start();

include('dbconn.php');// Database connection and settings

// checking the user

if(isset($_POST['Submit'])){

$user = mysqli_real_escape_string($con,$_POST['user']);

$pass = mysqli_real_escape_string($con,$_POST['pass']);

$sel_user = "select * from tbl_accholder where accholder_Username='$user' AND accholder_Password='$pass'";

$run_user = mysqli_query($con, $sel_user);

$check_user = mysqli_num_rows($run_user);

if($check_user==1){
while ($row = mysqli_fetch_array($run_user)) {
    $run_ID = $row['accholder_ID'];
    $run_user = $row['accholder_Username'];
}

$_SESSION['accholder_Username']= $user;
$_SESSION['accholder_ID']= $run_ID;

header( 'Location: MainMenu.php');

} else
                                echo "please wait while redirecting...";
                                echo "";
                                echo "";
ob_end_flush();
}

?>

A: Don't know if its causing your problem, but you have a leading space before the php declaration - this can be cause problems to the php rendering if you are setting header requests later in the code - there can be no characters rendered before the header request.
<?php

also you list the action of the form as "holderlogin.php"
but list the name of the file as "Holderlogin.php" - this might just be a typo when entering the code here but worth checking.

A: also - you have no method listed for your form, but are checking the $_POST array to check for "Submit". It should be:
<form method="POST" action="holderlogin.php">

A: You are checking whether $_POST['Submit'] is set.
However, in your form, the name attribute is Submit with an extra space:
<input id="Submit" name="Submit "type = "Submit" class="btn"/>

This might be the cause of the problem, since you said it shows me a blank page.


text:
Q: Steps of changing from 32-bit OS to 64-bit and changing RAM? My laptop is Lenovo T400, whose CPU is 64-bit and RAM is 1x2GB. When I bought it, it already had 32-bit Windows 7. Then I partition the hard drive and install 32-bit Ubuntu 12.04 alongside Windows 7.
Now I am going to reintall the Ubuntu part from 32-bit 12.04 to 64-bit (possibly the latest version), while still keeping 32-bit Windows 7.
I am also going to change my RAM from 1x2GB to 2x4GB.

*

*I heard that I have to make some change in BIOS (from a commend on
my another post, which has now been deleted). Do you know what
change it is? Is it for reinstalation of Ubuntu from 32-bit to
64-bit, or for changing RAM from 1x2GB to 2x4GB?

*What is the order of the following steps: change BIOS, reinstall
Ubuntu from 32-bit to 64-bit, change RAM from 1x2GB to 2x4GB?

Thanks!

A: No steps required really. I would load the system with the memory and then go ahead with the Ubuntu install. Keep in mind that Win 7 and Ubuntu 32 bit will load quite happily with 8 gigs of memory but at the most will only be able to access 4 gigs tops.
Consider upgrading your Win 7 to a 64 bit version too - just sounds like a waste to have a 32 bit OS on an 8 gig system.

A: No Bios changes required. simply goahead. probably this is the interface you're going to work with

Just Customize the existing ubuntu partition(meaning just delete and create again)
then just press next, next, next and you're there. you don't need to worry about bootloaders ubuntu GRUB will Take care of that. by the time you boot that will show you GRUB. hope you're familiar with that. in case any problem with boot order or GRUB just install EasyBCD http://neosmart.net/EasyBCD/
this allows you to Edit the boot order and more other things as well


text:
Q: linq get multiple values at certain conditions I am using this query to get the values in certain values on the basis of certain conditions..
for (int i = 0; i < 50; i++)
{
    DataRow dr = gridviewdt.NewRow();

    dr[0] = dt.AsEnumerable()
        .Where(l => l.Field<int?>("ID") == items[i].curing_id)
        .Select(l => l.Field<string>("description"))
        .First()
        .ToString();

    dr[1] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id
             select row).Count();

    dr[2] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id && row.Field<int?>("status") == 1
             select row).Count();

    dr[3] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id && row.Field<int?>("status") == 2
             select row).Count();

    dr[4] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id && row.Field<int?>("status") == 3
             select row).Count();

    griddt.Rows.Add(dr);
}

These above statements takes more time to execute the queries multiple times in the loop & also datatable dt contains hundreds of thousands of records. I want it to be something like
for (int i = 0; i < num_of_curing; i++)
{
    DataRow dr = gridviewdt.NewRow();

    dr[0] = dt.AsEnumerable()
        .Where(l => l.Field<int?>("ID") == items[i].curing_id)
        .Select(l => l.Field<string>("description"))
        .First()
        .ToString();

    data = dt.AsEnumerable().Where(l => l.Field<int?>("ID") == items[i].curing_id)
                .Select(g => new
                {
                    dr[1] = g.Count(),
                    dr[2] = (g.Field<int?>("status") == 1).Count(),
                    dr[3] = (g.Field<int?>("status") == 2).Count(),
                    dr[4] = (g.Field<int?>("status") == 3).Count()

                });

     gridviewdt.Rows.Add(dr);
}

Is it possible to write in above way or any other best possible manner ?

A: It is slow, because you are making several queries, while you can do the one.
This code will only make one query and store result in an array. Then, you can safely use this data.
Also, you don't need for loop, if i is limited to the count of items:
foreach (var item in items)
{
    DataRow dr = griddt.NewRow();

    var data = dt
        .AsEnumerable()
        .Where(l => l.Field<int?>("ID") == item.curing_id)
        .Select(l => new {
            description = l.Field<string>("description"),
            status = l.Field<int?>("status")
        })
        .ToArray();

    dr[0] = data[0].description;
    dr[1] = data.Count();
    dr[2] = data.Count(d => d.Status == 1);
    dr[3] = data.Count(d => d.Status == 2);
    dr[4] = data.Count(d => d.Status == 3);

    griddt.Rows.Add(dr);
}

A: You can use an anonymous object like this:
var data = (from row in dt.AsEnumerable()
            where row.Field<int?>("ID") == items[i].curing_id
            select new
            {
                dr1 =  row.Count(),
                dr2 =  (row.Field<int?>("status") == 1).Count(),
                dr3 =  (row.Field<int?>("status") == 2).Count(),
                dr4 =  (row.Field<int?>("status") == 3).Count(),
            }).FirstOrDefault();

And the populate your datarow like this
dr[1] = data.dr1;
dr[2] = data.dr2;


text:
Q: NSDictionary Posting Unicode Characters I need to post Unicode characters to a database. The database I am using receives a NSDictionary and stores that as a JSONObject.
The dictionary is created like:
NSMutableDictionary *messageDictionary = [[NSMutableDictionary alloc] init ];

[messageDictionary setObject:@"message" forKey:@"type"];
[messageDictionary setObject:@"È ê ü à ã" forKey:@"message"];

The database then stores the result as:
{
    type = message;
    message = \"\\U00c8 \\U00ea \\U00fc \\U00e0 \\U00e3\";
}

if I post just the string outside of the dictionary the database stores:
{
    message = È ê ü à ã
}

How do I prevent the NSDictionary from editing these characters and storing them the same way they are entered into a Text View. The same goes for when entering Emoji's into a Text View and sending that. The response I need stored is:
{
    type = messages;
    message = "È ê ü à ã";
}

A: Conversion from @"È ê ü à ã" to @"\U00c8 \U00ea \U00fc \U00e0 \U00e3" is not something NSDictionary does, so I would assume this is done by the JSON encoder.
I would expect the JSON decoder to put them back to their original form, so the answer is to use a good JSON decoder (by "good" I mean "one that works").
To quote an answer to this question:
2.5. Strings
The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
Any character may be escaped.


text:
Q: How can I hide a column of a  if a condition is met? I have a
 with several rows and columns. I want to hide the last column, if a specific variable foo in the code behind is -1.
Therefore, I cannot use CSS and the :last-child because in CSS, I do not have access to foo.
I tried to style the last column of a <colgroup> with <col style="@(foo == -1d ? "visibility: collapse" : "")"> but that did not collapse the entire column but still showed super- and subscripts   and sub.
Of course, I could replace

with

    @if (foo != -1)
    {

    }

at every row but I hope, there is a cleaner way.

A: You can use the @if (foo...) check to optionally define a CSS class. Make sure to use a class name that is unique given other CSS that may exist.
@if (foo == -1)
{

}
...

    A
    B
    X

    C
    D
    Y

Note that this will always render the last  of every
. You'll need to make sure that those cells (and specifically their content) do not cause errors when rendered.
Or you can use an inline style:
@{
  var tdStyle = foo == -1 ? "display: none;" : "";
}
...

    A
    B
    X

    C
    D
    Y

A: You can use the Blazor components for this:
MyLastColumn.razor
@if(Foo != -1){
  @ChildContent
}

@code {
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    [Parameter]
    public int Foo { get; set; }
}

And then use it:
<MyLastColumn Foo="@foo">content</MyLastColumn>


text:
Q: Advanced SQL condition based query building I'm trying to write a complex SQL query based on a condition. If the condition is satisfied, it should run the query with one condition, if not then another condition. How is this possible in SQL?
SELECT distinct support_id AS object_id, 2 as app_context_id,
            0 as domain_cdc_id, 'S' as object_type,
            'NEW' as domain_cdc_status, 1 as attribute_group_num,s
            sysdate as created_on
FROM fdrdbo.v_facility_support
WHERE support_version_valid_from_dt = to_date('${passedInVar}', 'yyyy/mm/dd')

IF ${passedInVar} is null, then I want to use the following WHERE condition instead:
WHERE SYSDATE BETWEEN support_version_valid_from_dt AND support_version_valid_to_dt

Thank you in advance.

A: This will work in Postgresql (to_date exists in Postgresql)
where
    support_version_valid_from_dt = to_date(:passedinvar, 'yyyy/mm/dd')
    or
    (
        sysdate between support_version_valid_from_dt and support_version_valid_to_dt
        and
        :passedinvar is null
    )

Notice that I'm assuming you are using a driver to pass the variable and not doing simple string substitution.
to_date will return null for a null argument. In Postgresql a comparison to null will return null. The second condition will only be checked if the passed variable is null.


text:
Q: Justify text in labelitemi I have used the below command to change the size of the bullet
\renewcommand{\labelitemi}{{\tiny$\bullet$}}

The text inside the bullet is not justified. How can I justify the text within the bullets.
Also, I have many bullet points, so I want to declare it globally, so that I do not have to repeat it again and again for each bullet.

A: This uses enumitem and it's label=... feature within \setlist, which does not require to set the label each time. It's set for all itemize environments then. If this is not requested, a new list can cloned.
\documentclass{article}

\usepackage{enumitem}

\setlist[itemize,1]{label={\tiny\textbullet}}

\usepackage{pgffor}
\begin{document}

\begin{itemize}
\foreach \x in {1,...,15} {
\item \x
}
\end{itemize}

\end{document}

A: Smaller bullets can indeed be a good stylistic choice. However, just \tiny\textbullet (that's essentially the same as \tiny$\bullet$) will print the small bullet too low.
One can raise it automatically by exploiting \vcenter:
\documentclass{article}

\renewcommand{\labelitemi}{%
  $\vcenter{\hbox{\tiny\textbullet}}$%
}

\begin{document}

Compare $\vcenter{\hbox{\tiny\textbullet}}$ with \textbullet

This is an itemized list:
\begin{itemize}
\item A
\item B
\end{itemize}
and this is another one
\begin{itemize}
\item A
\item B
\end{itemize}
where you see that redeclaring \verb|\labelitemi| is
not necessary.

\end{document}

A more flexible command that allows the bullet to change its size in different contexts (say for itemized lists in footnotes).
\documentclass{article}
\usepackage{pict2e}

\renewcommand{\labelitemi}{\smallerbullet{0.3em}} % <-- fix the diameter here
\DeclareRobustCommand{\smallerbullet}[1]{%
  $\vcenter{\hbox{%
    \setlength{\unitlength}{#1}%
    \begin{picture}(1,1)
    \put(0.5,0.5){\circle*{1}}
    \end{picture}%
  }}$%
}

\begin{document}

\begin{itemize}
\item 0.1em \smallerbullet{0.1em} and \textbullet
\item 0.15em \smallerbullet{0.15em} and \textbullet
\item 0.2em \smallerbullet{0.2em} and \textbullet
\item 0.25em \smallerbullet{0.25em} and \textbullet
\item 0.3em \smallerbullet{0.3em} and \textbullet
\item 0.35em \smallerbullet{0.35em} and \textbullet
\end{itemize}

This is an itemized list:
\begin{itemize}
\item A
\item B
\end{itemize}
and this is another one
\begin{itemize}
\item A
\item B
\end{itemize}
where you see that redeclaring \verb|\labelitemi| is
not necessary.

\end{document}

Once you have decided for the diameter that suits your taste, set it in the redefinition of \labelitemi. The top itemized list has a comparison of the new bullet with the standard one to help in the choice.


text:
Q: Data merge without Object ID in mongoose I'm using mongoose.
Just like 'Mysql Join',
I want to get the data that merge the parents and children collection below.
Parent
[
    {
        type: "A",
        results: [
            {
                "id": 111111
            },
            {
                "id": 222222
            }
        ]
    },
    {
        type: "B",
        results: [
            {
                "id": 333333
            },
            {
                "id": 444444
            }
        ]
    }
]

Child
[
    {
        dataId: 111111,
        results: [
            { "status": { key: "value" } }
        ]
    },
    {
        dataId: 222222,
        results: [
            { "status": { key: "value" } }
        ]
    },
    {
        dataId: 333333,
        results: [
            { "status": { key: "value" } }
        ]
    },
    {
        dataId: 444444,
        results: [
            { "status": { key: "value" } }
        ]
    },
]

Because ObjectId cannot be inserted,
it seems that it cannot be processed using the population method.
I want to merge the two data like Join in MySQL.
like below
Parent.find()
[
    {
        type: "A",
        results: [
            {
                "id": 111111,
                results: [
                    { "status": { key: "value" } }
                ]
            },
            {
                "id": 222222,
                results: [
                    { "status": { key: "value" } }
                ]
            }
        ]
    },
    {
        type: "B",
        results: [
            {
                "id": 333333,
                results: [
                    { "status": { key: "value" } }
                ]
            },
            {
                "id": 444444,
                results: [
                    { "status": { key: "value" } }
                ]
            }
        ]
    }
]

A: you could do this from javascript directly
first you get the parent from mongoDB
( use mongoose find method)
let parents = [
  {
    type: "A",
    results: [
      {
        id: 111111,
      },
      {
        id: 222222,
      },
    ],
  },
  {
    type: "B",
    results: [
      {
        id: 333333,
      },
      {
        id: 444444,
      },
    ],
  },
];

then you get the child from the database
let children = [
  {
    dataId: 111111,
    results: [{ status: { key: "value" } }],
  },
  {
    dataId: 222222,
    results: [{ status: { key: "value" } }],
  },
  {
    dataId: 333333,
    results: [{ status: { key: "value" } }],
  },
  {
    dataId: 444444,
    results: [{ status: { key: "value" } }],
  },
];

and the treatement to merge the parents with the children will be something like this

for (let parent of parents) {
  for (let objectId of parent.results) {
    for (let child of children) {
      if (child.dataId === objectId.id) {
        objectId.results = child.results;
        break;
      }
    }
  }
}

A: You can use this query:

*

*$unwind to get every result from the array to merge with the Child dataid.

*$lookup which is the "join" in mongodb. Here query is mergin field id into results from the Parent with dataId from the Child.

*$unwind again because $lookup creates an array.

*$group to group the values according the id.

*$project (this stage is optional) to not shown fields you don't want.

yourParentModel.aggregate([
  {
    "$unwind": "$results"
  },
  {
    "$lookup": {
      "from": "Child",
      "localField": "results.id",
      "foreignField": "dataId",
      "as": "child_results"
    }
  },
  {
    "$unwind": "$child_results"
  },
  {
    "$group": {
      "_id": "$_id",
      "type": {
        "$first": "$type"
      },
      results: {
        "$push": "$child_results"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "results._id": 0
    }
  }
])

Example here


text:
Q: How is a thread pool able to re-use threads? Our current course assignment specifies that we are supposed to create a manager for a thread pool using the "Object Pool Manager" design pattern which spawns a set amount of threads. The ownership of these threads shall be transferred to the client and then back to the pool after the client has finished using it. If no thread exists in the pool then the client has to wait.
My confusion comes from the fact that a thread is supposedly not reusable, which defeats the purpose of pooling them. Have I understood the assignment incorrectly?

A: Threads are reusable as long as they have not ended. A pool of threads generally involves threads that do work as it is given to them, and then wait for more work. Thus, they never end until explicitly told to do so. The trick is designing them in a way such that the work they are given ends, but the thread itself does not. Thread pools are useful because it is often relatively expensive to create/destroy threads.

A: @Kaliatech has already explained the concept behind re-use of threads. Also "The ownership of these threads shall be transferred to the client" is slightly misleading as the ownership of threads generally remain with the thread-pool/object-pool as it is the manager of this pool and the client should simply submits the task to the pool which can either complete successfully or fail. The thread continues to run ready to pick the next task submitted to the pool. As a design too the separation of task object ( Runnable/Callable) and the object representing thread execution (Thread) are designed to be different. Should the need arise the thread-pool is responsible for ramping up/down the number of threads as they are expensive to create and manage. Java ThreadPoolExecutor will be a good example to refer to how typically such a thread pool works.


text:
Q: combining the name of the file with todays date I am creating an excel sheet in c: with this name ABC_0607 and it also get created as shown below..
String outputDir = "C:/Report/";
FileOutputStream fw = new FileOutputStream(new File(outputDir, "ABC_0607.xls"));

Now as I am recieving this files on a daily basis and need to be stored in c: drive
so  I want to modify it name a little bit that is combination of filename+MM/DD/YYYY
so if today date is 3-July-2013 so file name should be like ABC_0607-MM/DD/YYYY that is ABC_0607-07/03/2013.
PLease advise how to achieve this

A: Use a StringBuilder initialized with the name of the file.Format the Date using a DateFormat and append the String to it.  Put the entire logic inside a method so that it can be reused without code duplication.

A: You can use this method to retrieve the name of your file:
public String getFileNameFrom(String name) {
    String currDate = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
    return name + "-" + currDate;
}

A: I have following code to create name for log file, it can be hourly, daily or minutely(lol)
SimpleDateFormat ymd = new SimpleDateFormat("yyyy_MM_dd");
SimpleDateFormat ymdh = new SimpleDateFormat("yyyy_MM_dd_HH");
SimpleDateFormat ymdhm = new SimpleDateFormat("yyyy_MM_dd_HH_mm");

Calendar dt = Calendar.getInstance();
dt.setTimeInMillis(moment);
String fName;
if (_splitType == SPLIT_HOUR)
    fName = ymdh.format(dt.getTime());
else if (_splitType == SPLIT_MINUTE)
    fName = ymdhm.format(dt.getTime());
else
    fName = ymd.format(dt.getTime());


text:
Q: Difference between attribute and property I'm using lazy initialization in Python in order to save loading time. I've some properties that are initialized only when they are used, so if they are never used, the cost for creating them are never charged. An example of it is this:
class myClass(object):
    anotherInfo = 1
    def __init__(self,var):
        self._MY_DATA = None
        self.var = var

    @property
    def my_data(self):
        if getattr(self, '_MY_DATA', None) is None:
            print "Populate my_data"
            my_data = self.var
            self._MY_DATA = my_data
        return self._MY_DATA

    def invalidate_data(self):
        self._MY_DATA = None

if __name__ == '__main__':
    x = myClass("1")
    print x.my_data
    x.invalidate_data()
    print x.my_data

My problem is the following, some events cause all properties to loose state, and I've to reset all of them (to the never used state). I want to do this automatically, so I need a list of all properties.
I could get this through reflection using the inspect mode, but I did not found any way of doing so.
Another is to add the property each time I execute the @property wrapper, but how can a write a wrapper that receives the getter function and the object in order to save the properties ?
The other method is to wrap the @property wrapper, in order to append to a list in the object(e.g. __properties__) what are my properties to reset.


text:
Q: Why does adding a hard constraint produce bad solutions? I am trying to use Optaplanner to optimally assign production units to a group of contractors. The goal is to assign the production units so that the real inventory is as close as possible to the optimal inventory. For this, I am using a soft constraint which, in simple terms, follows this basic equation:

This is the basis for my soft constraint score. The purpose of Optaplanner is to minimize this difference. However, I do have a hard constraint that specifies the minimum production units that can be assigned. Whenever this constraint is introduced to the problem, Optaplanner produces less than optimal solutions. It basically assigns all the available production units to one single contractor so as to not break the minimum production quantity constraint.
This ensures that no contractor is assigned a small amount of production units (assigning 0 is ok), but it has the unintended consequence that the soft constraint is not optimized at all. Extending the run time basically just moves the entirety of the production units around between different contractors.
It is not a matter of not having enough production units since I have around 10000 available units while the minimum production quantity is 120. This should be enough to assign it to several contractors and optimize the inventory instead of assigning the 10000 units to one single contractor.
Is there a way to include this hard constraint without Optaplanner completely ignoring the soft constraint?
EDIT: To clarify, the hard constraint is only punishing when the production units are bellow 120. It is not rewarding production units above 120. The max possible hard score is 0.
(For simplicity I said "assign units to contractors" when in reality Optaplanner is "assigning contractors to the units")

A: It's probably stuck in a deep local optima due to lack of smart enough moves to get out of it (and it's too deep for the metaheuristics to get out of it). If you turn on DEBUG (and later TRACE) logging, you'll see the decisions that optaplanner makes.
Try adding pillar change and swap moves:
<constructionHeuristic/>
<localSearch>
  <unionMoveSelector>
    <changeMoveSelector/>
    <swapMoveSelector/>
    <pillarChangeMoveSelector/>
    <pillarSwapMoveSelector/>
  </unionMoveSelector>
</localSearch>

If that doesn't help, you'll need a custom move.


text:
Q: Custom View above a keyboard not working in ios9 Have added a custom view consisting of buttons on top of the keyboard. The buttons are being displayed correctly but on tapping on the buttons, the underlying keys of the keyboard are pressed instead of the button actions.
UIWindow* tempWindow = [UIApplication sharedApplication].windows.lastObject;
for (UIView *keyboard in [tempWindow subviews]) {
    if ([[keyboard description] hasPrefix : @"<UIInputSetContainerView"]) {
    for(int i = 0 ; i < [keyboard.subviews count] ; i++)
       {
        UIView* hostkeyboard = [keyboard.subviews objectAtIndex:i];
        if([[hostkeyboard description] hasPrefix:@"<UIInputSetHost"] == YES){
            [hostkeyboard addSubview:extraRow];
            [hostkeyboard bringSubviewToFront:extraRow];
           }
       }
    }
}

extraRow is the UIView consisting of buttons.
Is there anything missing ?

A: You could do just add a custom view to the keyboard as an inputAccessoryView. Then it just assign the button the correct target you want it to fire when clicked on
- (void)textFieldDidBeginEditing:(UITextField *)textField {

    UIView  * theView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    [theView setBackgroundColor: [UIColor greyColor]];

    UITextField * txtTest = [[UITextField alloc] initWithFrame:CGRectMake(0, 5, theView.frame.size.width, 60)];
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 65, 100, 30)];

    [btn setTitle:@"Click my Button" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(alert:) forControlEvents:UIControlEventTouchUpInside];

    // Just put this to see the items or customize the color
    [txtTest setBackgroundColor:[UIColor whiteColor]];
    [btn setBackgroundColor:[UIColor blueColor]];

    // Need this to add it to the view
    [theView addSubview:txtTest];
    [theView addSubview:btn];

    textField.inputAccessoryView = theView;
}

A: One thing you might want to consider is setting the extraRow's exclusiveTouch property to YES. As a disclaimer I haven't tried this example myself but I think the problem you are having is due to the view passing along the touch event.


text:
Q: why does the numbers of maps increasing will affect the bandwidth and cluster utilization on hadoop? Recently I was reading the book, hadoop: the definitive guide which the part is two clusters copy data using distcp, and I saw the comment: "When data size is very large, it becomes necessary to limit the number of maps in order to limit bandwidth and cluster utilization"
I cannot get the meaning why? I think we should utilize the bandwidth as wide as possible to increase the efficiency of cluster. So why should we limit the number of maps?

A: Of course having more no. of mappers helps us to achieve higher parallelism, but it starts becoming a bottleneck if it is too high. For example, if you have mappers much more than the no. of CPU slots available on your slaves, most of the mappers will be in wait state. Likewise you may run out of memory and may face network congestion. Also, it'll take more time to create those many InputSplits and create so many maps. So, the no of mappers should be considerably high. Not too high, not too low. Actually framework does that for you under normal circumstances so that you don't have to worry. But sometimes you might want to do it on your own as per your requirements, but keeping the above said things in mind.
HTH


text: Q: XCode removes watchOS2 App when running iPhone target I have a problem, every time I run my iPhone target the Watch App gets uninstalled and I have to manually install it again via the companion App. The device log says: "The system does not trust application". I've seen the "Trust this computer" dialog once on the Watch and I tapped trust. Is there any way to re-trust? Thanks


text:
Q: python/Scipy Interpolation of 3D scattered data I want to implement a interpolation of a 3D scattered data using python.
Such as,
z[0,0] = 1, z[0,4] =2, z[2,2]=4, z[4,0]=3, z[4,4]= 2 (X like structured 2D vectors with z value)
and interpolate these data so that
I can derive a z value between this (x,y) coordinate like z[1,2], z[2,3], z[1,1], ..., etc.
I coded like below using scipy and numpy but I guess using numpy.empty((5,5)) is not suitable for my purpose because numpy.empty() add values which is irrelevant. And I want to interpolate only with 5 points.
from scipy import interpolate
import numpy as np
x = np.linspace(0,4,5)
y = np.linspace(0,4,5)
xx,yy=np.meshgrid(x,y)
z = np.empty((5,5)) # I think this is wrong
z[0,0] = 1, z[0,4] =2, z[2,2]=4, z[4,0]=3, z[4,4]= 2

f = interpolate.interp2d(x,y,z,kind='linear')

xt = np.linspace(0,4,10)
yt = np.linspace(0,4,10)
xxt, yyt = np.meshgrid(xt,yt)
ct = f(xt,yt)

my expected output is values with 2D 5x5 (or larger area such as 7x7, 9x9, etc) arrays which is the result of interpolation of 5 constant points.
Could you help me?


text:
Q: Why does the Material-UI Select does not display any option? Hello I was changing all my selects to Material-UI Selects (because they look better in my opinion) , but I'm struggling because I'm looking at a tutorial and I have exactly the same settings but I don't see any of the options I have set up

const [escuela, setEscuela] = useState("");

const handleChange2 = (event) => {
      setEscuela(event.target.value);
    };

<Select className= "SelectMultiple" value = {escuela} label = "Seleccione Escuela..." onChange={handleChange2}>
<MenuItem value={"Academia Internacional de Boquete"}>Academia Internacional de Boquete</MenuItem>
<MenuItem value={"Academia Internacional de David"}>Academia Internacional de David</MenuItem>
</Select>

A: You want to use MUI's Select but the Select in the screenshot is from react-select package. Both component name is Select so if you're migrating to the other library, you should use different default name to avoid mixing one with the other:
import ReactSelect from 'react-select'
import MuiSelect from '@mui/material/Select';


text:
Q: passing a file to constructor to read class Read
{
public:
    Read(ifstream &file)
    {
        mFile=file;
    }
private:
    ifstream mFile;
    string str;
};

int main()
{
    Read r("sample.txt");

    return 0;
}

I'm trying to use the constructor to read a file. I saw another example on stack overflow and tried to replicate it but failed. How do i properly read a file using a constructor.
Is the syntax way off?

A: You can't copy or assign ifstreams, but you can initialize them from a string literal. So you could do this:
class Read
{
public:
    Read(const char* filename) : mFile(filename) {}
private:
    ifstream mFile;
    string str;
};

Note that this would make Read non-copyable and non-assignable. But move construction and move assignment would work.
Note that, if you really want to pass an ifstream, then the best you can do is pass a temporary, and use the data member's move constructor. You can achieve it with this constructor:
Read(ifstream&& file) : mFile(std::move(file)) {}

Usage:
Read r1("file.txt");                // const char* ctor
Read r2(std::ifstream("file2.txt"); // ifstream&& ctor

A: "Sample.txt" isn't an ifstream. Instead, open the file with the passed string.

mFile.open(file);
  Where file is a c string.

A: Standard file streams cannot be copied. The assignment in the constructor is invoking the stream's private (delete'd in C++11) copy-assignment operator. The correct way do this would be to invoke the appropriate constructor with the member initializer-list. The parameter should be of type std::string as well.
Read(const std::string& file)
   : mFile(file)
// ^^^^^^^^^^^^^
{ }


text:
Q: How to capture still image and save with its city name with AV Foundation camera? I capture still image and save to camera roll with AV Foundation like this:
- (void) captureStillImage
{
    AVCaptureConnection *stillImageConnection =
    [self.stillImageOutput.connections objectAtIndex:0];
    if ([stillImageConnection isVideoOrientationSupported])
        [stillImageConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];

    [self.stillImageOutput
     captureStillImageAsynchronouslyFromConnection:stillImageConnection
     completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
     {
         if (imageDataSampleBuffer != NULL)
         {
             NSData *imageData = [AVCaptureStillImageOutput
                                  jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
             ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
             UIImage *image = [[UIImage alloc] initWithData:imageData];
             [library writeImageToSavedPhotosAlbum:[image CGImage]
                                       orientation:(ALAssetOrientation)[image imageOrientation]
                                   completionBlock:^(NSURL *assetURL, NSError *error){
              }];
         }
         else
         {
             NSLog(@"Error capturing still image: %@", error);
         }
     }
     ];
}

These images from my App when check again in Photos App don't have info about city name.
How to capture still image and save with its location name which can be display in photos app?
Thanks for help!

A: From the Docs : captureStillImageAsynchronouslyFromConnection

handler
A block to invoke after the image has been captured. The block
  parameters are as follows: imageDataSampleBuffer The data that was
  captured. The buffer attachments may contain metadata appropriate to
  the image data format. For example, a buffer containing JPEG data may
  carry a kCGImagePropertyExifDictionary as an attachment. See
  ImageIO/CGImageProperties.h for a list of keys and value types.

So using that you can get the meta data.
         CFDictionaryRef metaDict = CMCopyDictionaryOfAttachments(NULL, imageDataSampleBuffer, kCMAttachmentMode_ShouldPropagate);
         CFMutableDictionaryRef mutable = CFDictionaryCreateMutableCopy(NULL, 0, metaDict);

         NSDictionary *metaDict = [NSDictionary
                                  dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat:self.currentLocation.coordinate.latitude], kCGImagePropertyGPSLatitude,
                                  @"N", kCGImagePropertyGPSLatitudeRef,
                                  [NSNumber numberWithFloat:self.currentLocation.coordinate.longitude], kCGImagePropertyGPSLongitude,
                                  @"E", kCGImagePropertyGPSLongitudeRef,
                                  @"04:30:51.71", kCGImagePropertyGPSTimeStamp,
                                  nil];
         NSLog(@"%@",metaDict);
         CFDictionarySetValue(mutable, kCGImagePropertyGPSDictionary, (__bridge const void *)(metaDict));

and when saving to Asset Library use this method to add the meta data
[library writeImageToSavedPhotosAlbum:[image CGImage] metadata:mutable completionBlock: nil];


text:
Q: jQuery datatable table inside table causing mData undefined In one of my projects I am using datatables. This is one column structure in my table which is causing an error:

                Day Run

                M
                T
                W
                T
                F
                S
                S

Also this is the respective column:

                N
                N
                N
                N
                N
                N
                Y

I don't know why but this is throwing an error when initialized. This is the error I am facing.
Uncaught TypeError: Cannot read property 'mData' of undefined
I don't see anything wrong here. Any idea why its does not work?
Here is the live demo Demo

A: This is because you are initializing datatable by using class like:
$('.table').dataTable({searching: false, paging: false, responsive: true});

and the column definition are different for both the table, I think this is the issue.
Do one thing, provide different id to both the table and initiate datatable with those id's


text:
Q: Where to study category theory? I am attending a master in math, and I am very passionate about category theory. Especially, I like how limits extend a lot of results from a little "core" of the category to everything. I furthermore like beatiful algebra, like Galois theory, commutative algebra, homological algebra, finite representation theory...
Unfortunately, in my university there is few of this stuff. Where would you suggest me to go for a one-year exchange program, especially to deepen my categorical (but not logic) interests?
Thank you!
EDIT: Europe would be the best for geographical reasons, but I am open to international experiences. However, it is increasingly harder for me to get an exchange program with far countries (I come from Italy).

A: You can get a fair amount of category theory in the masters of parisian universities, mainly oriented towards algebraic geometry and algebraic topology. Also, you get a fair amount of categorical seminar around Paris (go figure...).
It depends on the year you attend, but Université Paris 6 (Pierre et Marie Curie) usually have courses on étale cohomology and sheaf theory for algebraic groups. Université Paris 7 (Diderot) usually have courses about homology/homotopy with a categorical point of view. Université Paris 13 (Saint-Denis) offers courses about homotopy and operad theory. Also, most courses can be followed independently of the university you registered in.
A little closer to Italy, there is quite a categorical team in Nice (Université Sophia-Antipolis), mostly around Carlos Simpson and Clemens Berger I would say. Definitely a good place for a categorical PhD, however I'm no sure it reflects into the master there.
Just my two french cents !

A: At the risk of falling into shameless publicity, my university (Université catholique de Louvain, in Belgium), has a research team in category theory and offers two category theory courses :

*

*the first one introduces the main concepts (categories, functors, natural transformations, Yoneda lemma, limits, adjunctions), and then covers regular and exact categories before turning to the abelian ones and all the homological lemmas.

*the second one is geared towards the Master students interested in research and the PhD students. Depending on the year, it can cover monads and Lawvere theories, homological and semi-abelian categories, categorical Galois theory...

In addition, there are several courses in algebra and algebraic topology where some amount of category theory is used.


text:
Q: How to test if Node.js app is able to start I'm trying to add a test to check if Node.js app is starting. for example it might crash after running npm start. and I want to verify it's able to start.
I tried searching the web for such ways to tests but couldn't find anything useful

A: In a production environment you can either use a very popular NPM module named "PM2(Process Manager 2)" or containerize your entire application and then let Docker handle the application's life-cycle

How to start an Node app under PM2: https://www.npmjs.com/package/pm2#start-an-application
Docker with "always" restart policy: https://docs.docker.com/config/containers/start-containers-automatically

A: If your app is an HTTP(S) server, then you might want to add it a dummy entry point, something like /hello which returns 200 (OK). This way you could run a command line HTTP client, such as curl, and see if it successfully gets the expected response.
However, this is not a unit test, it's an integration test.
Note also, that this test should be run as a separate process.


text:
Q: Simple way to change whole project to root relative paths I have inherited a web site that has all of the paths set using relative paths, that only work when the site is located in the web root.
I have put the site in a virtual directory, and none of the paths work correctly.

I can resolve this as follows:
<img src='<%= ResolveUrl("~/img/logo/BadCo.gif") %>' width="156" height="55" alt="BadCo" />

However, I do not want to have to manually change every single one, of hundreds of paths throughout the project, and coming up with a regex to do the replace would hurt my tiny brain.

A: Personally, I wouldn't have put the site in a virtual directory.
There's nothing evil about having paths specified from the web root.  This is pretty much how the site will eventually be deployed.
The approach you've taken means that code will need to execute every time you want to resolve a URL.  This is really something that should be happening for free, and it can.
If you're using Visual Studio's built-in web server for development, you can easily have a site that is defined at the web root.
If not, and you're on XP, consider using IISAdmin.NET.  This tool allows you to set up multiple websites on your local copy of IIS and switch between them as the need arises.
http://iisadmin.codeplex.com/

A: If it's feasible you could just make the it a web site proper in IIS and just assign it a different port.
I take this approach on my dev machine if I want to get a website working on IIS proper rather than Cassini. So everything will be under http://localhost:[portnumber]/.
If you have to use a virtual directory I'm out of ideas.

A: I guess a key question is how big this app is.
There aren't all that many different places to put a url. Why not search for
="/

and
='/

That is, an equal sign, a double or single quote, and a slash. That should turn up most of the places that assign a URL. Then you'd see all the places where you're setting such things, like src= and navigateurl= and whatever.
It would be a pain. I'm not saying you'd get it done in ten minutes. If this is something that you need to get done today and it's a big app, I wouldn't take it on. But if it's something you're going to be working on making changes to and testing for a week, I think you could make a first cut at cleaning up the the URL's and then see what shakes out in testing.


text:
Q: Ethernet differential signals I've 2 questions on Ethernet design:
Suppose I am using a current mode Ethernet PHY which requires termination resistor of 49.9 ohms to VDD on the Ethernet differential lines.
Can I increase the resistor value to 75ohms? Is it OK? Can someone tell me what impact it would have?
Question 2:
Can I place any sort of IC (assume a MUX (specific to an application)) between the magnetics and the RJ-45 connector for 100Mbps ethernet? Will it work or is there something I should take care?

A: *

*No. Ohm's law says same current through different resistance causes a proportionally different signal voltage.

*Yes. Chips intended for muxing Ethernet do exist.

A: *

*Probably not. The result is less terminated, of course, giving more crosstalk between symbols.  It's only 25% more, while the signal levels are +/-50% so to speak, so it should still work say with a short patch cable -- but you might not notice what distance it fails at, or under which data patterns.  (If you absolutely must use 75R's, use series-parallel combinations to make 50R proper.)

*Yes, but NOT AT THE MEDIA SIDE.  You can use one transformer set per connector, and switch the PHY side.  This requires a mux with extra voltage range (with push-pull or current-mode drive, the undriven side swings up to about 2*VDD by transformer action!), so probably needs an auxiliary supply.  Switches are available in such ratings, with low insertion loss and high bandwidth; though they're easier available / better performing at 3.3V (maybe consider a differential / full-bridge / gigabit-style PHY instead??).

You probably still need/want ESD protection for such a switch.  I think they're available with that integrated too, actually.


text:
Q: My function doesn't calculate a simple math operation I'm making a Temperature Calculator
Celsius and Farenheit
I'm a completely begginer in Python
I have Python 3.3
So, I made this function to calculate a Farenheit value to a Celsius value
def C():
    print('Enter a temperature:')
    Fvalue = input()
    print(int(Fvalue) - int(32) * int((5/9)))

I run it and it just prints the Fvalue itself, it doesn't make the math operations
I hope you can help me guys

A: The problem is, you are casting the value of 5 / 9 to an int, which will give you 0 as a value. Just remove the cast, and it will be fine. And also you need to add parenthesis around the subtraction.
Change your print statement to:
print((int(Fvalue) - 32) * 5/9)

A: Your real problem lies here:
int(5/9)

5/9 gives you 0.555 which when cast to int() gives you 0
Try this:
print((int(Fvalue) - 32) * 5/9)

A: int((5/9)) gives you 0, so int(32) * int((5/9)) is 0, so you simply print Fvalue
This should fix your issue:
print((int(Fvalue) - 32) * 5.0 / 9))

With some easy math, this expression would be cleaner:
print (Fvalue - 32) / 1.8

A: Your code be should be as given below, u don't require casting for integers 32 and (5/9),
def C():
print('Enter a temperature:')
Fvalue = input()
print(int(Fvalue) - 32 * 5/9)


text:
Q: How to place scrollable video ads in flutter app? I'm developing a Social media app. In which there is a section of short videos. exactly like the youtube short-videos, and Instagram reels are. I want to show scrollable video ads just like in youtube short-videos, Which must be skippable. I'm currently using AdMob for showing banner ad. I don't know, Is exactly same thing achievable with AdMob?
If anybody knows how to implement the exact same type of scrollable video ads, Let me know


text:
Q: Is there a less CPU-intensive alternative for TOmniMREW? I'm after a slim Single-Read Multi-Write lock, similar to TOmniMREW, but that would be less CPU-intensive in cases of contention.
TOmniREW uses only a spinlock, so threads will skyrocket to 100% CPU usage until they can acquire the lock.
Currently I'm using a Critical Section, and while it has less efficient behavior (I have more readers than writers), in case of contention threads relinquish their CPU times.
Contention happens very occasionally in my case, typically when a writer triggers a more complex (lengthy) operation, but when it does, the spinlocks have CPU usage skyrocket.
The Windows SRW implementation uses a similar strategy and is of no help (edit: actually it's about 2-3 times faster in some cases of high contention, but still exhibits the issue edit 2: TOmniMREW will be using SRW when available in future version, so speed will be the same).

A: Actually after more testing, it appears that Windows SRW does relinquish CPU, it just takes slightly more times for it to do so than I saw in my Critical Sections test.
So Windows SRW are the answer.

A: Have you read this article: Slim Reader/Writer Locks Rocks ?
It also contains a reference to a simple benchmark project of several alternatives


text:
Q: Suppress footer on first page of chapters How can I suppress the footer on the first page of the chapters from the code given below?
\documentclass{book}
\usepackage{lmodern}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{background}
\usetikzlibrary{calc}
\usepackage{lipsum}

\pagestyle{plain}

% auxiliary counter
\newcounter{chapshift}
\addtocounter{chapshift}{-1}

% the list of colors to be used (add more if needed)
\newcommand\BoxColor{%
  \ifcase\thechapshift blue!30\or red!30\or olive!30\or magenta!30\else yellow!30\fi}

% redefinition of \chaptermark to contain only the title
\renewcommand\chaptermark[1]{\markboth{\thechapter.~#1}{}}

%======================================================================================
%   PAGE HEADERS
%======================================================================================

\usepackage{etoolbox,fancyhdr} % Required for header and footer configuration

\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{\sffamily\normalsize\bfseries \ #1}{}} % Chapter text font settings
\renewcommand{\sectionmark}[1]{\markright{\sffamily\normalsize\thesection\hspace{5pt}#1}{}} % Section text font settings
\fancyhf{} \fancyhead[LE,RO]{\sffamily\normalsize\thepage} % Font setting for the page number in the header
\fancyhead[LO]{\rightmark%
\begin{tikzpicture}[overlay,remember picture]
  \node[fill=\BoxColor,inner sep=0pt,rectangle,text width=1cm,
    text height=4cm,align=center,anchor=north east]
  at ($ (current page.north east) + (-0cm,-2*\thechapshift cm) $)
  {\rotatebox{90}{\parbox{4cm}{%
    \centering\textcolor{black}{\scshape\leftmark}}}};
  \end{tikzpicture}} % Print the nearest section name on the left side of odd pages
\fancyhead[RE]{\leftmark%
  \begin{tikzpicture}[overlay,remember picture]
  \node[fill=\BoxColor,inner sep=0pt,rectangle,text width=1cm,
    text height=4cm,align=center,anchor=north west]
  at ($ (current page.north west) + (-0cm,-2*\thechapshift cm) $)
  {\rotatebox{90}{\parbox{4cm}{%
    \centering\textcolor{black}{\scshape\leftmark}}}};
  \end{tikzpicture}} % Print the current chapter name on the right side of even pages
\renewcommand{\headrulewidth}{.5pt} % Width of the rule under the header
\addtolength{\headheight}{2.5pt} % Increase the spacing around the header slightly
\newcommand{\footrulecolor}[1]{\patchcmd{\footrule}{\hrule}{\color{#1}\hrule}{}{}}
\renewcommand{\footrulewidth}{.5pt}
\cfoot[\fancyplain{}{}] {\fancyplain{}{\footnotesize\bfseries{Center Foot}}} \lfoot[\fancyplain{}{}]
{\fancyplain{}{\footnotesize\bfseries\itshape{Left Foot}}}
\rfoot[\fancyplain{}{}]
{\fancyplain{}{\footnotesize\bfseries\itshape{Right Foot}}}
\fancypagestyle{plain}{\fancyhead{}\renewcommand{\headrulewidth}{0pt}} % Style for when a plain pagestyle is specified

% Removes the header from odd empty pages at the end of chapters
\makeatletter
\renewcommand{\cleardoublepage}{
\clearpage\ifodd\c@page\else
\hbox{}
\vspace*{\fill}
\thispagestyle{empty}
\newpage
\fi}
\patchcmd{\@makechapterhead}
  {\vskip 40\p@}
  {\vskip 40\p@\stepcounter{chapshift}}{}{}
\makeatother

\begin{document}
\part{Part One}
\mainmatter
\chapter[Intro]{Introduction}
\lipsum[1-7]
\section{This is how we do it}
\lipsum[1-7]

\chapter{Results}
\lipsum[1-7]

\chapter{Some Sample Code}
\lipsum[1-7]

\part{Part Two}
\appendix
\renewcommand\chaptermark[1]{\markboth{\sffamily\normalsize\bfseries \appendixname~\thechapter}{}}
\chapter{This is Appendix A}
\lipsum[1-7]

\chapter{This is Appendix B}
\lipsum[1-7]

\end{document}

A: Below I've updated \chapter (thanks to xparse) to change the page style for only the first page of the chapter. The new page style - called chapter - can be updated to whatever you like using the regular fancyhdr styling. For example, the following removes all traces of it - both the header and the footer, as well as the rules:
\fancypagestyle{chapter}{%
  \fancyhf{}% Clear header/footer
  \renewcommand{\headrulewidth}{0pt}% No header rule
  \renewcommand{\footrulewidth}{0pt}% No footer rule
}

\usepackage{xparse}
\let\oldchapter\chapter
\RenewDocumentCommand{\chapter}{s o m}{%
  \cleardoublepage
  \IfBooleanTF{#1}
    {\oldchapter*{#3}}% \chapter*
    {\IfNoValueTF{#2}
       {\oldchapter{#3}}% \chapter{..}
       {\oldchapter[#2]{#3}}% \chapter[.]{..}
    }
  \thispagestyle{chapter}% Special \chapter-only page style
}

Here's your complete minimal example using the above chapter page styles and redefined \chapter command:

\documentclass{book}
\usepackage{lmodern}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{background}
\usetikzlibrary{calc}
\usepackage{lipsum}

\pagestyle{plain}

% auxiliary counter
\newcounter{chapshift}
\addtocounter{chapshift}{-1}

% the list of colors to be used (add more if needed)
\newcommand\BoxColor{%
  \ifcase\thechapshift blue!30\or red!30\or olive!30\or magenta!30\else yellow!30\fi}

% redefinition of \chaptermark to contain only the title
\renewcommand\chaptermark[1]{\markboth{\thechapter.~#1}{}}

%======================================================================================
%   PAGE HEADERS
%======================================================================================

\usepackage{etoolbox,fancyhdr} % Required for header and footer configuration

\fancypagestyle{chapter}{%
  \fancyhf{}% Clear header/footer
  \renewcommand{\headrulewidth}{0pt}% No header rule
  \renewcommand{\footrulewidth}{0pt}% No footer rule
}

\usepackage{xparse}
\let\oldchapter\chapter
\RenewDocumentCommand{\chapter}{s o m}{%
  \cleardoublepage
  \IfBooleanTF{#1}
    {\oldchapter*{#3}}% \chapter*
    {\IfNoValueTF{#2}
       {\oldchapter{#3}}% \chapter{..}
       {\oldchapter[#2]{#3}}% \chapter[.]{..}
    }
  \thispagestyle{chapter}% Special \chapter-only page style
}

\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{\sffamily\normalsize\bfseries \ #1}{}} % Chapter text font settings
\renewcommand{\sectionmark}[1]{\markright{\sffamily\normalsize\thesection\hspace{5pt}#1}{}} % Section text font settings
\fancyhf{} \fancyhead[LE,RO]{\sffamily\normalsize\thepage} % Font setting for the page number in the header
\fancyhead[LO]{\rightmark%
\begin{tikzpicture}[overlay,remember picture]
  \node[fill=\BoxColor,inner sep=0pt,rectangle,text width=1cm,
    text height=4cm,align=center,anchor=north east]
  at ($ (current page.north east) + (-0cm,-2*\thechapshift cm) $)
  {\rotatebox{90}{\parbox{4cm}{%
    \centering\textcolor{black}{\scshape\leftmark}}}};
  \end{tikzpicture}} % Print the nearest section name on the left side of odd pages
\fancyhead[RE]{\leftmark%
  \begin{tikzpicture}[overlay,remember picture]
  \node[fill=\BoxColor,inner sep=0pt,rectangle,text width=1cm,
    text height=4cm,align=center,anchor=north west]
  at ($ (current page.north west) + (-0cm,-2*\thechapshift cm) $)
  {\rotatebox{90}{\parbox{4cm}{%
    \centering\textcolor{black}{\scshape\leftmark}}}};
  \end{tikzpicture}} % Print the current chapter name on the right side of even pages
\renewcommand{\headrulewidth}{.5pt} % Width of the rule under the header
\addtolength{\headheight}{2.5pt} % Increase the spacing around the header slightly
\newcommand{\footrulecolor}[1]{\patchcmd{\footrule}{\hrule}{\color{#1}\hrule}{}{}}
\renewcommand{\footrulewidth}{.5pt}
\cfoot[\fancyplain{}{}] {\fancyplain{}{\footnotesize\bfseries{Center Foot}}} \lfoot[\fancyplain{}{}]
{\fancyplain{}{\footnotesize\bfseries\itshape{Left Foot}}}
\rfoot[\fancyplain{}{}]
{\fancyplain{}{\footnotesize\bfseries\itshape{Right Foot}}}
\fancypagestyle{plain}{\fancyhead{}\renewcommand{\headrulewidth}{0pt}} % Style for when a plain pagestyle is specified

% Removes the header from odd empty pages at the end of chapters
\makeatletter
\renewcommand{\cleardoublepage}{
\clearpage\ifodd\c@page\else
\hbox{}
\vspace*{\fill}
\thispagestyle{empty}
\newpage
\fi}
\patchcmd{\@makechapterhead}
  {\vskip 40\p@}
  {\vskip 40\p@\stepcounter{chapshift}}{}{}
\makeatother

\begin{document}
\part{Part One}
\mainmatter
\chapter[Intro]{Introduction}
\lipsum[1-7]
\section{This is how we do it}
\lipsum[1-7]

\chapter{Results}
\lipsum[1-7]

\chapter{Some Sample Code}
\lipsum[1-7]

\part{Part Two}
\appendix
\renewcommand\chaptermark[1]{\markboth{\sffamily\normalsize\bfseries \appendixname~\thechapter}{}}
\chapter{This is Appendix A}
\lipsum[1-7]

\chapter{This is Appendix B}
\lipsum[1-7]

\end{document}

Of course, another option would be to merely redefine the plain page style to suit your needs, as each \chapter uses \thispagestyle{plain} or the first page. This can be achieved using
\fancypagestyle{plain}{%
  % Your page style settings here...
}

With this you don't need to redefine \chapter.


text:
Q: How to get nth jQuery element In jQuery, $("...").get(3) returns the 3rd DOM element. What is the function to return the 3rd jQuery element?

A: if you have control over the query which builds the jQuery object, use :eq()
$("div:eq(2)")

If you don't have control over it (for example, it's being passed from another function or something), then use .eq()
var $thirdElement = $jqObj.eq(2);

Or if you want a section of them (say, the third, fourth and fifth elements), use .slice()
var $third4th5thElements = $jqObj.slice(2, 5);

A: If you already have the jquery object in a variable, you can also just treat it as a normal indexed array, without the use of jquery:
var all_rows = $("tr");
for(var i=0; i < all_rows.length; i++){
   var row = all_rows[i];
   //additionally, you can use it again in a jquery selector
   $(row).css("background-color","black");
}

Although the above example is not useful in any way, it is representing how you can treat objects created by jquery as indexed arrays.

A: You can use the :eq selector, for example:
$("td:eq(2)").css("color", "red"); // gets the third td element

Or the eq(int) function:
$("td").eq(2).css("color", "red");

Also, remember that the indexes are zero-based.

A: Why not browse the (short) selectors page first?
Here it is: the :eq() operator. It is used just like get(), but it returns the jQuery object.
Or you can use .eq() function too.

A: If I understand your question correctly, you can always just wrap the get function like so:
var $someJqueryEl = $($('.myJqueryEls').get(3));

A: If you want to fetch particular element/node or tag in loop for e.g.

Monday

Tuesday

Wednesday

Thursday

So, from above code loop is executed and we want particular field to select for that we have to use jQuery selection that can select only expecting element from above loop so, code will be
$('.weekdays:eq(n)');

e.g.
$('.weekdays:eq(0)');

as well as by other method
$('.weekday').find('p').first('.weekdays').next()/last()/prev();

but first method is more efficient when HTML <tag> has unique class name.
NOTE:Second method is use when their is no class name in target element or node.
for more follow https://api.jquery.com/eq/

A: I think you can use this
$("ul li:nth-child(2)").append(" - 2nd!");

It finds the second li in each matched ul and notes it.

A: .eq() -An integer indicating the 0-based position of the element.
Ex:
Consider a page with a simple list on it:

list item 1

list item 2

list item 3

list item 4

We can apply this method to the set of list items:
$( "li" ).eq( 2 ).css( "background-color", "red" );

For more information :  .eq()

A: For iterations using a selector doesn't seem to make any sense though:
var some = $( '...' );

for( i = some.length -1; i>=0; --i )
{
   // Have to transform in a jquery object again:
   //
   var item = $( some[ i ] );

   // use item at will
   // ...
}

A: Live Example to access and remove the Nth element with jQuery:

First

Second

Third

When it runs, there are two items in the ordered list that show, First, and Third.  The second was hidden.

A:  $(function(){
            $(document).find('div').siblings().each(function(){
                var obj = $(this);
                obj.find('div').each(function(){
                    var obj1 = $(this);
                    if(!obj1.children().length > 0){
                        alert(obj1.html());
                    }
                });

            });
        });

XYZ Pvt. Ltd.

ABC Pvt Ltd.


text:
Q: C++ / VS 2012 - Multi-project solution: Linker errors in one project but not another I have an MFC DLL which is used by another project in the same solution.  Everything works as it should when called from the consuming project, including the function I will be writing about below.
I have recently tried to put together a unit testing application for this DLL, which has been going well until the most recent addition to the DLL (which, as I said, I have proven to be working ok from the main project).
Note: I'm also showing the std::string one as it may be relevant (and is known working in my unit testing project).
The problem function is declared in the header file like this:
#pragma once

#include <string>
#include <afx.h>

#ifdef CALIBRATIONTOOL_EXPORTS
#define CALIBRATIONTOOL_API __declspec(dllexport)
#else
#define CALIBRATIONTOOL_API __declspec(dllimport)
#endif

namespace MyCompanyName
{
    namespace CalibrationTool
    {
        class FileUtils
        {
        public:
            CALIBRATIONTOOL_API static bool FileExists(std::string filename);

            CALIBRATIONTOOL_API static bool FileExists(CString filename);

        }; // end class FileUtils
    }; // end namespace CalibrationTool
}; // end namespace MyCompanyName

And implemented in the cpp:
#include "stdafx.h"
#include "FileUtils.h"
#include "StringUtils.h"
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>

#ifdef CALIBRATIONTOOL_EXPORTS
    #define CALIBRATIONTOOL_API __declspec(dllexport)
#else
    #define CALIBRATIONTOOL_API __declspec(dllimport)
#endif

namespace MyCompanyName
{
    namespace CalibrationTool
    {
        bool FileUtils::FileExists(std::string filename)
        {

            std::string filenameAsStdString(filename);
            std::string filenameWithDoubleBackslashes = MyCompanyName::CalibrationTool::StringUtils::SingleToDoubleBackslash(filenameAsStdString);
            std::ifstream ifile(filenameWithDoubleBackslashes);
            bool exists = (bool)ifile;
            ifile.close();
            return exists;
        }

        bool FileUtils::FileExists(CString filename)
        {
            std::ifstream ifile(filename);
            bool exists = (bool)ifile;
            ifile.close();
            return exists;
        }

    }; // end namespace CalibrationTool
}; // end namespace MyCompanyName

So far so good. And like I said, it's testing ok when called from the main project.  However, in my testing project, where it's called like this:
bool FileUtilsTest::FileExistsTestCString()
{
    bool passed = true;

    CString definitelyExists = _T("C:\\Windows\\system.ini");
    CString definitelyDoesntExist = _T("C:\\NotMuchChanceThatThisFileExists.zut");

    if (MyCompanyName::CalibrationTool::FileUtils::FileExists(definitelyExists))
        {
        // all is well
        CalibrationToolUnitTestsLogging::Write("Passed FileUtilsTest.FileExistsTestCString (files which exist). Successfully found C:\\Windows\\system.ini.");
    }
    else
    {
        // all is not well
        CalibrationToolUnitTestsLogging::Write("Failed FileUtilsTest.FileExistsTestCString (files which exist). Unable to find C:\\Windows\\system.ini.");
        passed = false;
    }
    // (and more testing, e.g. for files which don't exist)

return passed;
}

I get the error:
Error  4   error LNK2019: unresolved external symbol "__declspec(dllimport) public: static bool __cdecl MyCompanyName::CalibrationTool::FileUtils::FileExists(class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > >)" (__imp_?FileExists@FileUtils@CalibrationTool@MyCompanyName@@SA_NV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@@Z) referenced in function "private: bool __thiscall FileUtilsTest::FileExistsTestCString(void)" (?FileExistsTestCString@FileUtilsTest@@AAE_NXZ)   C:\_SVN\CalibrationToolUnitTests\FileUtilsTest.obj
Here's the working code in my main project, for completeness:
if ((MyCompanyName::CalibrationTool::FileUtils::FileExists(exists)) && (!MyCompanyName::CalibrationTool::FileUtils::FileExists(doesntExist)))
    {
        g_log.Write(log_debug, -1, _T("TEST"), _T("Seems fine."));
    }
    else
    {
        g_log.Write(log_debug, -1, _T("TEST"), _T("Something's up"));
    }

Can anyone suggest where I'm going wrong?

A: In Visual studio 10 (and I guess vs 2012 is the same) There are 3 different ways to add dependency.

*

*Manual - add the include/library paths in the project setting, and
add the library.

*New (prefer to do it like this...) - project -> properties.
choose: Common properties-> Framework and References.
Press "Add Reference". Now select the dependency.

*Old = add dependency - when you right click on project in the
solution explorer and choose "Add dependency"

I think your problem is that you used one way on one project and other way for the second.
Other possibility is that one project is static lib. so it doesn't need to be linked.


text:
Q: A submanifold of the space positive definite matrices Consider the space of $n \times n$ positive definite symmetric matrices and let $\Sigma$ be one such matrix. We make this space into a Riemannian manifold $M$ by means of the metric $$ds^2=tr(\Sigma^{-1}d\Sigma\Sigma^{-1}d\Sigma)$$
Now fix a $p<n$ and consider the collection $\Phi_p$ of all positive definite symmetric matrices which can be written
$$B^TB+D$$
for some $B$ and $D$ where $B$ is $p \times n$ and $D$ is a diagonal positive definite matrix. Here $B$ and $D$ are allowed to vary but $p$ must stay fixed. Is $\Phi_p$ an embedded submanifold of $M$ and if so how can I put the induced metric on it?

A: This Riemannian metric on the full space of all positive definite matrices turns up in the paper (and others)

*

*Olga Gil-Medrano, Peter W. Michor: The Riemannian manifold of all Riemannian metrics. Quarterly J. Math. Oxford (2) 42 (1991), 183--202
There are explicit formulas for geodesics and for curvature. There is only one incomplete geodesic, but the space if far from being geodesically convex.


text:
Q: Proving that the intersection over a general index is the null set Prove that the generalized intersection of the interval $[n,n+2]$ is the empty set.
 I can prove this by contradiction by assuming that there there is an $x$ in the intersection such that $n+2<x.$ I am just not sure where to go from there.

A: Suppose $X:=\bigcap_{n \in \mathbb Z}[n,n+2]$ is non-empty and let $x\in X.$ Then we have $n \leq x \leq n+2, \forall n \in \mathbb Z.$ In particular, $-3 \leq x \leq -1$ and $1 \leq x \leq 3.$ This gives a contradiction.