text:
Q: VBA to apply formats down a table I have a set of 227 workbooks to run this macro on. I start with a list of workbook names at a given filepath. For each file, the macro opens it, goes to a specified sheet, copies the first line of a table, and then format-paints that down through the rest of the sheet/table. It loops through each workbook until it's done all workbooks. For some reason, I'm getting a debug error on the PasteSpecial function, and I'm not quite sure why. The workbook and sheet references are valid, I've triple-checked them. Any glaring issues I'm overlooking?
Sub Macro2()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Path = ThisWorkbook.Sheets(1).Range("H6")

If Right(Path, 1) <> "\" Then
    Path = Path & "\"
End If

wsheet = ThisWorkbook.Sheets(1).Range("F10")

ThisWorkbook.Sheets(3).Range("A2:B20000").ClearContents
OutLn = 2
Line = 1

Do While ThisWorkbook.Sheets(2).Cells(Line, 1) <> ""
    OpnFil = ThisWorkbook.Sheets(2).Cells(Line, 1)
    Workbooks.Open fileName:=Path & OpnFil, UpdateLinks:=False
    ScanLn = 12
        Do While Workbooks(OpnFil).Sheets(wsheet).Range("A8:V8").Copy
            Workbooks(OpnFil).Sheets(wsheet).Cells.Range("A10:V1000000").PasteSpecial Paste:=xlPasteFormats
            Application.CutCopyMode = False
        Loop
    Workbooks(OpnFil).Close
    Line = Line + 1
Loop

End Sub


text:
Q: why  outputs the values of all ancestors tags As far as I know the XPath expression "/" should set the node context to the child axis of the root node. Here is the xml:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<test-case name="test-case-1">
    <object-under-test category="template" name="text-align"/>
    <parameters>
        <input name="text">text</input>
        <input name="min-lenght">8</input>
        <input name="align">left</input>
        <output name="result"/>
    </parameters>
    <criteria>
        <criterion class="equal" to="'text '"/>
    </criteria>
</test-case>

</xsl:stylesheet>

And this is the xsl:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
    <test>
        <xsl:apply-templates/>
    </test>
</xsl:template>
</xsl:stylesheet>

What is the default match pattern for <xsl:apply-templates>?
Why I get as an output the values of all tags?
This is the output:
<?xml version="1.0" encoding="UTF-8"?>
<test>text 8 left</test>

A:
As far as I know the XPath expression "/" should set the node context
  to the child axis of the root node.

No, it sets the context to the / root node itself.

What is the default match pattern for <xsl:apply-templates>?

"In the absence of a select attribute, the xsl:apply-templates instruction processes all of the children of the current node."
http://www.w3.org/TR/xslt/#section-Applying-Template-Rules

Why I get as an output the values of all tags?

It's because of the built-in template rules that are applied when your stylesheet does not have a template that matches the nodes you have applied templates to. In a nutshell, the built-in templates copy all descendant text nodes to the output.

redpajama_set_name: RedPajamaStackExchange


text:
Q: org.hibernate.TransientObjectException when referenced Object is In DB I hava two entities A and B like this:
class A{
     ....
     B b;
}

class B{
     ....
}

and there is an instance of B in Database with id 1. now when I want to add an instance of A which has a reference to the B with id=1 I get this Exception:
org.hibernate.TransientObjectException: object is an unsaved transient instance - save the transient instance before merging:

actually i get that exception  when i execute this code:
 entityManager.merge(a);

now if i change that to this:
a.setB(entityManager.find(B.class,a.getB().getId()))   // ensuring the object exist in DB
entityManager.merge(a);

then it works correctly! but I don't want to do that as the current B with id=1 may be different from the database version(and I want to save that in future and i don't want to save it now so i cant use cascade technique).
I know this question have been asked for thousands of times but all the answers say that the object B with id=1 should be in DB. OK it is there now but it's not working either. the only remaining point that may help is that b is an loaded by unmarshallinga a json string so its not loaded by Hibernate.
Does anybody have any idea?
Thanks.

A: If its a new instance it means its a transient instance and has no relation with the DB hence it can't save it. Only way is you have to load 'a' and then set as in your second set of code.


text:
Q: Position absolute without a set top property gives inconsistent rendering I'm working locally on a personal project, and I started noticing my navigation disappearing sometimes when refreshing.
Here is a video of the navigation disappearing without me doing anything else than executing a normal refresh in Google Chrome https://gfycat.com/ElegantNaiveKid
If I refresh again, the navigation comes back to the normal position.
looked at my CSS and saw that my navigation had position: absolute; and right: 0px;, but the top property was not set.
When I write  top: 0px; the inconsistent rendering stops.
This codepen is a litteral copy of the top of my page, with the exception of the : http://codepen.io/anon/pen/RNXWKr
On my page the navigation is made with php like this:
<?php
    $pages = [
        "work" => "Work",
        "about" => "About",
        "contact" => "Contact",
        "blog" => "Blog"
    ];
?>

<a href="<?php echo $pageURL ?>">

            <?php
                foreach ($pages as $pageLink => $pageName) {
                    echo "
$pageName
";
                }
            ?>

And then the site gets it like this: <?php require_once("elements/navigation.php") ?>
So anyone knows why this happens? Is this a bug?

A: I think you are seeing an artifact due to the part of the CSS specification related to absolute positioning and the static-position containing block.
If the offsets are not specified in your CSS for position: absolute, then the browser computes the static-position containing block and uses that positioning for the offsets.
However, the CSS specification does not really say precisely how to determine the static-position containing block, and as a result, different browsers do it differently.  It may be that Chrome has a somewhat fuzzy algorithm for the static-position computation and the result varies with refreshing the page.
As you notice, if you specify the top offset, the problem goes away because the static-position computation does not come into play.
You are not doing anything wrong, but just seeing the effects of a somewhat obscure part of the CSS specification.
Reference: http://www.w3.org/TR/2011/REC-CSS2-20110607/visudet.html#abs-non-replaced-width

A: You should not use absolute positioning. In your gif, as you inspect the list items, you can see that they are below that top header. Or you can keep the absolute positioning and set a high z-index. Have you looked at this issue in other browsers?


text:
Q: Finding location of the device I want to develop an app in HTML/JS where if the user has internet on and his app on , then I can locate his location in the google map.
Moreover, if his location changes, I can also know that.
I know app like FInd my Friend on iOS or FInd my iphone/Ipad on iOS are there, but how is it possible in html 5/ JS ??
If you can share a link or present some idea, that would be great.
I googled it up and if I have the co-ordinates i can get it on google map. But, how to get the coordinates from other device, if just his app is on.

A: You can use the navigator get the user's current position:
navigator.geolocation.getCurrentPosition(function (location)
{
     console.log(JSON.stringify(location, null, 4);
})

or watch their position:
navigator.geolocation.watchPosition(function (location)
{
     console.log(JSON.stringify(location, null, 4);
})

See here for reference

A: You can use HTML 5 to get the users location.  However, keep in mind that Google charges for the service (it's free with limits and conditions), both users have to accept the request from your site to access their location, and you can't access their location when they aren't actually in the browser on your site

A: Getting the location of the device can be done using the HTML5 Geolocation API.
Here's an example.
However, if you're attempting to get the location of another person's device you're probably going to need to build a web app that does that (some kind of RESTful that users can login into and/or share their geolocation info).
// create google map
function GoogleMap(position) {
    var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 20,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
    });

    var marker = new google.maps.Marker({
        map: map,
        position: location,
        animation: google.maps.Animation.DROP,
        title: "This is your location"
    });

    map.setCenter(location);
}
// show error if location can't be found
function showError() {
    alert("Location can't be found");
}
//execute geolocation
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(GoogleMap, showError);
}
else {
    alert("Your browser does not support Geolocation.");
}


text:
Q: Making matrix upper triangular by finding Jordan Normal Form I must make the following matrix upper triangular:
\begin{bmatrix}
    2    & 1 & 0 & 0 \\
    0 & 2 & 0 & 1 \\
    1    & 0 & 2 & 0 \\
    0 & 0 & 0 & 2
\end{bmatrix}
To do this, I'm calculating the Jordan Normal form outlined here.
There is only one eigenvalue, 2. So I must find three generalized eigenvectors (ugh).
To find the first one, I try to solve $(A-λI)v_2=v_1$, where $v_1$ is the first eigenvector:
\begin{bmatrix}
    0  \\
    0 \\
    1  \\
    0
\end{bmatrix}
So the equation is the following ($v_{21},v_{22},v_{23},v_{24}$ are the four components of $v_2$)
$$\begin{bmatrix}
    0    & 1 & 0 & 0 \\
    0 & 0 & 0 & 1 \\
    1    & 0 & 0 & 0 \\
    0 & 0 & 0 & 0
\end{bmatrix}
\begin{bmatrix}
    v_{21}  \\
    v_{22} \\
    v_{23}  \\
    v_{24}
\end{bmatrix}=
\begin{bmatrix}
    0  \\
    0 \\
    1  \\
    0
\end{bmatrix}$$
My problem is that there is a column of all zeros in the first matrix, which means that there are infinite solutions for $v_{33}$? I'm not sure what I'm doing wrong here but any help would be appreciated!

A: HINT
Since there is only an eigenvalue the Jordan canonical form is:
$$\begin{bmatrix}
    2    & 1 & 0 & 0 \\
    0 & 2 & 1 & 0 \\
    0    & 0 & 2 & 1 \\
    0 & 0 & 0 & 2
\end{bmatrix}$$
Since $J$ is obtained by $A$ from a similarity transfomation: $$P^{-1}AP=J$$
to find the generalized eigenvectors you need to solve the following system:
$$AP=PJ$$
More in detail, let ($v_i$ are the generalized eigenvectors, columns of P):
$$P=[v_1,v_2,v_3,v_4]$$
then P has to satisfy the following systems:
$$\begin{cases}Av_1=2v_1 \\ Av_2=v_1+2v_2 \\ Av_3=v_2+2v_3 \\ Av_4=v_3+2v_4\end{cases}$$
You have already solved the first now you can find $v_2$ from the second system of equation and so on.
For example the second system $(A-2I)v_2=v_1$ is:
$$\begin{bmatrix}
    0    & 1 & 0 & 0 \\
    0 & 0 & 0 & 1 \\
    1    & 0 & 0 & 0 \\
    0 & 0 & 0 & 0
\end{bmatrix}
    v_2=
\begin{bmatrix}
    0  \\
    0 \\
    1  \\
    0
\end{bmatrix}$$
thus
$$  v_2=
\begin{bmatrix}
    1  \\
    0 \\
    0  \\
    0
\end{bmatrix}$$
Finally you should obtain:
$$P=\begin{bmatrix}
    0 & 1 & 0 & 0 \\
    0 & 0 & 1 & 0 \\
    1 & 0 & 0 & 0 \\
    0 & 0 & 0 & 1
\end{bmatrix}$$


text:
Q: Could not load the Qt platform plugin "xcb" I was running a code from yolact which requires cv2 qt. I encounter the following error.

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in
"/home/zhengjie/anaconda3/envs/yolact-env/lib/python3.7/site-packages/cv2/qt/plugins"
even though it was found. This application failed to start because no
Qt platform plugin could be initialized. Reinstalling the application
may fix this problem.
Available platform plugins are: xcb, eglfs, linuxfb, minimal,
minimalegl, offscreen, vnc, wayland-egl, wayland,
wayland-xcomposite-egl, wayland-xcomposite-glx, webgl.

Within the directory of

/home/zhengjie/anaconda3/envs/yolact-env/lib/python3.7/site-packages/cv2/qt/plugins

I find the file: libqxcb.so I have tried re-installing qt but it does not work. Any help would be appreciated.

A: I also had the same problem.My opencv-python version is 4.5.3.56,in Linux.Then i reinstall opencv-python.
pip intsall opencv-python==4.3.0.36


text:
Q: Two sample $t$ test for the difference in means Assuming we have two independent samples, with the same variation, the T statistics is being constructed this way:
$$t = \frac{ (X_1 - X_2) - (\mu_1 - \mu_2)  } {S_p},$$
Where by $\bar X$ is denoted the sample mean, by $\mu$ the population mean.  Also, $S_p^2$ is
$$S_p^2 = \frac{ (n_1 - 1) S_1^2 + (n_2 - 1) S_2^2} {n_1 + n_2 - 2},$$
Where $S^2$ is the unbiased estimator of the variation (also referred as the sample variation), n is the population size.
$t$ has $n_1 + n_2 - 2$  DOF. My question is can we replace $S_p$ by $S_1$ or $S_2$ and get a $t$ with $n_1 - 1$ or $n_2 - 1$ DOF ? As far as I am seeing this is quite legit, as we will again get $N(0,1) / \sqrt{\chi^2(n_1-1)/(n_1-1)}.$
My other question is how are we able to construct this $t$ statistic, if the numerator and denominator are not independent?
Sorry for not being able to use MathJax properly.

A: (1) $t$ has $n_1 + n_2 - 2$ DOF. My question is whether we can replace $S_p$ by $S_1$ or $S_2$ and get a $t$ with $n_1 - 1$ or $n_2 - 1$ DOF ?
Because you are doing a 'pooled' t test, you have already assumed
that the variances $\sigma_1$ and $\sigma_2$ of the two populations
are equal, so we can write $\sigma_1 = \sigma_2 = \sigma.$
In that case $S_1,\, S_2\,$ and $S_p$ are all legitimate estimates
of $\sigma.$ So you $could$ legitimately make the substitution you
suggest and get $t$-statistics with the degrees of freedom you
state. $However,$ that would be a foolish substitution because,
under your assumptions, $S_p$ is the 'best' of the three estimates (being based on the most data),
and it will give you more 'power' to detect a significant
difference in means if such a difference exists.
(2) For normal data, the numerator and denominatorof $t$ $are\,$ (stochastically) independent. In particular, the random
variables $\bar X_1$ and $S_1$ are independent. Admittedly,
this is counterintuitive because $S_1$ is $functionally$
dependent on $\bar X_1$. (That is $\bar X_1$ appears in the
formula for $S_1.$) Similarly $\bar X_2$ and $S_2$ are
independent random variables. Finally, putting things together,
the numerator and denominator of $t$ are independent.
This independence of sample mean and sample SD is true $only$
for normal data. (Not for uniform data, exponential data, or
any other kind.) So it is not surprising that the result
for normal data would seem strange to you. But the independence for normal
data can be proved in a variety of ways (e.g., using linear
algebra or using moment generating functions).


text:
Q: Confused about .NET Standard vs .NET Core "interface vs implementation" explanations Context
Although I understand that .NET Standard is a specification. I also understand that platforms (like .Core or Xamarin or UWP) conforms ("implements", "supports")  picked version of .NET standard say 1.4 or 1.6. I also understand the .NET standard versions compatibility order.
Question
If I create a .NET Standard class lib in Visual Studio, and add some references, and compile it, then that particular compiled assembly must reference to  concrete particular assemblies in a particular platform. However this way this assembly bound to that platform, this makes no sense.
So there must be a less hard "reference" metadata, this compiled assembly's references must be satisfied different assemblies (with the same strong name?)
in different platform implementations, where the my assembly is about to run.
With all cloudy explanation what I miss really the explanation: How is this works in practice? The theory and analogies seem to be clear.
Missing I something?

A: All assemblies are compiled against a set of reference assemblies. This is true for all project types including .NET Standard, .NET Core and .NET Framework (and everything else.. except .NET <=3.5, but let's ignore that for simplicity).
.NET Standard defines a set of reference assemblies for each version that are used to compile .NET Standard assemblies against.
For .NET Standard 2.0, the most notable reference assembly is netstandard.dll. If you reference System.Object, the compiler will emit IL code referencing [netstandard]System.Object.
Any platform that "conforms" to .NET Standard 2.0 then has an implementation assembly netstandard.dll that either contains the type or contains type forwarding definitions. So for .NET Framework, there can be a netstandard.dll that contains a type forward to [mscorlib]System.Object. Another platform may have a different netstandard.dll that for instance forwards to [System.Runtime]System.Object.
In addition to netstandard.dll there are a few more libraries that are there to support .NET Standard 1.0-1.6 and a few other type forwarding dlls that form a compatibility shim for .NET Framework applications (See Compatibility shim used by .NET Standard 2.0 for an explanation).
There is also some tooling in place to actually allow .NET Standard assemblies being used on platforms that do not contain these forwarding assemblies. The NETStandard.Library NuGet package contains these for 1.0-1.6 and a new integrated MSBuild tooling adds support DLLs for .NET Framework 4.6.1+ for .NET Standard 1.5-2.0. .NET Framework 4.7.1 contains all the necessary assemblies so .NET Framework 4.7.1 projects do not need to add additional files to use .NET Standard assemblies.


text:
Q: The multi-part identifer "" can not be bound sql server 2008      With Vehicles As (
    Select Row_Number() Over (Order By Model.[Year] Desc, Vehicle.Msrp Asc, Vehicle.Id) As RowNumber
        , Make.[Name] As Style_Model_Make_Name
        , Model.[Name] As Style_Model_Name
        , Model.[Year] As Style_Model_Year
        , Style.Trim As Style_Trim
        , Style.[Name] As Style_Name
        , Style.BodyType As Style_BodyType
        , Vehicle.CompanyId As Company_Id
        , Vehicle.Id
        , Vehicle.StyleId As Style_Id
        , Vehicle.[Status]
        , Vehicle.Vin
        , Vehicle.StockNumber
        , Vehicle.ModelCode
        , Vehicle.Mileage
        , Vehicle.InteriorColor
        , Vehicle.InteriorColorCode
        , Vehicle.ExteriorColor
        , Vehicle.ExteriorColorCode
        , Vehicle.Certification
        , Vehicle.Selling
        , Vehicle.Internet
        , Vehicle.Special
        , Vehicle.Comment
        , Vehicle.IsNew
        , Vehicle.IsCertified
        , Vehicle.StockDate
From dbo.Vehicle (NoLock)
    Join dbo.Style (NoLock) On Style.Id = Vehicle.StyleId
    Left Join dbo.Engine ON dbo.Style.Id = dbo.Engine.StyleId
    Inner Join dbo.Model on dbo.Model.Id = dbo.Style.ModelId
    Inner Join dbo.Make ON dbo.Model.MakeId = dbo.Make.Id ON dbo.Style.ModelId = dbo.Model.Id
Where Vehicle.CompanyId in (9)
    And Vehicle._IsActive = 1
    And DateDiff(day, Vehicle.StockDate, GetDate()) >= @DaysInStock
    And Vehicle.Msrp Between @PriceMin And @PriceMax
    And Vehicle.Mileage Between @MileageMin And @MileageMax  And Convert(int, Model.[Year]) Between @YearMin And @YearMax And Vehicle.IsNew = 1 )

Select Style_Model_Make_Name
        , Style_Model_Name
        , Style_Model_Year
        , Style_Id
        , Style_Trim
        , Style_Name
        , Style_BodyType
        , Company_Id
        , Vehicle.Id
        , Vehicle.Vin
        , Vehicle.Mileage
        , Vehicle.StockNumber
        , Vehicle.ModelCode
        , Vehicle.InteriorColor
        , Vehicle.InteriorColorCode
        , Vehicle.ExteriorColor
        , Vehicle.ExteriorColorCode
        , Vehicle.Certification
        , Case When Vehicle.Msrp < @CallPrice Then 0 Else Vehicle.Msrp End As Msrp
        , Case When Vehicle.Selling < @CallPrice Then 0 Else Vehicle.Selling End As Selling
        , Vehicle.Internet
        , Vehicle.Special
        , Vehicle.Comment
        , Vehicle.IsNew
        , Vehicle.IsCertified
        , Vehicle.StockDate
    From Vehicles
    Where RowNumber Between @StartRowIndex And (@StartRowIndex + @MaximumRows) - 1

I am new to sql server and trying to figure things out.
I am trying to create a CTE to make selecting different columns easier. I assume there is something wrong with my FROM statement but I'm not sure what exactly is wrong. All the columns in the second SELECT statement have red sqiggles which return and error of "The multi-part identifer "" can not be bound" error. Have any ideas of how to fix this?

A: Remove Vehicle. from column names in your main SELECT:
Select Style_Model_Make_Name
            , Style_Model_Name
            , Style_Model_Year
            , Style_Id
            , Style_Trim
            , Style_Name
            , Style_BodyType
            , Company_Id
            , Vehicle.Id
            , Vehicle.Vin
            , Vehicle.Mileage
            , Vehicle.StockNumber
            , Vehicle.ModelCode
            , Vehicle.InteriorColor
            , Vehicle.InteriorColorCode
            , Vehicle.ExteriorColor
            , Vehicle.ExteriorColorCode
            , Vehicle.Certification
            , Case When Vehicle.Msrp < @CallPrice Then 0 Else Vehicle.Msrp End As Msrp
            , Case When Vehicle.Selling < @CallPrice Then 0 Else Vehicle.Selling End As Selling
            , Vehicle.Internet
            , Vehicle.Special
            , Vehicle.Comment
            , Vehicle.IsNew
            , Vehicle.IsCertified
            , Vehicle.StockDate
        From Vehicles
        Where RowNumber Between @StartRowIndex And (@StartRowIndex + @MaximumRows) - 1


text:
Q: $x^Ty \le 1$ for all $y$ with $||y||_2 = 1$ iff $||x||_2 \le 1$
$x^Ty \le 1$ for all $y$ with $||y||_2 = 1$ iff $||x||_2 \le 1$

I can prove $\Leftarrow$ but I can't see a way to prove $\Rightarrow$.
I start with Cauchy's inequality and have $x^Ty \le ||x||_2 ||y||_2 \le ||x||_2$ since $||y||=1$ but I can't figure a way to show that $||x||_2 \le 1$ from this.
Anyone have any ideas?

A: Let $y = \frac{x}{\|x\|_2}$, so $\|y\|_2 =1$. Then $$x^T y = \frac{x^T x}{\|x\|_2}=\frac{\|x\|_2^2}{\|x\|_2}=\|x\|_2,$$
giving the required result.

A little idea of why this is the natural approach to take: Our goal is to show that $\|x\|_2 \leq 1$, given that $\forall y, \|y\|_2 = 1 \implies x^T y \leq 1$. Since we know some statement is true for any $y$, it makes sense to try it at a particular $y$.
A natural choice for $y$ is then just $x$, bearing in mind that $\|x\|_2 = x^T x$. But, $x$ might not have the required magnitude. So, just scale it to make it work.


text:
Q: How to fix failed to open a session for the virtual machine kali-linux-2020.3-vbox-amd34 when I select Kali Linux and I click Start I get this error message :
Failed to load R0 module C:\Program Files\Oracle\VirtualBox/VMMR0.r0: Signature #2/3: Expected at least 2 valid paths, not 1.: \Device\HarddiskVolume2\Program Files\Oracle\VirtualBox\VMMR0.r0 (VERR_SUP_VP_UNEXPECTED_VALID_PATH_COUNT).
Failed to load VMMR0.r0 (VERR_SUP_VP_UNEXPECTED_VALID_PATH_COUNT).

anyone know how to fix it

A: The solution that worked for me was -
Uninstall Virtualbox's Extension Pack, then uninstall Virtualbox. Restart your computer.
I installed 6.0.24 version of Virtualbox and its Extension Pack.
Right-click the Virtualbox installer and choose Run As Administrator. Let the installation complete. Do not install the Extension Pack for now. Restart your computer again.
Now try Virtualbox.


text:
Q: Writing file: IOException: Stream closed I'm having trouble figuring out why I'm getting the above error with my code.  I create a new instance of both FileWriter and BufferedWriter each time the method is called, yet apparently the stream is already closed.
public static void addSpawn(Location spawn)
{
    File spawns = new File("spawns.dat");

    FileWriter write = null;
    BufferedWriter out = null;

    try
    {
        write = new FileWriter(spawns, true);
        out = new BufferedWriter(write);

        out.write(locToStr(spawn));
        out.newLine();
    }
    catch(Exception e)
    {
        System.out.println("Error writing spawn file: " + e.getMessage());
    }
    finally
    {
        if(write != null)
        {
            try
            {
                write.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }

        if(out != null)
        {
            try
            {
                out.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

Any help would be greatly appreciated.

A: BufferedWriter wraps a target Writer. When you close() it, it attempts to flush the underlying target Writer before closing it.
In your code, you invoke close() on the target FileWriter before invoking close on the BufferedWriter. When the BufferedWriter#close() tries to invoke flush on the FileWriter, that FileWriter is already closed and thus throws an exception.
You'll want to close BufferedWriter first. Better yet, use a try-with-resources
try (FileWriter write = new FileWriter(spawns, true); BufferedWriter out = new BufferedWriter(write);) {


text:
Q: Java for UI windows applications I'm .net developer and trying to study java.
I would like to know which kind of project ( on eclipse ) I can create Windows UI Applications like.
in Visual Studio this is very intuitive
any tips are welcome

A: As Andrew Thompson put it, there are a lot of choices in Java and so I would suggest you will probably want to start with the GUI introduction from the official documentation to get familiar yourself with the concept and terminology.
Then you can start to do the Java GUI tutorial (example swing) and I think this site is good on the tutorial. If you want your application to look and feel like what you have in Windows application, then take a look at this example code.
Last but not least, you will probably want to install this plugin from google to your eclipse as it assist very much during Java GUI development.


text:
Q: How do I sort a vector of pairs based on the second element of the pair? If I have a vector of pairs:
std::vector<std::pair<int, int> > vec;

Is there and easy way to sort the list in increasing order based on the second element of the pair?
I know I can write a little function object that will do the work, but is there a way to use existing parts of the STL and std::less to do the work directly?
EDIT:  I understand that I can write a separate function or class to pass to the third argument to sort.  The question is whether or not I can build it out of standard stuff.  I'd really something that looks like:
std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());

A: You can use boost like this:
std::sort(a.begin(), a.end(),
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

I don't know a standard way to do this equally short and concise, but you can grab boost::bind it's all consisting of headers.

A: For something reusable:
template<template <typename> class P = std::less >
struct compare_pair_second {
    template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {
        return P<T2>()(left.second, right.second);
    }
};

You can use it as
std::sort(foo.begin(), foo.end(), compare_pair_second<>());

or
std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());

A: Its pretty simple
you use the sort function from algorithm and add your own compare function
vector< pair<int,int > > v;
sort(v.begin(),v.end(),myComparison);

Now you have to make the comparison based on the second selection
so declare you "myComparison" as
bool myComparison(const pair<int,int> &a,const pair<int,int> &b)
{
       return a.second<b.second;
}

A: With C++0x we can use lambda functions:
using namespace std;
vector<pair<int, int>> v;
        .
        .
sort(v.begin(), v.end(),
     [](const pair<int, int>& lhs, const pair<int, int>& rhs) {
             return lhs.second < rhs.second; } );

In this example the return type bool is implicitly deduced.
Lambda return types
When a lambda-function has a single statement, and this is a return-statement, the compiler can deduce the return type. From C++11, §5.1.2/4:

...

*

*If the compound-statement is of the form { return expression ; } the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);

*otherwise, void.

To explicitly specify the return type use the form []() -> Type { }, like in:
sort(v.begin(), v.end(),
     [](const pair<int, int>& lhs, const pair<int, int>& rhs) -> bool {
             if (lhs.second == 0)
                 return true;
             return lhs.second < rhs.second; } );

A: EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

ORIGINAL ANSWER:
Just use a custom comparator (it's an optional 3rd argument to std::sort)
struct sort_pred {
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    }
};

std::sort(v.begin(), v.end(), sort_pred());

If you're using a C++11 compiler, you can write the same using lambdas:
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
    return left.second < right.second;
});

EDIT: in response to your edits to your question, here's some thoughts ...
if you really wanna be creative and be able to reuse this concept a lot, just make a template:
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
    bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
        Pred p;
        return p(left.second, right.second);
    }
};

then you can do this too:
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

or even
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());

Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P

A: You'd have to rely on a non standard select2nd

A: Try swapping the elements of the pairs so you can use std::sort() as normal.


text:
Q: unable to connect to mysql using hibernate  i am learning hibernate(version 4.1.0.Final) ,using database as mysql( version 5.5.37) i tried with different connection with port and without port also but of no use.The below is my hibernate.cgf.xml
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <!-- Names the annotated entity class -->
    <mapping class="org.ssis.prasad.dao.UserDetails"/>

</session-factory>

the below is error i am getting
Oct 26, 2014 1:49:54 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Oct 26, 2014 1:49:54 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.0.Final}
Oct 26, 2014 1:49:54 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 26, 2014 1:49:54 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 26, 2014 1:49:54 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Oct 26, 2014 1:49:54 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Oct 26, 2014 1:49:54 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Oct 26, 2014 1:49:54 PMorg.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Oct 26, 2014 1:49:54 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1
Oct 26, 2014 1:49:54 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Oct 26, 2014 1:49:54 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://127.0.0.1/test]
Oct 26, 2014 1:49:54 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Oct 26, 2014 1:49:54 PM org.hibernate.engine.jdbc.internal.JdbcServicesImpl configure
WARN: HHH000342: Could not obtain connection to query metadata : Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Oct 26, 2014 1:49:54 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 26, 2014 1:49:54 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
Oct 26, 2014 1:49:54 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Oct 26, 2014 1:49:54 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Oct 26, 2014 1:49:54 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Oct 26, 2014 1:49:54 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
ERROR: HHH000231: Schema export unsuccessful
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:675)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1086)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2483)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2516)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2301)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:190)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:173)
at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:52)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:368)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:305)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:294)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:475)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1740)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1778)
at org.ssis.prasad.hibernate.HibernateTest.main(HibernateTest.java:16)
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3119)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:599)
... 25 more

Oct 26, 2014 1:49:54 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Oct 26, 2014 1:49:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08S01
Oct 26, 2014 1:49:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1309)
at org.ssis.prasad.hibernate.HibernateTest.main(HibernateTest.java:18)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:675)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1086)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2483)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2516)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2301)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:190)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:173)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:277)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
... 5 more
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3119)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:599)
... 23 more

 So can any one please help me how to solve this.

A: The last packet sent successfully to the server was 0 milliseconds ago.

This message is the point. You can restart the MySql and have a try. Or you can search this message on Google.

A: When you installed MySQL you need start server by running mysqld.exe file or using gui. After it executing you will see: mysqld: ready for connections Version: '5.5.41' socket: '' port: 3306 ater that you can connect to your server. Read also: http://dev.mysql.com/doc/refman/5.5/en/windows-server-first-start.html


text:
Q: Implementing key-value pairs in Shiny selectInput I have key-value pair data that I want to using in a Shiny selectInput drop down list.
I want the user to select from a list of player names, but I then want to use the corresponding playerID to filter other data sets.
Is there a way to do this? My current code looks like:
selectInput("player","Select a player", Players$fullName),

I want the player drop down to be reactive based on a 'team' drop down.  My full code is:
library(shiny)
library(dplyr)

setwd("C:/Users/Michael/Documents/Baseball/Retrosheet/Shiny")
Teams <- read.csv("TeamID.csv")  # List of team names
Players <- read.csv("TeamBatter.csv") # TeamName, fullName, retroID
PlayerData <- read.csv("playerExpectedRBI.csv")  # Data keyed on PlayerID

todrop <- Players$retroID
names(todrop) <- Players$fullName

ui <- fluidPage(

  selectInput("team","Select a team:",Teams$teamID),
  selectInput("player", "Select a player", todrop),
  tableOutput("playerSummary")
)

server <- function(input,output,session){

 observe({
      PlayerList <- reactive({Players %>% filter(teamID == input$team) %>%  select(fullName,retroID)})
      updateSelectInput(session,"player", choices=PlayerList()$fullName)
      SelectedPlayerSum <- reactive({PlayerData %>% filter(resbatter == input$player)})
      output$playerSummary <- renderTable({SelectedPlayerSum()})
      })

    }

    shinyApp(ui = ui, server = server)

I'm getting the error:
Error in (function (choice, name)  :
  All sub-lists in "choices" must be named.

A: You basically need to create named list and pass it to dropdown. It will return playerID instead of player fullname.
library(shiny)

Players <- data.frame(fullname = c('John Doe', 'James Smith', 'John Smith'), playerID = c(1:3))
# create named list and pass it to dropdown
todrop <- Players$playerID
names(todrop) <- Players$fullname

ui <- fluidPage(
    selectInput("player","Select a player", todrop),
    uiOutput("out")
)

server <- function(input, output) {

    output$out <- renderUI({
        print(paste0("Players ID is: ", input$player)) # here you select player ID from dropdown (not fullnames) and can use input$player for your queries
    })
}

shinyApp(ui = ui, server = server)


text:
Q: Getting exception on bean shell assertion for org/json/simple/JSONArray error :_ jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval  org/json/simple/JSONArray
Import java method from project jar file which is placed in lib folder.
source code on written for pass json value in arraylist:
import jsonresponse.common.JsonResponseProcessor;
import assertions.AssertResponse;
import databaseresponse.common.DbResponseProcessors;
import org.json.simple.JSONArray;

String resJson = prev.getResponseDataAsString();
String res = resJson.get("queueId");
log.info("----->>>>"+resJson);

ArrayList list1 = new ArrayList();
list1.add("queueId");
list1.add("name");
list1.add("faxNumber");
list1.add("description");
list1.add("type");

ArrayList list2 = new ArrayList();
list2.add("userId");

ArrayList list3 = new ArrayList();
list3.add("agencyId");

ArrayList list4 = new ArrayList();
list4.add("usertypeId");

JsonResponseProcessor obj = new  JsonResponseProcessor();
System.out.println("%%%%%%%%%%%%%%fgfggfffgf%%%%%%%%%%%%%%%");
ArrayList Jsoin = obj.getvalueofsubmapoflist(resJson,".result[0]",list1);
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +Jsoin);

log.info(">>>"+Jsoin);

A: *

*Make sure you have all referenced .jar files in JMeter classpath (i.e. copy them to JMeter's "lib" folder). Don't forget to restart JMeter to pick the jars up

*If you still experience issues try putting your code inside try block like:
try {
    //your code here
}
catch (Throwable ex) {
    log.error("Problem in Beanshell", ex);
    throw ex;
}

This way you'll have informative stacktrace printed to jmeter.log file.

*One more way to get more information regarding your Beanshell script is putting debug(); directive to the beginning of your code. If will trigger debugging output into stdout
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on using Java and JMeter APIs from Beanshell test elements in JMeter tests.


text:
Q: general database modeling and django specific modeling I'm wondering what is the best way to model something like the following.
Lets say my company sells metal bars (parameters/fields are: length, profile_type, quantity etc.) of different profiles, where profiles may be pipe(pipe_diameter, wall_thickness) or hollow_rectangle(base, height, wall_thickness), or maybe some other profile with different parameters. Lets say maximum number of profiles would be 12, each profile having between 2-5 parameters.
Should everything be in a single table like
table_bars: id, length, quantity, profile_type, pipe_diameter, wall_thickness, base, height, etc.) where profile type would be (pipe, rectangle etc.)
or should every shape have its own table with its own parameters and in table_bars keep only id, length, quantity profile_type and profile_id)
and are there any django specific issues is multiple tables are the best answer?
Thanks

A: This is a classic issue and comes down to your own judgment.  I had a case like this many years ago and went for generalizing the parameters, in one table.  Then I made a second table that contained descriptions for the parameters based on the profile, and flags for which were required, optional, or ignored.
You various parameters might be:
Lentgh: Universal for all, no?
WidthOuter1: might be height of square or rectangle, radius of pipe, etc.
WidthOuter2: ignored for pipe and square, required for rectangle
WidthInner1: ignored for solid objects, required for hollow.  Treated just like WidthOuter1, ie., radius for pipes, dimension of square, first dimension for rectangles
WidthInner2: same ideas as WidthOther2 and Widthinner1
...And perhaps your other properties would yield to the same treatment.


text:
Q: Chrome scrolls to wrong location on anchor tags While working on this locally, chrome, safari and firefox (all on OS X) all scrolled to the proper locations when using the menu at the bottom.
Now that it's being accessed online (from a windows machine), chrome doesn't scroll to the right locations, but IE does. Interestingly, mobile safari is also having the same issue.
Each link in the footer at the bottom should scroll to its corresponding 'label'. IE does that fine, but chrome just puts me 'sort of near' there.
http://www.colinandmya.com/sitetest/index.html
Any help is greatly appreciated.
** EDIT: ADDED A JSFIDDLE **
(i hope i did it right... thanks again for letting me know the process)
http://jsfiddle.net/prefekt/aKJ3Y/
$(document).ready(function() {

function filterPath(string) {
return string
  .replace(/^\//,'')
  .replace(/(index|default).[a-zA-Z]

{3,4}$/,'')
  .replace(/\/$/,'');
  }
  $('a[href*=#]').each(function() {
    if ( filterPath(location.pathname) ==

filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
  var $targetId

= $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
  var $target = $targetId.length ? $targetId :

$targetAnchor.length ? $targetAnchor : false;
   if ($target) {
     var targetOffset = $target.offset().top;

 $(this).click(function() {
       $('html, body').animate({scrollTop: targetOffset}, 1000);
       return false;

 });
  }
}
  });
});

A: I think that the problem is how you are embedding the youtube video. z-index is ignored
try this script to fix
$(document).ready(function(){
    $('iframe').each(function(){
          var url = $(this).attr("src");
          var char = "?";
          if(url.indexOf("?") != -1){
                  var char = "&";
           }

          $(this).attr("src",url+char+"wmode=transparent");
    });
});

or just embed video in this way
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/xxxxxx?wmode=transparent" frameborder="0" wmode="Opaque">

and not in this way
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/xxxxx" frameborder="0" wmode="Opaque">

A: Move the following line:
var targetOffset = $target.offset().top;

To within the click event:
$(this).click(function() {
    var targetOffset = $target.offset().top;
    $('html, body').animate({scrollTop: targetOffset}, 1000);
    return false;
});

The variable was being set outside of the click event and this the targetOffset was not a current value when clicked. For more information on this, look up Javascript variable scope.


text:
Q: Android app unable to start activity componentinfo google map v2 i am trying to do this google map v2 tutorial and i run in to a problem
i did add the google-play-services-lib to my project
runing on emulator v:4.3 APILevel:18 cpu/abi:arm
i never used fragments befor soo i think that may be the root of the problem but i cant be sure
i am geting this error:

11-04 13:35:31.572: E/AndroidRuntime(1375): FATAL EXCEPTION: main
      11-04 13:35:31.572: E/AndroidRuntime(1375): java.lang.RuntimeException: Unable to start activity ComponentInfo{asaf.workfinder/asaf.workfinder.MainActivity}: android.view.InflateException: Binary XML file line #14: Error inflating class fragment
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.os.Handler.dispatchMessage(Handler.java:99)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.os.Looper.loop(Looper.java:137)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.ActivityThread.main(ActivityThread.java:5103)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at java.lang.reflect.Method.invokeNative(Native Method)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at java.lang.reflect.Method.invoke(Method.java:525)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at dalvik.system.NativeStart.main(Native Method)
      11-04 13:35:31.572: E/AndroidRuntime(1375): Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class fragment
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.Activity.setContentView(Activity.java:1895)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at asaf.workfinder.MainActivity.onCreate(MainActivity.java:13)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.Activity.performCreate(Activity.java:5133)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     ... 11 more
      11-04 13:35:31.572: E/AndroidRuntime(1375): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.MapFragment: make sure class name exists, is public, and has an empty constructor that is public
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.Fragment.instantiate(Fragment.java:592)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.Fragment.instantiate(Fragment.java:560)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.Activity.onCreateView(Activity.java:4738)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     ... 21 more
      11-04 13:35:31.572: E/AndroidRuntime(1375): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.maps.MapFragment" on path: DexPathList[[zip file "/data/app/asaf.workfinder-1.apk"],nativeLibraryDirectories=[/data/app-lib/asaf.workfinder-1, /vendor/lib, /system/lib]]
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     at android.app.Fragment.instantiate(Fragment.java:582)
      11-04 13:35:31.572: E/AndroidRuntime(1375):     ... 24 more

manifest.xml:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="asaf.workfinder"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="18" />
    <permission
        android:name="asaf.workfinder.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="asaf.workfinder.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

          <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="my api key" />

        <activity
            android:name="asaf.workfinder.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

layout:
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/tv1"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        />

    <fragment
          android:id="@+id/asafmap"
          android:layout_below="@+id/tv1"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

</RelativeLayout>

and MainActivity:
package asaf.workfinder;

import android.os.Bundle;
import android.view.View.OnCreateContextMenuListener;
import android.app.Activity;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}

A: you can follow this link....
http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/
Add google play services lib and mpas jar file into project...

A: Unable to instantiate fragment com.google.android.gms.maps.MapFragment: make sure class name exists, is public, and has an empty constructor that is public

Be sure you added the google_play_services correctly in ur project
Set Up Google Play Services SDK
BTW, Google Map V2 doesn't support to run in the emulator to run it in the emulator follow
this post


text:
Q: Issue in list view web part in Sharepoint Publishing page I have a the publishing Site "http://devsp11/sites/publishingSite".
Now on home page i want to provision list view web part with "Add new Item Link" of Documents library.
I have probisioned list view web part as below.Where i have inline with red is my list view web part adnd it's propert full toolbar.
But still i am not getting "Add new item Link" in list view web part.
Can anyone please help me out to find a root cause of this issue ?


text:
Q: Cases relationship in salesforce? Cases in salesforce are customer's question or feedback on the service they are providing.
Eg. if a company sell a product A. Then A will be added to opportunitylineItem. When we have a problem with product we need to log a case on a particular opportunitylineItem. But in standard salesforce service cloud case have lookup to contact and Account.
I am not able to understand if a Account have more than opportunity then how it identified to which product the case been loged (In standard salesforce service cloud). Please correct me if I am wrong.

A: Cases can't have links to Opportunity Line Items directly. However, there are two fields you can expose, Asset and Product, which allows you to link to a specific product, or an asset, which is an instance of a product that belongs to an account or contact.
Generally speaking, upon winning an opportunity, assets should be created for the account in order to note which products they actually have. This would also allow you to specify things like serial numbers, product, and custom attributes specific to your line of business. Some companies do this manually, some have written code to do this automatically, and some do not track this data at all (but, for most companies, I'd say that they probably should track this information).
In fact, if you are using assets, you can go to an account, locate the appropriate asset, and click the New Case button to automatically start a new case for that specific product. When everything is set up, creating a new case from the asset page will populate the account, contact, asset, and product for you automatically. This can greatly reduce the complexity needed to start a new case. Of course, it would also be possible to use other methods, like a Visualforce page, etc to populate this data, but can definitely be done out of the box with minimal effort required.

A: Case does not has direct standard relationship with Product object. There is standard object "Asset" which does this work.
There are two ways you can keep track of product for which the Case is logged.

*

*Create picklist on Case object and enter product code there. But that will increase the manual work as you will always have to update the multi-picklist when product is added. But advantage is that you can keep track Case related to multiple products on single record.

*You can create lookup relationship field Product and Opportunity on Case object and associate product and opportunity with that case. Here only one product can be associated with one case. But Case object have self relationship so, it can be utilized.


text:
Q: "Data connections" in azure I have a question about "Data connections" in azure.
I have an App Service. I published my API app there. In my app I have connection strings (I need to work with databases). Among numerous settings for my app I saw a "Data connections" item:
There you can add new connection (server, login, password). After creation you can look at connection string for this connection:
My questions are:
 1. what does it do? (I mean in my app I already have a connection string in Web.config and is there any advantages of using connection string in azure?)
 2. how to use this "connection from azure" in my app?
I'll appreciate any help.

A: After you add a Data Connection, you can find that it is configured to Connection strings section under Application settings blade. And for .NET apps, these connection strings are injected into your .NET configuration connectionStrings settings at runtime, overriding existing entries where the key equals the linked database name.

Besides, you can find Data Connection section is under Mobile tab, when we do with Azure Mobile Apps' Easy Tables, we need Data Connection to connect to a database.

A: Data connections help you create a SQL database in azure and then helps you add the necessary connection string so that you can use it form your app.
If you already have a database/connection string, you can ignore this.


text:
Q: On constructing a histogram using matplotlib, on what occasions should one expect the following error: ValueError: `bins` must be 1d, when an array I am receiving the error ValueError: `bins` must be 1d, when an array on construction of a histogram with matplotlib. I want to debug it myself, only wanting a direction, so I am not displaying the code.

A: As i understand your question you mast use not hyst
insert_axes.bar(x = tips_per_day['day'], height = tips_per_day['max'],
                width = 0.6, align = 'edge')
insert_axes.bar(x = tips_per_day['day'], height = tips_per_day['min'],
                width = -0.6, align = 'edge')


text:
Q: Using INTERVAL in PostgreSQL to add hours date/time Here is the code in PostgreSQL I am trying to run:
select DATE_ADD(whenbooked,INTERVAL 4 HOUR) from booking WHERE id = 12310;

OR I try to run this code:
select DATE_ADD('2010-11-19 01:11:22',INTERVAL 4 HOUR)

Both codes access date/time stored in the same manner:

2010-11-19 01:11:22

PostgreSQL error code is this:

ERROR: syntax error at or near "4"

it is referring to the '4' in the line 'INTERVAL 4 HOUR'.
I can't figure out what the issue is.
I need to compare a time/stamp (written in exactly the same format as above) with the stored time/date PLUS 4 hours.
So the desired end result is to return: '2010-11-19 05:11:22'.
If this can be done in PHP or directly in SQL?

A: Based on your comment

I am just typing these codes into PgAdmin.

It looks like you're actually using PostgreSQL not MySQL.
You can view your existing code running on PostgreSQL in action on PostgreSQL here which gives the same error as you get above.
To correctly work with dates in PostgreSQL, you can view a list of date functions on the PostgreSQL documentation site here
What you're trying to do is this:
SELECT TIMESTAMP '2010-11-19 01:11:22' + INTERVAL '4 HOURS';

A: I found a method that works for me in PHP:
$desiredEndTime = strtotime("2010-11-19 01:11:22 + 10 hours");
echo date("Y-m-d H:i:s", $desiredendtime);

Looks like it converts the date/time into a weird-looking integer. And then on the second line it converts it back into my desired format. Now I can just insert that back into SQL.
Thanks!

A: Convert it simply to timestamp with "strtotime" method and then you can do whatever you like with that


text:
Q: Fastest way to add a constant column into a array What is the fastest way to add a constant (1 in this test) into a array?
There is my attempt:
m=RandomInteger[100,{100000,30}];
(test1={##,1}&@@@m)//AbsoluteTiming//First
(test2=Join[m,ConstantArray[{1},Length@m],2])//AbsoluteTiming//First
(test3=Thread@Append[Transpose@m,1])//AbsoluteTiming//First
(test4=Join[#,{1}]&/@m)//AbsoluteTiming//First
(test5=Append[#,1]&/@m)//AbsoluteTiming//First
(test6=Join[m,{0}&/@m,2])//AbsoluteTiming//First
(test7=ArrayFlatten@{{m,0}})//AbsoluteTiming//First
(test8=ArrayPad[m,{{0,0},{0,1}}])//AbsoluteTiming//First

0.304553
0.171397
0.170948
0.054199
0.064244
0.013391
0.010672
0.009288

It's the first way a good answer?


text:
Q: How to use ASCII in array I want to write a program that takes a string text, counts the appearances of every letter in English and stores them inside an array.and print the result like this:
java test abaacc
a:***
b:*
c:**

* - As many time the letter appears.
public static void main (String[] args)  {
   String input = args[0];
   char [] letters = input.toCharArray();
   System.out.println((char)97);
   String a = "a:";
   for (int i=0; i<letters.length; i++) {
      int temp = letters[i];
      i = i+97;
      if (temp == (char)i) {
         temp = temp + "*";
      }
      i = i - 97;
   }
   System.out.println(temp);
}

A: Writing (char)97 makes the code less readable. Use 'a'.
As 3kings said in a comment, you need an array of 26 counters, one for each letter of the English alphabet.
Your code should also handle both uppercase and lowercase letters.
private static void printLetterCounts(String text) {
    int[] letterCount = new int[26];
    for (char c : text.toCharArray())
        if (c >= 'a' && c <= 'z')
            letterCount[c - 'a']++;
        else if (c >= 'A' && c <= 'Z')
            letterCount[c - 'A']++;
    for (int i = 0; i < 26; i++)
        if (letterCount[i] > 0) {
            char[] stars = new char[letterCount[i]];
            Arrays.fill(stars, '*');
            System.out.println((char)('a' + i) + ":" + new String(stars));
        }
}

Test
printLetterCounts("abaacc");
System.out.println();
printLetterCounts("This is a test of the letter counting logic");

Output
a:***
b:*
c:**

a:*
c:**
e:****
f:*
g:**
h:**
i:****
l:**
n:**
o:***
r:*
s:***
t:*******
u:*


text:
Q: Android app facebook login : NULL pointer exception My problem is somewhat like these only... First and Second Question. I've tried everything given on these posts but to no relief.
So I am using android-simple-facebook library to create a facebook login. Here's my LoginActivity.java
public class LoginActivity extends Activity {
    private Button mButtonLogin;
    private SimpleFacebook mSimpleFacebook;
    protected static final String TAG = LoginActivity.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mSimpleFacebook = SimpleFacebook.getInstance();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mButtonLogin = (Button) findViewById(R.id.button_login);
        setLogin();
    }

    public void setLogin() {

        final OnLoginListener onLoginListener = new OnLoginListener() {
            @Override
            public void onLogin() {
                Log.i(TAG, "Logged in");
            }
        };

        mButtonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mSimpleFacebook.login(onLoginListener);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
       // mSimpleFacebook = SimpleFacebook.getInstance();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mSimpleFacebook.onActivityResult(this, requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

}

But as soon as i click the login button, the app crashes with NullPointerException. Here's the LogCat
09-21 15:54:40.109: E/AndroidRuntime(21895): FATAL EXCEPTION: main
09-21 15:54:40.109: E/AndroidRuntime(21895): Process: www.kb.com, PID: 21895
09-21 15:54:40.109: E/AndroidRuntime(21895): java.lang.NullPointerException
09-21 15:54:40.109: E/AndroidRuntime(21895):    at www.kb.com.LoginActivity$2.onClick(LoginActivity.java:81)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at android.view.View.performClick(View.java:4438)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at android.view.View$PerformClick.run(View.java:18422)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at android.os.Handler.handleCallback(Handler.java:733)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at android.os.Handler.dispatchMessage(Handler.java:95)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at android.os.Looper.loop(Looper.java:136)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at android.app.ActivityThread.main(ActivityThread.java:5001)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at java.lang.reflect.Method.invokeNative(Native Method)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at java.lang.reflect.Method.invoke(Method.java:515)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
09-21 15:54:40.109: E/AndroidRuntime(21895):    at dalvik.system.NativeStart.main(Native Method)

A: Please check if you are using the correct API-call. The API documentation states for getInstance()
/**
 * Get the instance of {@link SimpleFacebook}.

 *

 * Important: Use this method only after you initialized this library
 * or by: {@link #initialize(Activity)} or by {@link #getInstance(Activity)}
 *
 * @return The {@link SimpleFacebook} instance
 */
public static SimpleFacebook getInstance() {
    return mInstance;
}

I did not see a call like initialize(Activity) or getInstance(Activity) in your code snippet.

A: As it turns out there was nothing wrong with the code or the library, but was an issue with android support lib. I finally found the solution here


text:
Q: Is there a formula for calculating length given pixel density? I know you can use various AR packages to do this, but wondering what the formula is to calculate length given a few known values.
For example, let's say my phone is at the same height as a wood dowel, that the dowel rests perpendicular to the phone, and that both the phone and the dowel are parallel to the ground. I know that the phone is exactly 10' away from the dowel and I know the pixel density of my phone is 512. I take a photo. On that photo I then pick one of the ends of the dowel and mark it and determine that it is exactly 1024 pixels from the center. What is the length of the dowel?
There has to be some sort of conversion of pixels to distance but I can't find it.
Anyone know what it is?

A: The problem is that the pixel density you're describing is for your phone's screen, but the measurements you want to take are from a picture taken with your camera. In fact, all the relevant measurements have to be from your camera. You would probably need to know the focal length, and the field of view.
I'm sure that you could come up with the proper formula to calculate it on your specific device, but you wouldn't be able to create a general formula for any device that uses your app. Those AR libraries generally use some markers (or calibration) to figure out the device's camera attributes, and they then use those measurements to calculate everything else.
So, in short, you're better off using the libraries that are made to do this, unless you want to implement all of the calibration in your app


text:
Q: nested alist to plist with alexandria Alexandria has been great to convert a simple alist to a plist, e.g.:
> (get-document "flower-photo-with-lytro")

((:|_id| . "flower-photo-with-lytro")
 (:|_rev| . "6-eb6d9b71251c167039d3e73d8c0c9a63")
 (:TITLE . "flower-photo-with-lytro")
 (:AUTHOR . "devnull")
 (:TEXT . "hello here is a  sample flower .... ")
 (:TIME . "3558566236"))

> (alexandria:alist-plist (get-document "flower-photo-with-lytro"))

(:|_id| "flower-photo-with-lytro" :|_rev| "6-eb6d9b71251c167039d3e73d8c0c9a63"
 :TITLE   "flower-photo-with-lytro" :AUTHOR "devnull"
 :TEXT "hello here is a sample flower .... " :TIME "3558566236")

How can I use alexandria to format a more structured alist like
> (invoke-view "hulk" "time")

((:|total_rows| . 2)
 (:|offset| . 0)
 (:|rows|
  ((:|id| . "flower-photo-with-lytro")
   (:|key| . "3558566236")
   (:|value| . "flower-photo-with-lytro"))
  ((:|id| . "hello-world-in-common-lisp-and-restas")
   (:|key| . "3558567019")
   (:|value| . "3558567019-hello-world-in-common-lisp-and-restas"))))

to obtain a plist with :id, :key and :value?

A: (defparameter *test*
  '((:|total_rows| . 2)
    (:|offset| . 0)
    (:|rows|
     ((:|id| . "flower-photo-with-lytro")
      (:|key| . "3558566236")
      (:|value| . "flower-photo-with-lytro"))
     ((:|id| . "hello-world-in-common-lisp-and-restas")
      (:|key| . "3558567019")
      (:|value| . "3558567019-hello-world-in-common-lisp-and-restas")))))

(defun rows-alist (tree)
  (list (car tree)
        (cadr tree)
        (alexandria:flatten (caddr tree))))

Well, I'll try to guess...

And if you wanted to rename the keywords:
(defun rows-alist (tree)
  (list (car tree)
        (cadr tree)
        (mapcar
         #'(lambda (x)
             (if (symbolp x)
                 (intern
                  (string-upcase (symbol-name x))
                  "KEYWORD") x))
         (alexandria:flatten (caddr tree)))))


text:
Q: Proof of Stirling number symmetric formulas I'm looking for a reference to a proof of formulas 6.26 and 6.27 in Concrete Mathematics:
$\def\sone#1#2{\left[#1\atop #2\right]}
\def\stwo#1#2{\left\{#1\atop #2\right\}}
$
$$ \stwo{n}{n-m} = \sum_k \binom{m-n}{m+k}\binom{m+n}{n+k}
\sone{m+k}{k} $$
$$\sone{n}{n-m} = \sum_k \binom{m-n}{m+k}\binom{m+n}{n+k}
\stwo{m+k}{k}$$

A: $\def\sone#1#2{\left[#1\atop #2\right]}
\def\stwo#1#2{\left\{#1\atop #2\right\}}
$
These formulas can be proved by Lagrange interpolation, using the fact that
$\stwo{n}{n-m}$ and $\sone{n}{n-m}$ are polynomials in $n$ of degree $2m$. See H. W. Gould, The Lagrange interpolation formula and Stirling numbers, Proc. Amer. Math. Soc. 11 (1960), 421–425


text:
Q: tutorial vid was made in 2018 need help. supposed to be a switch static void Main(string[] args)
    Console.WriteLine(GetDay(0));

static string GetDay(int dayNum) {
            string dayName;
            switch ("dayNum")
            {

                case 0 :
                    dayName = "Sunday";
                    break;
                case 1 :
                    dayName = "Monday";
                    break;
                case 2 :
                    dayName = "Tuesday";
                    break;
                case 3 :
                    dayName = "Wednesday";
                    break;
                case 4 :
                    dayName = "Thursday";
                    break;
                case 5 :
                    dayName = "Friday";
                    break;
                case 6 :
                    dayName = "Saturday";
                    break;
                defualt:
                    dayName = "invalid Day";
                    break;
            }
            return dayName;

im wracking my brain here all the code is except the number after case and its not registering the dayname that is supposed to be connected to the days
any help im doing a training video on youtube but its from 2018 and i think some of what hes teach has had subtle changes

A: switch ("dayNum") .. the variable dayNum is suposed to be without quotes.
like this,
switch (dayNum)

What you are doing is a switch statement on a string "dayNum" which will only be true in `case "dayNum".. but in your case you need to use the variable being passed as the argument. So, remove the quotes.


text:
Q: What is the highest check frequncy in WebDriverWait (python+selenium)? I'm using python3+selenium+Chrome, and I wonder what is the highest poll_frequncy here? cuz I really want it to be able to react fast enough...
eg:
WebDriverWait(driver, 50, 0.05).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".mui-amount-increase")))
Thanks a lot!!


text:
Q: Powershell: Filtering flat arrays I'm working on a PS script for making some of our processes easier and more automated and I've quickly found myself well outside my (limited) PowerShell knowledge.
Context: I'm building a UI that has two ComboBox controls and a handful of text boxes for creating resource calendars. The first ComboBox has a static list of 3 sub-divisions in my organization. The second ComboBox has a list of the offices in that division which should automatically update when a selection is made in the first box.
The end goal is to generate the Exchange Management Shell code necessary to create mailboxes with the necessary uniform naming convention:
New-Mailbox -Name 'Acme Inc $division $office $subdivision Resource Name' -Alias 'resourcename'-OrganizationalUnit '<path/to/OU>' -UserPrincipalName 'resourcename@acmeinc.lcl' -SamAccountName 'resourcename'

Right now I'm thinking I'll build these off of a single array which has three fields that correspond to division, sub-division, and office:
Note: Division 1 has no subdivisions, while division 2 has two subdivisions. Combobox 1 should list division 1, subdivision 1, subdivision 2.
$arr_AgencyOffices = @(
     'division 1','division 1','Aberdeen'
     'division 1','division 1','Perth'
     'division 1','division 1','Sacramento'
     'division 1','division 1','Long Beach'
     'division 1','division 1','New York'
     'division 1','division 1','Dallas'
     'division 1','division 1','Miami'
     'division 1','division 1','Vancouver'
     'division 2','subdivision 1','Sacramento'
     'division 2','subdivision 1','Tumwater'
     'division 2','subdivision 1','Vancouver'
     'division 2','subdivision 2','Aberdeen'
     'division 2','subdivision 2','Centralia'
     'division 2','subdivision 2','Sacramento'
     'division 2','subdivision 2','Long Beach'
     'division 2','subdivision 2','Shelton'
     'division 2','subdivision 2','Dallas'
     'division 2','subdivision 2','Stevenson'
     'division 2','subdivision 2','Miami'
     'division 2','subdivision 2','Vancouver'
)

Specific Question: How do I return only the matching office location values into $arr_Offices given any specific cbo1.SelectedItem?

A: What you show in your example is not a multi-dimensional array, it's just a regular flat array.
To get a multi-dimensional (or rather, a jagged) array, do:
$arr_AgencyOffices = @(
    @('division 1','division 1','Aberdeen'),
    @('division 1','division 1','Perth'),
    @('division 1','division 1','Sacramento'),
    @('division 1','division 1','Long Beach'),
    @('division 1','division 1','New York'),
    @('division 1','division 1','Dallas'),
    @('division 1','division 1','Miami'),
    @('division 1','division 1','Vancouver'),
    @('division 2','subdivision 1','Sacramento'),
    @('division 2','subdivision 1','Tumwater'),
    @('division 2','subdivision 1','Vancouver'),
    @('division 2','subdivision 2','Aberdeen'),
    @('division 2','subdivision 2','Centralia'),
    @('division 2','subdivision 2','Sacramento'),
    @('division 2','subdivision 2','Long Beach'),
    @('division 2','subdivision 2','Shelton'),
    @('division 2','subdivision 2','Dallas'),
    @('division 2','subdivision 2','Stevenson'),
    @('division 2','subdivision 2','Miami'),
    @('division 2','subdivision 2','Vancouver')
)

Now you can index into the value on two dimensions:
$arr_AgencyOffices[4][2] # New York

That being said, I would probably arrange the offices into a set of nested hashtables, like so:
$AgencyOffices = @{
    'division 1' = @{
        'division 1' = @(
            'Aberdeen'
            'Perth'
            'Sacramento'
            'Long Beach'
            'New York'
            'Dallas'
            'Miami'
            'Vancouver'
        )
    }
    'division 2' = @{
        'subdivision 1' = @(
            'Sacramento'
            'Tumwater'
            'Vancouver'
        )
        'subdivision 2' = @(
            'Aberdeen'
            'Centralia'
            'Sacramento'
            'Long Beach'
            'Shelton'
            'Dallas'
            'Stevenson'
            'Miami'
            'Vancouver'
        )
    }
}

Now you can index into the subdivision arrays using their actual names:
PS C:\> $AgencyOffices['division 2']['subdivision 1']
Sacramento
Tumwater
Vancouver

This makes it trivial to retrieve the correct lists for the comboboxes given that you can just take the selected text of the preceding choice to find the next list:
$combobox2List = $AgencyOffices[$combobox1.SelectedText].Keys

and so on


text:
Q: error says it a Pandas DataFrame when dumping a Python dict I have a Python dictionary, but when I try to dump it as a JSON file, it says it is a Pandas DataFrame!
import pandas as pd
import os
import re
import json

files_net = [f for f in os.listdir('.') if re.match(r'network_.+.json', f)]

networks = {}
for file in files_net:
    with open(file) as f:
        networks[re.search(r'network_(.+).json', file).group(1)] = pd.read_json(f)
type(networks)

>>> dict

with open('networks.json', 'w') as f:
    json.dump(networks, f)

TypeError: Object of type DataFrame is not JSON serializable

A: Yes networks is a dictionary, but values of it are pd.DataFrames because they come from pd.read_json; hence the error. You might try to_json whilst forming the key-value pairs:
networks[re.search(r'network_(.+).json', file).group(1)] = pd.read_json(f).to_json()

But since you are reading json anyway, you might use json module in the first place e.g. json.load(f).


text:
Q: PyTest not discovering new test module, but changes made in old test modules are reflected in execution (This has been fixed, please read the edit at the bottom even if nobody submits an answer)
I am writing tests for an app using PyTest, and had three test modules as of this evening. They work as expected, and any changes I make to them are reflected in the test execution (I intentionally put incorrect assertions to be completely sure). However, I added a new module this evening (which also begins with test_ and does not contain a class (so this SO answer does not apply), it is in fact almost identical in structure to one other test module) and no matter what I do PyTest refuses to discover it. I am using VS Code for development, but I tried running pytest from the terminal as well, to the same effect.
This issue on GitHub suggested I try rm -rf .cache which solved nothing. I tried removing all my __pycache__ files just to be safe as well as the .pytest_cache file, to no avail. I checked the contents of the .pytest_cache file after removing and running pytest again, and none of the new tests are shown in the nodeids. I do not get any errors, in particular test_grader.py, test_misc.py and test_solution_optimal.py work perfectly fine. Here is proof haha. test_solution_student.py is an exact copy of test_solution_optimal.py with a few deliberately incorrect assertions, but pytest won't discover it no matter what I do. Additionally, the __pycache__ in the tests directory contains a .pyc file corresponding to test_solution_student.py, which is just plain strange to me. I even tried renaming the file to something different thinking the discovery might be ignoring the second test because they both start with test_solution_, but nope.
I only enabled pytest as recommended here and the autoTestDiscover.... is enabled as well. However since running pytest from the terminal does not result in the discovery of the last module either I doubt it's an issue with my VS code settings file.
Directory structure:
Top-Level Directory
├── .pytest_cache
│   └── v
├── Grader
│   ├── (Several files to be tested)
│   ├── __init__.py
│   └── __pycache__
├── __pycache__
│   └── globals_store.cpython-37.pyc
├── graphs
│   ├── (Additional irrelevant files)
├── tests
│   ├── __pycache__
│   ├── test_grader.py
│   ├── test_misc.py
│   ├── test_solution_optimal.py
│   └── test_solution_student.py
└── venv
    ├── bin
    ├── include
    ├── lib
    └── share

I run pytest from the Top-Level Directory.
If somebody could give me a lead on what else I could try that might result in the test module being discovered I would forever be in your debt. I am not supposed to share the project since this is part of a homework assignment I am creating, but I am working on reproducing this issue in a dummy project.
Edit:
I "fixed" it; the issue lay with me duplicating the test_solution_optimal file, (duplicating code did smell funny to me, should have known to trust my intuition but I couldn't use that code out of the box and needed to make subtle modifications) which resulted in me redefining a fixture which I have now moved to a conftest.py file (I'm new to pytest, please forgive). I now know not to duplicate code (like, ever) but I am still curious as to why this was causing an issue which is why I chose not to add this as an answer to my question. If somebody could chime in with an explanation, be my guest :D


text:
Q: $RS$ is a subgroup if $RS=SR$ I'm stuck trying to prove that the product of two subgroups $R$ and $S$ is a subgroup too when $RS=SR$. I see I need to show that $RS$ is closed under its product and inverses. The first one I've proved by assuming that $RS = SR$:
$$r_1s_1\cdot r_2s_2 = r_1(s_1 r_2) s_2 = (r_1r_3) \cdot (s_3 s_2) $$, $s_1 r_2 = r_3 s_3$ since $RS=SR$.
The problem is to prove $(r_1 s_1)^{-1}\in RS$.
UPD:
The answer $(r_1 s_1)^{-1} = s_1^{-1} r_1^{-1}$ looks nice but it would be great if somebody would explain me why it is so.
UPD2:
The proof of the statement  $(r_1 s_1)^{-1} = s_1^{-1} r_1^{-1}$ is here.

A: You  have $(rs)^{-1}=s^{-1}r^{-1}\in SR=RS$.


text:
Q: Is there any difference between using a $watch and ng-change to detect the change in a select list? I've been using code like to watch in this case a couple of select dropdown lists:
   this.$watchCollection('[config.statusId, config.typeId]',
        function (newValue, oldValue) {
            if (_o.checkWatch(newValue, oldValue)) {
                _u.putConfigs(this.config);
                home.grid.backup = [];
                home.grid.data = [];
            }
        }.bind(this));

   var _checkWatch = function (newValue, oldValue) {
       for (var i = 0, l = newValue.length; i < l; i++) {
           if (newValue[i] === null || newValue[i] < 0 || newValue[i] >= 999
            || oldValue[i] === null || oldValue[i] < 0 || oldValue[i] >= 999)
               continue;
           if (newValue[i] !== oldValue[i]) {
               return true;
           }
       }
       return false;
   };

I was unaware of ng-change and I am now thinking it may be better to use that for detecting when a user changes the value in a select list.  With ng-change I could then call a function to do:
   _u.putConfigs(this.config);
   home.grid.backup = [];
   home.grid.data = [];

With this in mind can anyone think of a reason why I should not go to ng-change to detect when a user makes a change?

A: The $watch will check the values (old and new) and compare them every time anything causes the Angular $digest cycle to run. Using ng-change does roughly the same thing, but I believe it is syntactically more correct to use (not to mention that it appears to be less code in your case.)


text:
Q: Accordion script does not work in ajax update panel I am having jquery accordion plugin which is inside ajax update panel in an aspx page. The accordion section consists of header h3 tag and content div tag, content area also having aspx button. When the page loads we can hide or show content area by clicking on accordion header. The problem occurs after i click on aspx button which is in content area that accordion show and hide function stops working.
Here is the sample code.
<asp:ScriptManager ID="sm1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="upnlAccordion" runat="server" UpdateMode="Conditional" >
            <ContentTemplate>

Header

                        Content Text
                        <asp:Button ID="btnClick" runat="server" Text="Click Button" />

            </ContentTemplate>
        </asp:UpdatePanel>

A: You can move the updatepanel into the content div, which will prevent the accordioned elements from being redrawn and losing their bindings. This is the simplest solution I know of, and is pretty foolproof when interacting with plugins.


text:
Q: Storing address in a small database program I am writing a small program with a database organized with the following struct:
typedef struct {
    char fname[20];
    char lname[20];
    char phone[12];
    char address[50];
} database;

When I ask to input all the values of one entry, I do it as below (the var save is 0 at the beginning of the program):
   if(option == 1)
    {
        printf("\nPlease input each of the following parameters separated by space: \n");
        printf("Firstname Lastname Phone Address: \n");
        scanf("%s %s %s %s", &list[save].fname, &list[save].lname, &list[save].phone, &list[save].address);
        save++;
        printf("\n\n!!!!! DONE !!!!!\n\n");
    }

The problem is, I want the last string input (address) to be able to store a complete sentence with spaces. When I input something like for example Andres Guerra +15551234 55555 AB Ave., UT. It will only save in list[save].address the 55555, the rest of the things stays stored for the next input, causing storage discrepancies.
How can I save in the address struct element a complete sentence with spaces included?
NOTE: I also tried making an additional scanf of %s with the address alone, but it did not work either.
If I use Country instead of Address, the program works fine.

A: Try using
scanf("%s %s %s %49[0-9a-zA-Z ]",
  &list[save].fname,
  &list[save].lname,
  &list[save].phone,
  &list[save].address
);

I hope this helps.


text:
Q: Error:not all arguments converted during string formatting I have this signup page and when i am submitting the form i am getting this error:not all arguments converted during string formatting
class RegistrationForm(Form):
email = StringField('Email address')
password = PasswordField('password')
name = StringField('Name')

@app.route('/register/', methods=['GET', 'POST'])
def register():
try:
    form = RegistrationForm(request.form)
    if request.method == 'POST':
        email = form.email.data
        password = sha256_crypt.encrypt((str(form.password.data)))
        con = connection()
        cur=con.cursor()
        x = cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email)))
        if int(x) > 0:
            return render_template('register.html',form=form)
        else:
            cur.execute("INSERT INTO user (username,password,name) VALUES (%s,%s,%s);",(thwart(email),thwart(password),thwart(name),))
            con.commit()
            cur.close()
            con.close()
            return redirect(url_for('dashboard'))

    return render_template('register.html', form=form)
except Exception as e:
    return str(e)

A: x = cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email)))
The second argument of execute should be a tuple, you are missing a ,:
cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email),))
I guess that you also don't need the () around the %s but it depends on how your table actually looks like.
Further clarification:
('str') will evaluate to the string 'str', not to a tuple containing it.
In order to create a one-tuple, you must include a comma: ('str',).


text:
Q: Pycharm Not Displaying Line on Plot I am trying to plot a graph from a for-loop from z=0 to z=3.8 in 0.001 increments. I then have the program solve for X_e and I would like to plot z on the y-axis and X_e on the x-axis. However, when I run the code, the program provides all the values for z and X_e and shows a plot but no line is created. Below is my code and below that is the plot it creates but doesn't finish.
import numpy as np
import matplotlib.pyplot as plt
import math

case=int(input('Which Case [1 (PWR) or 2 (BWR)]? '))

if case == 1: # PWR
    H = 3.80 # m
    Lc = 3.80 # m
    D_rod = 0.0095 # m
    pitch = 0.0125 # m

    G = 3460 # kg/m^2-s
    q_0 = 33000 # W/m - Linear heat rate
    P_0 = 15 # MPa - Initial pressure
    T_f_in = 551 # Kelvin - Inlet temperature
    T_sat = 373 # Kelvin
    cp = 4.22 # kJ/kg
    hfg = 2256.4 # kJ/kg

    heated_parameter = 3.14 * D_rod # m
    area = pitch**2 - 0.25 * 3.14 * D_rod**2 # m^2
    volume = 0.5 * 3.14 * (D_rod)**2 * H # m^3

    circumference = 2*3.14*(D_rod/2) # m

    for z in np.arange(0,3.8,0.001):
        print(z)

        X_e = - q_0 * heated_parameter / (G * circumference * area * hfg) * H/3.14 * math.cos(3.14 *   z/H) - cp * (T_sat - T_f_in)/hfg

        print(X_e)
        plt.plot(X_e,z)

    plt.show()

This is the graph that is created.

A: You're passing single points to plt.plot. Use np.cos (which is vectorized) and skip the loop:
z = np.arange(0, 3.8, 0.001)
X_e = -q_0 * heated_parameter / (G * circumference * area * hfg) * H/3.14 * np.cos(3.14 * z/H) - cp * (T_sat - T_f_in)/hfg

plt.plot(X_e, z)

Output:

You might also consider using np.pi instead of 3.14.


text:
Q: Does DGML support different shapes? I've started to play with DGML, and I see in the schema that the Node element supports a Shape attribute.
I've tried things like
<Node Shape='square'... with no effect.
Is Shape really supported in DGML?

A: For rectangles, you can use       <Setter Property="NodeRadius" Value="0" />.

A: I don't appear to be able to get the shape attribute to affect anything either.
I assume you are using the new VS2010 viewer?
The following guide (which is a pretty handy reference, actually) does give this example:

Set the Shape property to None so that
  the icon replaces the shape. Use the
  Icon property to specify the location
  of the icon.

This does appear to work - setting shape="none" removes the shape.
It is likely that support for displaying different shapes has not been implemented in the viewer yet, so only 'none' makes any difference.

A: You might consider reading:
http://social.msdn.microsoft.com/Forums/en/vsarch/thread/84400dea-3426-4e0e-8271-6af52ae1d1fb
about my DSL that maps some shapes to attributes (though there is no software there as yet)