text:
Q: MySQL consuming a lot of CPU I'm having trouble with a new server. I installed the optimized configuration for Ubuntu server with EasyEngine of VirtuBox.
When migrating my website with template newspaper, the CPU consumption is very high.
Here is a mysql tuner report.

MySQL tuner result:

I have a database with more than 400 thousand posts. My server is:

*

*Intel Core i7-6700K CPU

*HDD 250 GB SSD

*RAM 16 GB DDR4-2133 PC4-17000

with easyengine + rediscache + wordpress.
With little access the consumption of CPU is a load average: 7.56, 3.43, 4.81.
Thank you in advance for your attention.

A: Use persistent connections, cpu will drop dramatically. Then check slow queries.

A: Observation, Mysqltuner.pl report indicates you have 32GB RAM rather than 16GB as indicated in your question information.
Suggestions to consider for your my.cnf [mysqld] section   Rate Per Second=RPS
innodb_io_capacity=10000  # from 200 to use more of SSD IOPS capacity
max_connections=200  # from 400 until you use more than 102 max_used_connections in a day
thread_cache_size=100  # from ? to reduce threads_created V8 refman CAP at 100
key_buffer_size=64M  # from 134M since less than 20% used
innodb_buffer_pool_instances=8  # from 12 to continue avoiding mutex contention
innodb_lru_scan_depth=128  # from 1024 to conserve CPU cycles every second
read_buffer_size=256K  # from ? for ~ default to minimize handler_read_next RPS
read_rnd_buffer_size=256K  # from ? for ~ default to minimize handler_read_rnd_next RPS
aria_pagecache_age_threshold=900  # from 300 to delay age out
aria_pagecache_buffer_size=512M  # from 128M to reduce aria_pagecache_reads RPS

Please POST text results of ulimit -a from OS so we know your limits.


text:
Q: External data in Android I have hardcoded data in my Android application. This will be in tree format. like this
<makes>
<make>
<name>abc</name>
<id>1</id>
</make>
... 10 more entries.
</makes>

Since this data will be hard coded, in my application, what can i use to easily parse in in my application. I can simply load it from my assets directory, and use xml parsing, but is there any inbuilt ways to use it. I know i can make a String array from xml resource, but how can i use this structure.

A: You could easily store that table as an SQLite database. This link might be helpful, particularly step 6.

A: You can use the XmlResourceParser class, that implements the XmlPullParser interface, and will allow you to parse the XML file, loading it from the resources folder. After that, I would recommend defining a Make class with the two properties defined in the XML and populate a List or other type of data structure with objects of that class while you loop through the xml file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: LINQ to Data : Clever Type Recognition Working on Maths problems, I'm very fond of LINQ to Data.
I would like to know if LINQ is smart enough to avoid a cast like .ToArray() when the IEnumerable I work with is already an array.
See example below:
/// <summary> Transforms an array of timeSeries into one ModelData. </summary>
public static ModelData ToModelData(this IEnumerable<TimeSerieInfo> timeSeries)
{
    var seriesArray = timeSeries as TimeSerieInfo[];
    return null != seriesArray ?
        new ModelData(seriesArray) :
        new ModelData(timeSeries.ToArray());
}

Does LINQ avoid the transformation to an array when the IEnumerable<TimeSerieInfo> timeSeries is already an array?
Thank you for help.

A: LINQ creates a copy of the array, and this is the correct behaviour IMO. It would be highly confusing if calling ToArray() and then modifying the returned array sometimes modified the original collection and sometimes didn't.

A: I suspect that it will do what you ask and create a new array. Could you not change your constructor of ModelData to take an IEnumerable instead?

A: LINQ does create a copy of the array; it creates a System.Linq.Buffer<T>, which creates a copy of the array.
You can create your own extension method though:
public static TSource[] ToArrayPreserved<TSource>(this IEnumerable<TSource> source)
{
    return (source as TSource[]) ??  source.ToArray();
}


text:
Q: System.Data.SQLite 1.0.101 unable to load dll since last update I have a Xamarin Forms project, in which I use the nuget package System.Data.SQLite (v1.0.101 last updated in 04/19/2016) and it was working well until some days ago.
Now I don't know if I have changed something that caused my app to crash, or if the last update of the package is the reason I cannot run it anymore.
I am trying to run a Windows Phone 8.1 (not Silverlight) app in debug mode and  x86 target on my local emulator.
The error I get is:

Unable to load DLL 'sqlite3': The specified module could not be found.
  (Exception from HRESULT: 0x8007007E)

Any help?

A: It seems to be missing the native sqlite3 library. If you have, or can restore, the previous Nuget package, can you compare them to see if library has been moved or accidentally left out?


text:
Q: VTK: visualize depth buffer I am trying to follow the example here: http://www.vtk.org/Wiki/VTK/Examples/Cxx/Utilities/ZBuffer to visualize the zbuffer. This works fine until I try to change the camera viewpoint.
My code is as follows: which is the same as the example except for the bit in bold:
// This demo creates depth map for a polydata instance by extracting
// exact ZBuffer values.
#include <vtkSmartPointer.h>

#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkBMPWriter.h>
#include <vtkWindowToImageFilter.h>
#include <vtkImageShiftScale.h>

int main(int argc, char *argv[]) {
        vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
        vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
        vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
        vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
        vtkSmartPointer<vtkRenderWindowInteractor> interactor = vtkSmartPointer<vtkRenderWindowInteractor>::New();

        vtkSmartPointer<vtkPLYReader> fileReader = vtkSmartPointer<vtkPLYReader>::New();
        vtkSmartPointer<vtkWindowToImageFilter> filter = vtkSmartPointer<vtkWindowToImageFilter>::New();
        vtkSmartPointer<vtkBMPWriter> imageWriter = vtkSmartPointer<vtkBMPWriter>::New();
        vtkSmartPointer<vtkImageShiftScale> scale = vtkSmartPointer<vtkImageShiftScale>::New();

        // Read .vtp file
        fileReader->SetFileName("mesh.ply");

        //Build visualization enviroment
        mapper->SetInputConnection(fileReader->GetOutputPort());
        actor->SetMapper(mapper);
        renderer->AddActor(actor);

        //change camera viewpoint
        vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New();
        camera->SetPosition(0, 0, 650);
        renderer->SetActiveCamera(camera);

        renWin->AddRenderer(renderer);
        interactor->SetRenderWindow(renWin);
        renWin->Render();

        // Create Depth Map
        filter->SetInput(renWin);
        filter->SetMagnification(1);
        filter->SetInputBufferTypeToZBuffer();        //Extract z buffer value

        scale->SetOutputScalarTypeToUnsignedChar();
        scale->SetInputConnection(filter->GetOutputPort());
        scale->SetShift(0);
        scale->SetScale(-255);

        // Write depth map as a .bmp image
        imageWriter->SetFileName("out2.bmp");
        imageWriter->SetInputConnection(scale->GetOutputPort());
        imageWriter->Write();

        return EXIT_SUCCESS;
}

Now the entire depth visualization is completely black. However, at this camera position the mesh renders just fine, so I don't think it's due to camera being too far away. Any ideas what I am doing wrong?

A: That probably because your far plane is near the object that is being rendered. Try to put, after camera creation, a better clip plane, as example:
camera->SetClippingRange(640, 1000);


text:
Q: Android: detect when app finishes installation I want to detect when an application in android has finished installation without using a brodcast receiver. Is this possible?

A: you might be able to read logs instead , but that requires "bad" permission , which is no longer supported as of API 16 (jelly bean) .


text:
Q: How to fold an inserted region with Open Tools API? I wanna insert a region in an edit view and then fold this region.
// fEditView: IOTAEditView;

var
  writer: IOTAEditWriter;
begin
  writer := fEditView.Buffer.CreateUndoableWriter;
  //...
  writer.Insert('{$REGION ''Documentation''}'#13#10'{$ENDREGION}');
  writer := nil;  // Flush the buffer
  fEditView.Position.GotoLine(lineNo); // go to the line number of the region
  fEditView.Paint;
end;

This code snippet will insert a region in the code editor. But the IDE needs some action to generate such a region in the code editor.
Is there any way to force the IDE do this action and then I can use
(fEditView as IOTAElideActions).ElideNearestBlock;

to fold it?

A: Found by grubby trial-and-error :-)
(fEditView as IOTAElideActions).EnableElisions;
(fEditView as IOTAElideActions).EnableElisions;
(fEditView as IOTAElideActions).ElideNearestBlock;

EnableElisions() appears to actually toggle the elisions feature.
Turning elisions off and back on again seems to have the desired effect. There is some not very pretty screen updating going on. Whether it is possible to suppress that I don't know.


text:
Q: Validation Summary and AJAX requests I'm writing a jQuery plugin that allow us to easily "hijax" a standard HTML form, submitting it via AJAX rather than a standard POST.
One thing the plugin needs to handle is validation errors and in ASP.NET MVC's case, ModelState errors on the server.
I've written an Action Filter that intercepts AJAX requests and returns the Modelstate errors as JSON. This works fine for field errors (i.e. those that have an input on the form):
$.ajax({
    url: this.action,
    type: "POST",
    data: $(this).serialize(),
    statusCode: {
        400: function (xhr, textStatus, errorThrown) {
            var errors = $.parseJSON(xhr.responseText);
            validator.showErrors(errors);
        }
    },
    success: function (response) {
        window.location.href = "/login/success";
    }
});

The jQuery Validate showErrors function looks for input elements with a name that matches the error key.
Since the standard convention in ASP.NET MVC is to do the following when you want to provide a "summary" error:
ModelState.AddModelError("", "Error without a key");

This causes jQuery validate to throw an exception.
The best solution I've come up with so far is to create a hidden input on my form:
<input type="hidden" name="summary" disabled/> <!-- prevent it from being submitted -->
@Html.ValidationMessage("summary")

And then execute the following on the server when I want to display a "summary" error:
ModelState.AddModelError("summary", "Summary error");

This is not ideal since it doesn't work well with multiple errors. A nicer solution would be to hook into how the unobtrusive validation plugin handles summary errors but I can't see how to do that.


text:
Q: ldapadd/ldapmodify: clarifications needed about these commands The ldapmodify man page states that:

The default for ldapmodify is to modify existing entries

Yet when I try to import an LDIF file with ldapmodify I get the below error:
ldapmodify: modify operation type is missing at line X

Q1: Why, which arguments should I add to my ldapmodify command?
If I import an LDIF file using ldapadd and the entry already exists I get the below error:
ldap_add: Already exists (68)

This can be ignored using the -c switch (for continue), however ldap_add won't update existing entries. Instead, in order to update existing entries one should use ldapmodify, however ldapmodify won't add missing entries.
Q2: Is there a way to import an LDIF files by creating missing entries AND updating existing ones at the same time?

A: Try the -a switch
Add or modify options:
  -a         add values (default is to replace)

A: The ldif for ldapmodify has a different syntax than a regular ldif.
For example: if you want to add the 'foo' entry with value 'bar' you should write your ldif like this:
dn: cn=ToModify,dc=example,dc=com
changetype: Modify
add: foo
foo: bar

replace: mail
mail: new@email.com

delete: unneededEntry

This ldif will add the attribute foo with value bar, update the mail attribute to new@email.com and delete the unneededEntry.
then invoke the ldapmodify command.
ldapmodify -f update.ldif

(if needed with other options like simple auth for example)

A: Goez answer seems fine.
However if you are unfamiliar with ldif it can make sense to use
ldapvi

instead. You can edit already existing entries or add new ones.
apt-get install ldapvi


text:
Q: How can I set a system variable only if it exists? I want to run this command when I start a MySQL session:
SET SESSION MAX_EXECUTION_TIME = 1000

But I am running this on two different MySQL versions, and one of them doesn't support MAX_EXECUTION_TIME so I get this error:
Unknown system variable 'MAX_EXECUTION_TIME'

I want to do something like
IF MAX_EXECUTION_TIME EXISTS THEN
SET SESSION MAX_EXECUTION_TIME = 1000
END IF

I have tried searching for things like "check if variable exists", "check if system variable exists", and "set system variable only if it exists" but I haven't found anything.
What is the right syntax for this?


text:
Q: c# Where can find System.Windows.Controls.dll I have problem with dll file and have  project which need this file System.Windows.Controls.dll for
listBox1.ItemsSource

error fix , and add  reference with this dll to fix error.
Where i can find this dll file?
Is there any download link ? Share please !
Thanks !
In "Add Reference" it doesn't exist !
Solution: http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe

A: Here are the steps:

*

*Right click on References in the Solutions Explorer (Solutions explorer is on the right of your IDE)

*Select Add Reference

*In the window that opens, Select Assemblies > Framework

*Check the PresentationFramework component box and click ok

A: This should be in the PresentationFramework.dll but that control is in the System.Windows.Controls namespace.
http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx
You can add it by going to your project, Right clicking on References > Add Reference > .Net Tab > And selecting this DLL

A: I was able to find the dll file by searching my computer for "System.Windows.Controls.dll". I found it under the following file location... "C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll"
Hope this helps!


text:
Q: infinite sum derivative of $f(x)=\sum_{n=1}^{\infty}x^n/n$ where $-1can't seem to approach this question about derivative of an infinite sum.
Let $f(x)=\sum_{n=1}^{\infty}x^n/n$ where $-1<x<1$
Then $f'(x)$ is?
Answer is $1/(1-x)$ for some reason

A: If $f(x)=\sum_{n=1}^{\infty}x^n/n$, then $f'(x)=\sum_{n=1}^{\infty}x^{n-1}=\sum_{n=0}^{\infty}x^n=\frac{1}{1-x}$ when $|x|<1$.


text:
Q: My JavaScript works as inline code but not as an include file. Any ideas why and how to fix it? I have this form:
<form id="searchForm" class="search_field" method="get" action="">
...
...
</form>

Then this javascript:
    var form = document.getElementById("searchForm");
    form.doSearch1.onclick = searchPage;
    form.doSearch2.onclick = searchPage;
    form.showFeatureChoices.onclick = function( )
        {
            var cbs = form.featType;
            for ( var c = 0; c < cbs.length; ++c )
            {
                cbs[c].checked = false;
            }
            document.getElementById("featuresDiv").style.display = "block";
        }

function searchPage()
{
    var form = document.getElementById("searchForm");
    var searchText = form.searchBox.value.replace(/-/g,"");
    form.searchBox.value = searchText;

    if (searchText != "")
    {
        // collect features to search for:
        var features = [ ];
        var featTypes = form.featType;
        for ( var f = 0; f < featTypes.length; ++f )
        {
            if ( featTypes[f].checked ) features.push( featTypes[f].value );
        }
        featureList = "'" + features.join("','") + "'";

        searchMsg("Searching for '" + searchText + "' ...");
        // startStatusUpdate(1000);
        // findTask.execute(findParams, showResults);
        var accord = dijit.byId("accordianContainer");
        var resultsPane = dijit.byId("resultsPane");
        accord.selectChild(resultsPane,true);

        doSearch( searchText, featureList );
    }
    else
    {
      searchMsg("No search criteria entered, enter search text");
    }
}

If I embed this code in same file as the <form..., it works fine.
If however, I have this js in another file and use as include file:
<script type="text/javascript" src="Views/JS/main.js"></script>

I get following error: "Object required" and it points to these lines:
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;

Any ideas how to fix this?
Just a bit more info, the js code shown above in a file called main.js which is in a folder called JS and Js is in a folder called Views. The

Thanks a lot in advance

A: When you include the JavaScript code in the same page, where is it in relation to the form element?  (Before or after it?)  How about when you reference the external JavaScript file?
I'm guessing that in the former case the code is at the end of the file, while in the latter case the script reference tag is at the beginning?
If that's true then what's happening is this code is being executed before the DOM is ready:
var form = document.getElementById("searchForm");
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;

If the form tag hasn't been rendered to the DOM yet then that first line won't find anything, and the subsequent lines will fail as a result.  One approach is to put the script reference tags at the end, but that seems like a hack to me.  Sometimes there are good reasons to keep them in the page header, not the least of which is cleaner management of the code in many cases.  There are other ways to hold off on executing JavaScript code until the DOM is ready.


text:
Q: .load() works only first time but .ajax() works fine every time The problem is because of slow network connections due to long distance access. The jQuery .load() function doesn't seems to load the HTML page from second time and browser had canceled or aborted the request in about 500 ms everytime. The same page when loaded using .ajax() is not causing a problem. Why jQuery .load() is been repeatedly aborted by the browser from second time? The response JSP page does contain several .ajax() requests. Is this causing problem from second time?

A: You can use ajaxSetup() before calling load() to set timeout
$.ajaxSetup({
    timeout: 30000
});

See: http://api.jquery.com/jQuery.ajaxSetup/

A: Please check timeout parameter
Referance
Demo
$.ajax({
    url: "/test_ajax_timeout/",
    type: "GET",
    dataType: "json",
    timeout: 15,
    success: function(response) { alert(response); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            alert(t);
        }
    }
});

If you changed timeout above a limit you will see error. You can set up an error callback as showed below
$.ajax({}).error(function(){ // Code });

A: I got the solution by using .ajaxSetup() before calling .load()  as recommended by @Chang
But I would like to use .ajax() call with some desired timeout instead of using .load() because the .ajaxSetup() is not recommended to use since it is used to configure default ajax options.
http://api.jquery.com/jQuery.ajaxSetup/


text:
Q: Why $\pi$ // Rationalize does not give a rational multiple of $\pi$ in my example? As an obvious example of π Rationalize, I see that
a := 3.1415926535897932384626433832795028841971693521632

π  Rationalize[N[a]/π ]

(* π *)

but when I try this way for another rational multiple of $\pi$, it does not give a rational multiple of $\pi$
b :=   (12343556574747/50000) π

π  Rationalize[N[b]/π ]

(* 7.75569*10^8 *)

I expected an answer the same as the original number $b$. Can someone please guide me where I am going wrong?
More precisely, I want to use this method to check whether the following number
$2.47518811442233432405585032549718484885918373175315936866881011953607\
8273196602710715450734911249987$
is a rational multiple of $\pi$ or not.

A: I want to show that without hypotheses, the problem of determining whether $x=a/\pi$ came from a rational number is unsolvable. But, spoiler alert, the OP's number 2.47... is probably not a rational multiple of Pi or it is not precise enough to determine whether it is.

First, a floating-point number $x$ comes with an uncertainty $dx$. If $x$ comes from rounding a rational number $y$ to the nearest floating-point number, then we have
$$x-dx \le y \le x+dx \,.$$
In Mathematica, $dx$ is given roughly by
dx = x * 10.^-Precision[x]

I say "roughly" because $dx$ will be a power of $2$ and the left and right uncertainties can be asymmetric at the boundaries where the floating-point exponent changes.  For instance, if $y$ rounds to $1$ in the current binary64 standard for machine precision (double precision), then we have $1-2^{-54} \le y \le 1+2^{-53}$.
Second, the rational numbers are dense in the real numbers, which means there are infinitely many rational numbers $\tilde y$ such that
$$x-dx \le \tilde y \le x+dx \,. \tag{1}$$

The problem is this: Given that we know $x$ (and therefore $dx$), find the rational number $y$ from among the infinitely many $\tilde y$ satisfying (1).  It is impossible, since too much information was lost when $y$ was rounded.
A solvable problem is this: Find the rational number $\tilde y$ satisfying (1) with the smallest denominator. This problem is solved in Mathematica by any of these calls:
yy = Rationalize[x, dx]
yy = Rationalize[x, 0]   (* uses the precision of x to determine dx *)
yy = Last@Convergents[x] (* uses the continued fraction expansion of x *)

Example.
Let's take a simpler version of the OP's second problem, without the Pi, which is a red herring anyway.
brat = (12343556574747/50000); (* == b/Pi *)
x = N[brat];
dx = x * 10.^-Precision[x];
yy = Rationalize[x, dx]
Rationalize[x, 0]
Last@Convergents[x]

(*  1048955437722  /  4249  *)

There is no way to infer from x that the original denominator was 50000.  It should be clear that yy is not the closest fraction, just the one with the smallest denominator within the uncertainty dx.  In fact brat is closer to x than yy.  One might think there is still hope to recover brat from x, but there is not.
A continued fraction convergent of x gives the rational number closest to x that has a denominator smaller than the denominator of the next convergent.  We will see from the convergents of x that there is always a better choice of a fraction than brat.
Let's look at the number x.  It is a fraction of the form $x_0/2^n$, which we can get using SetPrecision:
xx = SetPrecision[x, Infinity]

(*  8283620594510023 / 33554432  <-- x0/2^25 *)

Here are some of the convergents related to our problem. Since we have converted x to an infinite-precision fraction, we get more convergents:
Convergents[xx][[6 ;; 11]]
(*
  {  268348919935  /   1087,
    1048955437722  /   4249,  <-- smallest at mach. prec.
    1317304357657  /   5336,
    2366259795379  /   9585,
   10782343539173  /  43676,  <-- best with denom. < 140612
   34713290412898  / 140613}
*)

So if you knew that the denominator was between, say, 10000 and 100000, the best approximation is not brat, but 10782343539173/43676.  What we hoped to recover turns out to be a less than optimal solution.  I have no idea how to choose the correct solution from among all the less than optimal ones. I don't think it can be done.

Finally, we can come to a way to solve this problem, assuming $x$ is a good enough approximation of $y$.  In general rational numbers are harder to approximate by rational numbers (other than themselves) than irrational numbers.  We can use this to determine when a number is probably a rational number.  (I am not an expert in this field: I do not know whether there is a way to assign a probability to the result.)
Rationalize[x] solves the problem if the denominator of $y=p/q$ satisfies the criterion given in the docs:

The left-hand side of the inequality is $dx = |y-x|$.  The exponent $2$ shows up in various Diophantine approximation theorems. The most elementary is
$$\left| {p' \over q'} - {p \over q} \right| \ge {1 \over q'q} \ge {1 \over \mathop{\text{min}}(q',q)^2}\,.$$
From this we can infer on condition x should satisfy: Since the a small error in the denominator of x implies the error in approximating y = p/q is at least around 1/q^2, we should have
Accuracy[x] >= 2 Log10[q]

Then there are Dirichlet's theorem and its generalizations:  For an irrational $y$, there are infinitely many coprime integers $p'$ and $q'>0$ such that
$$\left| {p' \over q'} - y \right| \le {c \over (q')^2} \,,$$
where the constant $c = 1$ is Dirchlet's theorem.  See Diophantine approximation for more.
For a rational number, the error scaled by square of the denominator should be large, except once, when the error is zero.  If $x \approx p/q$, then one might expect the scaled error $(q')^2\left| {p' / q'} - x \right|$  will be small only once, provided $x$ is a good enough approximation. (Since we're changing $y$ to $x$, this needs proof, which I haven't done, but it seems to hold computationally.)  On the other hand, an irrational number will have several peaks in the scaled error.
Here's a look at some known irrational numbers:
Block[{$MaxExtraPrecision = 500},
 convE = Convergents[E, 100];
 scerrE = (E - convE) Denominator[convE]^2;
 convPi = Convergents[Pi, 100];
 scerrPi = (Pi - convPi) Denominator[convPi]^2;
 conv2 = Convergents[10 Sqrt[2], 100];
 scerr2 = (10 Sqrt[2] - conv2) Denominator[conv2]^2;
 ListLinePlot[RealExponent@{scerrE, scerrPi, scerr2}
  , PlotRange -> All, Frame -> True,
  PlotLegends -> {E, Pi, 10 Sqrt[2]}]
 ]

Here's an approximation of a rational number, similar to the problem in the OP. There's a shallow "peak" in 5th convergent, similar in magnitude to the irrational numbers above. This is followed by deep spike, followed by a large jump. It is so large because it is scaled by q^2, where q is the denominator of the 11th convergent; therefore 1/q will be less than the rounding error in x = N[y], and the jump in scaled error will be greater than Accuracy[x].
x = N[12346/33333 Pi, 30]/Pi;
conv = Convergents[SetPrecision[x, Infinity]];
scerr = (x - conv) Denominator[conv]^2;
ListLinePlot[RealExponent@scerr
 , PlotRange -> All, Frame -> True]

There's a disturbing issue in the behavior of Convergents[x]. It doesn't find the approximation we seek.   Apparently we need to increase the precision of x.
Convergents[x]
Convergents[SetPrecision[x, Infinity]]
(*
  {0, 1/2, 1/3, 3/8, 10/27, 1023/2762, 1033/2789, 2056/5551, 5145/13891}

  {0, 1/2, 1/3, 3/8, 10/27, 1023/2762, 1033/2789, 2056/5551, 5145/13891,
   12346/33333,
   192070822042862116379943873/518572550717213909387062135,
   ...10 fractions omitted...,
   939034248967552886981567682091/2535301200456458802993406410752}
*)

The deep spike is at the desired fraction 12346/33333.  This should be typical when $x$ is a good approximation to $y$.

If we put the ideas above together we can write a function findRationalMultiples[x, m] that will return a rational multiple of m in the form {p * m / q}, if x seems to be a rational multiple of m.  It returns an empty list {} if x appears not to be a rational multiple of m.  It may also return a list of rational multiples, depending on the parameters to PeakDetect[]. If x is a rational multiple of m, then the last element of the list is probably the correct answer; but such cases should be examined carefully.
The call findRationalMultiples[{x, m}, sm, sh, th] passes the smoothing, sharpness, and threshold parameters to PeakDetect[].
The call findRationalMultiples[{x, m}, sm, sh, th, True] returns an Association containing auxiliary data helpful in analyzing rational approximations of x/m.
ClearAll[findRationalMultiples];
findRationalMultiples[xm_, smoothing_ : 1, sharpness_ : 5,
   t_ : Automatic, verbose_ : False] :=
  Module[{x, m, conv, scalederror, data, threshold, res},
   {x, m} = Replace[xm, {y_Real :> {y, 1}}];
   x = x/m;
   res = <||>;
   res["Convergents"] = Convergents[x];
   res["ScaledError"] = Abs@(x - res["Convergents"])*
     Denominator[res["Convergents"]]^2;
   data = -RealExponent@res["ScaledError"];
   threshold =
    t /. {Automatic -> -Max@data/3, Scaled[s_] :> -s*Max@data};
   res["Peaks"] = PeakDetect[data, smoothing, sharpness, threshold];
   res["Answers"] =
    m*Extract[res["Convergents"], Position[res["Peaks"], 1]];
   If[verbose,
    res["SmoothData"] = GaussianFilter[data, {3, smoothing}];
    res,
    res["Answers"]
    ]
   ];

Example: A rational multiple of Pi.  You need enough digits to make a good approximation, and we set the working precision with SetPrecision a bit higher so that Convergents[] doesn't quit too soon.
digits = 15. + Log10[33000^2];
x = SetPrecision[
   Round[29/33000 Pi, 2^-Ceiling[Log2[10^digits]]],
   100];
findRationalMultiples[{x, Pi}]

(*  {(29 π)/33000}  *)

Rationalize fails on this example:
Rationalize[x/Pi]

(*  0.000878787878787878787878773416025526...  *)

OP's main question.  The function findRationalMultiples fails to find a rational multiple of Pi.  We asked for the verbose association, so that we can examine the details.
x = 2.475188114422334324055850325497184848859183731753159368668810119536078273196602710715450734911249987;
frm = findRationalMultiples[{x, Pi}, 1, 5, Automatic, True];

frm@"Answers"
(*  {}  *)

A plot of the scaled error shows several peaks, not just one as we would expect for a rational multiple.  Consequently, I think it is likely that the OP's x is not a rational multiple of Pi or x is a bad approximation of the real number it represents.
ListLinePlot[RealExponent@frm["ScaledError"][[;; 88]], PlotRange -> All]

Numerical caveat: As with most, if not all, numerical routines, it is possible to construct pathological examples that fool the routine.  For instance, y = Round[Pi, 1/2^b] will have the same initial convergents as Pi until the convergents differ from Pi by around 1/2^b or less.  But y is a rational number and findRationalMultiples[{N@y, 1}] works up to b == 27, returns multiple candidates up to b == 36, and returns no solutions for b >= 37.

Appendix.
Well, why not?, the post is already so long....  Here's a slightly different approach to findRationalMultiples using Mathematica's notion of accuracy to perform the role of scalederror.  It also returns an association, with slightly different keys and through Reap[findRationalMultiples[{x, m}]]; it uses Sow with the tag findRationalMultiples if you want to use Reap with tags.  Generally, because we increase the precision before calling Convergents, we get at least one, and often several, convergents at the end of the Convergents[] list whose error is zero at the scaled accuracy; we drop all but the one with the least denominator.
The Accuracy[] for comparing the difference of each convergent p/q from x is set to -Log10[1/q^2] plus the parameter scale.  The default value 4 corresponds roughly to the constant $c$ used in Rationalize[x] (see docs or quote above); however, the behavior here is somewhat different than Rationalize.  If x is found by rounding an unpathological rational number, then findRationalMultiples[{x, 1}, s] should find a single good candidate at both smaller and larger scales.  (The chances of finding more good candidates increases as the scale s decreases, and vice versa.) At small enough scales, findRationalMultiples[{x, 1}, s] will fail on any x probably.
[TBD: Just realized that trim needs some adjustment; sometimes the good candidate is adjacent to the bad candidates, but I have to run. Drats.]
ClearAll[findRationalMultiples];
findRationalMultiples::mult = "Multiple good candidates found at scale ``; returning first. Use Reap for more information.";
findRationalMultiples::noans = "No good candidates found at scale ``; returning first convergent with zero error. Use Reap for more information.";
findRationalMultiples[xm_, scale_ : 4] :=
  Module[{x, m, conv, trim, zeros, res},
   {x, m} = Replace[xm, {y_Real :> {y, 1}}];
   x = x/m;
   res = <||>;
   res["Convergents"] = Convergents[SetPrecision[x, Infinity]];
   res["Errors"] = MapThread[SetAccuracy,
     {SetPrecision[x, N@Precision[x]] - res["Convergents"],
      scale + 2 Max[5, -Log10[x], #] & /@
       Log10@N@Denominator@res["Convergents"]}];
   trim = LengthWhile[Reverse@res["Errors"], # == 0 &];
   (* compare first two zeros to be dropped
      IF the accuracy jump > Precision[x] or Log10[denominator] >= Precision[x]
      THEN first one is a good candidate, so decrement trim *)
   If[trim > 1 &&
     Accuracy[res["Errors"][[-trim]]] < Accuracy[res["Errors"][[1 - trim]]] - Precision[x],
    trim--
    ];
   zeros = Position[Drop[res["Errors"], 1 - trim], z_ /; z == 0];
   res["Candidates"] = m*Extract[res["Convergents"], zeros];
   res["Answer"] = Replace[res["Candidates"], {a_, ___} :> a];
   Sow[res, findRationalMultiples];
   Switch[Length@res["Candidates"],
    0 | 1, Message[findRationalMultiples::noans, scale],
    2, Null,
    _, Message[findRationalMultiples::mult, scale]
    ];
   res["Answer"]
   ];

My example from above has stable results at different scales:
digits = 15. + Log10[33000^2];
x = SetPrecision[
   Round[29/33000 Pi, 2^-Ceiling[Log2[10^digits]]],
   100];
findRationalMultiples[{x, Pi}]
findRationalMultiples[{x, Pi}, 2]
findRationalMultiples[{x, Pi}, 8]
(*
(29 π)/33000
(29 π)/33000
(29 π)/33000
*)

Rationalization of the OP's number is unstable with change of scale. The first trial below reproduces one of the other posts' answers, but the instability suggests it's doubtful that x came from rounding.
x = 2.475188114422334324055850325497184848859183731753159368668810119536078273196602710715450734911249987;
findRationalMultiples[{x, Pi}]

(*  (528518980406819854 π)/670814204566564617  *)

findRationalMultiples[{x, Pi}, 2]

findRationalMultiples::mult :  Multiple good candidates found at scale 2; returning first. Use Reap for more information. >>

(*  (105618056127 π)/134054016857  *)

findRationalMultiples[{x, Pi}, 8]

findRationalMultiples::noans :  No good candidates found at scale 8; returning first convergent with zero error. Use Reap for more information.

(*  (127783177086971763037570942964097163555065759781296 π) /
      162186739686443508647264007143241471430512176744729         *)

A: b = (12343556574747/50000) \[Pi];

N[b, 20]/Pi // Rationalize[#, 0] &

(* 12343556574747/50000 *)

Rationalize[(2.\
4751881144223343240558503254971848488591837317531593686688101195360782\
73196602710715450734911249987/Pi), #] & /@ (10^Range[-10, -5])

(* {86111/109295, 24592/31213, 12257/15557, 11711/14864, 8123/10310, \
26/33} *)

A: Expansion into a continuous fraction can be used.
In your example
a = 2.4751881144223343240558503254971848488591837317531593686688101195\
36078273196602710715450734911249987;
ContinuedFraction[a/\[Pi]]

{0,1,3,1,2,2,472,1,2,3,1,1,1,1,1,2,3,3,2,4,2,2,2,4,5,243,1,2,6,2,3,1,1,2,1,16,1,24388,1,4,2,2,1,1,1,1,20,2,1,1,6,6,1,3,1,8,1,1,2,5,4,13,1,1,6,3,2,300,6,103,5,2,3,3,2,1,3,1,3,16,2,1,4,1,1,3,34,1}

There is a large element 24388. Dropping all elements starting with it gives
b = FromContinuedFraction@{0, 1, 3, 1, 2, 2, 472, 1, 2, 3, 1, 1, 1, 1,
    1, 2, 3, 3, 2, 4, 2, 2, 2, 4, 5, 243, 1, 2, 6, 2, 3, 1, 1, 2, 1,
   17}

$$
\frac{528518980406819854}{670814204566564617}
$$
with error
a/\[Pi] - b///N

$$\text{9.11146$\grave{ }$*${}^{\wedge}$-41}$$
If all digits in your number are correct it is not a rational number with a small denominatior. If only 40 digits or so are true then b looks like the best candidate. But if only a few digits are true one can take segments up to the previous relatively large numbers, say
FromContinuedFraction@{0, 1, 3, 1, 2, 2}

$$\frac{26}{33}$$


text: Q: A question about Shoenfield's absoluteness theorem and $0^{\sharp}$ Shoenfield's theorem states that any $\Pi_{3}^{1}$ sentence that holds in $V$ holds in $L$, but I know that it is consistent with ZFC that there exists a set $A\subset \mathbb{N}$ where $A\not\in L$ and $A$ is $\Delta_{3}^{1}$, so $A$ and $\mathbb N \setminus A$  are $\Pi_{3}^{1}$. But, for any integer $n$ the statments $n\in A$ and $n \not\in A$ are $\Pi_{3}^{1}$, so $A^{L}$ and $A$ must be the same set by comprehension schema, an aparent contradiction with the consistency of "there exists a $\Delta_{3}^{1}$ non-constructible set of integers." I don't understand this situation.


text:
Q: How to achieve cross domain tracking on my own web analytic site? I would like someone to point me to good resources on how to  track activity on other sites that belong to me that are on other domains.
I have searched for information on this topic but have been unable to find anything other than when using Google Analytics.
I have not tried anything other than looking at sending some specific header information.


text:
Q: Problem with a proof of a statement about the arithmetic root of a rational number Let $x$, $y$, $n$ be  natural numbers and $(x,y)=1$ (the greatest common divisor of $x,y$ is 1). I wish to prove that if $\sqrt[n]\frac{x}{y}$ is a rational number then there are natural numbers $p$, $q$ such that  $x=p^n$  and $y=q^n$.
My attempt.
If $\sqrt[n]\frac{x}{y}=\frac{a}{b}$ and $(a,b)=1$ then $\frac{x}{y}=\frac{a^n}{b^n}$ and next
$xb^n=ya^n$. Hence $x|xb^n=ya^n$ but $(x,y)=1$. Therefore $x|a^n$. Similarly $y|b^n$, $b|y$, $a|x$. I don't know how to obtain that $x$ and $y$ are $n$-th powers of natural numbers.

A: You missed just one little step. As you said $x\mid a^n$ and $y\mid b^n$. Now, $a^n\mid xb^n$ and since $(a,b)=1$, we have that $(a^n,b^n)=1$ and thus $a^n\mid x$. So $a^n\mid x \mid a^n$ implies $x=\pm a^n$. Same for $y$.


text:
Q: Abstraction from database - handling ID types I am using MongoDB in a project, where relationships between collections are created via referencing a unique document ID of a special BSON ObjectID type.
So I can have a School document like this:
{ name : 'Country School', _id : ObjectId("aaaaaaaaaaaaaa") }

Also, I can have a Subject document like this:
{ name: 'Maths', _id : ObjectId("yyyyyyyyyyyyy") }

And then Teacher document in Teachers collection:
{ name "Mr Brown", school: ObjectID("aaaaaaaaaaaaaa"), subject:  ObjectId("yyyyyyyyyyyyy") }

The problems start when I need to update Teacher document in View:

*

*How should the controller return Teacher object to the View?

Clearly, to facilitate a layer of abstraction from the DB I need to convert this ObjectID into a string. It becomes a bit of a mess when Teacher has many properties that are essentially ObjectIDs - each time I go back and forth between View and Controller I end up needing bespoke code to convert each of these properties to ObjectID and back to string.
When going from "Controller" -> "View" I can easily check which fields have type 'ObjectId' and convert them to string. But when I am going "View" -> "Controller", is the only solution to hard-code which fields should become ObjectId? Maybe somehow include a reference to the type of the field in the field name, i.e. if file name is 'school_objectid' - convert it.
Is there an elegant solution to this problem?

A: Maybe you should consider not referencing the object ID in your code at all?
But the root of your problem is, you seem to be trying to use MongoDB as if it is a relational database.
In mongo, your entities are more or less supposed to stand alone.
Also, from your application, you should be looking things up with their natural key (or at least an application layer key, perhaps a guid)... I hope no one takes this suggestion as being against surrogate keys, nothing is further from a the truth. Surrogate keys are great, but even better when used in combination with natural keys.

A: The best solution I could arrive at after a little bit of research is to create class definitions for objects that are essentially returned from the database.

*

*add two constructors for them: one taking in entity that database driver returns, and one that takes in JSON returned by the web front-end.

*Then add a method that returns an instance of the object with all BSON ID fields as strings (for use in the web front-end), and one that returns them as they are (of type ObjectID) to use with the DB driver.

It would be interesting to see what approach would experienced software architects employ


text:
Q: Angular ui-grid header row selection, selects all rows I have created pagination using Angular ui-grid. My requirement is if i select header row of the grid then all rows should be selected on the same page. But it is selecting all rows in every page which are present in the pagination. Ex:- If i am on 1st page of pagination then it should select all rows on 1st page only. But now it is selecting all rows in next 10 pages.

A: You can use
selectAllVisibleRows(event) Api

Refer: http://ui-grid.info/docs/#/api/ui.grid.selection.api:PublicApi


text:
Q: display specific pdf page in the UIWebview ios I am currently working on a project and I have ios need to display a pdf file.
However i want choose the page to display.
For example see page 10 of 37 in a UIWebView.
I have not found a way to cleanly separate the pages of a pfd.
thank you for your help.

A: Use UIWebView's delegate method to do this:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
   //Check if file still loading
   if(!webView.isLoading)
   {
     //now traverse to specific page
     [self performSelector:@selector(traverseInWebViewWithPage) withObject:nil afterDelay:0.1];
   }
}

Now add below method to traverse to your page. Note need valid PDF file path and provide your valid specific page no you want traverse in PDF file.
-(void)traverseInWebViewWithPage
{
   //Get total pages in PDF File ----------- PDF File name here ---------------
   NSString *strPDFFilePath = [[NSBundle mainBundle] pathForResource:@"yourPDFFileNameHere" ofType:@"pdf"];
   NSInteger totalPDFPages = [self getTotalPDFPages:strPDFFilePath];

   //Get total PDF pages height in webView
   CGFloat totalPDFHeight = yourWebViewPDF.scrollView.contentSize.height;
   NSLog ( @"total pdf height: %f", totalPDFHeight);

   //Calculate page height of single PDF page in webView
   NSInteger horizontalPaddingBetweenPages = 10*(totalPDFPages+1);
   CGFloat pageHeight = (totalPDFHeight-horizontalPaddingBetweenPages)/(CGFloat)totalPDFPages;
   NSLog ( @"pdf page height: %f", pageHeight);

   //scroll to specific page --------------- here your page number -----------
   NSInteger specificPageNo = 2;
   if(specificPageNo <= totalPDFPages)
   {
      //calculate offset point in webView
      CGPoint offsetPoint = CGPointMake(0, (10*(specificPageNo-1))+(pageHeight*(specificPageNo-1)));
      //set offset in webView
      [yourWebViewPDF.scrollView setContentOffset:offsetPoint];
   }
}

For calculation of total PDF pages
-(NSInteger)getTotalPDFPages:(NSString *)strPDFFilePath
{
   NSURL *pdfUrl = [NSURL fileURLWithPath:strPDFFilePath];
   CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);
   size_t pageCount = CGPDFDocumentGetNumberOfPages(document);
   return pageCount;
}

Enjoy coding .....

A: You can use  setContentOffset property of webview to show that page,
[[webView scrollView] setContentOffset:CGPointMake(0,10*pageheight) animated:YES];

where pageheight=your page height, 10 is your page no,


text:
Q: What is the black, finned, metal part in this picture of a board? Can someone explain what this black part is?

This a WLAN module.

A: That's a heatsink. Hence the metal feel (good heat transport), the high surface area (high rate of heat transport through convection), and the black color (high emissivity).


text:
Q: D preserving constness (DLang) I would (1) like to declare an unsigned integer that has the same size as the given typename or type of a given expression, and (2) provide a type conversion to that type that simply passes the bitpattern of the argument unchanged. (Even in the case of passing a float, say, I need it converted to a uint of the correct width that preserves the bitpattern faithfully.)
How should I deal with preserving the constness of the type unchanged, in both cases, not casting away const or immutable?
Here's my partial attempt:
template TUint_t( alias T )
    {
    static if ( T.sizeof * 8 == 64 )
        alias TUint_t = uint64_t;
    else static if ( T.sizeof * 8 == 32 )
        alias TUint_t = uint32_t;
    else static if ( T.sizeof * 8 == 16 )
        alias TUint_t = uint16_t;
    else static if ( T.sizeof * 8 == 8 )
        alias TUint_t = uint8_t;
    else static assert ( false );
    }

auto ConvertToBitPattern( T )( inout T x )
    {
    return * cast( TUint_t!(T) * ) &x;
    }

A: Use std.traits.CopyConstness, which returns the second type parameter with the const-ness qualifier of the first.
template TUint_t( alias T )
{
    static if ( T.sizeof * 8 == 64 )
        alias U = uint64_t;
    else static if ( T.sizeof * 8 == 32 )
        alias U = uint32_t;
    else static if ( T.sizeof * 8 == 16 )
        alias U = uint16_t;
    else static if ( T.sizeof * 8 == 8 )
        alias U = uint8_t;
    else static assert ( false );

    // Apply T's const-ness to U
    alias TUint_t = CopyConstness!(T, U);
}

Note: this does not copy shared. std.traits.CopyTypeQualifiers will copy const and shared-ness.


text:
Q: Can't scroll by click, autocomplete, IE I have the following code:
 $("#inputFindLocation").autocomplete({

        minLength: 2,
        source: function (request, response) {
            $.getJSON(BASE_URL + "/Extract/FindLocation", {
                searchForString: $("#inputFindLocation").val()
            }, response);
        },
        select: function (event, ui) {
            if (ui.item && ui.item.XCoordinate && ui.item.YCoordinate) {
                panTo(ui.item.XCoordinate, ui.item.YCoordinate);
                $("#dialogFindLocation").dialog("close");
                $("#inputFindLocation").val("");
            }
        },
        open: function (event, ui) {

            $(this).autocomplete("widget").css("z-index", 110);

           return false;
        }
    }).data("ui-autocomplete")._renderItem = function (ul, item) {
        return $("<li>")
        .append("<a>" + item.PlaceName + " (" + item.County + ", " + item.Municipality + ")</a>")
        .appendTo(ul);

    };

This works fine In Firefox. However, In Internet Explorer I can't navigate/scroll down the list by clicking on the down arrow icon In the scroll bar. The first Item are always selected. If I hold in the down arrow icon, It works.
If I drag down to the end of the list, and then click on the up arrow, It scrolls up to the beginning of the list, instead of one item at time.
It seems like the first item are "selected" by default, and that's why this error occur. But how can I solve this?
Here Is a similar question: jQuery UI Autocomplete IE Cursor Position Bug


text:
Q: Proving a this sequence converges using epsilon definition I am not certain how to prove this sequence converge using the epsilon definition
Here is the sequence
$a_j=\frac{j^2+3}{2j^2-j+9}$
I turned the sequence into a function and for the limit I got
$j \rightarrow\infty \frac{j^2+3}{2j^2-j+9}=\frac{1}{2}$
So for the delta epsilon proof I have to find a number M such that for all
j>M then $|\frac{j^2+3}{2j^2-j+9}-\frac{1}{2}|<\epsilon$
I having trouble finding M
This is my work
$|\frac{j^2+3}{2j^2-j+9}-\frac{1}{2}|<\epsilon$
$=|\frac{(2)(j^2+3-(2j^2-j+9)}{2(2j^2-j+9)}|<\epsilon$
$=|\frac{j-3}{4j^2-j+9}|<\epsilon$
$=|(\frac{1}{j})\frac{1-3/j}{4-1/j+9/j}|<\epsilon$
I am not sure, what to do now
I guess find an integer larger than my rightmost fraction but how?

A: If you use that $|j-3|<j$  and $2j^2-j>j^2$ for $j\ge2$, you get that
$\displaystyle\frac{|j-3|}{2(2j^2-j+9)}<\frac{j}{2j^2-j+9}<\frac{j}{2j^2-j}<\frac{j}{j^2}=\frac{1}{j}$ for $j\ge 2$;
so now you just need to ensure that $j\ge 2$ and $\frac{1}{j}<\epsilon$.


text:
Q: How can i add an id and selector to nsdictionary? How can i add an id and selector to nsdictionary? These doesn't works:
id target = mainTarget;
    SEL selector=mainSelector;
    NSDictionary *tAndS=[[NSDictionary alloc]initWithObjectsAndKeys:target,@"target",selector,@"selector", nil];

A: The documentation says:

In general, a key can be any object (provided that it conforms to the
  NSCopying protocol—see below)

A selector does not conform to NSCopying, but you can convert one to a string (which does conform to the protocol):
NSString* sel = NSStringFromSelector(@selector(hello:));

The id is no different. If your object conforms to NSCopying then you're good to go. If not, you'll have to wrap it in something that does, such as NSData or just implement NSCopying (the latter would be "cleanest").

A: Try using NSMutableDictionary like this
NSMutableDictionary *tAndS = [[NSMutableDictionary alloc]init];
[tAndS setObject:target forKey:selector];


text:
Q: An upper bound on the number of regions in $\mathbb{R}^3$ from the interection of unit spheres If you place $n$ unit spheres in $\mathbb{R}^3$, then the number of regions formed by the intersection of the spheres should be bounded above by $n^3$.
This is something that a book handwaved as "easy to show", but I can't get a handle on how to prove this.
It's possible to place 4 unit spheres in a configuration like a tetrahedron to get $2^4 = 16$ regions, but beyond that, we can't place another unit sphere that intersects every single region. Of course, 16 is well below $4^3 = 64$. The bound of $n^3$ only becomes nontrivial at $n = 10$, because $2^{10} > 10^3$. I don't know how I would begin counting the number of regions that each new unit sphere can intersect to create new regions.

A: The maximum number of regions formed by an arrangement of $d$-dimensional hyperspheres is
$$ R_d(n) = {n-1 \choose d} + \sum_{k=0}^{d} {n \choose k}$$
When we add the $n$th sphere $s_n$, each region either stays the same or is bisected (creating two regions). Thus the total number of regions $R_d(n)$ is the number of previous regions $R_d(n-1)$ plus the number of previous regions that are bisected $R_{d-1}(n-1)$. To explain the second term, suppose we are in dimension three. The intersection of $s_n$ with $s_{i<n}$ is at most $n-1$ circles on $s_n$. The regions on $s_n$ formed by these circles are the region bisectors and the maximum number of them is just the the dimension-reduced problem $R_2(n-1)$. In general,
$$ R_d(n) = R_d(n-1) + R_{d-1}(n-1) $$
The first equation then follows by induction. Note that these values agree with those proved by @user141614.
$$ \begin{array} (
R_2(n) &= n^2 - n + 2 \\
R_3(n) &= \frac{n^3 + 3n^2 + 8n}{3}
\end{array}
$$

A: Claim 1: $n\ge1$ circles drawn on a sphere divide the sphere into at most $n(n-1)+2$ regions.
Proof: For $n=1$ this is obvious. Suppose we have $k-1$ circles , and investigate what happens when you draw a new circle $c$.
The new circle $c$ may intersect the previous circles at no more than $2(k-1)$ points; so the previous circles divide $c$ into at most $2(k-1)$ arcs. Each of these arc split a region in two. So the increase in the number of regions will be at most
$2(k-1)$; the total number of regions cannot exceed $2+\sum\limits_{k=2}^n 2(k-1)=n(n-1)+2$.
The proof shows that this bound is sharp; if every two circles intersect and the intersection points do not collide then we have exactly $k(k-1)+2$ regions.
Claim 2: $n$ spheres divide the space into at most
$2+\sum\limits_{k=2}^{n} \big((k-1)(k-2)+2\big)= \frac{n^3-3n^2+8n}3$
regions.
(You can repeat the same proof.)


text:
Q: What PHP application design/design patterns do you use? Please share your favorite application design / design patterns for use in PHP with me. Some things I'd like to know:

*

*How your folders are designed

*How you use object oritentation in your PHP applications

*Do you have a standard way of dealing with CRUD, pagination, or any other common tasks?

*How do you avoid using repetitive code? What's your approach to libraries/sharing common code, etc?

*What are ways in which you can make your code more elegant?

You don't have to answer all of these, answering any or a few of these will be helpful.
The reason I'm asking this,is because I'm very tired of writing repetitive, ugly code in PHP and I want to make a small framework for my freelancing projects which will make programming easier and let me focus on the challenging/business tasks rather than form validation, pagination, and the other mundane activities which make up 80% of programming work in PHP
All opinions appreciated!

A: I imagine a lot of php developers have followed a similar route to mine: small scripts -> procedural/inline-code -> possibly a look at templating -> OOP -> then a framework. I think it may be quite common for a PHP developer to have "grown up" with PHP, learning design patterns to match the features available with the current version.
MVC is the most frequently used design pattern in the popular frameworks being used today. CakePHP is my framework of choice although Symphony and Zend are very popular too – it's well worth trying out a few and it'll soon become apparent which you feel most comfortable with.
For most projects (where rapid development and portable code are the priorities) I use Cake, however for light weight apps (one I developed recently was Good Baad) that you'd like to run fast (on low spec hardware) and do not need the bulk/weight added by the functionality of one of the large frameworks I recommend reading Rasmus Lerdorf's article on his No Framework PHP MVC framework.
Basically if you're after a true object oriented language that encourages beautiful code and the best design practices PHP is always going to lose out to the likes of Ruby Python and  C#. But, PHP has its strengths e.g. no need for a templating language (it is one), PHP can run very fast and cheaply and does not need the weight of a large framework for all applications.
I'd encourage adopting a design pattern that takes the manageability of a design pattern like MVC and combine it with PHP's strengths.

A: I almost feel like a broken record, but I would recommend that you take a look at some of the common frameworks for two reasons:

*

*Even if you choose not to use one, some of them are very well written and very well designed. I particularly like Zend Framework but I'll come back to that in a second.

*Ask yourself why you're reinventing the wheel. Do you really feel that you understand the same design problems everyone else faces so much better than the community behind (insert framework of choice here) to justify writing something from scratch? Speaking as one who originally looked at several frameworks and decided that they were too big, presented too much of a learning curve or too much overhead and so developed my own, I can tell you that writing your own from scratch is a big pain if you can simply use an existing one that can be easily extended.

Speaking of using a framework that can be easily extended, I have had very positive experiences with Zend Framework. It's cohesive and yet loosely coupled structure makes it possible to quickly and easily extend any existing component and the entire framework is designed around the idea that you will need to write your own helper and plugin classes to add to its overall functionality.
I've found Zend Framework to be so completely flexible that I am running a single website as part Zend Framework MVC and part my old crappy framework and even older crappier code that I haven't gotten to rewrite yet. In fact, because during our rewrite we found one page that ran unacceptably slow using the old framework, I've switched the single page to run under the Zend Framework architecture.
To answer some of your questions, I would recommend that you look into Patterns of Enterprise Application Architecture by Martin Fowler. He provides a lot of valuable insights into how to solve a number of these common problems like how to create a database interaction layer in your application. Fowler also covers topics like MVC and Front Page Controller.

A: I might get voted down for this, but if you really do want to write your own framework, I say go for it because you will learn a lot from the experience. The other frameworks mentioned here are great and tested and you wouldn't be making a bad decision using them, but it's your choice.
Before starting to write your framework, look at the other frameworks (at their syntax, directory structure, naming schema, design patterns, etc) and try to figure out why they did what they did and what, if anything, you would do differently. Try out a few tutorials and play with their code, make a few sample apps. If, after doing that, you don't like using them, then go ahead and start planning your framework, keeping what worked and improving what didn't.
If you do decide to roll your own, here are a few things I would recommend from my own experience:

*

*Make Security Your Top Priority - If
you write a data access layer, use
bound parameters. If you write a form
class, guard against CSRF and XSS.
Catch your exceptions and handle your
errors. Make sure that your PHP
environment is secure. Don't try
coming up with your own encryption
algorithm. If you don't concentrate
on security, it's not worth writing
your own framework.

*Comment Your Code - You will need
comments to help you remember how
your code works after a while. I
usually find that docblock comments
are more than enough. Beyond that,
comment why you did something, not
what you did. If you need to explain
what, you may want to refactor.

*Single Responsibility Classes and
Methods - Most of your classes and
methods should do one thing and only
one thing. Especially watch out for
this with the database - Your
pagination class shouldn't rely on
your data access object, nor should
almost any other (low-level) class.

*Unit Test - If each of your methods
does only one thing, it should be far
easier to test them and it will
result in better code. Write the test
first, then the code to pass the
test. This will also give you greater
freedom to refactor later on without
breaking something.

*Abstract Similar Classes - If you
have more than one class that does
similar things, create a parent class
that uses the similarities between
the classes and extend it.

*Delegate and Modularize - If you're
writing a validation system (and
chances are you probably would),
don't include each validator as a
method in some super validation
class. Separate them into individual
classes and call them as needed. This
can be applied in many areas:
filters, languages, algorithms,
validators, and so on.

*Protect and Privatize - In most
cases, it's better to use getter and
setter methods rather than allowing
direct access to class variables.

*Consistent API - If you have a
render() method and a draw() method
that do the same things in different
classes, pick one and go with it
across all classes. Keep the order of
the parameters the same for methods
that use the same parameters. A consistent API is an easier API.

*Remember Autoloading - The class
names can get a little clunky and
long, but the way Zend names the
classes and organizes the directories
makes autoloading a lot easier. Update: As of PHP 5.3, you should begin using namespaces.

*Never echo or print anything - Give
it as a return value and let the user
decide if it should be echoed. A lot
of times you'll use the return value
as a parameter for another method.

*Don't Try to Solve the World's
Problems - Solve your own first. If
you don't need a feature right now,
like a class for localizing numbers
or dates or currency, don't write it.
Wait until you need it.

*Don't Preoptimize - Build a few
simple applications with your
framework before fine tuning it.
Otherwise, you can spend a lot of
time on nothing productive.

*Use Source Control - If you spend
countless hours creating a
masterpiece, don't risk it getting
lost.

A: i've explained most of my PHP methodology here.
but nowadays, i just use Django everywhere i can.

A: I started out with the smarty templating engine when i first got tired of mixing code and html.  After hacking for a while, I realized that writing my own framework is just duplicating work.
I've done a few projects with Joomla, which is really a CMS but it gives clients a lot of control over content.
Ultimately I've settled on using a real framework for my projects.  I'm using symfony, which is inspired by Rails and is very well documented, but I've heard cakePHP and ZendFramework are also very good.

A: I use Zend Framework, which pretty much defines folder layout and OOP (MVC paradigm). For common tasks, such as for example pagination I use Zend_Paginator (my model classes  implement Zend_Paginator_Adapter_Interface), for validation I use Zend_Validate classes etc. Thanks to that I can fully concentrate on business logic instead of reinventing the wheel.

A: Using Zend Framework and Doctrine, my folder structure usually looks like this:
root
  app
    config         (db config, routing config, misc config)
    doctrine       (fixtures, migrations, generated stuff, etc)
    lib
    logs
    models         (doctrine models)
    modules        (zend mvc modules)
    bootstrap.php
  docs             (db diagrams, specs, coding standards, various docs)
  pub              (web root)
  tests
  tools            (console tools, i.e. doctrine-cli)
  vendor           (zend and doctrine libraries, preferably as svn-externals)

A: I have to agree with the above posters. If you're not using a framework when programming in PHP you're really programming with your hands tied behind your back. I personally recommend CodeIgniter. It's the fastest framework around, it's very easy to learn, and has a very active community. All of your questions will be answered by the framework:
* How your folders are designed

CodeIgniter (or any framework for that matter) separates your logic into views, models, and controllers, each with their own folder.
* Do you have a standard way of dealing with CRUD, pagination, or any other common tasks?

CI has a pagination library, and it has 3rd party libraries like DataMapper for wrapping your CRUD calls in an object oriented way (ORM).
* What are ways in which you can make your code more elegant?

The seperation of the model, view, and controller make for very elegant code.
(The 2 questions I didn't answer are pretty much implied when using the framework)

A: I've been messing around writing my own stuff for a while now and everytime I can never get around to finishing it fully because I get stuck on something.
And then comes the part where I come to realization of whether I am doing something right.
And as such I have given up on writing my own an going with a crowd favourite: Zend.
I looked at others but it seems Zend has been around a while and they know their things.
MVC is also the way I am going forward with anything I write now.


text:
Q: Binding a click event to a frame below a label I have a frame with three labels in it, and I would like to click anywhere in the frame to trigger an event. Unfortunately, the labels are on top of the frame and the clicks aren't registering.
frame=tk.Frame(root)
frame.pack()
frame.bind("<1>", function)

L1=tk.Label(frame, text="Label_1")
L1.pack()
L2=tk.Label(frame, text="Label_2")
L2.pack()
L3=tk.Label(frame, text="Label_3")
L3.pack()

Do I need to bind the click event to each label?
Edit for clarity: I have a frame with three labels in it. I have it this way because it's the only way I could format the three strings properly (just one Label object doesn't allow much for formatting individual parts). I would like to click anywhere in the frame to trigger an event, i.e. click any of the labels, anywhere, and have the same event triggered. Right now I can see three solutions:

*

*I find a way to click through the labels to click the frame

*I find a way to format the three Labels as one Label. I don't think it's possible to format a Label like a printf though.

*I bind the same command to each Label.

Potential 4th solution: I create a Frame that inherits from a Button. Not sure if this is possible either. Maybe I can add multiple Labels to a Button?
Is there another way to do this?


text:
Q: Format or change MySql database data to realpath using preg_match or preg_replace in PHP I am storing HTML data in MySQL database for some reason. how to get all image,css and jss file src from MySQL data and change it to realpath.
Like  to
Same as  to
And  to
Using preg_match or preg_replace in PHP

A: Try to run this regex
/(?:src|href)="(.*?)"/g

Using preg_replace it will be something like this:
preg_replace('/(?:src|href)="(.*?)"/g', 'http:localhost/$1', 'Your field in database');

But test it not in production code, but in your local testing environment as I didn't test it.


text:
Q: openssl_pkcs7_sign(): error getting private key When trying to use TCPDF to generate a pdf and sign it, i get the error:
openssl_pkcs7_sign(): error getting private key.

and:
Undefined offset: 1 in ..\tcpdf\tcpdf.php on line 7604

I have found the following stackoverflow posts and tried to follow their solutions:

*

*Warning: openssl_pkcs7_sign(): error getting private key using WAMP

*Warning: openssl_pkcs7_sign() [function.openssl-pkcs7-sign]: error getting private key in C:\xampp\htdocs\this\tcpdf\tcpdf.php on line 8366
Unfortunately, nothing works.
I have tried to use:
$certificate = "file://" . getcwd() . "/objects/dummy_cert.cert";

or
$certificate = "file://" . __DIR__ "/objects/dummy_cert.cert";

or writing the absolute path by hand.
My script is executed from the project root path, from which /objects/ is the next folder in which my dummy_cert.cert lies.
What is happening here and how can i fix this?
I even logged the content of $certificate to be sure it generates the correct path. The generated path, copied into Google Chrome address bar, immediately loads the content of the .cert file.

A: You need the 'file://' prefix and the realpath to file:
//in your case
$certificate = 'file://'.realpath('/objects/dummy_cert.cert');
// OR for other cases
$certificate = 'file://'.realpath('../upper_folder/objects/dummy_cert.cert');
// OR
$certificate = 'file://'.realpath('C:/objects/dummy_cert.cert');

A: This is what has worked for me in an online linux server:
 $certificate = 'file://'. __DIR__ .'/your/relative/path/to/this/file/tcpdf.crt';

 $info = array(
                  'Name' => 'TCPDF',
                  'Location' => 'Office',
                  'Reason' => 'Testing TCPDF',
                  'ContactInfo' => 'http://www.tcpdf.org',
                  );
    $pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);

Notice that you are missing a point after the "DIR__ "
Also, I used the test .crt file that goes as an example in TCPDF library with password "tcpdfdemo". I think is better to test first with that file, to make sure that the problem is not related to your crt.


text:
Q: How to get name of ProcessInstanceStep in apex? I have to get the name of ProcessInstanceStep with apex. In my case it is Approval Request Submitted. There is no the name field in ProcessInstanceStep object, but I think it is possible to get it via some lookups.
Thanks

A: if you need to get the step name of a given ProcessInstanceStep you may have to run a separate query against ProcessInstanceNode using the ProcessInstanceId, on the field ProcessNodeName it will have the step name.
E.g.
SELECT Id, ProcessNodeName
FROM ProcessInstanceNode
WHERE
  ProcessInstanceId = '<ProcessInstanceId From ProcessInstanceStep>'

Note: there lookups indirectly but on the parent object ProcessInstance (e.g. Nodes references ProcessInstanceNode & Steps references ProcessInstanceStep)


text:
Q: Batch not Working (If) master.bat
@echo off
    if !%~1! == !--Instance! (
        if !%~2! == !old! (
            echo Old instance
            set /p InstanceId= Enter the InstanceId:
            echo %InstanceId%
        )
        if !%~2! == !new! (
            echo New instance
        )
    ) else (
        if !%~1! neq !--Instance! (
            echo Bad command: Unknown Flag/Switch %1
        ) else (
            if !%~2! neq !new! **(
                echo Bad command: Incorrect Flag value %2
            )
        )
    )

Q1 : The above piece of code works fine for all the conditions except the last one marked as (**) for readbility. I am not able to comprehend why ?
    i am running the following command
master.bat --Instance abc

Q2: also i wish to change the same (**) line to check for another value say 'old' (quotes for clarity). how to do that ? will this work
if !%~2! neq !new! or !%~2! neq !old! (
      echo Bad command: Incorrect Flag value %2
 )

A: answer for q1 : Finally i recognized where i was going wrong, actually the control was never reaching the block with (**).
answer for q2 : and making slight changes in the code snippet above it will work in the manner expected.
@echo off
setlocal

if !%~1! == !--Instance! (
    if !%~2! == !old! (
        echo Old instance
        echo %InstanceId%
        set /p InstanceId= Enter the InstanceId:
        call DescribeOldEC2.bat %InstanceId%
        echo %InstanceId%
    ) else (
        if !%~2! == !new! (
            echo New instance
        ) else (
            echo Bad command: Incorrect Flag value %2
        )
    )
) else (
    if !%~1! neq !--Instance! (
        echo Bad command: Unknown Flag/Switch %1
    )

endlocal


text:
Q: creating cdata in xml     ><![CDATA[BEGIN:VCARD
VERSION:3.0
FN:D Formatted Name
N:D Surname;D Given name;D Additional names;D Name prefix;D Name Suffix
ORG:D Organization Unit;D Org Unit
END:VCARD
]]>

how do i write this in a xml file i have to replace all 'D' with user entered value.

A: IMO if you are using .NET then when you are writing XML use the Linq to XML classes (XElement, XDocument etc) they provide a DOM free way of writing code.
Then writing a CData section is trivial....
var result = new XElement("MyElemName",
                new XCData("BEGIN:VCARD......etc")
             );

Note when reading from a CData section in Linq to XML, you don't need to do anything special, just use the (string) typecast overload on the Element and it will handle the CData section for you....
var cdataBit = (string)x.Element("MyElemName");


text:
Q: Implement SelectField for Material-UI v1.0.0-alpha.21 - Menu anchorEl issue Since Material-UI v1.0.0 hasn't implemented yet the selectField I'm trying to implement my own using TextField, Menu and MenuItem Components.
This is my code:
export default class SelectField extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            anchorEl: undefined,
            open: false,
        };
    }

    handleClick = event => {
        this.setState({ open: true, anchorEl: event.currentTarget });
    };

    handleRequestClose = () => {
        this.setState({ open: false });
    };

    handleMenuItemClick = (event, index) => {
        this.setState({ open: false });
        this.props.onChange(index);
    };

    render(){
        const { style, name, label, value, onChange, children } = this.props;

        return (
            <div>
            <TextField style={style} onClick={this.handleClick} type="text" name={name} label={label} value={value} InputProps={{ placeholder: label }} />
                <Menu open={this.state.open} anchorEl={this.state.anchorEl} onRequestClose={this.handleRequestClose} >
                    {children.map((key) =>
                        <MenuItem key={key.value} selected={key.value === this.props.value} onClick={event => this.handleMenuItemClick(event, key.  value)} >
                            {key.name}
                        </MenuItem>,
                    )}
                </Menu>
            </div>
        );
    }
}

Now my first problem comes when I try to positioning the Menu. At Material-UI docs I saw they used the property anchorEl to do put the menu in front of the element that is opening it. Ok, that works fine until you use selected property with lots of items. And I also want to ajust the position of the menu to be downside the TextField.
Also but not that much important. I want to set the width of the menu to the width of the TextField and also I want to allow search by writing o the Menu.

A: I met the same problem about the positioning of the menu yesterday. After checking out the source code of the Menu.js, I found that the Menu Component is wrapped by the internal Popover Component. So you could pass anchorOrigin prop to the Menu Component realizing customized positioning. But in my tests, it could only receive the anchorOrigin prop. There will be an error when you pass the targetOrigin prop, so I am trying to figure it out.


text:
Q: dgrid add new row on button click I am trying to make an editable grid. I would like to provide users to be able to like more rows if needed. I tried going to their documentation yet it wasn't obvious.
Also, what does grid.newRow() do?

A: If you're trying to add a new row, you can always just add a new entry to the underlying grid store first.
Say you have a grid (named "grid" of users), you can have your button do this:
var button = new Button({
    label: "Add User",
    onClick: function() {
        var user = {id: 1, name: "test"};
        grid.store.add(user);
    }
});

Also I don't believe the regular grids have a newRow option, only the onDemandGrid or onDemandList has a newRow option. But the above code should work for what you asked for.


text:
Q: Mongo: db.cloneCollection doesn't work in 2.4.6? I'm trying to clone a collection from one Mongo host to another:
I have two mongo instances v.2.4.6 installed on two hosts:
host1 and host2 (host1 and host2 are actually IPs but replaced with name to simplify the question). Both hosts are in the same network and I can successfully open other server's mongo console from the first server using:
on host1:
mongo --host host2

But when I do in the mongo shell of the first server:
on host1:
db.cloneCollection("host2:27017", "my_db.my_collection")

The output is:
{ "ok" : 1 }

But the my_db database is not created on the host1. I tried to create empty database but the collection isn't copied either. I tried to create empty collection in it, but the collection items are not copied.
Note: The my_db.my_collection on host2 is not empty. Have double checked that.
Guys, could you please check if the db.cloneCollection() works for you on mongo 2.4.6?
If so - maybe I'm missing some prerequisite?

A: Mongodb for Windows, v 2.4.6
First mongod with default params: port -> 27017, dbpath -> c:\data\db
Second mongod with params: port -> 27018, dbpath -> c:\data\db1
Logged to the second mongod. Use test db. Execute:
db.cloneCollection("localhost:27017","db.test.so000")

Not cloned. Then execute:
db.cloneCollection("localhost:27017","so000")

It was cloned. So, suggestion in this case -- do not use full path to collection.
Updated
Just investigated some documentation: http://docs.mongodb.org/manual/reference/command/cloneCollection/#dbcmd.cloneCollection
If you want to use db prefix, you should run clone this way:
db.runCommand({cloneCollection: "test.so000", from: "localhost:27017"})

It will clone collection so000 as well. It will create db even if db test doesn't exist on this second server.


text:
Q: how to know if an estimator is unbiased I have some doubt about this excercise, can someone help me?
Let $(X_1,\dots,X_n)$ be independent identically distributed random variables with p.d.f. $$f(x) = \theta^2 x \exp(-\theta x),$$     with $x>0$.
Is $T(X_1,\dots,X_n)= 1/X_1$ an unbiased estimator of $\theta$?
I know that this estimator is unbiased when $E(X)$ is equal to $\theta$, but how can I find $E(X)$ of an estimator
it's different from $E(X)$ of a random varible ?

A: Hint :
Using the law of the unconscious statistician you get that
$$E[\frac{1}{X}] = \int_{0}^{\infty} \frac{f(x)}{x} dx$$


text:
Q: find who the manager using boolean datatype(true, false) in ismanager column There are set of data listed under table employee like empid, empname, position, managerid, ismanager.
Here some employees are manager and some not. If that employee is manager it has to show 1 in ismanager column, if that employee is not manager it has to show 0 in ismanager column, if empid is listed in managerid then ismanager should be updated to 1 else it should be 0.
create table usertable (
    empid int primary key,
    empname varchar(40),
    position varchar(40),
    managerid int,
    foreign key (managerid) references usertable(empid),
    ismanager bit(1)
);

This is what I have tried:
update usertable  set ismanager=
case
when empid  in (select managerid from usertable) then 1
else 0
end;

A: As they are all set to 0 currently, you only need to update the ones who are managers:
UPDATE usertable u1
JOIN (SELECT DISTINCT managerid FROM usertable WHERE managerid IS NOT NULL) u2
    ON u1.empid = u2.managerid
SET u1.ismanager = 1;

If they are all set to null and you need to set both the 1s and 0s:
UPDATE usertable u1
LEFT JOIN (SELECT DISTINCT managerid FROM usertable WHERE managerid IS NOT NULL) u2
    ON u1.empid = u2.managerid
SET u1.ismanager = (u2.managerid IS NOT NULL);

Of course, you could ditch the redundant ismanager column and retrieve it dynamically:
SELECT *, EXISTS (SELECT 1 FROM usertable WHERE managerid = u.empid) AS ismanager
FROM usertable u;


text:
Q: Updating Visual studio multiple projects references I have a vs solution which have many projects probably in the range of 30 to 40. Of course, each project have their project references such as to oracle data access dll. My question or pain is that to do an upgrade to any of my other application, e.g. oracle db, i would have to manually change all 30 project's references.
Is there a simpler way to do so?


text:
Q: How to split NSArray into UITableView sections alphabetically I have having trouble using an indexed table with section headers. Currently I have the indexes down the right hand side and I have the section headers showing correctly, the headers only show if there is data inside of that section.
The problem I am having is splitting the NSArray into parts so I can calculate the numberOfRowsInSections correctly. Currently I have the correct number of sections displaying with the correct headers but all of the data is in each section, rather than being split depending on the first letter of the name.
Here is a screenshot of how it currently looks:
All of the data goes into each sections, 5 rows in each. The number of sections (3) is correct
My code for this is as follows:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [firstLetterArray objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{

    NSMutableSet *mySet = [[NSMutableSet alloc] init];

    BRConnection *connection = nil;
    NSMutableArray *firstNames = [[NSMutableArray alloc] init];
    for (connection in _connections)
    {
        [firstNames addObject:connection.firstName];
    }
    firstNamesArray = firstNames;
    NSLog(@"%@", firstNamesArray);
    for ( NSString *s in firstNames)
    {
        if ([s length] > 0)
            [mySet addObject:[s substringToIndex:1]];
    }

    NSArray *indexArray = [[mySet allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    firstLetterArray = indexArray;

    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

    if ([title isEqualToString:@"{search}"])
    {
        [tableView setContentOffset:CGPointMake(0.0, -tableView.contentInset.top)];
        return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
    }
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConnectionCell"];

    // Display connection in the table cell
    BRConnection *connection = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        connection = [searchResults objectAtIndex:indexPath.row];
    } else {
        connection = [_connections objectAtIndex:indexPath.row];
    }

    cell.textLabel.text = connection.fullName;
    cell.textLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:18];
    cell.detailTextLabel.text = connection.company;
    cell.detailTextLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:12];

    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    NSUInteger sections = [firstLetterArray count];
    return sections;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];

    } else {
        return [_connections count];
    }
}

Any help would be greatly appreciated, I just cant seem to split the NSArray conenctions into a alphabetical list to get the correct rows in a section. Thanks in advance everyone!

A: Where and how are you populating _connections? You're using that array to decide the number of rows per section and to populate those rows, but _connectionsis returning the entire list. You need to split the data in _connections up alphabetically.
For example, perhaps you could use an NSMutableArray of NSMutableArrays to group the data by letter. Since you already seem to know how to sort alphabetically, now you just need to identify the first characters of each string to group them properly. To do this, try:
NSString *currentPrefix;

// Store sortedConnections as a class variable (as you've done with _connections)
// so you can access it to populate your table
sortedConnections = [[NSMutableArray alloc] init];

// Go through each connection (already ordered alphabetically)
for (BRConnection *connection in _connections) {

    // Find the first letter of the current connection
    NSString *firstLetter = [connection.fullName substringToIndex:1];

    // If the last connection's prefix (stored in currentPrefix) is equal
    // to the current first letter, just add the connection to the final
    // array already in sortedConnections
    if ([currentPrefix isEqualToString:firstLetter]) {
        [[sortedConnected lastObject] addObject:connection];
    }

    // Else create a new array in sortedConnections to contain connections starting
    // with this current connection's letter.
    else {
        NSMutableArray *newArray = [[NSMutableArray alloc] initWithObject:connection];
        [sortedConnections addObject:newArray];
    }

    // To mark this latest array's prefix, set currentPrefix to contain firstLetter
    currentPrefix = firstLetter;
}

(This sort would work even if the first letters are unknown.)
Then to get the number of rows per section, use [sortedConnections objectAtIndex:section] instead of _connections:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [[sortedSearchResults objectAtIndex:section] count]; // hypothetically
    } else {
        return [[sortedConnections objectAtIndex:section] count];
    }
}

And to populate the table essentially do the same using [sortedConnections objectAtIndex:indexPath.section]:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConnectionCell"];

    // Display connection in the table cell
    BRConnection *connection = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        connection = [[sortedSearchResults objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; // hypothetically
    } else {
        connection = [[sortedConnections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }

    cell.textLabel.text = connection.fullName;
    cell.textLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:18];
    cell.detailTextLabel.text = connection.company;
    cell.detailTextLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:12];

    return cell;
}

A: Hope that helps you, i don't know if is the best way to do, but it works =)
NSArray *names = @[@"Ana Carolina", @"Ana carolina", @"Ana luiza", @"leonardo", @"fernanda", @"Leonardo Cavalcante"];

NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
for( NSString*string in names ){
    [firstCharacters addObject:[[string substringToIndex:1] uppercaseString]];
}
NSArray *allLetters = [[firstCharacters allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
int indexLetter = 0;
NSMutableArray *separeNamesByLetters = [NSMutableArray new];

for (NSString *letter in allLetters) {
    NSMutableDictionary*userBegeinsWith = [NSMutableDictionary new];
    [userBegeinsWith setObject:letter forKey:@"letter"];
    NSMutableArray *groupNameByLetters = [NSMutableArray new];
    NSString *compareLetter1 = [NSString stringWithFormat:@"%@", allLetters[indexLetter]];
    for (NSString*friendName in names) {
        NSString *compareLetter2 = [[friendName substringToIndex:1] uppercaseString];

        if ( [compareLetter1 isEqualToString:compareLetter2] ) {
            [groupNameByLetters addObject:friendName];
        }
    }
    indexLetter++;
    [userBegeinsWith setObject:groupNameByLetters forKey:@"list"];
    [separeNamesByLetters addObject: userBegeinsWith];
}

NSLog(@"%@", separeNamesByLetters);

output:
 (
        {
        letter = A;
        list =         (
            "ana carolina",
            "Ana carolina",
            "Ana luiza"
        );
    },
        {
        letter = F;
        list =         (
            fernanda
        );
    },
        {
        letter = L;
        list =         (
            leonardo,
            "Leonardo Cavalcante"

        )
    }
)

A: Just in case you have custom objects , little modification in @Leo
NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
        for( ETUser *user in self.follwings){
            [firstCharacters addObject:[[user.name substringToIndex:1] uppercaseString]];
        }
        NSArray *allLetters = [[firstCharacters allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
        int indexLetter = 0;
        NSMutableArray *separeNamesByLetters = [NSMutableArray new];

        for (NSString *letter in allLetters) {

            NSMutableDictionary*userBegeinsWith = [NSMutableDictionary new];

            [userBegeinsWith setObject:letter forKey:@"letter"];

            NSMutableArray *groupNameByLetters = [NSMutableArray new];

            NSString *compareLetter1 = [NSString stringWithFormat:@"%@", allLetters[indexLetter]];

            for (ETUser *user in self.follwings) {

                NSString *compareLetter2 = [[user.name substringToIndex:1] uppercaseString];

                if ( [compareLetter1 isEqualToString:compareLetter2] ) {

                    [groupNameByLetters addObject:user];
                }
            }
            indexLetter++;
            [userBegeinsWith setObject:groupNameByLetters forKey:@"list"];
            [separeNamesByLetters addObject: userBegeinsWith];
        }

        self.follwings = [[NSMutableArray alloc]initWithArray:separeNamesByLetters];


text:
Q: How do I make this R code run faster Goal: Generate a set of rectangular boxes and stack them onto a 10x10 grid.  My function getCoordinates generates numBoxes randomly sized boxes with integer lengths between 1 and 10. The variable gridTops keeps track of the max height occupied by each cell of the 10x10 grid.  The function returns a two element list containing a matrix with coordinates of the stacked boxes and gridTops.
getCoordinates<-function(numBoxes){
  # Generates numBoxes random sized boxes with integer dimensions between 1 and 10.
  # Stacks them and returns results
  boxes<-data.frame(boxId=1:numBoxes,
                    xDim=sample(10,numBoxes, replace=TRUE),
                    yDim=sample(10,numBoxes, replace=TRUE),
                    zDim=sample(10,numBoxes, replace=TRUE))
  gridTops<-matrix(0,nrow=10,ncol=10)
  coordinates<-matrix(nrow=nrow(boxes),
                      ncol=6,
                      dimnames=list(boxes$boxId,c("x1","y1","z1","x8","y8","z8")))
  for(i in 1:nrow(boxes)){
    mylist<-addBox(boxes[i,], gridTops);
    coordinates[i,]<-mylist[["coordinates"]];
    gridTops<-mylist[["gridTops"]];
  }
  return(list(boxes=boxes, coordinates=coordinates));
}

addBox<-function(boxDimensions, gridTops){
  #Returns a list of coordinates and the updated gridTops matrix
  xd<-boxDimensions$xDim
  yd<-boxDimensions$yDim
  zd<-boxDimensions$zDim
  x1<-0
  y1<-0
  z1<-max(gridTops[1:xd,1:yd])
  gridTops[1:xd,1:yd]<-(z1+zd)
  coordinates<-c(x1,y1,z1,x1+xd,y1+yd,z1+zd)
  return(list(coordinates=coordinates,gridTops=gridTops))
}

As an example,
test<-getCoordinates(5)
test[["boxes"]]
  boxId xDim yDim zDim
1     1    5    2    4
2     2    9    1    4
3     3    1    7    7
4     4   10    6    1
5     5    5    8   10
test[["coordinates"]]
  x1 y1 z1 x2 y2 z2
1  0  0  0  5  2  4
2  0  0  4  9  1  8
3  0  0  8  1  7 15
4  0  0 15 10  6 16
5  0  0 16  5  8 26

As you can see, my method of stacking the boxes is just putting one on top another with one corner on the (x=0,y=0) cell.  Simple enough, but it's taking a long time to stack 10000+ boxes.  For example
system.time(getCoordinates(10000))
 user  system elapsed
2.755   0.414   3.169

I think my for loop is slowing things down, but I don't know how to apply an apply function in this situation.  How can I speed this thing up?
Edit: The method addBox is subject to change.  As I mentioned, it simply stacks one box right on top the next.  This is a naive packing algorithm, but I wrote it for illustrative purposes.

A: Changing boxes from a data.frame to a matrix speeds it up considerably for me.
I changed
boxes<-data.frame(

to
boxes <- cbind(

and edited the places you accessed boxes in the two functions, went from :
R>system.time(getCoordinates(10000))
   user  system elapsed
  1.926   0.000   1.941
R>getCoordinates <- edit(getCoordinates)
R>addBox <- edit(addBox)
R>system.time(getCoordinates(10000))
   user  system elapsed
  0.356   0.002   0.362


text:
Q: Constraint Violation Property Path when using Sets I can't get my mind to wrap around a problem I have with a requirement concerning JSR303 bean validation (I'm currently using Hibernate Validator).
Assuming I have the following domain model
class Foo {
   private Set<Bar> bars = new HashSet<>();

   @Valid
   public Set<Bar> getBars() { ... }
}

class Bar {
   private String name;

   @NotBlank
   public String getName() { ... }
}

Say I have a foo instance with two bars with one of the two names being empty.  After validating foo I'm holding a @NotBlank constraint violation with a property path bars[].name in my hand. Which is all well, but...
is there any way I can find out which of the two bars had its name empty? Or am I forced to use a List here and introspect the - then unique - property path using reflection?

A: The latest release of Hibernate Validator, 5.2.0.CR1, provides a solution for this. You can unwrap property path nodes and get the property value. That way you know which Bar instance is affected:
Set<ConstraintViolation<Foo>> constraintViolations = ...;

Path path = constraintViolations.iterator().next().getPropertyPath();
Iterator<Path.Node> nodeIterator = path.iterator();

Path.Node node = nodeIterator.next();
Bar bar = (Bar) node.as( PropertyNode.class ).getValue();


text:
Q: is there any way of capture a flow of actions with chrome and export to selenium? I want to know if is possible to capture a lot of actions like a flow and export to selenium, in order to repeat that flow.
For example, I need to uninstall and reinstall and configure a few applications each day several times, the process is always the same, and it's a long process, so in order to avoid navigate between code to capture all IDs and classes, is there any way of doing that?
Kind regards.

A: I think Selenium IDE is basically what you are looking for. It is a Chrome or Firefox extension that has a record and play back feature, and it is able to export working code in a variety of languages (including python).
Word of caution: tests produced by the tool tend to be pretty unreliable/flaky, you can attain much better stability by coding with WebDriver.

A: Using pyautogui or something similar you could record the location of each click and either use the color of certain pixels to intiate different stages or waiting x amount of time before click each saved point on screen


text:
Q: C# equivalent to Java SSL-socket-connection Hey guys I'm trying to write an AXL-client (SOAP) for the Cisco Unified Communications Manager. For that purpose I need to establish an ssl-connection to the AXL-service. Unfortunatly I dont know much about all that ssl-stuff.
However I was able to find a working Java-example, that does, what I want. The problem is, i need that in C#.NET. So I'm hoping, that someone could "translate" the following Java-code in a C#-version. But it has to do exactly the same, espacially the authentication and certificate-stuff.
Here is the code:
    String sAXLSOAPRequest = "...";
    byte[] bArray = null; // buffer for reading response from
    Socket socket = null; // socket to AXL server
    OutputStream out = null; // output stream to server
    InputStream in = null; // input stream from server

    X509TrustManager xtm = new MyTrustManager();
    TrustManager[] mytm = { xtm };
    SSLContext ctx = SSLContext.getInstance("SSL");
    ctx.init(null, mytm, null);
    SSLSocketFactory sslFact = (SSLSocketFactory) ctx.getSocketFactory();

    socket = (SSLSocket) sslFact.createSocket("192.168.1.100", Integer.parseInt("8443"));
    in = socket.getInputStream();
    // send the request to the server
    // read the response from the server
    StringBuffer sb = new StringBuffer(2048);
    bArray = new byte[2048];
    int ch = 0;
    int sum = 0;
    out = socket.getOutputStream();
    out.write(sAXLSOAPRequest.getBytes());

    while ((ch = in.read(bArray)) != -1) {
        sum += ch;
        sb.append(new String(bArray, 0, ch));
    }
    socket.close();
    // output the response to the standard output
    System.out.println(sb.toString());

and this is the MyTrustManager-Class:
public class MyTrustManager implements X509TrustManager {
MyTrustManager() {
    // create/load keystore
}

public void checkClientTrusted(X509Certificate chain[], String authType)
        throws CertificateException {
}

public void checkServerTrusted(X509Certificate chain[], String authType)
        throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
    return null;
}

}
Any help would be appreciated.
Thanks
edit: sorry i should have mentioned: youre right i can generate a proxy-class, but sadly its not working properly. cisco did a really bad job with that (not to mention the really bad documentation). the proxy class throws some xml-errors when parsing some responses. so i have to do it manually for that cases...
i'll worry about the certificate security later

A: Have you tried consuming the web service the "proper" way?  Add a SOAP web service reference to your C# project in Visual Studio, gets the stubs etc?  That's the easiest way of doing it from C#.  You can just specify a https protocol in the URL when you add the reference.