text:
Q: Strongly Type RadioButtonList MVC 3 Is this even possible? Maybe i am stupid but i cannot apply any of the answers here or elsewhere to my specific situation.
What i want to do is pass a strongly typed model of Quiz to my view. Quiz has a collections of questions. Question has a collection of possibleanswers.
Questions look like:

*

*Question.Text

*Question.Id

*Question.PossibleAnswers

PossibleAnswers look like:

*

*PossibleAnswer.Id

*PossibleAnswer.Value

*PossibleAnswer.Label

*PossibleAnswer.Selected

I want to pass the Quiz to the view, the view should setup the form where each Question has a radiobuttonlist(group) of PossibleAnswers.
Question1 text blah blah blah:
<input id="1_1" type="radio" name="question1"  value="1" />
<input id="1_2" type="radio" name="question1"  value="2" />
<input id="1_3" type="radio" name="question1"  value="3" />

Now i don't care exactly the format for the id's of the radio buttons in the group.. clearly MVC must care.. so whatever way works i want to do that. But i would expect when i submit the form to the action i should be able to loop through the Questions and get the possibleAnswer in each Question's possibleAnswer collections with the .isAnswer marked as true:
foreach(var item in model.Questions)
{
    foreach(var aitem in item.PossibleAnswers)
    {
        if(aitem.Selected)
           //do some stuff
    }
}

so i don't get it.. this:
@foreach (var item in Model.Questions)
{
    @foreach (var jitem in item.PossibleAnswers)
    {
        @Html.RadioButtonFor(x => item.QuestionId, jitem.Value)

    }

 }

is not even close.. can someone please explain what i am doing wrong? Is my model wrong? Can MVC do this? Do i need to change the PossibleAnswer model type to RadioButtonListItems or something? help!
------------------------------------ ** UPDATE ** ----------------
@for (int i = 0; i < Model.Questions.Count(); i++)
{

@Model.Questions.ElementAt(i).QuestionText

    @Html.RadioButtonListFor(m => m.Questions.ElementAt(i).AnswerRadios,
        "Question" + i);
}

This code seems to work! At least it will output some radiobuttons.. BUT it is outputting the html as special entities..

    <input id="Question0_1" name="Question0_value" type="radio" value="17" />
    1

    <input id="Question0_2" name="Question0_value" type="radio" value="18" />
    2

    <input id="Question0_3" name="Question0_value" type="radio" value="19" />
    3

    <input id="Question0_4" name="Question0_value" type="radio" value="20" />
    4

    <input id="Question0_5" name="Question0_value" type="radio" value="21" />
    5

A: Here is what I use.  I have made some minor modifications but it works great.


text:
Q: how to resolve : index out of bound C# arrays, streams i get index out of bound on line :   stream.Read(fileBytes[i], 0, fileBytes[i].Length);
any help would be appreciated . thanks :)
string[] path = new string[15];
byte[][] fileBytes = new byte[10][];
for (int i = 1; i <= 10; i++) {

 path[i] = @ "C:\Users\t-chkum\Desktop\InputFiles\1MB\" + i + ".txt ";

 // readind data/*
 FileStream stream = File.OpenRead(path[i]);
 fileBytes[i] = new byte[stream.Length];

 //  Console.WriteLine(stream.Length);
 stream.Read(fileBytes[i], 0, fileBytes[i].Length);
 stream.Close();
}

A: You are iterating from i=1 to 10 inclusive. But, the size of the array is 10 i.e. the index goes from 0 to 9. So, either start i from 0, or index using i-1. Also, use try-catch. This would help you to debug better.
Otherwise, the code is working fine for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I set sales receipt GST (sales tax or GST centre) attributes via external application? (Non US) I am working with a Non US version of QuickBooks online (QuickBooks Online Plus Australia). I'm trying to deal here with our Goverment services tax or GST which is 10%. What I want to do is create a sales receipt that calculates the total charge to the customer and displays the GST component through calculation. Right now the GST is being added to the charge, I simply want to acknowledge how much GST is included in the total charge.
I am using the traditional SDK QBXML for QB online (SalesTaxLineAdd). I have alternatively tried setting up the tax through the GST centre but doing so seems not to be harmonious with the SDK because when I create a sales receipt through the SDK in line with the GST centre, for the field "All Amounts Are" it automatically sets it as "Out of Scope of GST" and ideally I would want this to automatically be "Inclusive of GST". For the line Items the SDK doesn't set the "GST Which" field at all which then requires manually setting it to GST. What would be ideal is if the SDK did this all automatically.
As a workaround using the SDK and the SalesTaxLineAdd element, I have been subtracting 10% from each line item price so that "SalesTaxLineAdd" adds the 10% which then represents the true total. I will accept this If I have to but if a customer calls and asks how much they paid for their last order I will be telling them the price exclusive of gst.
If I work with the REST API v2 is it more flexible for this specific scenario?
Your help is appreciated

A: It appears that your solution is still the recommended solution from Intuit.
From their online documentation: https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/020_key_concepts/Tax_Inclusive.2FExclusive

For sending TaxInclusive, the developers need to do the calculation for exclusive amount and then assign it to the lines and send the remaining tax amount in the TxnTaxDetail Line.

It also looks like their original intention was to categorize all tax amounts in this way, but the business logic and SDK end up with slightly different results:
From known issue QBO-37013: https://developer.intuit.com/docs/0025_quickbooksapi/0058_faq/qbo_v3_known_issues

Business logic is assigning tax inclusive amounts to Line.Amount instead of the required tax exclusive amount when GlobalTaxCalculation='TaxInclusive'.


text:
Q: Javascript library to emulate chrome's device change I need to implement a functionality that closely emulates Chrome's device change functionality, that enables the user to see our website under different devices. I could implement it manually, but I'm pretty sure that this is a kinda common problem and there probably is a library that does it.
If not, can anyone point out how does Chrome implements it? Thanks!
P.S. Obviously, the solution should work on other browsers too, as many as possible. I only mention it because I mentioned Chrome several times and a confusion that I'm trying to implement Chrome-specific app might arise ;)

A: Found https://github.com/nerijusgood/viewport-resizer. I haven't checked it into detail yet, but on the surface it looks like it would do the job. Sharing it as it could be of use to someone else in the future :)


text:
Q: Locate mistake in matrix inverse I recently asked a question about RREF and have incorporated the helpful responses into my problem. I get the same answer every time but it is incorrect.

Does anyone know what I am doing wrong?
Thanks again.

A: You make a mistake here: $$R_1-R_2\to R_1$$ because in that line $R_1-R_2$ is $$1\quad -1\quad 0\quad\mid\quad 1\quad -4\quad 12.$$

A: You made a mistake at
$R_1 + R_3 \to R_3,$
the last row should be $\begin{bmatrix} 0 & 1 & 4 & 1 & 1 & 1 \end{bmatrix}$
Remark:

*

*$R_i + cR_j \to R_i$ is an elementary step.

*$R_j + cR_i \to R_i$ is actually two steps, it consists of $R_i + \frac1cR_j \to R_i$ and $cR_i$.

*That is where you store the result matters.

*While we can't see the difference now, it plays a role when you compute determinant.


text:
Q: How do I consolidate several invoices that at one point were backordered and then fulfilled in mysql For example I have a 1 invoice with 1 that was in stock and 3 that weren't in stock. Later on, the 2 invoices were created for those backordered ones. I want to be able to consolidate all those invoices into one displaying that 3 that were shipped and 1 that is still on backorder.
mysql table is as follows:

order_id
price
model
quantity
previous_id

1788
1,200
SBS
-1
Null //backordered

1788
1,200
SSC
-1
Null //backordered

1788
1,200
SAC
1
Null

1788
1,200
SBB
-1
Null //backordered

Second invoice

order_id
price
model
quantity
previous_id

1811
1,200
SBB
1
1788

Third invoice

order_id
price
model
quantity
previous_id

1865
1,200
SSC
1
1788

So as you can see previous_id tracks which was the original order for backordered items.
My mysql code is:
SELECT * FROM order_product where order_id = 1788 or previous_id = 1788
which displays all 6 rows but I want to be able to see 3 ordered and 1 backorder. Total should be showing 4 rows.
The final version should look like this:

order_id
price
model
quantity
previous_id

1788
1,200
SBS
-1
Null //backordered

1788
1,200
SSC
1
Null

1788
1,200
SAC
1
1788

1788
1,200
SBB
1
1788

How do I achieve this?

A: In mysql 8 you can do
The rownumber rn 1 has always the higher number in case of only -1, there is no order , if the number is positive it would be selected row

CREATE TABLE orders (
  `order_id` INTEGER,
  `price` VARCHAR(5),
  `model` VARCHAR(3),
  `quantity` INTEGER,
  `previous_id` VARCHAR(18)
);

INSERT INTO orders
  (`order_id`, `price`, `model`, `quantity`, `previous_id`)
VALUES
  ('1788', '1,200', 'SBS', '-1', 'Null //backordered'),
  ('1788', '1,200', 'SSC', '-1', 'Null //backordered'),
  ('1788', '1,200', 'SAC', '1', 'Null'),
  ('1788', '1,200', 'SBB', '-1', 'Null //backordered'),
  ('1811', '1,200', 'SBB', '1', '1788'),
  ('1865', '1,200', 'SSC', '1', '1788');

SELECT
`order_id`, `price`, `model`, `quantity`, `previous_id`
FROM
(SELECT
`order_id`, `price`, `model`, `quantity`, `previous_id`
, ROW_NUMBER() OVER ( PARTITION BY `model` ORDER BY `quantity` DESC) rn
FROM orders
WHERE `order_id` = '1788' OR `previous_id` = '1788') t1
WHERE rn = 1

order_id | price | model | quantity | previous_id
-------: | :---- | :---- | -------: | :-----------------
    1788 | 1,200 | SAC   |        1 | Null
    1811 | 1,200 | SBB   |        1 | 1788
    1788 | 1,200 | SBS   |       -1 | Null //backordered
    1865 | 1,200 | SSC   |        1 | 1788

db<>fiddle here
For your new requirement

CREATE TABLE orders (
  `order_id` INTEGER,
  `price` VARCHAR(5),
  `model` VARCHAR(3),
  `quantity` INTEGER,
  `previous_id` VARCHAR(18)
);

INSERT INTO orders
  (`order_id`, `price`, `model`, `quantity`, `previous_id`)
VALUES
  ('1788', '1,200', 'SBS', '-1', 'Null //backordered'),
  ('1788', '1,200', 'SSC', '-1', 'Null //backordered'),
  ('1788', '1,200', 'SAC', '1', 'Null'),
  ('1788', '1,200', 'SBB', '-1', 'Null //backordered'),
  ('1811', '1,200', 'SBB', '1', '1788'),
  ('1812', '1,200', 'SBB', '1', '1788'),
  ('1865', '1,200', 'SSC', '1', '17

SELECT
`order_id`, `price`, `model`, `quantity`, `previous_id`
FROM
(SELECT
`order_id`, `price`, `model`, `quantity`, `previous_id`
, ROW_NUMBER() OVER ( PARTITION BY `model` ORDER BY `quantity` DESC) rn
,(SELECT COUNT(*) FROM orders WHERE `model` = o1.`model` AND `quantity` <> -1) mx
FROM orders o1
WHERE `order_id` = '1788' OR `previous_id` = '1788') t1
WHERE rn <= IF(mx = 0 , 1,mx)

order_id | price | model | quantity | previous_id
-------: | :---- | :---- | -------: | :-----------------
    1788 | 1,200 | SAC   |        1 | Null
    1811 | 1,200 | SBB   |        1 | 1788
    1812 | 1,200 | SBB   |        1 | 1788
    1788 | 1,200 | SBS   |       -1 | Null //backordered
    1865 | 1,200 | SSC   |        1 | 1788

db<>fiddle here
this is the last one

CREATE TABLE order_product (
  `order_id` INTEGER,
  `price` VARCHAR(5),
  `model` VARCHAR(3),
  `qty` INTEGER,
  `previous_id` VARCHAR(18)
);

INSERT INTO order_product   (order_id, price, model, qty, previous_id)
VALUES   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1807', '1,200', 'CBL', '1', 1788)
,   ('1806', '1,200', 'CBL', '1', 1788)
,   ('1899', '1,200', 'CBL', '1', 1788)
,   ('1809', '1,200', 'SPL', '1', 1788);

SELECT
`order_id`, `price`, `model`, `qty`, `previous_id`
FROM
(SELECT
`order_id`, `price`, `model`, `qty`, `previous_id`
, ROW_NUMBER() OVER ( PARTITION BY `model` ORDER BY `qty` DESC) rn
,(SELECT COUNT(*) FROM order_product WHERE `model` = o1.`model` AND `qty` <> -1) mx
,(SELECT COUNT(*) FROM order_product WHERE `model` = o1.`model` AND `qty` = -1) nx
FROM order_product o1
WHERE `order_id` = '1788' OR `previous_id` = '1788') t1
WHERE rn <= IF(mx = 0 , nx,mx+ IF(nx=0, 0,nx -mx))

order_id | price | model | qty | previous_id
-------: | :---- | :---- | --: | :----------
    1807 | 1,200 | CBL   |   1 | 1788
    1806 | 1,200 | CBL   |   1 | 1788
    1899 | 1,200 | CBL   |   1 | 1788
    1788 | 1,200 | CBL   |  -1 | null
    1788 | 1,200 | CBL   |  -1 | null
    1788 | 1,200 | CBL   |  -1 | null
    1809 | 1,200 | SPL   |   1 | 1788

db<>fiddle here

CREATE TABLE order_product (
  `order_id` INTEGER,
  `price` VARCHAR(5),
  `model` VARCHAR(3),
  `qty` INTEGER,
  `previous_id` VARCHAR(18)
);

✓

INSERT INTO order_product   (order_id, price, model, qty, previous_id)
VALUES   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1788', '1,200', 'CBL', '-1', Null)
,   ('1807', '1,200', 'CBL', '1', 1788)
,   ('1806', '1,200', 'CBL', '1', 1788)
,   ('1899', '1,200', 'CBL', '1', 1788)
,   ('1809', '1,200', 'SPL', '1', 1788);

SELECT
`order_id`, `price`, `model`, `qty`, `previous_id`
FROM
(SELECT
`order_id`, `price`, `model`, `qty`, `previous_id`
, ROW_NUMBER() OVER ( PARTITION BY `model` ORDER BY `qty` DESC) rn
,(SELECT COUNT(*) FROM order_product WHERE  `qty` <> -1) mx
,(SELECT COUNT(*) FROM order_product WHERE `model` = o1.`model` AND `qty` <> -1) mx1
,(SELECT COUNT(*) FROM order_product WHERE `model` = o1.`model` AND `qty` = -1) nx
FROM order_product o1
WHERE `order_id` = '1788' OR `previous_id` = '1788') t1
WHERE rn <= IF(mx = 0 , nx,mx1+ IF(nx=0, 0,nx -mx))

order_id | price | model | qty | previous_id
-------: | :---- | :---- | --: | :----------
    1807 | 1,200 | CBL   |   1 | 1788
    1806 | 1,200 | CBL   |   1 | 1788
    1899 | 1,200 | CBL   |   1 | 1788
    1788 | 1,200 | CBL   |  -1 | null
    1788 | 1,200 | CBL   |  -1 | null
    1809 | 1,200 | SPL   |   1 | 1788

db<>fiddle here


text:
Q: Efficiently collect links in dataframe Say I have a dataframe of type
individual,  location, food
         1          A     a
         1          A     b
         1          B     a
         1          A     c
         2          C     a
         2          C     b

where individuals are creating links between location and food. I would like to collect all links on the individual basis. That is, if an individual was observed at locations A and B and had (eventually) food at a, b, and c, I want to link all these locations and food types against each other:
    location   food
           A      a
           A      b
           A      c
           B      a
           B      b
           B      c
           C      a
           C      b

One - extremely inefficient - way of doing so is
import itertools
def foo(group):
    list1 = group.location.unique()
    list2 = group.food.unique()
    return pd.DataFrame(data=list(itertools.product(list1, list2)), columns=['location', 'food'])
df.groupby(df.individual).apply(foo)

Is there any better way to get this done?

A: You can pick up some efficiency by using numpy's meshgrid.
import itertools
import numpy as np
def foo(group):
    list1 = group.location.unique()
    list2 = group.food.unique()
    return pd.DataFrame(data=list(itertools.product(list1, list2)), columns=['location', 'food'])

def bar(group):
    list1 = group.location.unique()
    list2 = group.food.unique()
    product = np.meshgrid(list1, list2)
    # reversing the order is necessary to get the same output as foo
    list3 = np.dstack([product[1], product[0]]).reshape(-1, 2)
    return pd.DataFrame(data=list3, columns=['location', 'food'])

On my machine there was a small, (~20 %) speedup
In [66]: %timeit df.groupby(df.individual).apply(foo)
100 loops, best of 3: 2.57 ms per loop

In [67]: %timeit df.groupby(df.individual).apply(bar)
100 loops, best of 3: 2.16 ms per loop


text:
Q: How to set max and min limit of zoom for an ID of an element with JS or JQUERY? In my app I've a DIV tag with id mainDiv
and I've applied zooming, but the problem is its zooming without a limit means no upper limit and lower limit.
I'm tring in google but its showing google map api's but I need css properties or js or jquery fixes.
The code is like this: Its SVG ZOOMING
if(evt.wheelDelta)
        delta = evt.wheelDelta / 3600; // Chrome/Safari
    else
        delta = evt.detail / -90; // Mozilla

    var z = 1 + delta; // Zoom factor: 0.9/1.1

    var g = getRoot(svgDoc);

    var p = getEventPoint(evt);

    p = p.matrixTransform(g.getCTM().inverse());

    // Compute new scale matrix in current mouse position
    var k = root.createSVGMatrix().translate(p.x, p.y).scale(z).translate(-p.x, -p.y);

        setCTM(g, g.getCTM().multiply(k));

    if(typeof(stateTf) == "undefined")
        stateTf = g.getCTM().inverse();

    stateTf = stateTf.multiply(k.inverse());

please help

A: anything like this?
(function ($) {

var $parent = $('#floor_plan');

if($parent.length) {

    // set-up panzoom
    var $panzoom = $parent.find('.panzoom').panzoom({
        increment       : 0.5,
        minScale        : 1,
        maxScale        : 2,
        startTransform  : 'scale(4.0)',
        $zoomIn         : $parent.find('A[href=#zoom_in]'),
        $zoomOut        : $parent.find('A[href=#zoom_out]'),
        contain         : 'invert'
    }).panzoom('zoom', true);

    // handle scrolling in and out
    $panzoom.parent().on('mousewheel.focal', function (e) {

        e.preventDefault();

        var delta = e.delta || e.originalEvent.wheelDelta;
        var zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0;

        $panzoom.panzoom('zoom', zoomOut, {
            increment   : 0.1,
            animate     : false,
            focal       : e
        });
    });
}

})(jQuery);
http://jsfiddle.net/576a4qeh/1/


text:
Q: Unable to retrieve EntityManagerFactory for unitName - JPA configs problems I'm making a Maven EJB module, and i have troubles when i run tests using JUnit and Embedded GlassFish container.
EJB module consists of JPA entity and EJB stateless session bean.
whole project can be found here
https://github.com/muhamed-hassan/service-layer
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence                                  http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="custmgr-pu" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/customerCM_PU</jta-data-source>
        <class>model.Customer</class>
        <properties>
            <property name="eclipselink.target-database" value="MySQL"/>
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
            <property name="eclipselink.logging.level" value="ALL"/>
        </properties>
    </persistence-unit>
</persistence>
I'm getting this kind of exception
`java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName custmgr-pu`

Note that i put persistence.xml file under src/main/resources/META-INF directory, because i'm using a maven ejb project.


text:
Q: Losing EventArgs after Routing of Attached Event WPF/MVVM I am doing MVVM project and I have such problem: after Routing of some Attached Event, I'm losing EventArgs. For RoutingEvent I used this code:
public class RoutedEventTrigger : EventTriggerBase<DependencyObject>
    {
        RoutedEvent _routedEvent;

        public RoutedEvent RoutedEvent
        {
            get { return _routedEvent; }
            set { _routedEvent = value; }
        }

        public RoutedEventTrigger()
        {
        }
        protected override void OnAttached()
        {
            Behavior behavior = base.AssociatedObject as Behavior;
            FrameworkElement associatedElement = base.AssociatedObject as FrameworkElement;

            if (behavior != null)
            {
                associatedElement = ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;
            }
            if (associatedElement == null)
            {
                throw new ArgumentException("Routed Event trigger can only be associated to framework elements");
            }
            if (RoutedEvent != null)
            {
                associatedElement.AddHandler(RoutedEvent, new RoutedEventHandler(this.OnRoutedEvent));
            }
        }
        void OnRoutedEvent(object sender, RoutedEventArgs args)
        {
            base.OnEvent(args);
        }
        protected override string GetEventName()
        {
            return RoutedEvent.Name;
        }
    }

Part from xaml:
<ListView>
  <i:Interaction.Triggers>
    <localP:RoutedEventTrigger RoutedEvent="ScrollViewer.ScrollChanged">
      <cmd:EventToCommand Command="{Binding ScrollCommand}" />
    </localP:RoutedEventTrigger>
  </i:Interaction.Triggers>

My handler in MVVM :
ScrollCommand = new RelayCommand<ScrollChangedEventArgs>(e =>
            {
                MessageBox.Show("HorizontalChange " + e.HorizontalChange");
            });

Handler is invoked, but e is null.
What I'm doing wrong and how can i get that Args?
As mvvm base I using mvvm-light.

A: Hi you should set the PassEventArgsToCommand to true on the EventToCommand.


text:
Q: Save RTP vp8 payload packets to .webm file I have saved a video call to a .pcap file with Wireshark, and I want to acquire the video from RTP packets. RTP packets payload type is vp8, I could find out the vp8 RTP packets by using libpcap library in C++. Then I saved the contents of all RTP vp8 packets to a file. But i can not convert this raw vp8 data to .mp4 by using ffmpeg. ffmpeg gives error during conversion. ffmpeg conversion error : Invalid data found when processing input
What are the steps to get .mp4 or .webm video file from vp8 RTP packets?
Edit :  I could get raw VP8 data excluding VP8 payload descriptor, payload header and keyframe header. Then I added ivf header and frame header for each vp8 raw frame, according to ivf document
IVF Document
But When I want to convert my ivf file (output1) to output1.mp4 by using ffmpeg
ffmpeg -i output1 -c:v vp8 output1.mp4
I get errors

A: JanusGateway is having functionality to convert RTP (VP8/VP9/H264/Opus) to (webm/mp4). It will just encode RTP to corresponding container(webm/mp4/opus), no transcoder is included.
You can use ffmpeg to transcode it to any other format.
In brief, janus will store RTP packets in a file by adding a prefix header in each packet. Then we can use post processor to convert vp8 RTP packets to webm.
https://github.com/meetecho/janus-gateway/blob/master/postprocessing/pp-webm.c
You can see the live demo & Documentation.


text:
Q: ember-cli-mirage response headers are missing from XHR object Trying to understand the inconsistency in the response between using my api vs ember-cli-mirage.
I have a handler waiting for a response for a POST request to authenticate a user. The expected parameters for the handler are response, status and xhr:
(e.g. .then(function(response, status, xhr) {...}).
Using my API I receive what I'd expect- response is the data, status is the statusText and xhr is the xhr object. However using ember-cli-mirage everything comes under response (kind of), and status and xhr are both undefined.
Snippets of my code are below:
mirage/config.js
this.post(URI.AUTH_SIGN_IN, function(db, request) {
  const responseHeaders = {
    'access-token': 'abcxyz123',
    'client': 'foobarbaz',
    'token-type': 'Bearer',
    'expiry': '1497364419',
    'uid': 'user@example.com'
  };

  const user = {
    data: { id: 1, type: 'user', attributes: { uid: 'user@example.com', email: 'user@example.com', name: 'John Doe', provider: 'email' } }
  };

  return new Mirage.Response( 200, responseHeaders, user );
});

authenticators/devise.js
authenticate(identification, password) {
  ...
  this.makeRequest( credentials ).then(function(response, status, xhr) {
    // persists the five headers needed to send to devise-token-auth
    // with mirage; response = Response {type: "default", status: 200, ok: true, statusText: "OK", headers: Headers…}, status = undefined, xhr = undefined
    // with actual api; response = Object {data: Object}, status = "success", xhr = Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function…}

    // As a result below will fail :(
    // TypeError: Cannot read property 'getResponseHeader' of undefined
    var result = {
        'access-token': xhr.getResponseHeader( 'access-token' ),
        expiry:         xhr.getResponseHeader( 'expiry' ),
        tokenType:      xhr.getResponseHeader( 'token-type' ),
        uid:            xhr.getResponseHeader( 'uid' ),
        client:         xhr.getResponseHeader( 'client' )
      };
   });
}

I believe I'm doing it all correctly, but I've been known to be wrong :). Any help is much appreciated.

A: Hm, I'm not sure why makeRequest is returning undefined for the second and third params.
I made a simple Twiddle and the args seem correct for getJSON:
https://ember-twiddle.com/70229e352f37b4e437ced8509a4415d9?openFiles=routes.application.js%2C
model() {
  return Ember.$.getJSON('/foo').then((data, response, object) => {
    return object.getAllResponseHeaders();
  });
}

There may be something slightly different with how Pretender handles the mocked response or iwth how makeRequest works, so I'd suggest to start by looking there.


text:
Q: How to extract top 5 sum values by their top 3 sum reasons please I need to review this query:
=QUERY('BD3'!A:Q, "SELECT D,Q,
SUM(M) WHERE I='W34' AND M>0 AND L='Huacho'
GROUP BY D,Q
ORDER BY SUM(M) DESC LIMIT 5",-1)

I obtain this:

But I need something like this:


text:
Q: Python p value for panda row I am very new on Python. I have a panda dataframe here. It looks like a 2D matrix with 26 columns and 9047943 rows. Let say:
array([[123,234,345],
       [567,543,342],
       [735,276,697]])

This time I want to calculate the correlation coefficient and the p-value for each row. i.e. The correlation coefficient and the p-value for [123,234,345]. Then go to the next row [567,543,342]. I think the answer should look like this T-test in Pandas
I have done lot of research but I cannot find the answer. Any suggestion? Thanks a lot for your help!

A: May be something like this. Let's say your data frame is df and given that all the columns in your df are int/float:
import numpy as np
df.apply(lambda x: np.corrcoef(x), axis=1)


text:
Q: The output does not match with the input (C language) I am making a simple C program that would ask your age and gender. If your gender is not M or F the program will ask for a different input. If your age is less than zero, the program will require for another input. This is my code:
#include<stdio.h>

int main(){

    int a;
    char g;

    entry:
    printf("%s","AGE : ");
    scanf("%d", &a);
    getchar();

    insert:
    printf("%s","GENDER :");
    scanf("%s", &g);
    getchar();

    while (a < 0){
        goto entry;
        }

    switch(g){

        case 'M':{
            printf("I am a %d yr old male", a);break;
        }
        case 'F':{
            printf("I am a %d yr old female", a);break;
        }
        default:{
            goto insert; break;
        }
    }

    return 0;
}

and this is an example of the program running
AGE : 21
GENDER :M
I am a 0 yr old male

A: Altough I detected a weirdness (see the large comment) in code, it outputs as you expected so you can use an approach like this:
#include<stdio.h>
#include<stdbool.h>

int main(){

    int age, a;
    char g;
    bool validInput;

    do {
        validInput = true;

        printf("%s","AGE : ");
        scanf("%d", &age);
        /*
         * If you use directly the 'a' var, somehow it will not print
         * input age. That's why I had to use a = age assignment.
         * This is weird, if someone knows why this happens let me
         * know please.
         */
        a = age;
        if(a < 0) {
            validInput = false;
        }

        printf("%s","GENDER : ");
        scanf("%c", &g);
        getchar();
        if(g != 'M' && g != 'F') {
            validInput &= false;
        }

    } while(!validInput);

    switch(g){

        case 'M':
            printf("I am a %d yr old male\n", a); break;
        case 'F':
            printf("I am a %d yr old female\n", a); break;
        default:
            printf("Oops! Something went wrong...\n");
    }

    return 0;
}


text:
Q: Cannot clone object , as the constructor either does not set I get this runtimeError: Cannot clone object <keras.wrappers.scikit_learn.KerasClassifier object at 0x7f9d95dd50f0>, as the constructor either does not set or modifies parameter batch_size
when executing gridsearch in deep learning Jason Bownlee.
# MLP for Pima Indians Dataset with grid search via sklearnfrom keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
import numpy
# MLP for Pima Indians Dataset with 10-fold cross validation via sklearn
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
import numpy
# MLP for Pima Indians Dataset with 10-fold cross validation via sklearn
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
import numpy
# Function to create model, required for KerasClassifier
def create_model(optimizer= 'rmsprop' , init= 'glorot_uniform'):
    # create model
    model = Sequential()
    model.add(Dense(12, input_dim=8, kernel_initializer= 'uniform' , activation= 'relu' ))
    model.add(Dense(8, kernel_initializer = 'uniform' , activation= 'relu' ))
    model.add(Dense(1, kernel_initializer = 'uniform' , activation= 'sigmoid' ))
    # Compile model
    model.compile(loss= 'binary_crossentropy' , optimizer= 'adam' , metrics=['accuracy'])
    return model
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
from google.colab import drive
drive.mount('/content/drive')
dataset = numpy.loadtxt("/content/drive/My Drive/Colab Notebooks/pima-indians-diabetes.csv", delimiter=",", skiprows=1)
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
model = KerasClassifier(build_fn=create_model, verbose=0)
# grid search epochs, batch size and optimizer
optimizers = [ 'rmsprop' , 'adam']
init = [ 'glorot_uniform' , 'normal' , 'uniform']
epochs = numpy.array([50, 100, 150])
batches = numpy.array([5, 10, 20])
param_grid = dict(optimizer=optimizers, nb_epoch=epochs, batch_size=batches, init=init)
grid = GridSearchCV(estimator=model, param_grid=param_grid)
grid_result = grid.fit(X, Y)
# summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
for params, mean_score, scores in grid_result.grid_scores_:
    print("%f (%f) with: %r" % (scores.mean(), scores.std(), params))

RuntimeError                              Traceback (most recent call last)
....
---> 56 grid_result = grid.fit(X, Y)
RuntimeError: Cannot clone object <keras.wrappers.scikit_learn.KerasClassifier object at 0x7f375a51b2b0>, as the constructor either does not set or modifies parameter nb_epoch

A: I had this exact problem and solved it by changing the numpy.arrays to a list. e.g.
batches = [5, 10, 20]

In summary, use lists (as you have done for optimizers, init etc) and not numpy.array


text:
Q: Material UI position Box element to bottom of parent Hello everyone I have the following structure:
  <Box width="100%" height="100%" p={1}>
       <Box my={1} display="flex" justifyContent="center">

       </Box>
       <Box color="text.disabled">

       </Box>
       <Box mt={3}>
         position at bottom
       </Box>
 </Box>

I am trying to fix the bottom box to the bottom of its parent. So far I have tried:
marginTop: "auto"
bottom: 0
And neither of them work.

A: You could use a position="absolute" box.Here are some good examples: https://www.w3schools.com/css/css_positioning.asp
Important is that the parent box is also positioned. Here is your code expanded:
<Box width="100%" height="100%" p={1} position="relative">
   <Box my={1} display="flex" justifyContent="center">

   </Box>
   <Box color="text.disabled">

   </Box>
   <Box mt={3} position="absolute" bottom="0px">
     position at bottom
   </Box>
</Box>

A: You can do something like this using flexbox.

#container {
  display: flex;
  flex-direction: column;
  height: 500px;
}

#top {
  background-color: salmon;
  min-height: 100px;
}

#middle {
  background-color: lightgreen;
  min-height: 100px;
  flex-grow: 1;
}

#bottom {
  background-color: lightblue;
  min-height: 50px;
}


text:
Q: Minimal polynomial and field extensions I know that, in general, for field  extensions $F(\alpha)$ and $F(\beta)$ of a field $F$ with the minimal polynomial of $\alpha$ over $F$ equal to that of $\beta$, it is not necessarily true that $F(\alpha)=F(\beta)$.
Now I was wondering, are there certain extra conditions on $F$ for which this statement would hold?
More specifically, is this, for example, true if $F=\mathbb{Q}$ or does the statement depend on $\alpha$ and $\beta$?


text:
Q: Algorithm for best fit rectangle I'm looking for an algorithm to do a best fit of an arbitrary rectangle to an unordered set of points.   Specifically, I'm looking for a rectangle where the sum of the distances of the points to any one of the rectangle edges is minimised.  I've found plenty of best fit line, circle and ellipse algorithms, but none for a rectangle.  Ideally, I'd like something in C, C++ or Java, but not really that fussy on the language.
The input data will typically be comprised of most points lying on or close to the rectangle, with a few outliers.  The distribution of data will be uneven, and unlikely to include all four corners.

A: Here are some ideas that might help you.
We can estimate if a point is on an edge or on a corner as follows:

*

*Collect the point's n neares neighbours

*Calculate the points' centroid

*Calculate the points' covariance matrix as follows:

*

*Start with Covariance = ((0, 0), (0, 0))

*For each point calculate d = point - centroid

*Covariance += outer_product(d, d)

*Calculate the covariance's eigenvalues. (e.g. with SVD)

*Classify point:

*

*if one eigenvalue is large and the other very small, we are probably on an edge

*otherwise we should be on a corner

Extract all corner points and do a segmentation. Choose the four segments with most entries. The centroid of those segments are candidates for the rectangle's corners.
Calculate the normalized direction vectors of two opposite sides and calculate their mean. Calculate the mean of the other two opposite sides. These are the direction vectors of a parallelogram. If you want a rectangle, calculate a perpendicular vector to one of those directions and calculate the mean with the other direction vector. Then the rectangle's direction's are the mean vector and a perpendicular vector.
In order to calculate the corners, you can project the candidates on their directions and move them so that they form the corners of a rectangle.

A: Here's a general idea. Make a grid with smallish cells; calculate best fit line for each not-too-empty cell (the calculation is immediate1, there's no search involved). Join adjacent cells while making sure the standard deviation is improving/not worsening much. Thus we detect the four sides and the four corners, and divide our points into four groups, each belonging to one of the four sides.
Next, we throw away the corner cells, put the true rectangle in place of the four approximate
 lines and do a bit of hill climbing (or whatever). The calculation of best fit line may be augmented for this case, since the two lines are parallel, and we've already separated our points into the four groups (for a given rectangle, we know the delta-y between the two opposing sides (taking horizontal-ish sides for a moment), so we just add this delta-y to the ys of the lower group of points and make the calculation).
The initial rectangular grid may be replaced with working by stripes (say, vertical). Then, at least half of the stripes will have two pronounced groupings of points (find them by dividing each stripe by horizontal division lines into cells).

1For a line Y = a*X+b, minimize the sum of squares of perpendicular distances of data points {xi,yi} to that line. This is directly solvable for a and b. For more vertical lines, flip the Xs and the Ys.
P.S. I interpret the problem as minimizing the sum of squares of perpendicular distances of each point to its nearest side of the rectangle, not to all the rectangle's sides.

A: The idea of a line of best fit is to compute the vertical distances between your points and the line y=ax+b.  Then you can use calculus to find the values of a and b that minimize the sum of the squares of the distances.  The reason squaring is chosen over absolute value is because the former is differentiable at 0.
If you were to try the same approach with a rectangle, you would run into the problem that the square of the distance to the side of a rectangle is a piecewise defined function with 8 different pieces and is not differentiable when the pieces meet up inside the rectangle.

In order to proceed, you'll need to decide on a function that measures how far a point is from a rectangle that is everywhere differentiable.

A: I am not completely sure, but You might play around first 2 (3?) dimensions over the PCA  from your points. it will work reasonably fast for the most cases.


text:
Q: Swap two fonts in all styles in Microsoft Word? In a sample document, there are a bunch of styles (in Garamond) based on Plain Text (Courier). I would like to change those styles to another font (Georgia, for example).
Since the styles in question are in Garamond but all based on Courier (from Plain Text) i would guess that each of the styles has had their fonts changed individually. Which makes me think i have to change each to the new font individually.
But... that can't be the only way to do this, right? There must be a way to make a wholesale font change to a group of styles like this. Or is there maybe something missing from my picture of how styles work.
If it matters, i'm using Word 2007.
Edit: I am not asking about replacing fonts with Control-H, unless you have a way to subsequently apply those changes to the affected styles.
Preferably the solution would be one that i could later explain to less-technical users how to do the same. So while the VBA solution might solve the problem for me this time, it is limited to script-savvy users.

A: To wholesale replace fonts in Word :

*

*Open the Replace dialog

*Click inside the "Find what" field
(but don't type any search string)

*Click on the More button

*Click on the Format button and choose Font

*Choose your font name (you may also set style and size for finer control)

*Click OK

*Click inside Replace with (but don't type any search string)

*Repeat the process for choosing the replacement font

*Click Find Next plus Replace or click Replace All, to execute the replacement.

A: I think the only way of redefining propeties of a large set of styles in one go would be to automate using VBA.
What I would do here instead is redefine an underlying style (probably Normal rather than Plain Text, as Normal is the default for new text in a blank document) with the base properties of your document's text (language, Garamond font, size, line spacing and perhaps paragraph spacing) and change the other styles to be based on that.
This will give you more maintainable set of styles in the longer run.
If all your headings are going to be a different font, say Helvetica, you might want to set say Heading 6 as that font and base all other headings on that, but I don't think there's much need to use a much more complex model of 'inheritance'.

A: If the inheritance from one style to another has been overridden explicitly with a different font in each one, you are stuck with changing it back in each one.
However, if this is a .dotx template, you could do this with some find-and-replace in the xml of the file which will probably be quicker than figuring out a way to do this with VBA.
Best book for any of this kind of work when busting open the 2007 file formats is Advanced Office Documents 2007 edition by Stephanie Krieger
Aside: while it won't help reduce the effort this time round, the 'right' way to change these will be to choose or create a theme font set, with your chosen font for headings and for body text. Then in your styles choose 'Georgia (Headings)" or "Comic Sans (Body)" rather than the font face by itself. For lower-level styles base them on a previous one ideally (eg Heading 2 from Heading 1). Selecting the 'theme' fonts rather than explicit choices means that future changes are made far simpler by just changing the font set.
PS: please please please don't use Comic Sans for your body text.


text:
Q: Create Multiple Child Records from Parent Record I have two custom objects: Parent (Parent__c) and Child (Child__c). The goal here is for the user to click a button on the Child Related List and enter data in input fields to create new Child records.
Here's my code:
Controller:
public class AddingChildController {
Id parentId;
public List<Child__c> childList {get;set;}
public Integer rowNum{get;set;}

public AddingChildController(){
    Id childId = ApexPages.currentPage().getParameters().get('childId');
    childList = new List<Child__c>();
    childList.add(new Child__c());
}

public void insertChild(){
    insert childList;
}

public void insertRow(){
    childList.add(new Child__c());
}

public void delRow(){
    rowNum =
Integer.valueof(apexpages.currentpage().getparameters().get('index'));
    childList.remove(rowNum);
}
}

Visualforce Page:
<apex:page controller="AddingChildController" >
<apex:form >
    <apex:variable var="rowNum" value="{!0}" />
    <apex:pageBlock >
        <apex:variable var="rowNum" value="{!0}" />
        <apex:PageBlockTable value="{!childList}" var="int">
        <apex:facet name="footer">
            <apex:commandLink value="Add" action="{!insertRow}"/>
            </apex:facet>
            <apex:column headerValue="Name">
                <apex:inputField value="{!int.Name}"/>
            </apex:column>
            <apex:column headerValue="Age">
            <apex:inputField value="{!int.Age__c}"/>
            </apex:column>
             <apex:column headerValue="Delete">
            <apex:commandLink style="font-size:15px; font-weight:bold; text-align:center;color:red;" value="X" action="{!delRow}">
                <apex:param value="{!rowNum}" name="index"/>
                </apex:commandLink>
                <apex:variable var="rowNum" value="{!rowNum+1}"/>
            </apex:column>
        </apex:PageBlockTable>
    <apex:pageBlockButtons >
        <apex:commandButton value="Save" action="{!insertChild}"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>

  </apex:form>
</apex:page>

I've created the button and I can see the Visualforce page, but when I got to save the records, I get the following error:

Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]
  Error is in expression '{!insertChild}' in component  in page addchildrenvfpage: Class.AddingChildController.insertChild: line 14, column 1

Any suggestions on how to fix this?
*NEW VERSION**
 public class AddingChildController {
 Id parentId;
 public List<Child__c> childList {get;set;}
 public Integer rowNum{get;set;}

public AddingChildController(){
Id parentId = ApexPages.currentPage().getParameters().get('parentId');
childList = new List<Child__c>();
childList.add(new Child__c(Parent__c = parentId));
   }

public void insertChild(){
    insert childList;
   }

public void insertRow(){
   childList.add(new Child__c(Parent__c = parentId));
    }

public void delRow(){
rowNum =
Integer.valueof(apexpages.currentpage().getparameters().get('index'));
    childList.remove(rowNum);
    }
   }

A: It looks like your objects are in a master-detail relationship, so the child cannot be created without a parent. In your constructor, as you create your child objects, you're not populating that parent lookup:
public AddingChildController(){
    Id childId = ApexPages.currentPage().getParameters().get('childId');
    childList = new List<Child__c>();
    childList.add(new Child__c());
}

There should be a line in here like
    childList.add(new Child__c(Parent__c = parentId));

In order to do that, you have to have the parent's Id. If your page is designed to take the Id of the parent object in the childId URL parameter, you'd use that value.
A similar change would need to be made to insertRow().
Working Minimal Example
I used the Account and Contact sObjects as an example and stripped this down to the essential functionality. I'm able to insert new child records with this page and controller.
Visualforce Page
<apex:page controller="TestQ232413Controller" >
    <apex:form >
        <apex:pageBlock >
            <apex:PageBlockTable value="{!childList}" var="int">
                <apex:facet name="footer">
                    <apex:commandLink value="Add" action="{!insertRow}"/>
                </apex:facet>
                <apex:column headerValue="FN">
                    <apex:inputField value="{!int.FirstName}"/>
                </apex:column>
                <apex:column headerValue="LN">
                    <apex:inputField value="{!int.LastName}"/>
                </apex:column>
            </apex:PageBlockTable>
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!insertChild}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>

    </apex:form>
</apex:page>

Controller
public class TestQ232413Controller {
    Id parentId;
    public List<Contact> childList {get;set;}

    public TestQ232413Controller(){
        Id parentId = ApexPages.currentPage().getParameters().get('parentId');
        childList = new List<Contact>();
        childList.add(new Contact(AccountId = parentId));
    }

    public void insertChild(){
        insert childList;
    }

    public void insertRow(){
        childList.add(new Contact(AccountId = parentId));
    }
}

List Button on Contact
Content Source: URL, /apex/TestQ232413?parentId={!Account.Id}


text:
Q: React JS + REDUX + JWT Authentication JSON issue I have tried a lot to get this done but i dont know why the json is not printing on the DIV tag
I am getting a user1 is undefined
i am using my own api to fetch data which is populate in users.

{ success: true, user: "Normal User" }

JSON is as above
got the authorized token and logged in with it successfully but when i get the JSOn i cant show the user in the HTML page
please help!
Thanks in advance
this is my HomePage.jsx
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

import { userActions } from '../_actions';

class HomePage extends React.Component {
    componentDidMount() {
        this.props.dispatch(userActions.getAll());
    }
    render() {
        var { user, users1 } = this.props;
        console.log(user); // token
        console.log(users1); // json with names and all
        return (

Hi {users1.user} !

                    <Link to="/login">Logout</Link>

        );
    }
}

function mapStateToProps(state) {
    const { users, authentication } = state;
    const { user } = authentication;
    // var users1 = {"success":true,"user":"Normal User"}
    var users1 = users.users
    return {
        user,
        users1
    };
}

const connectedHomePage = connect(mapStateToProps)(HomePage);
export { connectedHomePage as HomePage };```

A: Looks like you didn't parse JSON after the fetch and users1 in your case is a string. Try JSON.parse(users1).


text:
Q: CodeIgniter Validation: possible to validate GET query strings? The form validation library seems to only work on POST. I need to use query strings and would like to use CI to validate the passed values. Is there a way to do this?

A: See this page for the CodeIgniter 3 solution:-
http://www.codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post
For CodeIgniter 2 you can do $_POST = $_GET; before $this->form_validation->run() as mentioned above.

A: The current Codeigniter 3.0 development branch provides an option to insert your own variable instead of $_POST. So you could start using 3.0.
Alternatively, the only way in CI2.1 is to do $_POST=$_GET before you run the validation.

A: You could overwrite the Form_validation function run in a MY_Form_Validation and modify it.

A: Reference How do I validate a form field in Codeigniter when using Get parameters?
Before validation rules, set the validation data with the following code.
 $this->form_validation->set_data($_GET);


text:
Q: How to select which PowerPoint to edit in Excel VBA? I am building a report where users will take tables from Excel and paste them into a PowerPoint.  Since I won't know what the users will name the PowerPoint, I am giving them two options.  If the one they want is not open, they will open it.  What I am having trouble is if the one they want is already open, how can I have them select it?  This is what I have so far:
Dim ans As Integer
Dim pptName As String
Dim ppt As PowerPoint.Application
Dim myPres As PowerPoint.Presentation
Dim arr() As String
Dim j As Variant

ans = MsgBox("Is the PowerPoint already open?", vbYesNo + vbQuestion)

If ans = vbYes Then
    For Each myPres in ppt.Presentations
        Redim Preserve arr(j)
        arr(j) = myPres.Name
        j = j + 1
    Next

    'How to use the names of all the current ppts in the array and let a user select which one from that list
    Set myPres = ppt.Presentations(1)
Else
    MsgBox ("Please choose PowerPoint to open.")
    'openDialog is a function I have already created
    pptName = openDialog()
    Set myPres = ppt.Presentations.Open(pptName)
End If

Any suggestions would be greatly appreciated!

A: It's a little long, But I've included the code in the regular Module, and also the User_Form.
Code Module
Option Explicit

Public PPTFileName As String  '<-- defined as Public, will get it from the User_Form's ListBox

Sub SelectPPTPresentation()

' === this loop through all open PowerPoint Presentations is using Late Binding
' === to avoid future problems when working with multiple Office Versions

Dim ppApp                               As Object
Dim ppPres                              As Object
Dim ObjPres                             As Object

If MsgBox("Is the PowerPoint already open?", vbYesNo + vbQuestion) = vbYes Then
    On Error Resume Next
    Set ppApp = GetObject(, "PowerPoint.Application")
    On Error GoTo 0

    If ppApp Is Nothing Then
        MsgBox "No PowerPoint is open!"
    Else
        If ppApp.Presentations.Count > 0 Then ' check that at least 1 Presentation is open
            For Each ObjPres In ppApp.Presentations ' loop through all open presnetations (
                UserForm1.OpenPPPres_LB.AddItem ObjPres.FullName '<-- add their full names to the User_Form ListBox
            Next ObjPres
        End If
    End If
    UserForm1.Show '<-- show the User_Form with the ListBox of all open PPT presentations

    ' loop through all open presnetations (check Full Name: Path and name)
    For Each ObjPres In ppApp.Presentations
        If StrComp(ObjPres.FullName, PPTFileName, vbTextCompare) = 0 Then
            Set ppPres = ObjPres  ' <-- set the current PPT pres to the selected Item from the ListBox
            Exit For
        End If
    Next ObjPres
    MsgBox "Selected Presentation is " & ppPres.Name ' <-- just for confirmation >> show Name (without Path)

Else  ' <-- you will need to modify this section to fit the upper section

'    MsgBox ("Please choose PowerPoint to open.")
'    'openDialog is a function I have already created
'    pptName = openDialog()
'    Set myPres = ppt.Presentations.Open(pptName)
'
End If

End Sub

User_Form Code the event is under the "OpenPPPres_LB" ListBox DblClick event:
Private Sub OpenPPPres_LB_DblClick(ByVal Cancel As MSForms.ReturnBoolean)

Dim i           As Long

For i = 0 To OpenPPPres_LB.ListCount - 1
    If OpenPPPres_LB.Selected(i) Then
        PPTFileName = OpenPPPres_LB.List(i) ' <-- save the PPT filename
        Exit For
    End If
Next i

Unload UserForm1

End Sub

Screen-shot of the User_Form populated with the current Open Presentations:


text:
Q: Is there a way to make a multiset? Is there a way to create a multiset in python? I have my set here:
{'a', 'u', 'i', 'o', 'e'} but I would like to have repeated characters, but still unorganised. Thanks

A: This is not possible in python since a set in python is by definition meant to be unique.
You can however install external packages to implement a multiset:
pip install multiset

A: Sure, you can use:
from multiset import *
vowels_set = Multiset('auioe')

"A multiset is similar to the builtin set, but it allows an element to occur multiple times. It is an unordered collection of elements which have to be hashable just like in a set. It supports the same methods and operations as set does, e.g. membership test, union, intersection, and (symmetric) difference. Multisets can be used in combination with regular sets for those operations." - https://multiset.readthedocs.io/en/stable/

A: The multiset library suggested here is fine - just to add a standard-library alternative, you can also use the Counter object from the collections library. You have to watch out as a Counter CAN have negative counts, which is not valid for a multiset; however there are set operations provided which will only ever produce positive counts and basically act like multisets. Counters return a count of zero for items not in the set, and let you check for set membership with the in operator, as you'd expect.
For anyone wondering about dictionaries vs lists vs sets...
A multiset is conceptually similar to a dictionary. That is, a multiset is equivalent to a dictionary whose keys are set items and values are counts of how many of that item are in the set. Using a simple dictionary is a bit awkward though - you have to make sure counts aren't allowed to drop to negative numbers, you have to check if a key is in the dictionary before you check its count, etc. And there are no set operations like union and intersection, or addition and subtraction.
A list can store multiple copies of an element, but removing an element from it involves searching through the whole list, which is inefficient. Convenient set operations also aren't available for lists (except addition).

A: It sounds like you want a list:
vowels = ['a','u','a','i','o','e']

A list can take repeated characters and is unordered.
This is the doc page for lists if you want to find out more


text:
Q: Python type comparison table PHP has 'PHP type comparison tables' is there anything like that for Python?

A: Yes, here (also included image below):
http://imgur.com/3rOmPD0
From https://twitter.com/ngkabra/status/449904315012878337

A: Python is strongly typed; such a table is not required except between basic numeric types and basic string types. For numeric types, they are coerced to long (in 2.x) or float as required. For string types, things are not as simple and so unicode (in 2.x) should be used where possible.
>>> 3 > 2.4
True
>>> 'a' < u'あ'
True
>>> u'a' < 'あ'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)

Comparison across incompatible types in 2.x will not act as you expect.
>>> 2 < '3'
True
>>> 3 < '2'
True

Comparison across incompatible types in 3.x will fail.
3>> 2 < '3'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()


text:
Q: how to calculate quota with analytic function row by row? We have a problem with using analytic function in Oracle.
We want to calculate remaining_quota column from other columns. Our data is grouped by branch_id and region_id. Each branch and region has a quota value(In example 1077).
If quota value is larger than remaining_quota value, we doesn't change remaining_quota value.
I hope following example has been descriptive.

We created a query to calculate remaining_quota with sum over partition by functions but we failed.
Sample query and result
SELECT   CUSTOMER_NUM, BRANCH_ID, REGION_ID, TOTAL_QUOTA, QUOTA,
                 TOTAL_QUOTA -
                 SUM (CASE
                           WHEN TOTAL_QUOTA - QUOTA < 0
                              THEN 0
                           ELSE QUOTA
                        END) OVER (PARTITION BY BRANCH_ID, REGION_ID ORDER BY BRANCH_ID,
                    REGION_ID,DESC)
                     AS REMAINING_QUOTA
            FROM MY_TABLE
           WHERE BRANCH_ID = 723 AND REGION_ID = 822
        ORDER BY BRANCH_ID,
                 REGION_ID DESC

Please help us to deal with this problem.
Thanks...

IMPROVE :

In fact, I discarded some columns from table because of decreasing query complexity.
Our test table has these columns.
  CUSTOMER_NUM        NUMBER,
  BRANCH_ID           NUMBER,
  ACCOUNT_NUM         NUMBER,
  TOTAL_QUOTA         NUMBER,
  QUOTA               NUMBER,
  REGION_ID           NUMBER,
  LOB_CODE            NUMBER,
  ESTIMATED_END_DATE  DATE,
  TOTAL_AMOUNT        NUMBER

We create data structure of this table in SQLFiddle. Link : http://sqlfiddle.com/#!4/94fe4/1/0
My original fail query is :
SELECT   CUSTOMER_NUM, BRANCH_ID, REGION_ID,LOB_CODE,ESTIMATED_END_DATE,TOTAL_AMOUNT, TOTAL_QUOTA, QUOTA,
                 TOTAL_QUOTA -
                 SUM (CASE
                           WHEN TOTAL_QUOTA - QUOTA < 0
                              THEN 0
                           ELSE QUOTA
                        END) OVER (PARTITION BY BRANCH_ID, REGION_ID, LOB_CODE ORDER BY BRANCH_ID,
                    REGION_ID,
                    LOB_CODE,
                    ESTIMATED_END_DATE,
                    TOTAL_AMOUNT DESC)
                     AS REMAINING_QUOTA
            FROM TEST_TABLE
           WHERE BRANCH_ID = 723 AND REGION_ID = 822
                 AND LOB_CODE = 934
        ORDER BY BRANCH_ID,
                 REGION_ID,
                 LOB_CODE,
                 ESTIMATED_END_DATE,
                 TOTAL_AMOUNT DESC

I modified your solution query which includes GREATEST function. But it is not enough for us. With this function if remaining quota is negative you set this value to zero. However, if remaining quota is negative, we don't want to decrease quota value. This value must remain as same.
We want to get a result like the following query: (We add "or QUOTA between 471 and 472" row for right result. There is not a row in this way actually  )
SELECT   CUSTOMER_NUM, BRANCH_ID, REGION_ID,LOB_CODE,ESTIMATED_END_DATE,TOTAL_AMOUNT, TOTAL_QUOTA, QUOTA,
                 TOTAL_QUOTA -
                 SUM (CASE
                           WHEN TOTAL_QUOTA - QUOTA < 0
                      or QUOTA between 471 and 472
                              THEN 0
                           ELSE QUOTA
                        END) OVER (PARTITION BY BRANCH_ID, REGION_ID, LOB_CODE ORDER BY BRANCH_ID,
                    REGION_ID,
                    LOB_CODE,
                    ESTIMATED_END_DATE,
                    TOTAL_AMOUNT DESC)
                     AS REMAINING_QUOTA
            FROM TEST_TABLE
           WHERE BRANCH_ID = 723 AND REGION_ID = 822
                 AND LOB_CODE = 934
        ORDER BY BRANCH_ID,
                 REGION_ID,
                 LOB_CODE,
                 ESTIMATED_END_DATE,
                 TOTAL_AMOUNT DESC

A: It seems like the basic query is:
SELECT CUSTOMER_NUM, BRANCH_ID, REGION_ID, TOTAL_QUOTA, QUOTA,
       TOTAL_QUOTA - SUM(QUOTA) OVER (PARTITION BY BRANCH_ID, REGION_ID
                                      ORDER BY BRANCH_ID, REGION_ID DESC
                                     ) AS REMAINING_QUOTA
FROM MY_TABLE
WHERE BRANCH_ID = 723 AND REGION_ID = 822
ORDER BY BRANCH_ID, REGION_ID DESC;

Let me note that the order by clauses are not stable, because there are duplicates.  It would be nice to have some other column, such as an id or datetime value that would really make the ordering consistent.
Your seem to be concerned about negative remaining quotas.  Handle that after the calculation. Just use the greatest()function:
SELECT CUSTOMER_NUM, BRANCH_ID, REGION_ID, TOTAL_QUOTA, QUOTA,
       GREATEST(0,
                TOTAL_QUOTA - SUM(QUOTA) OVER (PARTITION BY BRANCH_ID, REGION_ID
                                               ORDER BY BRANCH_ID, REGION_ID DESC
                                              )
               ) AS REMAINING_QUOTA
FROM MY_TABLE
WHERE BRANCH_ID = 723 AND REGION_ID = 822
ORDER BY BRANCH_ID, REGION_ID DESC;


text:
Q: Como faço para para printar de Lado usando end=" " com o Módulo Time incluido import time
for i in range(0,10,+1):
    print(".", end="")
    time.sleep(1)

Quero saber como faço para printar os . de lado ex: ...
Durante esse tempo de 1 segundo... quando não uso o end ele funciona mas
printando para baixo.

A: Para continuar a impressão na mesma linha a medida que ela acontece,
além de mudar o caractere de final de linha com o parâmetro end, é necessário passar também o parâmetro flush=True para sincronizar o arquivo sem que o final de linha esteja presente:
import time
for i in range(0,10,+1):
    print(".", end="", flush=True)
    time.sleep(1)


text:
Q: Connecting Flask To AWS RDS using Flask-SQLAlchemy I have been trying to connect my aws RDS database instance to a flask application I have downloaded. I have been following  https://medium.com/@rodkey/deploying-a-flask-application-on-aws-a72daba6bb80 and using the flask app on this github to connect to the database https://github.com/inkjet/flask-aws-tutorial. I have set the permissions on my RDS server correctly and have been using the following code to connect to the DB.
# edit the URI below to add your RDS password and your AWS URL
# The other elements are the same as used in the tutorial
# format: (user):(password)@(db_identifier).amazonaws.com:3306/(db_name)

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{userName}:{password}@{endpoint}:3306/{dbName}'

# Uncomment the line below if you want to work with a local DB
#SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'

SQLALCHEMY_POOL_RECYCLE = 3600

WTF_CSRF_ENABLED = True

I am still receiving a timeout error:
    {path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:834: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Traceback (most recent call last):
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 583, in connect
    **kwargs)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 728, in create_connection
    raise err
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 716, in create_connection
    sock.connect(sa)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect
    return fn()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect
    return _ConnectionFairy._checkout(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout
    rec = pool._do_get()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get
    self._dec_overflow()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get
    return self._create_connection()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection
    return _ConnectionRecord(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__
    self.__connect(first_connect_check=True)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect
    connection = pool._invoke_creator(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
    return dialect.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "db_create.py", line 4, in <module>
    db.create_all()
  File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/sql/schema.py", line 4465, in create_all
    ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2103, in _run_visitor
    with self._optional_conn_ctx_manager(connection) as conn:
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2095, in _optional_conn_ctx_manager
    with self._contextual_connect() as conn:
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2311, in _contextual_connect
    self._wrap_pool_connect(self.pool.connect, None),
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2349, in _wrap_pool_connect
    e, dialect, self
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1591, in _handle_dbapi_exception_noconnection
    sqlalchemy_exception, with_traceback=exc_info[2], from_=e
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect
    return fn()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect
    return _ConnectionFairy._checkout(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout
    rec = pool._do_get()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get
    self._dec_overflow()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get
    return self._create_connection()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection
    return _ConnectionRecord(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__
    self.__connect(first_connect_check=True)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect
    connection = pool._invoke_creator(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
    return dialect.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect
    raise exc
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)")
(Background on this error at: http://sqlalche.me/e/e3q8

If any more information is needed, please let me know!

A: Based on the comments, the issue was that RDS's  public accessibility setting was not enabled.
The solution was to enable it.


text:
Q: How i can use `WHERE` on `JOIN`? I have this sql code
SELECT sites.id, sites.url, GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories
        FROM sites
        LEFT JOIN categories_data ON sites.id = categories_data.sites_id WHERE categories_data.deleted=0
        LEFT JOIN categories ON categories_data.categories_id = categories.id WHERE categories.deleted=0
        WHERE sites.deleted=0 GROUP BY sites.id'

Where return this error
Database_Exception [ 1064 ]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN categories ON categories_data.categories_id = categories.id WHERE cate' at line 4 [ SELECT sites.id, sites.url, GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories FROM sites LEFT JOIN categories_data ON sites.id = categories_data.sites_id WHERE categories_data.deleted=0 LEFT JOIN categories ON categories_data.categories_id = categories.id WHERE categories.deleted=0 WHERE sites.deleted=0 GROUP BY sites.id ]

So, how i can use WHERE on JOIN?
Thank.

A: you cannot add WHERE clause on the ON clause of the joint tables. Separate them with conditional operator (AND/OR),
SELECT sites.id,
       sites.url,
       Group_concat(categories.name, '|', categories.color SEPARATOR ',') AS
       categories
FROM   sites
       LEFT JOIN categories_data
              ON sites.id = categories_data.sites_id
                 AND categories_data.deleted = 0                  -- <<== HERE
       LEFT JOIN categories
              ON categories_data.categories_id = categories.id
                 AND categories.deleted = 0                       -- <<== HERE
WHERE  sites.deleted = 0
GROUP  BY sites.id

To further gain more knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins

A: Just use AND
SELECT sites.id, sites.url, GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories
        FROM sites
        LEFT JOIN categories_data ON sites.id = categories_data.sites_id AND categories_data.deleted=0
        LEFT JOIN categories ON categories_data.categories_id = categories.id AND categories.deleted=0
        WHERE sites.deleted=0 GROUP BY sites.id'

A: I think it was mentioned above, but alternatively you could specify all of these filters in the WHERE statements. This is what it might look like.
    SELECT sites.id, sites.url,
    GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories

    FROM sites
     LEFT JOIN categories_data ON sites.id = categories_data.sites_id
     LEFT JOIN categories ON categories_data.categories_id = categories.id

    WHERE
     sites.deleted=0
     and categories_data.deleted=0
     and categories.deleted=0

    GROUP BY sites.id'

When you've got errors, it might help to try the query in a very standard format before optimizing for speed and load.
SELECT...FROM...WHERE...GROUP BY etc.


text:
Q: Magento whitescreening when data model load called I've set up my config.xml and my controller, my data model class and resource class and I can see that the classes are loading and can echo out the object and NULL data object information.
However, when I try to call the ->load method of the data model object, I get the whitescreen of death.  I've double checked and triple checked my config.xml and I'm not sure what I'm doing wrong or what to look for next...can anyone help?
Thanks!
Kristina

A: PHP never errors out without telling you why, it's just a matter of finding the right log.
First, check your Magento exception log
var/log/exception.log

Second, check your PHP Error log.  If you're not sure where the that, run phpinfo() from a blank file on your server and look for the
error_log

variable.  If this isn't set, set it via the ini_set function, or by changing your php.ini file.
If you leave error_log unset, PHP will send logs to the "SAPI error logger", which is a fancy way of saying your apache error log.
Finally, although it won't help with all white screen cases, try turning developer mode on.  There's the following line in index.php
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    Mage::setIsDeveloperMode(true);
}

So either set MAGE_IS_DEVELOPER_MODE in your .htaccess file, or just comment out the conditional.  This will turn off the default error reporting and output exceptions/errors/warnings/etc to the browser.


text:
Q: Accessing React Elements (not components) for re-rendering The code looks something like this:
renderComponents : function (overlay) {
    var rtnOne = this.renderOne ('a'); // returns React Components
    var rtnTwo = this.renderTwo ('b'); // returns React Components
    var rtnThr = this.renderThr ('c'); // returns React Components

    ReactDOM.render (
        React.createElement ('div',
            {className : 'bigMama'},
            rtnThr,
            React.createElement ('div',
                {className : 'littleMama'},
                rtnOne,
                rtnTwo
            )
        ),overlay)
    );
},

Now my thinking is that when I update a component through rtnOne (), I have a function which does this. As you probably notice, I am appending the component to the element in DOM through its class, which is clearly wrong.
updateRtnOne : function (a) {
    var rtnOne : renderOne (a);  // returns updated React Components
    ReactDOM.render (rtnOne,,document.getElementsByClassName ('littleMama')[0];
    )
}

How can I store a ref to React

 so that I can pass the updated components from 'rtnOne ()' into it.
From my understanding, I cannot attach ref to basic React div elements (which are not components). How can I 'get' the

 so I can append the component to it?
Thanks


text:
Q: codeigniter database where or_where clause solution i dont know the codeigniter db translate of this sql query
select * from table
where a=1 and (b=1 or c=1 or d=1)

$this->db->where $this->db->or_where ?!?!

someone give me an help ?
thanks a lot
best regards

A: I think this is the query you are looking for.
$query = $this->db->select("*")
         ->from("table")
         ->where("a", 1)
         ->group_start()
                    ->where("B", 1)
                    ->or_where('c', 1)
          ->group_end()
          ->get()
          ->result_array();

var_dump($query);

A: If you reed the doc
you can see that if you use or_where you will make a query like
$this->db->where('name !=', $name);
$this->db->or_where('id >', $id);

// Produces: WHERE name != 'Joe' OR id > 50

A: Use this code.
$this->db->select('*');
$this->db->where('a', 1);
$this->db->or_where('b', 1);
$this->db->or_where('c', 1);
$this->db->or_where('d', 1);


text:
Q: First file loaded in cakephp I'm preparing for an interview and i'm new to cakephp, while searching in the internet i came across this questions...
"What is the first file that gets loaded when you run a application using cakephp?"
Answer: Interviewer : what is the first file that gets loaded when you run a application using cakephp.,
Candidate : can you change that file.
Interviewer: yes
bootstrap.php , yes it can be changed , either through index.php , or through htaccess
Which file is loaded first, if that particular file is not changable.
I tried to find out the answer, but couldn't get it.
Can any one help me on this please?

A: The very first file being loaded is index.php (as per the .htaccess rewrite rules) in the webroot folder, which will add CakePHP's core in the include path
CakePHP 1.3
if (!defined('CORE_PATH')) {
        if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
            define('APP_PATH', null);
            define('CORE_PATH', null);
        } else {
            define('APP_PATH', ROOT . DS . APP_DIR . DS);
            define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
        }
    }
    if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
        trigger_error("CakePHP core could not be found.  Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php.  It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
    }

CakePHP 2.1
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
        if (function_exists('ini_set')) {
            ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path'));
        }
        if (!include('Cake' . DS . 'bootstrap.php')) {
            $failed = true;
        }
    } else {
        if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) {
            $failed = true;
        }
    }

It then includes bootstrap.php in both case.
So the answer is : index.php and you shall not modify it (unless you are in some particular cases), then app/Config/bootstrap.php and you may modify it.

A: This might be helpful:
As of cake 2.6 here is the order of config files to be loaded
core.php
database.php
bootstrap.php
routes.php


text:
Q: why IdentityHashMap uses linear probing for collision resolution As we know in java collections framework every class in Map uses Chaining for collision resolution but IdentityHashMap uses linear probing for the same.
If you see the java docs, it has mentioned:

For many JRE implementations and operation mixes, this class will
  yield better performance than HashMap (which uses chaining rather than
  linear-probing).

My questions are:

*

*why the implementors have used liner probing only for IdentityHashMap instead of all the Map implementations if performance is better in linear probing

*Why there is a performance gain in linear Probing then chaining.
Tanks.

A: This may shed some light (taken from the Oracle website):

Implementation note: This is a simple linear-probe hash table, as described for example in texts by Sedgewick and Knuth. The array alternates holding keys and values. (This has better locality for large tables than does using separate arrays.) For many JRE implementations and operation mixes, this class will yield better performance than HashMap (which uses chaining rather than linear-probing).

Although chaining may be better for most implementations, it is not so for every implementation.
EDIT Also found this, perhaps it's less trivial (taken from here):

The motivation for using probing is that it is somewhat faster than following a linked list, but that is only true when a reference to the value can be placed directly in the array. That isn't practical for all other hash-based collections, because they store the hash code as well as the value. This is for reasons of efficiency: a get operation must check whether it has found the right key, and since equality is an expensive operation, it makes sense to check first whether it even has the right hash code. Of course, this reasoning doesn't apply to IdentityHashMap, which checks object identity rather than object equality.

As background/clarification, an IdentityHashMap differs from an ordinary HashMap in that two keys are considered equal only if they are physically the same object: identity, rather than equals, is used for key comparison.
EDIT: discussion that helps in finding the answer (from comments below):
Trying:

but that is only true when a reference to the value can be placed directly in the array. That isn't practical for all other hash-based collections, because they store the hash code as well as the value. I have a doubt that why can't hashMap put the key, value and hash code in the array and use linear probing if linked list traversal is more costly then direct array?

wlyles:

likely because of space usage. That would take up more data in each slot. And I should point out that, while traversal is less costly for linear probing, the total find operation could be more costly (and less predictable) because linear probing is often plagued by clustering, where many keys have the same hash value. As said by @delnan in another comment, For example, if keys 1..20 hash to consecutive slots, and the 21st hashes to the same slot as the 1st, lookup for it (or for a not-present key that hashes to the 1st slot) needs 20 probes. Using a list would take fewer probes. For further clarification: because of the way that IdentityHashMap compares key values, the chance of collisions is very small. Thus, the main weakness of linear probing - collisions that lead to clumping - is largely avoided, making it more desirable in this implementation.
For further clarification: because of the way that IdentityHashMap compares key values, the chance of collisions is very small. Thus, the main weakness of linear probing - collisions that lead to clumping - is largely avoided, making it more desirable in this implementation

A: When you build an identity hash map, there is no chance of finding two instances that are equal to each other yet are not the same object. It also uses System.identityHashCode, which has a chance of collisions that is known upfront to the designers of IdentityHashMap, and is known to be very small. Under these "laboratory" conditions, linear probing appears to be a better choice in terms of performance.
I suspect that the reason the designers of the class library used chaining rather than linear probing in "regular" hash maps is their desire to maintain decent performance even when hash functions are suboptimal.

A: From Docs:

Implementation note: This is a simple linear-probe hash table, as described for example in texts by Sedgewick and Knuth. The array alternates holding keys and values. (This has better locality for large tables than does using separate arrays.) For many JRE implementations and operation mixes, this class will yield better performance than HashMap (which uses chaining rather than linear-probing).

The Reason is that this class` will yield better performance than HashMap.