text:
Q: Are variables always assumed to be real in Jordan Decomposition? If you give the following input in Mathematica 9.0 (Student Edition):
JordanDecomposition /@ ({{1, #}, {#, -1}} & /@ {i, I})

Mathematica gives you two completely different results. Shouldn't there be several cases for the decomposition in case that the eigenvalues are undefined or coincide?

A: To settle this once and for all:
Consider the Jordan decomposition of a symbolic generalization of your matrix:
jd[x_, y_] = JordanDecomposition[{{1, x + I y}, {x + I y, -1}}]

whose explicit expression is
   {{{(1 - Sqrt[1 + x^2 + 2 I x y - y^2])/(x + I y),
      (1 + Sqrt[1 + x^2 + 2 I x y - y^2])/(x + I y)}, {1, 1}},
    {{-Sqrt[1 + x^2 + 2 I x y - y^2], 0}, {0, Sqrt[1 + x^2 + 2 I x y - y^2]}}}

Of note in this result is that the second element is a diagonal matrix, thus showing that JordanDecomposition[] tacitly assumes diagonalizability. We also note that one of the eigenvalues is the negative of the other; we can thus expect failure if these eigenvalues both become equal; that is:
Reduce[1 + x^2 + 2 I x y - y^2 == 0 && x ∈ Reals && y ∈ Reals]
   (y == -1 && x == 0) || (y == 1 && x == 0)

Or put another way,
x + I y /. {ToRules[%]}
   {-I, I}

These are our problem points. Check:
jd[0, -1]
   {{{I, I}, {1, 1}}, {{0, 0}, {0, 0}}}

jd[0, 1]
   {{{-I, -I}, {1, 1}}, {{0, 0}, {0, 0}}}

and we see that the results here are not what they should be:
JordanDecomposition[{{1, -I}, {-I, -1}}]
   {{{I, I}, {1, 0}}, {{0, 1}, {0, 0}}}

JordanDecomposition[{{1, -I}, {-I, -1}}]
   {{{-I, -I}, {1, 0}}, {{0, 1}, {0, 0}}}

Ah, there's that Jordan block!

In summary, per Daniel's comment:

Symbolic linear algebra in Mathematica assumes generic values for symbols.

In other words: JordanDecomposition[] won't assume your matrix is defective unless it actually is.

A: From the tutorial on Advanced Matrix Operations,
"Jordan decomposition in general writes any square matrix in the form as s.j.s^-1."
http://reference.wolfram.com/language/tutorial/AdvancedMatrixOperations.html
It does not state that the form is unique.
m1 = {{1, i}, {i, -1}};

{s1, j1} = JordanDecomposition[m1]

{{{(1 - Sqrt[1 + i^2])/i,
         (1 + Sqrt[1 + i^2])/i},
       {1, 1}}, {{-Sqrt[1 + i^2], 0},
       {0, Sqrt[1 + i^2]}}}

m1 == s1.j1.Inverse[s1] // Simplify

True

m2 = m1 /. i -> I;

{s2, j2} = JordanDecomposition[m2]

{{{-I, -I}, {1, 0}}, {{0, 1}, {0, 0}}}

m2 == s2.j2.Inverse[s2]

True

Consequently, both are valid Jordan decompositions and neither assumes or requires that matrix values be real.


text:
Q: Azure Client IServiceFilter doesn't work I'm trying to implement an Azure Mobile service in my android application, using the official xamarin's azure component. I've to invoke the asure service using a filter, and I've simply done this:
class Filter : IServiceFilter
{
    public System.Threading.Tasks.Task Handle(IServiceFilterRequest request, IServiceFilterContinuation continuation)
    {
        throw new NotImplementedException();
    }
}

As you can see it's a simple implementation of IServiceFilter, but it fails! Here's the error

TimestampFilter' does not implement interface member
  'Microsoft.WindowsAzure.MobileServices.IServiceFilter.Handle(Microsoft.WindowsAzure.MobileServices.IServiceFilterRequest,
  Microsoft.WindowsAzure.MobileServices.IServiceFilterContinuation)'.
  'TimestampFilter.Handle(Microsoft.WindowsAzure.MobileServices.IServiceFilterRequest,
  Microsoft.WindowsAzure.MobileServices.IServiceFilterContinuation)'
  cannot implement
  'Microsoft.WindowsAzure.MobileServices.IServiceFilter.Handle(Microsoft.WindowsAzure.MobileServices.IServiceFilterRequest,
  Microsoft.WindowsAzure.MobileServices.IServiceFilterContinuation)'
  because it does not have the matching return type of
  'System.Threading.Tasks.Task'

Anyone knows why?? Thanks

A: The error message indicates that the return type is incorrect, so I had a look at the Assembly Browser:
public Task<IServiceFilterResponse> Handle(IServiceFilterRequest request,IServiceFilterContinuation continuation)
{
    throw new NotImplementedException();
}

That should compile for you now

redpajama_set_name: RedPajamaStackExchange


text: Q: What are the sine and cosine of all the compass directions? The directions on a compass, the principal winds, half-winds, quarter-winds, etc, all correspond to angles that result of starting with a basic North-East-South-West compass rose and iteratively bisecting directions. What are the values of sine and cosine of the angles that correspond to these directions?


text:
Q: Testing Dropwizard 'Application' class I'm looking to test the Dropwizard 'Application' class without bootstrapping an entire Dropwizard server.
I'd essentially just like to ensure that the one bundle I'm registering is registered successfully.
All the routes I've been down so far result in NullPointer exceptions due to various other components not being setup correctly. Is there an easy path here?
public class SentimentApplication extends Application<SentimentConfiguration> {

    public static void main(final String[] args) throws Exception {
        new SentimentApplication().run(args);
    }

    @Override
    public String getName() {
        return "Sentiment";
    }

    @Override
    public void initialize(final Bootstrap<SentimentConfiguration> bootstrap) {
        bootstrap.setConfigurationSourceProvider(
            new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
                    new EnvironmentVariableSubstitutor(false)
            )
        );
    }

    @Override
    public void run(final SentimentConfiguration configuration,
                    final Environment environment) {
        // TODO: implement application
    }

}

A: You can register a simple command and call run method of your application with that command instead of server command. That way your application will be executed without running a server.
I wanted to do sth similar to what you want. (Considering ExampleApp as main Application class of my code) I wanted to write a test to make sure that there is no exception parsing the configuration. (Because KotlinModule() should have beed registered to environment.objectMaooer in initialize method of app, otherwise we would have had a runtime error.) I achieved it with sth similar to:
import io.dropwizard.cli.EnvironmentCommand
import io.dropwizard.setup.Bootstrap
import io.dropwizard.setup.Environment
import com.example.config.ExampleConfiguration
import net.sourceforge.argparse4j.inf.Namespace
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull

class DummyCommand(app: DummyApp) : EnvironmentCommand<ExampleConfiguration>(app, "dummy", "sample test cmd") {
    var parsedConfig: ExampleConfiguration? = null

    override fun run(environment: Environment, namespace: Namespace, configuration: ExampleConfiguration) {
        parsedConfig = configuration
    }
}

class DummyApp : ExampleApp() {
    val cmd: DummyCommand by lazy { DummyCommand(this) }

    override fun initialize(bootstrap: Bootstrap<ExampleConfiguration>) {
        super.initialize(bootstrap)
        bootstrap.addCommand(cmd)
    }
}

class ExampleAppTest {
    @Test
    fun `Test ExampleConfiguration is parsed successfully`() {
        val app = DummyApp()
        app.run("dummy", javaClass.getResource("/example-app-test/test-config.yml").file)
        val config = app.cmd.parsedConfig
        assertNotNull(config)
        assertEquals("foo", config.nginxUsername)
    }
}


text:
Q: Bessel function integral How to solve the integral for $J_1{(2x\sin{\frac{\theta}{2}})}$ at $[0,\pi]$? If solving by Matlab, please provide me the source. Thank you!

A: A simple analytical result is derived from the series representation of $J_1$:
$$J_1(z) = \sum_{k=0}^{\infty} \frac{(-1)^k}{k! (k+1)!} \left ( \frac{z}{2}\right )^{2 k+1} $$
as well as the integral
$$\int_0^{\pi/2} du \, \sin^{2 k+1}{u} = \frac{2^{2 k}}{\displaystyle (2 k+1) \binom{2 k}{k}}$$
Thus
$$\begin{align}\int_0^{\pi} d\theta \, J_1\left (2 x \sin{\frac{\theta}{2}} \right ) &= \sum_{k=0}^{\infty} \frac{(-1)^k}{k! (k+1)!} x^{2 k+1} \int_0^{\pi} d\theta \, \sin^{2 k+1} {\frac{\theta}{2}} \\ &= 2 \sum_{k=0}^{\infty} \frac{(-1)^k}{k! (k+1)!} x^{2 k+1} \int_0^{\pi/2} du \, \sin^{2 k+1}{u} \\ &= \sum_{k=0}^{\infty} \frac{(-1)^k}{(k+1)(2 k+1)} \frac{(2 x)^{2 k+1}}{(2 k)!}\\ &= \frac1{x}\sum_{k=0}^{\infty} \frac{(-1)^k}{(2 k+2)!} (2 x)^{2 k+2}\\ &= \frac{1-\cos{2 x}}{x}\end{align} $$


text:
Q: Is there a way to inject additional keys into translation table I want to create a directive / component which will provide it's own translations to the translate provider. So I wonder if there is a way to manipulate/add keys to the translationTable object within directive. Something like $translatePartialLoader.addPart('{ "MY_TEST_VAR": "This is test"}') to the preferred language.

A: Currently there is a discussion about it at
https://github.com/angular-translate/angular-translate/issues/316.


text:
Q: How can we disable muted dates in angularjs bootstrap datepicker directive? I need to disable all dates which are not from the currently focused month.
Tried using date-disabled attribute based on selected date, but it forever disables dates. The dates remain disabled when month is changed.
I thought of an alternative solution : All dates not from currently focused month have a class "text-muted" applied to them. Tried to create the below directive which checked the class and disabled dates. But this is not working at all. Can anyone take a look?
HTML:
<datepicker ng-model="dt" show-weeks="false" disable-muted-dates />

Javascript:
    angular.module('app', ['ui.bootstrap'])
    .directive('disableMutedDates',[function () {
        return {
            link:function (scope,element) {
                var datepicker = element;
                var table = angular.element(datepicker.children()[0]);
                var tbody = angular.element(table.children()[1]);
                var trs = angular.element(tbody.children());
                for (var i = trs.length - 1; i >= 0; i--) {
                    var tr = angular.element(trs[i]);
                    var tds = angular.element(tr.children());
                    for (var j = tds.length - 1; j >= 0; j--) {
                        var td = angular.element(tds[j]);
                        if (angular.element(td.children()[0]).prop('tagName') === 'BUTTON') {
                            var button = angular.element(td.children()[0]);
                            var span = angular.element(button.children()[0]);
                            if (span.hasClass('text-muted')) {
                                button.attr('disabled',true);
                            };
                        };
                    };
                };
            }
        }
    }])

PEN : http://codepen.io/cyrilpanicker/pen/qdpPjY?editors=101


text:
Q: my float class is deactivating my rollover class Thanks to the generous help of someone at stackoverflow, I was able to put different colored CSS  boxes over different  images and remove the css boxes (revealing the images) whenever there was a mouseover. this is the code i used fiddle http://jsfiddle.net/alexdickson/fyYcC/
However, I also wanted the boxes to align horizontally in a float, so (being a beginner) I put another class (called float) around the images (in class rollover) but it deactivated the rollover.
Is there a better way to implement the float than I have done below?
Thanks for your help in advance

.float
{
float: left;
width: 200px;
border: 1px solid #fff;
margin: 0 15px 15px 0;
padding: 5px 10px 10px 10px;
}

A: You can add the float class directly to the class of the inner div.
Also, float generally isn't a very good class name. You should give it a semantically meaning name, and attach its presentation via the CSS. You are leaking CSS implementation details into the HTML.
jsFiddle.

A: I forked the jsfiddle you posted and was able to float them left with two rows of 3 images. You can just add more to each container for more horizontal images, and add more containers to add more rows. http://jsfiddle.net/robx/592ba/1/


text:
Q: Reading file in pre-cleanup stage in a deferred work item I writing a Windows Minifilter Driver which needs to read the entire file (only files with size up to a specific threshold) on IRP_MJ_CLEANUP. As FltReadFile may not be called from the preop callback I queued the job to a work queue and did it there. When I finish reading the file I call FltCompletePendedPreOperation and invoke the post-cleanup callback which also handles the post operation as deferred work. Here are snippets of my code:
static NTSTATUS HandlePreCleanup(_In_ PFLT_CALLBACK_DATA Data,
                                 _Out_ PVOID *Context)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PFLT_INSTANCE Instance;
    PFILE_OBJECT FileObject;
    PVOID Buffer = NULL;
    LARGE_INTEGER FileOffset;

    FileObject = Data->Iopb->TargetFileObject;
    Instance = Data->Iopb->TargetInstance;

    Buffer = ExAllocatePoolWithTag(PagedPool,
                                   (ULONG) FILE_CHUNK_SIZE,
                                   PPFILTER_FILE_POOLTAG);
    if (Buffer == NULL) {
        PPERROR("Failed allocating file chunk\n");
        Status = STATUS_MEMORY_NOT_ALLOCATED;
        goto out;
    }

    FileOffset.QuadPart = 0;
    for (;;) {
        ULONG BytesRead;

        Status = FltReadFile(
            Instance, FileObject, &FileOffset,
            (ULONG) FILE_CHUNK_SIZE, Buffer,
            FLTFL_IO_OPERATION_DO_NOT_UPDATE_BYTE_OFFSET,
            &BytesRead, NULL, NULL
        );
        if (!NT_SUCCESS(Status)) {
            if (Status == STATUS_END_OF_FILE) {
                Status = STATUS_SUCCESS;
                break;
            }

            PPERROR("Failed reading from file %wZ: error %d\n",
                    &FileObject->FileName, Status);
            goto out;
        }

        FileOffset.QuadPart += BytesRead;
    }

out:
    if (Buffer != NULL) {
        ExFreePoolWithTag(Buffer, PPFILTER_FILE_POOLTAG);
    }

    return Status;
}

static VOID DeferredPreCallback(_In_ PFLT_DEFERRED_IO_WORKITEM WorkItem,
                                _In_ PFLT_CALLBACK_DATA Data,
                                _In_opt_ PVOID Context)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PVOID PostContext = NULL;

    UNREFERENCED_PARAMETER(Context);

    switch (Data->Iopb->MajorFunction) {
    case IRP_MJ_CLEANUP:
        Status = HandlePreCleanup(Data, &PostContext);
        break;
    default:
        NT_ASSERTMSG("Unexpected deferred pre callback operation",
                     FALSE);
        break;
    }

    FltCompletePendedPreOperation(Data,
                                  FLT_PREOP_SUCCESS_WITH_CALLBACK,
                                  PostContext);
    FltFreeDeferredIoWorkItem(WorkItem);
}

static NTSTATUS QueueWork(_Inout_ PFLT_CALLBACK_DATA Data,
                          _In_ PFLT_DEFERRED_IO_WORKITEM_ROUTINE WorkRoutine,
                          _In_ PVOID Context)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PFLT_DEFERRED_IO_WORKITEM WorkItem = NULL;

    WorkItem = FltAllocateDeferredIoWorkItem();
    if (WorkItem == NULL) {
        Status = STATUS_MEMORY_NOT_ALLOCATED;
        PPERROR("Failed allocating work item\n");
        goto failed;
    }

    Status = FltQueueDeferredIoWorkItem(WorkItem, Data, WorkRoutine,
                                        CriticalWorkQueue, Context);
    if (!NT_SUCCESS(Status)) {
        PPERROR("Failed queuing work item to queue: error %d\n",
                Status);
        goto failed;
    }

    return STATUS_SUCCESS;

failed:
    if (WorkItem != NULL) {
        FltFreeDeferredIoWorkItem(WorkItem);
    }

    return Status;
}

static FLT_PREOP_CALLBACK_STATUS DeferPreCallback(
    _Inout_ PFLT_CALLBACK_DATA Data,
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _Out_ PVOID *CompletionContext
)
{
    NTSTATUS Status = STATUS_SUCCESS;

    UNREFERENCED_PARAMETER(FltObjects);
    UNREFERENCED_PARAMETER(CompletionContext);

    Status = QueueWork(Data, DeferredPreCallback, NULL);
    if (!NT_SUCCESS(Status)) {
        return FLT_PREOP_SUCCESS_NO_CALLBACK;
    }

    return FLT_PREOP_PENDING;
}

CONST FLT_OPERATION_REGISTRATION OperationRegistrations[] = {
    {
        IRP_MJ_CLEANUP,
        0,
        DeferPreCallback,
        DeferPostCallback,
        NULL
    },
    { IRP_MJ_OPERATION_END },
};

This proves to work for a while but the system seems to hang (deadlock?) after a while. The problem seems to be with the call to FltReadFile since the hang does not occur when removing this call. Any ideas on why this might happen or how to debug it further?

A: Well, apparently the problem was that FltReadFile was given a FileOffset which was not aligned with the volume sector size. This is a problem apparently if FileObject was created for non-cached IO (See the Remarks section in https://msdn.microsoft.com/en-us/library/windows/hardware/ff544286(v=vs.85).aspx). As I have no control on how the FileObject in question was created there may be cases in which it was indeed created for non-cached IO. To fix this I added the following check at the end of the for(;;) loop:
if (BytesRead < FILE_CHUNK_SIZE) {
        break;
}

This should work if FILE_CHUNK_SIZE is a multiple of the volume sector size.


text:
Q: How to unit-test a public method that has private methods in MVP pattern When using the MVP pattern for WinForms, I sometimes need to call private methods in my public methods of the presenter and change a few properties of the view. In these situations, how can I efficiently unit test the changes to the view and the behavior of the private methods?
public void OnFileNameChanged(string fileName)
{
    _settings = FirstPrivateOperation()

    if (_settings == null)
    {
        _view.A = false;
        return;
    }

    var config = SecondPrivateOperation();

    if (config == null)
    {
        _view.B = true;
        return;
    }

    _view.C = true;
}

A: Some options, based on what you showed, would be :

*

*mock the two methods which set these values,

*break _settings and config or even the two methods which provide the results into a separate class ( like a configuration kind of thing ) and inject the interface of that class as a dependency at whatever level it makes sense. You can then mock those values.

I would pursue one of these options.
In regards to the View values, I would try to separate that. There are  number of issues with this code.

*

*you have a OnFileNameChanged metho and you probably can't change its signature and doesn't return anything. So, I would separate the code even more. Take the code out of it and create another method that you control. Do not add any View setting in that one. The purpose ifs to cover the logic and return an object with some calculated values.
Then, in the OnFileNameChanged you assign what you need for the view stuff. In short, take the logic part out and deal with it somewhere else and test that.

You have 3 values that you are assigning to the View object, so make your new method return either one value, or an object with three values, covering each possibility.
public void OnFileNameChanged(string fileName)
{
   var calculatedValues = CalculateValues(//might need some params here)

   _view.A = calculatedValues.A;
   _view.B = calculatedValues.B;
   _view.C = calculatedValues.C;
}

public MyReturnType CalculateValues()
{
     var result = new MyReturnType();
     var config = FirstPrivateOperation();
     if ( config == null ) { return result; }

     //etc etc
}

public MyReturnType
{
      public Whatever A { get;set }
      public Whatever B { get;set }
      public Whatever C { get;set }
}

you can go even further and deal with the private methods in a different way. you might want to add a separate class to replace them and then that makes theme easier to test / mock as well.


text:
Q: How to add default namespace to loaded XmlDocument so that validation "works" We have some xml data that uses a certain namespace, but does not actually declare a namespace for it. We want to validate it, but invalid elements in default namespace don't get caught because xmlns is not set so by xml rules anything goes. At this stage of processing document has possibly been loaded for a long time, and is not necessarily in original form anyways (so namespace manager is probably out of the question).
<root>
   <valid />
   <notvalid />
</root>

var xd = new XmlDocument();
xd.Load(xmlstring);
xd.Validate((sender, args) =>
{
   ...
});

A: You can't modify XmlDocument on the fly, because XmlNodes are already created with a certain namespace. You have to modify the document and reparse it/reread via XmlNodeReader.
You can set attributes on XmlDocument, but for namespace they'll actually enforce anything only after reload of document (from modified copy).
var target = "urn:foobar";
var xd = new XmlDocument();
xd.Load(xmlstring);

// set default namespace to a schema identifier,
// this is not enforced in this 'xd' document yet.
xd.DocumentElement.SetAttribute("xmlns", target);
var newXd = new XmlDocument();

// reload document into new instance
newXd.Load(xd.OuterXml);

// attach the schema URI to schema identifier
newXd.Schemas.Add(target, "file:///c|/temp/foobar.xsd");
newXd.Validate((sender, args) => {
    ... // now elements in default namespace are validated against "foobar.xsd"
});

This probably would be "better" done with XmlNodeReader, LAAEFTR.


text:
Q: why I can't install libpq-dev I try sudo apt-get install libpq-dev and I got this error
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libpq-dev : Depends: libssl-dev but it is not going to be installed
             Depends: krb5-multidev but it is not going to be installed
             Depends: comerr-dev but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I also run this command apt-cache policy libpq-dev libssl-dev krb5-multidev comerr-dev and this is the result
libpq-dev:
  Installed: (none)
  Candidate: 9.3.4-1
  Version table:
     9.3.4-1 0
    500 http://sd.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
libssl-dev:
  Installed: (none)
  Candidate: 1.0.1f-1ubuntu2
  Version table:
     1.0.1f-1ubuntu2 0
        500 http://sd.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
krb5-multidev:
  Installed: (none)
  Candidate: 1.12+dfsg-2ubuntu4
  Version table:
     1.12+dfsg-2ubuntu4 0
        500 http://sd.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
comerr-dev:
  Installed: (none)
  Candidate: 2.1-1.42.9-3ubuntu1
  Version table:
     2.1-1.42.9-3ubuntu1 0
        500 http://sd.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages

output of sudo apt-get install libssl-dev krb5-multidev comerr-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 comerr-dev : Depends: libcomerr2 (= 1.42.9-3ubuntu1) but 1.42.9-3ubuntu1.2 is to be installed
 krb5-multidev : Depends: libkrb5-3 (= 1.12+dfsg-2ubuntu4) but 1.12+dfsg-2ubuntu5.1 is to be installed
                 Depends: libk5crypto3 (= 1.12+dfsg-2ubuntu4) but 1.12+dfsg-2ubuntu5.1 is to be installed
                 Depends: libgssapi-krb5-2 (= 1.12+dfsg-2ubuntu4) but 1.12+dfsg-2ubuntu5.1 is to be installed
 libssl-dev : Depends: libssl1.0.0 (= 1.0.1f-1ubuntu2) but 1.0.1f-1ubuntu2.15 is to be installed
              Recommends: libssl-doc but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

what i can do to fix this?

A: Your sources are very outdated, ex. of current versions,
libpq-dev - 9.3.10-0ubuntu0.14.04
libssl-dev - 1.0.1f-1ubuntu2.16
krb5-multidev - 1.12+dfsg-2ubuntu5.2
comerr-dev - 2.1-1.42.9-3ubuntu1.3
Open Software & Updates, make sure that both trusty-security & trusty-updates are enabled under the Updates tab, then reload your sources & see if you get the current versions. If both were already enabled then open a terminal & run sudo apt-get update, then check for current versions.
If that doesn't help then again open Software & Updates & on main page switch to a different mirror in the Download from: section, reload sources, ect.

A: As I can see here and in your question, you have some (manually?) installed packages which conflict with the packages in the Ubuntu standard repositories. The packages that you want to install, need exactly the required versions of the dependencies.
Run the commands below:
sudo apt-get update
sudo apt-get install libssl1.0.0=1.0.1f-1ubuntu2 ibcomerr2=1.42.9-3ubuntu1

to downgrade each of them.
For the other packages you have to enable trusty-security and trusty-updates (with a little script taken from here). This packages contains a higher version than the installed version.
sudo apt-get install git
git clone https://github.com/kos0/addRemoveDistribution.git
cd addRemoveDistribution

sudo ./enableDisableDistribution.pl enable security
sudo ./enableDisableDistribution.pl enable updates

After that
sudo apt-get update
sudo apt-get install libpq-dev


text:
Q: How to requests.Session().get if website does not keep me logged in? I am trying to complete a webscrape of a page that requires a log-in first. I am fairly certain that I have my code and input names ('login' and 'password') correct yet it still gives me a 'Login Failed' page. Here is my code:
payload = {'login': 'MY_USERNAME', 'password': 'MY_PASSWORD'}
login_url = "https://www.spatialgroup.com.au/property_daily/"

with requests.Session() as session:

    session.post(login_url, data=payload)
    response = session.get("https://www.spatialgroup.com.au/cgi-bin/login.cgi")
    html = response.text

print(html)

I've done some snooping around and have figured out that the session doesn't stay logged in when I run my session.get("LOGGEDIN_PAGE"). For example, if I complete the log in process and then enter a URL into the address bar that I know for a fact is a page only accessible once logged in, it returns me to the 'Login Failed' page. How would I get around this if my login session is not maintained?

A: It's very difficult to help you without having the actual website you are working with. That being said I would recommend you changing this line:
session.post(login_url, data=payload)

to this one:
session.post(login_url, json=payload)

hope this helps

A: As others have mentioned, its hard to help here without knowing the actual site you are attempting to log in to.
I'd point out that you aren't using any set HTTP headers at all, which is a common validation check for logins on webpages. If you're sure that you are POSTing the data in the right format (form encoded versus json encoded), then I would open up Chrome inspector and copy the user-agent from your browser.
s = requests.Session()
s.headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
    'Accept': '*/*'
}

Also, it's good practice to check the response status code of each web request you make using a try/except pattern. This will help you catch errors as you write and test requests, instead of blindly guessing which requests are erroneous.
r = requests.get('http://mypage.com')
try:
    r.raise_for_status()
except requests.exceptions.HTTPError:
    print('oops bad status code {} on request!'.format(r.status_code))

Edit: Now that you've given us the site, inspecting a login attempt reveals that the form data isn't actually being POSTed to that website, but rather it's being sent to a CGI script url.
To find this, open up Chrome Inspector and watch the "Network" tab as you try to login. You'll see that the login is actually being sent to https://www.spatialgroup.com.au/cgi-bin/login.cgi, not the actual login page. When you submit to this login page, it executes a 302 redirect after logging in. We can check the location after performing the request to see if the login was successful.
Knowing this I would send a request like this:
s = requests.Session()

# try to login
r = s.post(
    url='https://www.spatialgroup.com.au/cgi-bin/login.cgi',
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
    },
    data={
        'login': USERNAME,
        'password': PASSWORD
    }
)

# now lets check to make sure we didnt get 4XX or 5XX errors
try:
    r.raise_for_status()
except requests.exceptions.HTTPError:
    print('oops bad status code {} on request!'.format(r.status_code))
else:
    print('our login redirected to: {}'.format(r.url))

# subsequently if the login was successful, you can now make a request to the login-protected page at this point


text:
Q: I am trying to connect product sale records to the appropriate purchase record in SQL I have a transaction table with both purchases and sales. Purchase datetime, quantity, unit cost as well as the corresponding Sales data.
I can separate the transactions with queries no problem there. What I need to do is determine which purchase order supplied the product sold and the difference in purchase and sale rate.
transDate     | transType     | Product | transQty | transRate
12/5/20       | purchase      | pencils | 124      | $5.12
12/6/20       | sale          | pencils | 32       | $6.12
12/7/20       | sale          | pencils | 67       | $6.21
12/8/20       | purchase      | pencils | 65       | $4.85
12/10/20      | sale          | pencils | 44       | $6.32
12/11/20      | purchase      | pencils | 14       | $6.11

The purchase on 12/5 covers the sales on 12/6, 12/7, and a portion of the sale in 12/10 with the purchase on 12/8 covering the remainder of 12/10.
Reorganized tables
tblPurchaseRecords
pID | transDate | Product | pQty | pTransRate | pRemaining
1   | 12/5/20   | pencils | 124  | $5.12     | 124
2   | 12/8/20   | pencils | 65   | $4.85     | 65
3   | 12/11/20  | pencils | 14   | $6.11     | 14

tblSaleRecords
sID | transDate | Product | sQty | sTransRate | sRemaining
1   | 12/6/20   | pencils | 32   | $6.12     | 32
2   | 12/7/20   | pencils | 67   | $6.21     | 67
3   | 12/10/20  | pencils | 44   | $6.32     | 44

New table
tblProfitLoss
pID | sID | plQty | plRate | plValue

tblProfitLoss is a many-to-many table with sID and pID forming the primary key.
plQty is the MIN(pRemaining, sRemaining). This value is subtracted from both pRemaining and sRemaining. One or both of the two values will be reduced to 0, advancing the respective index(es) by 1.
Resulting in this:
tblPurchaseRecords
pID | transDate | Product | pQty | pTransRate | pRemaining
1   | 12/5/20   | pencils | 124  | $5.12     | 0
+pID | sID | plQty | plRate | plValue
 1   | 1   | 32    | $1.00  | $32.00
 1   | 2   | 67    | $1.09  | $73.03
 1   | 3   | 25    | $1.20  | $30
2   | 12/8/20   | pencils | 65   | $4.85     | 46
+pID | sID | plQty | plRate | plValue
 2   | 3   | 19    | $1.47  | $27.93
3   | 12/11/20  | pencils | 14   | $6.11     | 14

tblSaleRecords
sID | transDate | Product | sQty | sTransRate | sRemaining
1   | 12/6/20   | pencils | 32   | $6.12     | 0
+pID | sID | plQty | plRate | plValue
 1   | 1   | 32    | $1.00  | $32.00
2   | 12/7/20   | pencils | 67   | $6.21     | 0
+pID | sID | plQty | plRate | plValue
 1   | 2   | 67    | $1.09  | $73.03
3   | 12/10/20  | pencils | 44   | $6.32     | 0
+pID | sID | plQty | plRate | plValue
 1   | 3   | 25    | $1.20  | $30
 2   | 3   | 19    | $1.47  | $27.93

I can do this with VBA but I was hoping to learn how to do it with SQL.


text:
Q: Find count of WordPress users by role and search string for user name I want to get the total number of results after searching WordPress users by role and a string that matches the user name.
What I tried so far:
$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$user_query = new WP_User_Query($args);
$auth_count= $user_query->get_total();

But it returns 0 everytime.
Note:
Perhaps it can be done by:
$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$auth_count= count(get_users($args));

or by querying with
global $wpdb;

But is there any more resource friendly method?

A: This worked:
$search_txt replaced by esc_attr($search_txt).'*':
$args= array('echo'=>false, 'role' => 'author', 'search'=>esc_attr($search_txt).'*');
$user_query = new WP_User_Query($args);
$auth_count= $user_query->get_total();

A: Adding this as an answer here for reference for anyone searching for WP_User_Query stuff:
As per the docs The search field on WP_User_Query uses * for wildcard text search, and will search on login, nicename, email and URL, unless specified otherwise.
E.g. to match any name containing bob you need:
$args = array(
    'search'         => '*bob*'
);

$user_query = new WP_User_Query( $args );


text:
Q: Javascript 3 step signup script not working I found a multi step form on codepen.io but when adding the requiered scripts and the javascript i get a error in google chrome Uncaught TypeError: b.easing[this.easing] is not a function. I also have the problem where when i press next the next field show up below the existing one.
heres my code:

<form id="msform">

Account Setup

Social Profiles

Personal Details

  <fieldset>

Create your account

This is step 1

    <input type="text" name="email" placeholder="Email" />
    <input type="password" name="pass" placeholder="Password" />
    <input type="password" name="cpass" placeholder="Confirm Password" />
    <input type="button" name="next" class="next action-button" value="Next" />
  </fieldset>

  <fieldset>

Social Profiles

Your presence on the social network

    <input type="text" name="twitter" placeholder="Twitter" />
    <input type="text" name="facebook" placeholder="Facebook" />
    <input type="text" name="gplus" placeholder="Google Plus" />
    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="button" name="next" class="next action-button" value="Next" />
  </fieldset>

  <fieldset>

Personal Details

We will never sell it

    <input type="text" name="fname" placeholder="First Name" />
    <input type="text" name="lname" placeholder="Last Name" />
    <input type="text" name="phone" placeholder="Phone" />
    <textarea name="address" placeholder="Address"></textarea>
    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="submit" name="submit" class="submit action-button" value="Submit" />
  </fieldset>

</form>

You declared both jQuery and Easing after running the script. This is like trying to start a car before putting the engine in.
The example below should work.
<!DOCTYPE HTML>

<form id="msform">

Account Setup

Social Profiles

Personal Details

  <fieldset>

Create your account

This is step 1

    <input type="text" name="email" placeholder="Email" />
    <input type="password" name="pass" placeholder="Password" />
    <input type="password" name="cpass" placeholder="Confirm Password" />
    <input type="button" name="next" class="next action-button" value="Next" />
  </fieldset>

  <fieldset>

Social Profiles

Your presence on the social network

    <input type="text" name="twitter" placeholder="Twitter" />
    <input type="text" name="facebook" placeholder="Facebook" />
    <input type="text" name="gplus" placeholder="Google Plus" />
    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="button" name="next" class="next action-button" value="Next" />
  </fieldset>

  <fieldset>

Personal Details

We will never sell it

    <input type="text" name="fname" placeholder="First Name" />
    <input type="text" name="lname" placeholder="Last Name" />
    <input type="text" name="phone" placeholder="Phone" />
    <textarea name="address" placeholder="Address"></textarea>
    <input type="button" name="previous" class="previous action-button" value="Previous" />
    <input type="submit" name="submit" class="submit action-button" value="Submit" />
  </fieldset>

</form>


text:
Q: limit php varible output in script I have this code:
  $feature_title = trim($array_item[0]);
                                $feature_value ="";
                                if(isset($array_item[1]))
                                {
                                    $feature_value = trim($array_item[1]);
                                }

                                if($feature_title!="" && $feature_value!="" )
                                {
                                    $t= $this->addProductFeature($product->id,$default_language_id, $feature_title , $feature_value);
                                }

Problem is that sometimes the $feature_value is too long. I would like to to limit the output to 200 chars and thought that "trim" would be enough but it is not.
Any ideas ?

A: I finally changed
 $t= $this->addProductFeature($product->id,$default_language_id, $feature_title , $feature_value);

to
$t= $this->addProductFeature($product->id,$default_language_id, $feature_title , substr($feature_value,0,255));

Hope I didn't brake anything. Seems to work though
Thanks everyone


text:
Q: Making Haskell code more idiomatic (440 Hz tone) Here's what I have. It generates a 5 second Au file with a 440 Hz sine wave, inspired by this question.
-- file: tone.hs

import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Binary.Put

-- au format header: https://en.wikipedia.org/wiki/Au_file_format
header :: Double -> Integer -> Integer -> Put
header dur rate bps = do
  putLazyByteString $ BLC.pack ".snd"
  putWord32be 24
  putWord32be $ fromIntegral $ floor $ fromIntegral bps * dur * fromIntegral rate
  putWord32be 3
  putWord32be $ fromIntegral rate
  putWord32be 1

-- audio sample data
samples :: Double -> Integer -> Integer -> Double -> Double -> Put
samples dur rate bps freq vol =
    foldl1 (>>) [put i | i <- [0..numSamples-1]]
  where
    numSamples = floor $ fromIntegral rate * dur
    scale i = 2 * pi * freq / fromIntegral rate * fromIntegral i
    sample i = vol * sin (scale i)
    coded samp = floor $ (2 ^ (8*bps-1) - 1) * samp
    put i = putWord16be $ coded $ sample i

freq = 440 :: Double    -- 440 Hz sine wave
dur = 5 :: Double       -- played for 5 seconds
rate = 44100 :: Integer -- at a 44.1 kHz sample rate
vol = 0.8 :: Double     -- with a peak amplitude of 0.8
bps = 2 :: Integer      -- at 16 bits (2 bytes) per sample

main =
    BL.putStr $ runPut au
  where
    au = do
      header dur rate bps
      samples dur rate bps freq vol

If you're running Linux, you can listen with runghc tone.hs | aplay. For other operating systems, you can probably redirect output to a .au file and play it in an audio player.
How can I make this code more idiomatic? For example:

*

*I wrote fromIntegral all over the place. Could I have avoided that?

*Should/could I be using a different package for outputting the binary data?

*Am I using reasonable types?

A: Nothing really bad here. foldl1 (>>) [put i | i <- [0..numSamples-1]] is equivalent to mapM_ put [0 .. numSamples-1]. Rate should just be a Double, that gets you rid of the fromIntegrals.
Data.Binary.Put is really fine for binary output. One might question whether it's good to write the samples to the monad right away (it might be more flexible to keep them as directly-accessible floating-point values in some suitable container (like chunks of Data.Vector.Storable) and only put them from some generic function right in the end), but performance-wise your approach is actually very efficient. And since it's not IO your using, you can always get the data back in a safe, pure way.

A: You can use the type checker to help you remove the fromIntegral calls:

*

*Comment out your type signature for header

*Also comment out your main definition

*Load the code into ghci

*Use :t header to see what GHC comes up with for the type signature of header.

Doing this yields:
*Main> :t header
header
  :: (Integral a1, Integral a2, RealFrac a) =>
     a -> a2 -> a1 -> PutM ()

This suggests that we can remove the fromIntegral on the rate and bps parameters, and indeed, this definition of header typechecks:
header dur rate bps = do
  putLazyByteString $ BLC.pack ".snd"
  putWord32be 24
  putWord32be $ floor $ bps * dur * rate
  putWord32be 3
  putWord32be $ fromIntegral rate
  putWord32be 1

and the type is now:
*Main> :t header
header :: (Integral a, RealFrac a) => a -> a -> a -> PutM ()

Note that we still have a fromIntegral on rate which we could eliminate by using floor, e.g.:
  putWord32be $ floor rate

which changes the type of header to RealFrac a => a -> a -> a -> PutM ().
The main point is to use the type checker to help you understand what the most general type signature a function could have.


text:
Q: Prove that the following products of prime numbers equals to infinity I can't understand how to show that the product
$\prod_{p \equiv 1(mod 3)}\frac{p}{p-1}=\infty$
and
$\prod_{p \equiv 2(mod 3)}\frac{p}{p-1}=\infty$
I was shown a similar proof without the limitation of the modulu, but I think I didn't understand that one either, any help with how to prove this would be much appreciated.
I also have a hint, if one of the products is finite, what does it say about the Dirichle L-Series? I'm not sure where to take it.
edited: hint updated.

A: The product
$$
\prod_{p\equiv 1 (\bmod 3)}\frac{p}{p-1}=\prod_{p\equiv 1 (\bmod 3)}\left(1+\frac{1}{p-1}\right)
$$
converges if and only if the sum
$$
\sum_{p\equiv 1 (\bmod 3)}\frac1{p-1}
$$
does (just take the logarithm of the infinite product to see it).
Now, the sum in question is infinite because of Dirichlet's theorem on primes in arithmetic progression.
Similar for the other residue class, ${p\equiv 2 (\bmod 3)}$.


text:
Q: Can't add attributes to classmethods This following snippet will cause a AttributeError: 'classmethod' object has no attribute 'val'. Any idea why and how to work around this?
class App(object):
    @classmethod
    def cfn(kls, *args):
        print kls, args
    cfn.val = 10

A: It actually is possible to add a custom attribute to your classmethod.
NB tested on Python 3.4 only
TL;DR
class classmethod_with_custom_attribute(object):
    def __init__(self, val):
        self.val = val

    def __call__(self, func):
        def wrapped_func(*args, **kwargs):
            return func(*args, **kwargs)
        wrapped_func.val = self.val
        wrapped_func = classmethod(wrapped_func)
        return wrapped_func

class App(object):
    @classmethod_with_custom_attribute(val=10)
    def cfn(cls, *args):
        print(cls, args)

Explanation
First of all, you have to understand how decorators work, because classmethod is a decorator.
Writing
@classmethod
def cfn(cls, *args):
    print(cls, *args)

is actually the same as writing
def cfn(cls, *args):
    print(cls, *args)
cfn = classmethod(cfn)

Now if you try to add an attribute to your method, do not write it as
@classmethod
def cfn(cls, *args):
    print(cls, *args)
cfn.val = 10

because it is equivalent to
def cfn(cls, *args):
    print(cls, *args)
cfn = classmethod(cfn)
cfn.val = 10

so you are adding the attribute to a method returned by decorator, not your actual method. The simple solution is to add the attribute to your method and after that decorate it:
def cfn(cls, *args):
    print(cls, *args)
cfn.val = 10
cfn = classmethod(cfn)

This way you decorate the method that already has an attribute attached and apparently decorator returns the same method object, so you don't lose your attribute.
We could all agree that this syntax is not really nice and hard to read. It is much nicer to keep the decorator syntax. You can put all the logic in a custom decorator like this:
class classmethod_with_custom_attribute(object):
    def __init__(self, val):
        self.val = val

    def __call__(self, func):
        def wrapped_func(*args, **kwargs):
            return func(*args, **kwargs)
        wrapped_func.val = self.val
        wrapped_func = classmethod(wrapped_func)
        return wrapped_func

Here we do the same, note the part where custom attribute is assigned before classmethod decorator call. Now we can use the decorator like this:
@classmethod_with_custom_attribute(val=10)
def cfn(cls, *args):
    print(cls, args)

Now you can call
App.cfn.val

and it will work as expected

A: Class methods simply don't support adding arbitrary attributes to them. Your best bet is to take the data you were going to put in a class method attribute and stick it somewhere else.


text:
Q: Performance difference on insert-sort in C and python I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.
I've profiled both codes and the insert-sort function is the place where the time is most spent.
Here is the C function:
void
insert_sort (vec_t * vec)
{
    int j;
    for (j = 1 ; j < vec->n ; j++){
        int key = vec->v[j];
        int i = j - 1;
        while (i >= 0 && vec->v[i] > key){
            vec->v[i+1] = vec->v[i];
            i--;
        }
        vec->v[i+1] = key;
    }
}

Here is the python function:
def insert_sort (ln):
    for j in range(1, len(ln)):
        key = ln[j]
        i = j-1
        while i >= 0 and ln[i] > key:
            ln[i+1] = ln[i]
            i-=1
        ln[i+1] = key

The test was made with 10000 integers, each one randomly generated between 0 and 10000.
The results for the time spent in each function was:

*

*C time: 0.13 seconds

*python time: 8.104 seconds

Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster.
I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a pythonic way to doing things that I could use in the insert-sort?

A: My first thought was that the laptop I have at hand right now, a Macbook Pro, must be comparable to but slightly better than your machine -- I don't have enough of your surrounding code to try your C example (what's a vec_t, etc, etc), but running the Python you coded gives me:
$ python -mtimeit -s'import inso' 'inso.insort(inso.li)'
10 loops, best of 3: 7.21 msec per loop

vs your 8.1 seconds.  That's with you code put in insort.py, preceded by:
import random
li = [random.randrange(10000) for _ in xrange(10000)]

array doesn't help -- actually slows things down a bit.  Then I installed psyco, the Python JIT helper (x86-only, 32-bit only), further added:
import psyco
psyco.full()

and got:
$ python -mtimeit -s'import inso' 'inso.insort(inso.li)'
10 loops, best of 3: 207 usec per loop

so a speedup of about 7.21 / 0.000207 = 34830 times -- vs the 8.04 / 0.13 = 62 times that surprised you so much;-).
Of course, the problem is that after the first time, the list is already sorted, so insort becomes must faster.  You didn't give us enough of the surrounding test harness to know exactly what you measured.  A more realisting example (where the actual list isn't touched so it stays disordered, only a copy is sorted...), without psyco:
$ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 13.8 sec per loop

Oops -- so your machine's WAY faster than a Macbook Pro (remembers, core don't count: we're using only one here;-) -- wow... or else, you're mismeasuring.  Anyway, WITH psyco:
$ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 456 msec per loop

So psyco's speedup is only 13.8 / 0.456, 30 times -- about half as much as the 60+ times you get with pure-C coding.  IOW, you'd expect python + psyco to be twice as slow as pure C.  That's a more realistic and typical assessment.
If you we writing reasonably high-level code, psyco's speedup of it would degrade from (say) 30 times down to much less -- but so would C's advantage over Python. For example,
$ python -mtimeit -s'import inso' 'sorted(inso.li)'
100 loops, best of 3: 8.72 msec per loop

without psyco (in this case, psyco actually -- marginally -- slows down the execution;-), so that's another factor of 52 over psyco, 1582 overall over non-psyco insort.
But, when for some reason or other you have to write extremely low-level algorithms in python, rather than using the wealth of support from the builtins and stdlib, psyco can help reduce the pain.
Another point is, when you benchmark, please post ALL code so others can see exactly what you're doing (and possibly spot gotchas) -- your "scaffolding" is as tricky and likely to hide traps, as the code you think you're measuring!-)

A: So, here are some lessons you should take away from this:

*

*Interpreted Python is on the slow side.  Don't try to write your own FFT, MPEG encoder, etc. in Python.

*Even slow interpreted Python is probably fast enough for small problems.  An 8 second run time is not horrible, and it would take you much longer to write and debug the C than the Python, so if you are writing something to run once, Python wins.

*For speed in Python, try to rely on built-in features and C modules.  Let someone else's C code do the heavy lifting.  I worked on an embedded device where we did our work in Python; despite the slow embedded processor, the performance was decent, because C library modules were doing most of the work.
For fun and education, please repeat your Python test, this time using the built-in .sort() method on a list; it probably won't be quite as fast as the C, but it will be close.  (Although for really large data sets, it will beat the C, because insertion sort sucks.  If you rewrote the C to use the C library qsort() function, that would be the speed champ.)
A common Python design "pattern" is: first, write your app in Python.  If it is fast enough, stop; you are done.  Second, try to rewrite to improve speed; see if there is a C module you can use, for example.  If it is still not fast enough, consider writing your own C module; or, write a C program, using the Python prototype code as the basis for your design.

A: What method did you use to measure the time?
Doing this sort of thing, I find python is at least 30 times slower than C
The C compiler may be able to use some optimisations that Python doesn't even attempt
If might be interesting to try psyco, that type of code is well suited to it.
building on Alex's answer, I tried cython. In his case cython turns the for loop and everything into pure C, so now I can compare C, python and psyco
now i have this insort.py

import psyco
import random
li = [random.randrange(10000) for _ in xrange(10000)]

def insort (ln):
    for j in range(1, len(ln)):
        key = ln[j]
        i = j-1
        while i >= 0 and ln[i] > key:
            ln[i+1] = ln[i]
            i-=1
        ln[i+1] = key

#psyco.bind(insort)

import pyximport; pyximport.install()
import pyxinsort

def pyx_setup():
    pyxinsort.setup(li)

def pyx_insort():
    pyxinsort.insort(li)

and this pyxinsort.pyx

cdef int ln[10000]

def insort(li):
    cdef int i,j,key
    for j in range(1, len(li)):
        key = ln[j]
        i = j-1
        while i >= 0 and ln[i] > key:
            ln[i+1] = ln[i]
            i-=1
        ln[i+1] = key

def setup(li):
    cdef int i
    for i in range(1, len(li)):
        ln[i]=li[i]

The code for insort is virtually identical. li is passed in for its length. ln is the array that is sorted and is prepopulated by setup, so I can isolate building the list from the sort
python

$ python2.5 -mtimeit -s'import inso' 'list(inso.li)'
10000 loops, best of 3: 84.5 usec per loop
$ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 21.9 sec per loop

psyco

$ python2.5 -mtimeit -s'import inso' 'list(inso.li)'
10000 loops, best of 3: 85.6 usec per loop
$ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 578 msec per loop

cython ( this is running exactly the same algorithm converted to C and compiled )

$ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup()'
10000 loops, best of 3: 141 usec per loop
$ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup();inso.pyx_insort()'
10 loops, best of 3: 46.6 msec per loop

cython beats psyco by a factor of 16 and Python by a factor of 470!
For completeness, i've included the corresponding piece of C code generated by cython

  for (__pyx_v_j = 1; __pyx_v_j < __pyx_1; __pyx_v_j+=1) {
    __pyx_v_key = (__pyx_v_9pyxinsort_ln[__pyx_v_j]);
    __pyx_v_i = (__pyx_v_j - 1);
    while (1) {
      __pyx_2 = (__pyx_v_i >= 0);
      if (__pyx_2) {
        __pyx_2 = ((__pyx_v_9pyxinsort_ln[__pyx_v_i]) > __pyx_v_key);
      }
      if (!__pyx_2) break;
      (__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = (__pyx_v_9pyxinsort_ln[__pyx_v_i]);
      __pyx_v_i -= 1;
    }
    (__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = __pyx_v_key;
  }

A: Python is a dynamic language and the standard implementation uses an interpreter to evaluate code. This means that where the compiled C code can escape with a single machine instruction, for instance assigning to vec->v[i+1], Python's interpreter has to look up the sequence variable from the local scope, look up its class, find the item setting method on the class, call that method. Similarly for the compare, addition. Not to mention that executing almost every bytecode results in an indirect branch mispredict in the CPU that causes a pipeline bubble.
This is the sort of code that would benefit a lot from JIT compilation to native code and runtime type specialization, like unladen-swallow and PyPy are starting to do.
Otherwise the code is pretty much pythonic in the sense that if one needs to implement insertion sort, this is how one would do it in Python. It's also very unpythonic because you should use the very efficient built-in sort.

A: What's wrong with:
ln.sort()


text:
Q: Customize Firebase / Google Identity Platform Multifactor Authentication Confirmation Email I have successfully and deceivingly easily added Firebase authentication for my web ap. I've found during my work that it's actually just a wrapper over the identity platform product from GCP. I've found this out while working on adding two factor authentication via phone for the app as well.
Everything works fine for the amount of complexity 2fa brings.
The problem I am now facing is that every time I enroll a user to the second factor, they get a horrendous automatically generated email which I just can't seem to understand where to change.
I know that transactional emails are a bit unwieldy in Firebase, so I fear the worse on customization, which is why I am asking:
Where do you change, or disable that email? I am already notifying the user their phone was validated and they just got the SMS on their phone, there is no need for another ugly notification.
That said, the documentation does say an email will be delivered upon running the multiFactoruser.enroll method, but not much else.
I've also found that the identity platform allows for programmatic enrollment via the admin SDK which is I guess my next plan if the email cannot be disabled.
This seems straightforward enough, but I'm wondering if it will also send a validation SMS or that is simply it, if the user adds a wrong phone, they will then be locked out of their account.


text:
Q: Cannot progammatically change IIS website's physical path I'm trying to change the path to some of my IIS sites programmatically. The change only takes
effect only for one of the sites (the same one) and not all of them. Can anyone see what I am doing wrong here?
using WebAdministration = Microsoft.Web.Administration;

using (WebAdministration.ServerManager serverManager = new WebAdministration.ServerManager())
{
    serverManager.Sites.ToList().ForEach(site =>
    {
        site.Stop();
        serverManager.CommitChanges();
        //ChangeDirectoryOfSite(site
        site.Applications.ToList().ForEach(app =>
        {
            //ChangeDirectoryOfApplication
            //if (app.VirtualDirectories?.Attributes["path"]?.Value...
            app.VirtualDirectories.Attributes["path"].Value = ...
            //if (app.VirtualDirectories?.Attributes["physicalPath"]?.Value?
            app.VirtualDirectories.Attributes["physicalPath"].Value = ...
            app.VirtualDirectories.ToList().ForEach(virtualDir =>
            {
                //ChangeDirectoryOfVirtualDirectoy
                //if (virtualDir.Attributes["path"].Value...
                virtualDir.Attributes["path"].Value = ...
                //if (virtualDir.Attributes["physicalPath"].Value...
                virtualDir.Attributes["physicalPath"].Value = ...
            }
            site.Start()
        }
        serverManager.CommitChanges();
    }
}

A: The answer was to .CommitChanges() after each value change:
I marked the code changes with // <-- Add this below
using WebAdministration = Microsoft.Web.Administration;

using (WebAdministration.ServerManager serverManager = new WebAdministration.ServerManager())
{
    serverManager.Sites.ToList().ForEach(site =>
    {
        site.Stop();
        serverManager.CommitChanges();
        //ChangeDirectoryOfSite(site
        site.Applications.ToList().ForEach(app =>
        {
            //ChangeDirectoryOfApplication
            //if (app.VirtualDirectories?.Attributes["path"]?.Value...
            app.VirtualDirectories.Attributes["path"].Value = ...
            serverManager.CommitChanges(); // <--- Add this
            //if (app.VirtualDirectories?.Attributes["physicalPath"]?.Value?
            app.VirtualDirectories.Attributes["physicalPath"].Value = ...
            serverManager.CommitChanges(); // <--- Add this
            app.VirtualDirectories.ToList().ForEach(virtualDir =>
            {
                //ChangeDirectoryOfVirtualDirectoy
                //if (virtualDir.Attributes["path"].Value...
                virtualDir.Attributes["path"].Value = ...
                serverManager.CommitChanges(); // <--- Add this
                //if (virtualDir.Attributes["physicalPath"].Value...
                virtualDir.Attributes["physicalPath"].Value = ...
                serverManager.CommitChanges(); // <--- Add this
            }
            site.Start()
        }
        serverManager.CommitChanges();
    }
}


text:
Q: how to display images from sd card using ImageLoader I'm Getting MalformedURLException while displaying images from sd card using ImageLoader, it getting error of  java.net.MalformedURLException: Protocol not found: /storage/emulated/0/classnkk_images/3_20150928162260013.png . Can possible to pass sd card path to imageloader.
Log Cat
09-30 06:40:24.056  14267-14343/? W/System.err﹕ java.net.MalformedURLException: Protocol not found: /storage/emulated/0/classnkk_images/3_20150928162260013.png
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at java.net.URL.<init>(URL.java:176)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at java.net.URL.<init>(URL.java:125)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at com.example.tazeen.classnkk.ImageLoader.getBitmap(ImageLoader.java:68)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at com.example.tazeen.classnkk.ImageLoader.access$000(ImageLoader.java:23)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at com.example.tazeen.classnkk.ImageLoader$PhotosLoader.run(ImageLoader.java:134)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-30 06:40:24.056  14267-14343/? W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

Here is my ImageLoader Class
public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService= Executors.newFixedThreadPool(5);
    }

    int stub_id = R.drawable.ic_launcher;
    public void DisplayImage(String url, int loader, ImageView imageView)
    {
        stub_id = loader;
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(loader);
        }
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(8000);
            conn.setReadTimeout(8000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }

        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

A: It seems you are having a malformed url - as the error says.
Therefore check if you have a proper URL.
Something similar to your question:
MalformedURLException in android when downloading a zip file.


text:
Q: How can I install the latest versions of NumPy/Scipy/Matplotlib/IPython/Pandas on Ubuntu Users sometimes need to know how to install a newer version of Pandas than their OS package manager offers. Pandas requires NumPy, and works best with SciPy, Matplotlib and IPython.
How can I install the latest versions of NumPy/Scipy/Matplotlib/IPython/Pandas?

A: Using Ubuntu, here is how to install the entire NumPy/Scipy/Matplotlib/IPython/Pandas
stack from Github in a virtualenv using Python2.7:
Note: The instructions below install the latest development version of each package. If you wish to install the latest tagged version, then after git clone, inspect the tags available with
git tag

and select the version you wish to install with
git checkout tag-name

Install virtualenv and virtualenvwrapper:
sudo apt-get install python-virtualenv
sudo pip install virtualenvwrapper

# edit ~/.bashrc to include
source /usr/share/virtualenvwrapper/virtualenvwrapper.sh

# edit ~/.profile to include
export WORKON_HOME=$HOME/.virtualenvs

# You may have to log out then log back in to make the change effective

Make a virtualenv
mkvirtualenv --system-site-packages dev
workon dev

# If you want to make this virtual environment your default Python,
# edit ~/.bashrc to include
workon dev

Add site-packages to sys.path:
add2virtualenv $USER/.virtualenvs/dev/lib/python2.7/site-packages

Install Cython
pip install -U Cython

Install git
sudo apt-get install git

Install NumPy
cd ~/src
git clone https://github.com/numpy/numpy.git

sudo apt-get install python-dev build-essential
sudo apt-get install libatlas-base-dev libatlas3gf-base

# ensure clean build
# this is not necessary the first time, but useful when upgrading
cd ~/src/numpy
/bin/rm -rf ~/src/numpy/build
cdsitepackages && /bin/rm -rf numpy numpy-*-py2.7.egg-info

cd ~/src/numpy
python setup.py build --fcompiler=gnu95
python setup.py install

Install SciPy
cd ~/src
git clone https://github.com/scipy/scipy.git

# ensure clean build
cd ~/src/scipy
/bin/rm -rf ~/src/scipy/build
cdsitepackages && /bin/rm -rf scipy scipy-*-py2.7.egg-info

cd ~/src/scipy
git clean -xdf
python setup.py install

Install Matplotlib dependencies
pip install -U pyparsing
pip install -U six
pip install -U python-dateutil
pip install -U pytz
sudo apt-get install libzmq-dev
pip install -U tornado pygments pyzmq
pip install -U nose
sudo apt-get install python-qt4 python-qt4-doc python-pyside python-cairo python-wxgtk2.8 python-gtk2 dvipng

apt-cache depends python-matplotlib | awk '/Depends:/{print $2}' | xargs dpkg --get-selections
sudo apt-get build-dep python-matplotlib

Install Matplotlib
cd ~/src/
git clone https://github.com/matplotlib/matplotlib

# ensure clean build
cd ~/src/matplotlib
/bin/rm -rf ~/src/matplotlib/build
cdsitepackages && /bin/rm -rf matplotlib* mpl_toolkits

# compile and install
cd ~/src/matplotlib
python setup.py build
python setup.py install

Install IPython
cd ~/src
git clone https://github.com/ipython/ipython.git

# ensure clean build
cd ~/src/ipython
/bin/rm -rf ~/src/ipython/build
cdsitepackages && /bin/rm -rf ipython-*-py2.7.egg

cd ~/src/ipython
python setupegg.py install

Install Pandas
cd ~/src
git clone https://github.com/pydata/pandas.git
cd ~/src/pandas

# update
git fetch origin
git rebase --interactive origin/master

# ensure clean build and install
/bin/rm -rf ~/src/pandas/{build,dist} && cdsitepackages && /bin/rm -rf pandas* && cd ~/src/pandas && python setup.py build_ext --inplace && python setup.py install

Updating:
The advantage of
the git approach is that it provides a way to always keep these packages
up-to-date:
cd ~/src/package-name
git fetch origin
git rebase --interactive origin/master

Follow the instructions above to ensure a clean build, and then rebuild and
reinstall the package.
Shorthand for using pip with GitHub directly
The above steps to clone and install packages can be automated to an extent with pip.  For example, we can also install NumPy like this:
pip install git+git://github.com/numpy/numpy.git

The updating would then be just
pip install numpy --upgrade --force-reinstall

--force-reinstall flag may be needed because pip checks the version from PyPI and doesn't update if the current version isn't smaller.

A: Via the Anaconda distribution:
Download and install
wget http://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh -O miniconda.sh
chmod +x miniconda.sh
./miniconda.sh -b
export PATH=/home/travis/miniconda/bin:$PATH
conda update conda --yes

Install just the packages in the title in their own environment:
conda create --name myenv --yes python=3.4 pandas matplotlib ipython-notebook
source activate myenv

Note: I believe anaconda supports Python versions 2.6, 2.7, 3.3, and 3.4.


text:
Q: rating-widget not showing on ajax call My problem is that the star rating plugin (http://rating-widget.com/) that im using is not showing when i use an ajax function for searching and filtering.
When the page first loads its working fine the star rating is showing

but when i use the filter and search function the star rating disappear. This image is when i choose motivational in the dropdownlist

this is the code for the mainpage where the image, search and filter function is

                     Search
                     <input type="text" name="search_text" id="search_text" placeholder="Search for name or topic" class="form-control"/>

            Filter
                <select name="sortdrpdwn" id="sortdrpdwn" class="form-control" style="width:100%;">
                    <option value="all">All</option>
                    <option value="motivational">Motivational</option>
                    <option value="technology">Technology</option>
                    <option value="business">Business</option>
                    <option value="leadership">Leadership</option>
                    <option value="innovation">Sales</option>
                    <option value="entertainment">Entertainment</option>
                    <option value="healthcare">Health Care</option>
                </select>

filterSp.php this is the php file that is called when i use filter dropdown list and inside it is the plugin java script for star rating.
  <?php

        error_reporting(E_ALL & ~E_NOTICE);
        error_reporting(E_ERROR | E_PARSE);

        $connect = mysqli_connect("localhost", "root", "", "srdatabase");

        if(isset($_POST['search_text']))
        {
            $search = mysqli_real_escape_string($connect, $_POST["search"]);

            $query = "
            SELECT * FROM speakers
            WHERE speaker_fullname LIKE '%".$search."%'
            OR speaker_specialization1 LIKE '%".$search."%'
            OR speaker_specialization2 LIKE '%".$search."%'
            OR speaker_specialization3 LIKE '%".$search."%'
            OR speaker_specialization4 LIKE '%".$search."%'
            OR speaker_specialization5 LIKE '%".$search."%'
            ";
        }

        else
        {
            $filter = mysqli_real_escape_string($connect, $_POST["filter"]);

            if($filter == "all")
            {
                $query = "SELECT * FROM speakers";
            }

            else if($filter == "motivational")
            {
                $query = "SELECT * FROM speakers WHERE speaker_specialization1 = 'motivational' OR speaker_specialization2 = 'motivational' OR speaker_specialization3 = 'motivational' ";
            }

            else if($filter == "technology")
            {
                $query = "SELECT * FROM speakers WHERE speaker_specialization1 = 'technology' OR speaker_specialization2 = 'technology' OR speaker_specialization3 = 'technology' ";
            }

            else if($filter == "business")
            {
                $query = "SELECT * FROM speakers WHERE speaker_specialization1 = 'business' OR speaker_specialization2 = 'business' OR speaker_specialization3 = 'business' ";
            }

            else if($filter == "leadership")
            {
                $query = "SELECT * FROM speakers WHERE speaker_specialization1 = 'leadership' OR speaker_specialization2 = 'leadership' OR speaker_specialization3 = 'leadership' ";
            }

            else if($filter == "innovation")
            {
                $query = "SELECT * FROM speakers WHERE speaker_specialization1 = 'innovation' OR speaker_specialization2 = 'innovation' OR speaker_specialization3 = 'innovation' ";
            }

            else if($filter == "entertainment")
            {
                $query = "SELECT * FROM speakers WHERE speaker_specialization1 = 'entertainment' OR speaker_specialization2 = 'entertainment' OR speaker_specialization3 = 'entertainment' ";
            }

            else if($filter == "healthcare")
            {
                $query = "SELECT * FROM speakers WHERE speaker_specialization1 = 'healthcare' OR speaker_specialization2 = 'healthcare' OR speaker_specialization3 = 'healthcare' ";
            }
        }
            $result = mysqli_query($connect, $query);

            if(mysqli_num_rows($result) > 0)
            {
                    while ($array = mysqli_fetch_array($result))
                    {
                            $output .= '

'.$array["speaker_fullname"].'

'.$array["speaker_specialization1"].'

'.$array["speaker_specialization2"].'

'.$array["speaker_specialization3"].'

                                      //The div where the star rating will show

                            ';
                    }
            }
            echo $output;
         ?>
// Star rating javascript

searchSp.php this is the php file that is called when i use search function and inside it is the plugin java script for star rating.
<?php

error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);

$connect = mysqli_connect("localhost", "root", "", "srdatabase");

    $search = mysqli_real_escape_string($connect, $_POST["search"]);

    $query = "
    SELECT * FROM speakers
    WHERE speaker_fullname LIKE '%".$search."%'
    OR speaker_specialization1 LIKE '%".$search."%'
    OR speaker_specialization2 LIKE '%".$search."%'
    OR speaker_specialization3 LIKE '%".$search."%'
    ";

    $result = mysqli_query($connect, $query);

    if(mysqli_num_rows($result) > 0)
    {
        while ($array = mysqli_fetch_array($result))
        {
                $output .= '

'.$array["speaker_fullname"].'

'.$array["speaker_specialization1"].'

'.$array["speaker_specialization2"].'

'.$array["speaker_specialization3"].'

                ';
           }
    }
    echo $output;
 ?>

A: in the  searchSp.php you are not passing the rating script to the ajax respond.
Like i said in the comment you can use the sdk, if so there is no need for the javascript your searchSp.php would be like
<?php

error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
    // Use API site scope.
define('RW_SDK__API_SCOPE', 'site');

// Modify the following definitions to your site details.
define('RW_SDK__SITE_ID',         '__YOUR_SITE_ID__');
define('RW_SDK__SITE_PUBLIC_KEY', '__YOUR_SITE_PUBLIC_KEY__');
define('RW_SDK__SITE_SECRET_KEY', '__YOUR_SITE_SECRET_KEY__');

// Include RatingWidget's SDK.
require dirname(__ROOT__) . '/ratingwidget.php';

// Init SDK with your site details (assumes that the SDK located in same folder of this example).
$rw_api = new \RatingWidget\Api\Sdk\RatingWidget(
    RW_SDK__API_SCOPE,
    RW_SDK__SITE_ID,
    RW_SDK__SITE_PUBLIC_KEY,
    RW_SDK__SITE_SECRET_KEY
);

$item_id = $array["id"]; // Replace that with your rating id.

// If you want the rating to work with Rich-Snippets,
// set the rating class to one of the following values:
//     product, page, blog-post, post, front-post, item
$rating_class = 'product';
$connect = mysqli_connect("localhost", "root", "", "srdatabase");

$search = mysqli_real_escape_string($connect, $_POST["search"]);

$query = "
SELECT * FROM speakers
WHERE speaker_fullname LIKE '%".$search."%'
OR speaker_specialization1 LIKE '%".$search."%'
OR speaker_specialization2 LIKE '%".$search."%'
OR speaker_specialization3 LIKE '%".$search."%'
";

$result = mysqli_query($connect, $query);

if(mysqli_num_rows($result) > 0)
{
    while ($array = mysqli_fetch_array($result))
    {
            $output .= '

'.$array["speaker_fullname"].'

'.$array["speaker_specialization1"].'

'.$array["speaker_specialization2"].'

'.$array["speaker_specialization3"].'

'.
                         $rw_api->EchoAggregateRating($item_id).'

            ';
       }
}
echo $output;
?>

see this ->

A: Change the height from height:150px to height:220px


text:
Q: Grep: Count the number of times a string occurs if another string does not occur I have a set of many .json.gz files. In each file, there are entries such as this:
{"type":"e1","public":true, "login":"username1", "org":{"dict","of":"lots_of_things"}}
{"type":"e2","public":true, "login":"username2"}

No matter where in each nested dict "login" appears, I want to be able to detect it and take the username, only if the key "org" does not exist anywhere in the nested dict. I also want to count the number of times each username appears in the files.
My final output should be a file of dicts that looks like this:
{'username2: 1}

because of course username1 wouldn't be counted: the key "org" appears in its dict.
I'm looking for something like:
zgrep -Rv "org" . | zgrep -o 'login":"[^"]*"' /path/to/files/* | cut -d'"' -f3 | sort | uniq -c | sed '1i{
       s/\s*\([0-9]*\)\s*\(.*\)/"\2": \1,/;$a}' > outputfile.txt

I'm not sure about this part:
zgrep -Rv "org" . |

The rest successfully creates the type of file I'm looking for. I'm just unsure about the order of operations here.
EDIT
I should have been more clear, I apologize. There are also often multiple instances of the key "login" per main dict object. For example (using "k" for any key that is not login and not org, and using "v" for a value):
{"k":"v","k":{"k":{"k":"v","login":"username1"},"k":"v"},"k":{"k":"v","login":"username2"}}
{"k":{"k":"v","k":"v"},"k":{"org":{"k":"v","k":v,"login":"username3"},"k":"v"},"k":{"k":"v","login":"username4"}}
{"k":{"k":"v"},"k":{"k":{"k":"v","login":"username1"},"login":"username2"}}

Since the key org appears in the second dict, I want to exclude usernames 3 and 4 from the dict I make and save to a file.
For example, I want this in a file:
{'username1': 2}
{'username2': 2}

A: not grep but gnu sed job with script, your data in 'a'
i=
for e in $(sed -nE '/.*\borg\b.*/!s/.*"login":"(\w+)".*/{\1:}/p' a)
{
let i++;echo ${e/:/:$i}
}

use '>' at end to save in file
if better regex : 'pcregrep' installed, it does as well;
pcregrep -io '(?!.*\borg\b.*)(?<="login":")\w+(?=".*)' a

replace sed...  script above, with a bit adjusted printout

A: AWK solution and replacing find -R with more reliable find:
find . -type f -name "*.json.gz" -print0 | xargs -0 zgrep -v -h '"org"' | awk '{ if ( match($0,/"login":"[^"]+"/) ) logins[substr($0,RSTART+8,RLENGTH-8)]++; } END { for ( i in logins ) print("{" i ":" logins[i] "}"); }'

Example output:
{"username2":1}

A: This worked:
zgrep -v "org" *.json.gz | zgrep -o 'login":"[^"]*"' | cut -d'"' -f3 | sort | uniq -c | sed '1i{
       s/\s*\([0-9]*\)\s*\(.*\)/"\2": \1,/;$a}' > usernames_2011.txt


text:
Q: Optimized report caching I have an SSRS 2008 R2 that I want to enhance performance on.  Is it possible to cache this report for all clients over a given date range so that even if they select one part of this report, it will still run off of the cache vs. datasource?  For example, if I cache 1/1/12-6/1/13 for Regions A-C and then the user runs this report for 1/1/13-6/1/13 for Region A only, will it run off of cache or the datasource?
If I set this report to expire a temporary copy of the report every 15 minutes, does that mean that if the user waits > 15 minutes, that it won't run off of cache?

A: There are various options for caching reports with parameters. Taken from the relevant documentation for SSRS 2008 R2:

To improve server performance, you can preload the cache. You can preload the cache with a collection of parameterized report instances in two ways:

*

*Create a cache refresh plan. When you create a refresh plan, you can specify a schedule for a single report or specify a shared schedule.

*Create a data-driven subscription that uses the Null Delivery Provider. When you specify the Null Delivery Provider as the method of delivery in the subscription, the report server targets the report server database as the delivery destination and uses a specialized rendering extension called the null rendering extension. In contrast with other delivery extensions, the Null Delivery Provider does not have delivery settings that you can configure through a subscription definition.

For your exact scenario's the best thing you can do to get an exact answer is try it out, using the mentioned documentations (and links therein) to understand and tweak the details.
(The last question you ask confuses me a bit; if a cached report (w/o preloaded cache) expires after 15 minutes then the report will be run the first time after that, and remain cached for another new 15 minutes.)


text:
Q: How to fetch password from Alfresco UI page which has been created by admin for the new user? I had used this code for auto generation of mails. Now the problem is password shown in the mail is the password as generated by the script. I want the password to be fetched from alfresco new user page, where the admin has created the password for the new user not any random string.
Below is the script that i generated for automatic mail generation.
if (document.isContainer && document.displayPath == "/Company Home/User Homes") {
var owner = document.properties["cm:owner"];
var pNode = people.getPerson(owner);
if (pNode!=null && pNode.exists()){

    var userName = pNode.properties.userName;
    var email = pNode.properties.email;
    var randPassword = Math.random().toString(36).substr(2, 30)+"-"+(Date.now());

    people.setPassword(userName, randPassword);
    logger.debug("Invitation mail: User "+userName+" password has been changed.");

    var mail = actions.create("mail");
    //mail.parameters.from = "noreply@customdomain";
    mail.parameters.to = email;
    mail.parameters.subject = "Welcome to the site, login: "+userName+", password: "+randPassword;
    mail.parameters.template = companyhome.childByNamePath("Data Dictionary/Email Templates/Invite Email Templates/invite_user_email.ftl");
    var templateModel = new Array();
    templateModel['newPassword'] = randPassword; // use ${newPassword} expression inside template
    mail.parameters.template_model = templateModel;
    mail.executeAsynchronously(document);
    logger.debug("Invitation mail has been sent to "+email);
} else {
    logger.warn("Invitation mail: User not found: "+owner);
}
}

Please guide me how to proceed further.

A: You can't decode password from its hash. You can only encode new password and match it with hash.
You can modify Alfresco Share to store raw password in custom user aspect, but this is very bad practice. Admin shouldn't know user password.

A: The final answer has been posted in  Auto-generation of email with username and random password on creation of new user-- by @Imagine


text:
Q: How to call asynchronous request synchronously with a timeout value? I have to synchronously call an asynchronous api request. Since this api request takes long time to answer, I also want to set a timeout to fail the api-request and continue with null. Here's my code to call this api:
private suspend fun call(
    accessStage: AccessStage,
): Response? = withContext<Response?>(Dispatchers.IO) {

    return@withContext withTimeoutOrNull(1000) {

        suspendCoroutine<Response?> { continuation ->

            val request = External3rdPartyApi.newRequest(
                accessStage
            ) { response, throwable ->

                continuation.resume(response)
            }

            request.parameters = hashMapOf<String, String>().apply {
                put["token"] = External3rdPartyApi.TOKEN
                put["salt"] = External3rdPartyApi.calculateSalt(accessStage)
            }
            request.executeAsync()
        }
    }
}

I can't change how External3rdPartyApi works.
I think above code looks evil. Also, I read in another answer:

withTimeout { ... } is designed to cancel the ongoing operation on timeout, which is only possible if the operation in question is cancellable.

So, should I use suspendCancellableCoroutine instead of suspendCoroutine?
How can I write it in a better way?

A: Using suspendCoroutine is fine if you can't (or do not wanna) handle cancelation of the Coroutine. But because you have a timeout, you should consider using suspendCancellableCoroutine and handle the cancelation event to stop the work (in the third party function - if you can).
suspendCancellableCoroutine<T> { continuation ->
  continuation.invokeOnCancellation { throwable ->
    // now you could stop your (third party) work
  }
}

When your third party function throws an exception, you could try-catch it and finish your continuation using either resuming with the exception or return a null value (depends on your use case):
suspendCancellableCoroutine<T?> { continuation ->
  try {
    continuation.resume(thirdParty.call())
  } catch (e: Exception) {
    // resume with exception
    continuation.resumeWithException(e)
    // or just return null and swallow the exception
    continuation.resume(null)
  }
}

Lets put all together
suspend fun call(): Response? = withContext(Dispatchers.IO) {
  return@withContext withTimeoutOrNull(1000L) {
    return@withTimeoutOrNull suspendCancellableCoroutine { continuation ->
      try {
        continuation.resume(External3rdPartyApi.newRequest(accessStage))
      } catch (e: Exception) {
        // resume with exception
        continuation.resumeWithException(e)

        // or just return null and swallow the exception
        continuation.resume(null)
      }

      // in case the coroutine gets cancelled - because of timeout or something else
      continuation.invokeOnCancellation {
        // stop all the work
      }
    }
  }
}


text:
Q: Multiple path variables in one url I am trying to construct a URL that can take in multiple ids at once so I am able to return two people at once, but I am getting a number format exception
String url = "http://test.com/Services/people/{id}/Identifier"
Map<String, String> params = new HashMap<String, String>();
params.put("id", {"1234","5678"});
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                                    .queryParam("DOB", "myDOB");
String uriBuilder = builder.build().encode().toUriString();
restTemplate.exchange(uriBuilder , HttpMethod.PUT, requestEntity,
                class_p, params);

This is getting a number format exception from passing in multiple ids, is there a way to do that in a different format?

A: GET /Services/people/42 is a request for "people" resource with id 42.
A request for multiple people by some criteria is not a resource request, but a query, so should use query parameters.
E.g. GET /Services/people/find?id=13&id=29
or maybe POST /Services/people/find with payload {"id": [1234, 5678]} (Content-Type: application/json).
What you're trying to do is wrong, for a RESTful service.


text:
Q: Expression tree evaluation without recursion in c I want to write a function where an expression tree is passed and the result of the arithmetic expression tree is returned. I saw a lot of question and read a lot of blogs. All of them says to use stack and blindly print it in inorder. But since I have operators too in the tree, simply printing them wont help. How can I evaluate the arithmetic expression? Thank you.
the expression tree structure
typedef struct EXPR_NODE{

    char *type;
    char *content;

    struct EXPR_NODE *left_node;
    struct EXPR_NODE *right_node;

    struct EXPR_NODE *prev_node;  //this is for stack operation only
    struct EXPR_NODE *next_node;  //this is for stack operation only

} expr_node;

so my sample expression will be 2 * 1 + 3

expr_node *root = calloc(1, sizeof(expr_node));
root->type = "+";
root->content = "PLUS";

expr_node *left1 = calloc(1, sizeof(expr_node));
left1->type = "3";
left1->content = "INT";

expr_node *right1 = calloc(1, sizeof(expr_node));
right1->type = "*";
right1->content = "ASTERIX";

//left and right of root

root->left_node = left1;
root->right_node = right1

expr_node *left2 = calloc(1, sizeof(expr_node));
left2->type = "1";
left2->content = "INT";

expr_node *right2 = calloc(1, sizeof(expr_node));
right2->type = "2";
right2->content = "INT";

//left and right of right1
right1->left_node = left2;
right1->left_node = right2;

so the tree looks like
       +
      / \
     3   *
        / \
       1   2

So when I pass the root node to the function I need it return 5 in String. I accomplished it with recursion but i need to do it with iteration.


text:
Q: iOS: Convert UnsafeMutablePointer to String in swift? As the title says, what is the correct way to convert UnsafeMutablePointer to String in swift?
//lets say x = UnsafeMutablePointer<Int8>

var str = x.memory.????

I tried using x.memory.description obviously it is wrong, giving me a wrong string value.

A: If the pointer points to a NUL-terminated C string of UTF-8 bytes, you can do this:
import Foundation

let x: UnsafeMutablePointer<Int8> = ...
// or UnsafePointer<Int8>
// or UnsafePointer<UInt8>
// or UnsafeMutablePointer<UInt8>

let str = String(cString: x)

A: Times have changed. In Swift 3+ you would do it like this:
If you want the utf-8 to be validated:
let str: String? = String(validatingUTF8: c_str)

If you want utf-8 errors to be converted to the unicode error symbol: �
let str: String = String(cString: c_str)

Assuming c_str is of type UnsafePointer<UInt8> or UnsafePointer<CChar> which is the same type and what most C functions return.

A: this:
let str: String? = String(validatingUTF8: c_str)

doesn't appear to work with UnsafeMutablePointer<UInt8>
(which is what appears to be in my data).
This is me trivially figuring out how to do something like the C/Perl system function:
let task = Process()
task.launchPath = "/bin/ls"
task.arguments = ["-lh"]

let pipe = Pipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
var unsafePointer = UnsafeMutablePointer<Int8>.allocate(capacity: data.count)
data.copyBytes(to: unsafePointer, count: data.count)

let output : String = String(cString: unsafePointer)
print(output)
//let output : String? = String(validatingUTF8: unsafePointer)
//print(output!)

if I switch to validatingUTF8 (with optional) instead of cString, I get this error:
./ls.swift:19:37: error: cannot convert value of type 'UnsafeMutablePointer<UInt8>' to expected argument type 'UnsafePointer<CChar>' (aka 'UnsafePointer<Int8>')
let output : String? = String(validatingUTF8: unsafePointer)
                                    ^~~~~~~~~~~~~

Thoughts on how to validateUTF8 on the output of the pipe (so I don't get the unicode error symbol anywhere)?
(yes, I'm not doing proper checking of my optional for the print(), that's not the problem I'm currently solving ;-) ).


text:
Q: How to use all features of widgetVar in primefaces ? I want ondouble click the size of input text will increase and when it is not on focus it will gain its original width.
    <p:inputText widgetVar="user"
    doubleclick="PF('user').style.width = '300px'"
    oncomplete="PF('user').style.width = '175px'"/>

like this I want to dynamically add style classes to it ? If any one have any link where complete reference of how to use widgetVar is given please give me. Thanks.


text:
Q: styling back end widget form and enabling multi widget feature I am reading this tutorial from the end of 2008 on how to make widget and so far everything works fine except that I have few questions that I couldn't find answers there.
I need to style back end widget form somewhat different and for that purpose I would like to be able to add class to it that will render only in dashboard.
I am using these 2 functions to build my widget:
 wp_register_sidebar_widget(SAASJOTC_WIDGET_ID,
    __('Text Ripple'), 'widget_saasjotc');

  wp_register_widget_control(SAASJOTC_WIDGET_ID,
    __('Text Ripple'), 'widget_saasjotc_control');

Is this method deprecated considering year of the article I am reading? If yes please could you provide me with better way and why?
With this method I can add only one widget to the sidebar and I need to be able to add more. How can this be achieved?
Any help appreciated. Sorry if there are any difficulties in my description. I'll be happy to clarify it further for you if need arises.

A: I don't know if the tutorial uses any deprecated function, you can check that enabling WP_DEBUG in your wp-config.php.
Anyway, by the time it was written the new Widgets API didn't exist.
The Codex is your friend, read the Codex:
http://codex.wordpress.org/Widgets_API
And for styling the widgets admin area refer to this post:
Highlight custom widgets in the admin area?