text:
Q: getOwnerComponent() returns undefined in controller of which view was embedded on-demand I want to nest a second view into my root view if some requirements are met. This works fine by creating a XMLView object and adding it to the <page> aggregation of the <App> element. But when I try to access the default model (which is created by the manifest.json file) via this.getOwnerComponent().getModel(), it throws:

Uncaught TypeError: Cannot read property 'getModel' of undefined

It worked in the root controller but in the nested controller, this.getOwnerComponent() returned undefined again.
It even works if the view is added right at the beginning in the root view. Maybe I'm adding it the wrong way to the view in my controller?

RootView.view.xml:
<mvc:View controllerName="test.demo.controller.RootView" xmlns:mvc="sap.ui.core.mvc">
    <App id="app" xmlns="sap.m">
        <Page id="page" title="{i18n>title}">
            <Button text="load nested view" press=".onLoadButtonPress"/>
        </Page>
    </App>
</mvc:View>

RootView.controller.js:
sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/core/mvc/XMLView"
], function (Controller, XMLView) {
    "use strict";

    return Controller.extend("test.demo.controller.RootView", {
        onLoadButtonPress: function () {
            this.mDefault = this.getOwnerComponent().getModel(); // works just fine
            alert(this.mDefault);
            XMLView.create({
                viewName: "test.demo.view.NestedView"
            }).then(function(oView) {
                this.byId("page").addContent(oView);
            }.bind(this));
        }
    });
});

NestedView.view.xml:
<mvc:View xmlns:mvc="sap.ui.core.mvc" controllerName="test.demo.controller.NestedView">
  <!-- ... -->
</mvc:View>

NestedView.controller.js:
sap.ui.define([
    "sap/ui/core/mvc/Controller"
], function (Controller) {
    "use strict";

    return Controller.extend("test.demo.controller.NestedView", {
        onInit: function () {
            this.mDefault = this.getOwnerComponent().getModel(); // throws Uncaught TypeError: this.getOwnerComponent() is undefined
            alert(this.mDefault);
        }
    });
});

In the manifest.json, I added the GWSAMPLE_BASIC OData service as the default model.

A: When the caller in the application code creates on-demand a view or any other instance of ManagedObject, from which the owner component information needs to be accessible, it should be done within the method runAsOwner from your target sap.ui.core.Component. For example:
// XMLView required from "sap/ui/core/mvc/XMLView"
onLoadButtonPress: async function() {
  const fn = () => XMLView.create({ viewName: "test.demo.view.NestedView" });
  const oView = await this.getOwnerComponent().runAsOwner(fn);
  this.byId("page").addContent(oView);
},

Sample: https://embed.plnkr.co/29UrnDHpTHquNWuH
According to the API reference:

Ownership for objects is only checked by the framework at the time when they are created. It is not checked or updated afterwards. And it can only be detected while the Component.runAsOwner function is executing. Without further action, this is only the case while the content of a UIComponent is constructed or when a Router creates a new View and its content. (source)

Then in the controller of the nested view, calling this.getOwnerComponent() returns the correctly assigned component instead of undefined, and thus this.getOwnerComponent().getModel() works.

Tip: when loading fragments, favor the controller API loadFragment over Fragment.load since loadFragment automatically calls Fragment.load with the controller's component.runAsOwner.src


text:
Q: Installing Scrapy throws exceptions again and again I've tried to install  Scrapy the usual way:
Python 2, pip, pip install Scrapy
I read that Python3, Windows10 and 64bit are not so good for Scrapy so I've installed 32bit Ubuntu to Oracle Virtualbox. I've also followed the advice of codereviewvideos and applied:
sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev libxml2-dev libxslt1-dev python-dev libxml2-dev libxslt1-dev python-dev libxml2-dev libxslt-dev python-dev lib32z1-dev build-essential libssl-dev libffi-dev python-dev

https://codereviewvideos.com/blog/scrapy-1-1-ubuntu-15-10/
...but still throws error code 1 about lxml and the installation apt-gethas thrown: unable to locate package lib32z1-dev

A: The command you used won't work on windows....
have you try to follow indication to install scrapy on windows :
https://doc.scrapy.org/en/0.10.3/intro/install.html#intro-install-step3
And also you should install lxml :
pip install lxml
Scrapy need other packages, you will find the list here :
https://doc.scrapy.org/en/latest/intro/install.html
on windows it's recommended to use conda  (https://docs.continuum.io/anaconda/install)
"Though it's possible to install Scrapy on Windows using pip, we recommend you to install Anaconda or Miniconda and use the package from the conda-forge channel, which will avoid most installation issues."

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convergence to Charactersitic Function a.e. I'm working on the following problem in Folland:

If $\mu(E_n) < \infty$ for $n \in \mathbb{N}$ and $\chi_{E_n} \rightarrow f$ in $L^1$, then $f$ is equal (a.e.) to the characteristic function of a measurable set.

There are two hints given here:

*

*(Ex 3) If $\{f_n\}$ is a sequence of measurable functions on $X$, then $\{ x: \lim f_n(x) \text{ exists}\}$ is a measurable set.

*(Ex 5) If $X= A \cup B$ where $A,B \in \mathcal{M}$, a function $f$ on $X$ is measurable iff $f$ measurable on $A$ and $B$.

I understand the idea, I think --
$\chi_{E_n} \rightarrow f$  in $L^1$ will imply a subsequence converging to $f$ a.e. The limit will be $1$'s and $0$'s so will be a characteristic function. I'm having trouble putting it together rigorously though. In particular I saw this post whose accepted answer mentions convergence for $k$ large enough, which I don't understand becuase we converge a.e (what if we blow up?).

A: The hints seem a bit silly to me.  If you know the fact that (*) an $L^1$-convergent sequence has an a.e.-convergent subsequence, then what you have just said is exactly the proof: since $\chi_{E_n}(\omega)$ is $0$ or $1$ for any $n$, then $f(\omega)$ must also be zero or one a.e.  Moreover $f$ is a measurable function by assumption.  So if we let $E = \{f = 1\}$ (which is measurable) then $f = \chi_E$ a.e.
If you don't know, or aren't allowed to use, the fact (*), then I guess you have to proceed differently, and maybe the hints are useful in that case.  I haven't thought much about it yet.


text:
Q: Creating a DbGeography describing a rectangle I have a two points describing a rectangle:
a Northeast Lat/Long and a Southwest Lat/Long.
What will be the correct and efficient way to generate a simple rectangle entity that can be stored in a DbGeography field?
Note that later on I would like to use that field to determine if a POINT is inside this Rectangle.
I realize I should use DbGeography.FromText(...) methods, but I'm not sure how.

A: The FromText method expects a WKT representation, in this case for a polygon:
Something like this should do the trick:
DbGeography box = DbGeography.FromText(
    string.Format("POLYGON(({0} {1}, {0} {2}, {3} {2}, {3} {1}, {0} {1}))",
                         nwLongitude,
                         nwLatitude,
                         seLatitude,
                         seLongitude), 4326);

A: In case you have the NE and SW coordinates , you can use this :
DbGeography box = DbGeography.FromText(
        string.Format("POLYGON(({0} {1}, {0} {2}, {3} {2}, {3} {1}, {0} {1}))",
                             swLongitude,  //nwLongitude,
                             neLatitude, //nwLatitude,
                             swLatitude, //seLatitude,
                             neLongitude, //seLongitude
    ), 4326);


text:
Q: WPF Layout - Geting a column to fill available space I have a ListBox that has a grid in its template to allow 4 columns.  One column is the actual text of the ListBox.  I want that column to fill the available horizontal space.
The column definitions are:
<ControlTemplate TargetType="ListBoxItem">
    <Grid ScrollViewer.CanContentScroll="True" Margin="2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="20" />
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="30" />
        </Grid.ColumnDefinitions>
        <CheckBox VerticalAlignment="Center" Grid.Column="0" IsChecked="{Binding IsSelected,
                  RelativeSource={RelativeSource TemplatedParent},
                  Mode=TwoWay}" />
        <TextBlock VerticalAlignment="Center" Grid.Column="1" Margin="5,0,5,0" Text="{Binding Id}" />
        <TextBlock VerticalAlignment="Center" Grid.Column="2" Margin="5,0,5,0" Text="{Binding Title}" />
        <Button HorizontalAlignment="Right" Grid.Column="3" Tag="{Binding Id}" Margin="5,0,5,0">-></Button>
    </Grid>
</ControlTemplate>

I have tried several permutations of this and nothing will get it to fix in the window except for an explicit size setting.  Then when I resize the window it does not resize with it.
The ListBox is wrapped in a ScrollViewer to allow vertical scrolling (I am guessing that is what is messing me up.)
Any ideas on how to get the third column to fill just the available space and no more?

A: Do you need the control behaviours of ListBox, or are you using it for layout only.
If you are using it just for layout, you could swap the ListBox for a ItemsControl inside of a ScrollViewer.
This code (butchered to work in designer) show this:
<ScrollViewer>
    <ItemsControl>
        <!--<ListBox>-->
        <Grid Margin="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="20" />
                <ColumnDefinition Width="50" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="30" />
            </Grid.ColumnDefinitions>

            <CheckBox VerticalAlignment="Center" Grid.Column="0" IsChecked="True" />
            <TextBlock VerticalAlignment="Center" Grid.Column="1" Margin="5,0,5,0" Text="Id" />
            <TextBlock VerticalAlignment="Center" Grid.Column="2" Margin="5,0,5,0" Text="Title" />
            <Button HorizontalAlignment="Right" Grid.Column="3" Margin="5,0,5,0">-></Button>
        </Grid>
        <!--</ListBox>-->
    </ItemsControl>
</ScrollViewer>

The ListBox has some property of killing width on it's children, just like a TreeView does. So if you can avoid using it, for just layout reasons, this may be your fastest options.
Otherwise you'll need to databind the width of you Grid to the width of the dummy object outside the ListView, but the messy party is dealing with the width change as the scrollbar appears/disappears.

A: Why do you need to wrap the ListBox in a ScrollViewer?  The ListBox automatically displays the ScrollViewer when its contents don't fit in the available space.  You can remove it from the XAML and it should still work okay.  At least, it did for me.  :)
I tried your ControlTemplate out and it seemed to work really well.  The problem is that while the 3rd column resizes to the width of the ListBox, if the text in the 3rd column is very long, the 4th column won't appear until all of the text is visible.
I also tried another layout method, which I'm not sure about performance-wise, but the idea was to use a DockPanel instead of a Grid.  I added the third column last in the XAML to make it fill the remaining space, and docked it to the left (I docked the 4th column to the right).  It still would want to display the entire string in the 3rd column.  I don't know why this is happening, and why the text won't wrap or use an ellipsis when the available space isn't enough for the text to display.
<Window.Resources>
    <Style TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <DockPanel Width="Auto">
                        <CheckBox Width="20" VerticalAlignment="Center" DockPanel.Dock="Left" IsChecked="{Binding IsSelected,
                                        RelativeSource={RelativeSource TemplatedParent},
                                        Mode=TwoWay}" />
                        <TextBlock Width="50" VerticalAlignment="Center" DockPanel.Dock="Left" Margin="5,0,5,0" Text="hi" />
                        <Button Width="30" HorizontalAlignment="Right" DockPanel.Dock="Right" Margin="5,0,5,0">-></Button>
                        <TextBlock VerticalAlignment="Center" DockPanel.Dock="Left" Margin="5,0,5,0" Text="afdjfksdhahjklfadshjlasffasdlhjsafdlhjasdfasfhdjlaslfhdjsfdhjlsfdlhjsfdhjsfdddsd" TextTrimming="CharacterEllipsis" TextWrapping="WrapWithOverflow" />
                    </DockPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

A: Yes I would suggest the scroll viewer is messing you up, you could bind the Grid's width to the parent objects actual width, so there is a defined size in which the * has to actually fill.

A: I finally figure this out.
The containing list box needed to set the horizontal scroll bar to disabled like this:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"

Once I did that the grid sized perfectly.
One of these days I will figure out how all this "declarative stuff" works.


text:
Q: extjs searching deep into store data? In the Flex app, the metadata is loaded as xml which has very good functions for searching deep into the xml nodes. In the extjs version I have converted the xml data to json, keeping the deep hierarchical content, and am loading to an extjs Store using a json reader. I have not created a model, deeming this not necessary as the model does not add add any search functionality(?). I am looking at store.find, store.findBy which can use a function, store.findRecord etc, but these functions look very 'one-levelish'. I need to go to the 'Tabs' "node", find its child 'Tab' with 'Name' of 'Tab1', and find the value of its attribute 'Title' ... am using the description "node" but it is hierarchical json data. Am I missing store functionality that would do this, should I use the store's raw json data - does json have better search functionality, or shall I revert to brute-force javascript by looping through all the "nodes"? I was hoping to avoid looping and find a function of some kind. As always, tia

A: Well, what I understood from our comments is that you need a kinda storage to access your JSON data as quickly and easily as possible.
JSON means JavaScript Object Notation, so it's an object!
Ok, I give you two examples.
First of all, setup JSON data:
{
    "users": [{
        "user": {
            "id": 0 ,
            "name": "foo" ,
            "age": 22 ,
            "skills": [{
                "type": "bowcrafting" ,
                "skillLevel": 50 ,
                "levels": [10, 25, 50, 75, 90, 95, 99, 100]
            }]
        }} , {
        "user": {
            "id": 1 ,
            "name": "bar" ,
            "age": 71 ,
            "skills": [{
                "type": "fencing" ,
                "skillLevel": 32 ,
                "levels": [10, 25, 50, 90, 95, 99, 100]
            } , {
                "type": "swordsmanship" ,
                "skillLevel": 73 ,
                "levels": [10, 25, 50, 75, 80, 85, 90, 95, 99, 100]
            }]
        }} , {
        "user": {
            "id": 2 ,
            "name": "foobar" ,
            "age": 132 ,
            "skills": [{
                "type": "tactics" ,
                "skillLevel": 90 ,
                "levels": [10, 25, 50, 90, 95, 99, 100]
            } , {
                "type": "carpentery" ,
                "skillLevel": 86 ,
                "levels": [10, 25, 50, 75, 90, 95, 99, 100]
            } , {
                "type": "hiding" ,
                "skillLevel": 100 ,
                "levels": [10, 25, 50, 65, 75, 80, 85, 90, 95, 99, 100]
            }]
        }
    }]
}

And now here we got two ways to follow:
First way: we can imagine the above JSON saved into a file called nested-json.json and we read it with a simple store. Than, we can use findBy search to find what we need:
var jstore = Ext.create ('Ext.data.Store', {
    fields: ['id', 'name', 'age', 'skills'] ,

    proxy: {
        type: 'ajax' ,
        url: 'nested-json.json' ,
        reader: {
            type: 'json' ,
            root: 'users' ,
            record: 'user' ,
            idProperty: 'id'
        }
    } ,

    autoLoad: true
});

Ext.create ('Ext.button.Button', {
    text: 'Push me' ,
    renderTo: Ext.getBody () ,
    handler: function (btn) {
        var index = jstore.findBy (function (user, id) {
            // Here's the hint
            if (user.data.skills.skillLevel === 50) return id;
            else return -1;
        });

        if (index != -1) {
            // It will print 'foo' because it's the user
            // that has the skillLevel equal to 50
            console.log (jstore.getAt(index).get ('name'));
        }
    }
});

The other way is to imagine the above JSON as an object, read directly from a raw JSON data. At this point, just use it as a javascript object:
// Users model: required by JSON reader
Ext.define ('Users', {
    extend: 'Ext.data.Model' ,
    fields: ['id', 'name', 'age', 'skills']
});

// JSON reader
var jreader = Ext.create ('Ext.data.reader.Json', {
    model: 'Users' ,
    root: 'users' ,
    record: 'user' ,
    idProperty: 'id'
});

// Reads records directly from raw JSON
var users = jreader.readRecords ({
    "users": [{
        "user": {
            "id": 0 ,
            "name": "foo" ,
            "age": 22 ,
            "skills": [{
                "type": "bowcrafting" ,
                "skillLevel": 50 ,
                "levels": [10, 25, 50, 75, 90, 95, 99, 100]
            }]
        }} , {
        "user": {
            "id": 1 ,
            "name": "bar" ,
            "age": 71 ,
            "skills": [{
                "type": "fencing" ,
                "skillLevel": 32 ,
                "levels": [10, 25, 50, 90, 95, 99, 100]
            } , {
                "type": "swordsmanship" ,
                "skillLevel": 73 ,
                "levels": [10, 25, 50, 75, 80, 85, 90, 95, 99, 100]
            }]
        }} , {
        "user": {
            "id": 2 ,
            "name": "foobar" ,
            "age": 132 ,
            "skills": [{
                "type": "tactics" ,
                "skillLevel": 90 ,
                "levels": [10, 25, 50, 90, 95, 99, 100]
            } , {
                "type": "carpentery" ,
                "skillLevel": 86 ,
                "levels": [10, 25, 50, 75, 90, 95, 99, 100]
            } , {
                "type": "hiding" ,
                "skillLevel": 100 ,
                "levels": [10, 25, 50, 65, 75, 80, 85, 90, 95, 99, 100]
            }]
        }
    }]
});

// Here's the magic
Ext.each (users.records, function (user) {
    console.log ('*** USER ***');
    console.log (user);

    console.log ('id: ' + user.get ('id'));
    console.log ('name: ' + user.get ('name'));
    console.log ('age: ' + user.get ('age'));

    Ext.each (user.get ('skills'), function (skill) {
        console.log ('*** SKILL ***');
        console.log (skill);

        console.log ('type: ' + skill.type);
        console.log ('level: ' + skill.skillLevel);

        console.log ('*** LEVELS ***');
        Ext.each (skill.levels, function (level) {
            console.log (level);
        });
    });
});

Here's a jsfiddle to test this last one: jsfiddle
I hope to have understood what you requested. If I didn't, please let me know with an example made by yourself ;)


text:
Q: How do I handle rows that were deleted from the source using SSIS Slowly Changing Dimension I am trying to implement an ETL process for our Type 1 slowly changing dimension tables in a SQL 2014 database. The load needs to happen across servers, and I would prefer not to use linked servers.
I have been looking for ways to do this in SSIS and found the slowly changing dimension wizard which works fine except that this seems to only allow either inserting new rows or updating rows where there is a match on the business key, however I haven't found a place where it allows me to handle when a record exists in the dimension table but was deleted from the source. I would like to make sure these are deleted. Am I missing something? Has anyone found a better way to handle this in SSIS?
I know that I could just dump everything into another table on the destination server and write a TSQL merge, but there just seems like should be a simple way to do this in SSIS.

A: First, I would avoid the SCD functionality in SSIS, as its performance tends to be terrible - I've actually been told to avoid it by MS certified trainers, as well as plenty of people with a lot of experience. It's OK-ish on very small dimensions, but quickly tends to become unmanageable. There's a blog post here from someone who thinks it's usable in some situations, but even they suggest using a staging table for updates.
If you want to do this in SSIS you could use a Lookup to find the rows that need to be deleted (find the rows in your destination which aren't in the source using the no match output), then an OLE DB Command to delete them. But I'd give some serious thought to simply moving the data over to a staging area and doing this in TSQL, because SSIS will do it row by agonising row. Similarly to the SCD tool - it might be OK on small amounts of data, but if you're dealing with larger amounts (or might be in future), it may well become unmanageable.
If you don't want to move all of the data over to a staging area, you could use SSIS to build up a table only holding the unique IDs of the rows that need deleting, then fire off an Execute SQL Task from the Control Flow to delete them all at once.


text:
Q: Where is the source of the formula $\sum_{j=0}^\infty \bigl(j+\frac{1}{2}\bigr)^{n-1}\frac{2^{j+1/2}}{\binom{2j+1}{j+1/2}}$ for an integer sequence? The infinite series representation
\begin{equation}
\frac1\pi\sum_{j=0}^\infty \biggl(j+\frac{1}{2}\biggr)^{n-1}\frac{2^{j+1/2}}{\binom{2j+1}{j+1/2}}, \quad n\ge0
\end{equation}
for the positive integer sequence
\begin{gather}
1, 1, 2, 7, 35, 226, 1787, 16717, 180560, 2211181, 30273047,\\
458186752, 7596317885, 136907048461, 2665084902482,\\
55726440112987, 1245661569161135, 29642264728189066,\\
748158516941653967, 19962900431638852297,\\
561472467839585937560, 16602088291822017588121, \dotsc
\end{gather}
appears at https://oeis.org/A014307.

But there is no reference given for this series representation.
Could you please help find a source (such as a paper, a monograph, a book, a handbook, and the like, but not a website) including this series representation or its proof? Thank you very much.
By the way, I established a closed-form expression
\begin{equation}
\sum_{k=0}^{n}(-1)^kS(n,k) (2k-1)!!, \quad n\ge0
\end{equation}
and others for the above sequence, where $S(n,k)$ denotes the Stirling numbers of the second kind.

A: I don't have a reference, but it is not hard to prove the result. You want to prove that if
$$\left(\frac{e^x}{2-e^x}\right)^{1/2}=\sum_{n=0}^\infty a_n \frac{x^n}{n!}$$
then
$$a_n=\frac 1\pi\sum_{j=0}^\infty \left(j+\frac 12\right)^{n-1}\frac{2^{j+1/2}}{\binom{2j+1}{j+1/2}}. $$
I am not a fan of non-integer binomial coefficients, so I write
$$\frac 1{\binom{2j+1}{j+1/2}}=\frac{\pi(j+1/2)(1/2)_j}{2^{2j+1}j!}.$$
Here,
$(a)_j=a(a+1)\dotsm(a+j-1)$ is the Pochhammer symbol. So we want to prove
$$a_n=\sum_{j=0}^\infty\left(j+\frac 12\right)^{n}\frac{(1/2)_j}{j!2^{j+1/2}}.$$
Now simply plug one series into the other and change order of integration. I get
$$\sum_{n=0}^\infty a_n \frac{x^n}{n!}=\sum_{j=0}^\infty\frac{(1/2)_j}{j!2^{j+1/2}}\sum_{n=0}^\infty \left(j+\frac 12\right)^{n} \frac{x^n}{n!}
=\sum_{j=0}^\infty\frac{(1/2)_j}{j!2^{j+1/2}}e^{(j+1/2)x}.
$$
Now we are reduced to the binomial series
$$\frac 1{(1-t)^{1/2}}=\sum_{j=0}^\infty\frac{(1/2)_j}{j!}\,t^j$$
(with $t=e^{x}/2$).
(It would have been more pedagogical to write this backwards: First use the binomial theorem to expand your function in a series of $e^x$ and then use
the Taylor series of the exponential function.)


text:
Q: Skip through Errors while looping in R Hello I am trying to skip over some Error messages and continue with the loop by writing an empty csv to my working d directory.
##############################

Friday <- Sys.Date()-3

# Get Previous 4 days
Thursday <- Friday - 1
Wednesday <- Thursday -1
Tuesday <- Wednesday -1
Monday <- Tuesday -1

# format dates for loop
Friday <- format(Friday, "%Y%m%d")
Thursday<- format(Thursday, "%Y%m%d")
Wednesday<- format(Wednesday, "%Y%m%d")
Tuesday<- format(Tuesday, "%Y%m%d")
Monday<-format(Monday, "%Y%m%d")

# STOCKs to pull
stock1 <- c ("SPY.A","PCMI.O", "AMZN.O") # should generate error on 2nd occurance

# create function to retrieve data
pull = function (stock1){

AAPLFRI<- read.delim(header=TRUE, stringsAsFactor=FALSE,
                   paste(sep="",
                         "http://hopey.netfonds.no/tradedump.php?date=",
                         Friday,"&paper=",stock1,"&csv_format=txt"))

AAPLTHURS <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                      paste(sep="",
                            "http://hopey.netfonds.no/tradedump.php?date=",
                            Thursday,"&paper=",stock1,"&csv_format=txt"))

AAPLWED <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                    paste(sep="",
                          "http://hopey.netfonds.no/tradedump.php?date=",
                          Wednesday,"&paper=",stock1,"&csv_format=txt"))

AAPLTUES <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                     paste(sep="",
                           "http://hopey.netfonds.no/tradedump.php?date=",
                           Tuesday,"&paper=",stock1,"&csv_format=txt"))

AAPLMON <- read.delim(header=TRUE, stringsAsFactor=FALSE,
                    paste(sep="",
                          "http://hopey.netfonds.no/tradedump.php?date=",
                          Monday,"&paper=",stock1,"&csv_format=txt"))

#Eliminate unwanted Columns in Data
AAPLMON <- AAPLMON[,c(1:3)]
AAPLTUES <- AAPLTUES[,c(1:3)]
AAPLWED <- AAPLWED[,c(1:3)]
AAPLTHURS <- AAPLTHURS[,c(1:3)]
AAPLFRI <- AAPLFRI[,c(1:3)]

# Try to skip over errors when binding data

if (is.error(rbind(AAPLMON,AAPLTUES,AAPLWED, AAPLTHURS, AAPLFRI ))){

SERIES <- 1

}

SERIES <- rbind(AAPLMON,AAPLTUES,AAPLWED, AAPLTHURS, AAPLFRI )

#Write .CSV File
write.csv(SERIES,paste(sep="",stock1,"_",Friday,".csv"))

}

# Use Apply to repeat through "stock1"
apply(t(stock1), 2, pull)-> listo

The problem is that there is no is.error() that I know of? and I am not sure how to implement the try() wrapper to get the desired outcome.

A: tryit <- try(rbind(AAPLMON,AAPLTUES,AAPLWED, AAPLTHURS, AAPLFRI ))

if(inherits(tryit, "try-error")){
    # do something when error
} else {
    # do something when no error
}


text:
Q: Copy and paste values in google sheet with macro dont work When I paste values from a formula with macro in google sheet the cell show empty
I need to copy the result of =now but only with values, the problem is that don't copy anything, for the example, y write the =now formula in F2 and I need to copy only the values in D2
spreadsheet.getRange('F2').activate();
  spreadsheet.getCurrentCell().setFormula('=NOW()');
  spreadsheet.getRange('D2').activate();
  spreadsheet.getRange('F2').copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);

I need that paste values to save this moment if I copy the formula its update in every change and it is no valid for me

A: Try it this way:
function macro1() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  sh.getRange('F2').activate();
  sh.getCurrentCell().setFormula('=NOW()');
  SpreadsheetApp.flush();
  sh.getRange('D2').activate();
  sh.getRange('F2').copyTo(sh.getActiveRange(),SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}


text:
Q: Simple Constraint Logic Programming sample CLP(Q) gives error in Prolog I've started to learn Prolog and I follow the RIPTutorial PDF. At the Constraint Logic Programming CLP(Q) section, it says:
Constraint Logic Programming CLP(Q) implements reasoning over rational numbers
Example:
?- { 5/6 = X/2 + 1/3 }.
X = 1.

When I've tried this line on SWI-Prolog on Windows, it gave:
ERROR: Unknown procedure: {}/1 (DWIM could not correct goal)
The same line on commandline SWI-Prolog-7.2.0 on macOS gives:
ERROR: toplevel: Undefined procedure: {}/1 (DWIM could not correct goal)
How to get the expected output of X = 1. ?

A: Using SWI-Prolog.
As noted in the comments you need to load the code for CLP(Q) first.
?- use_module(library(clpq)).
true

Then enter the query as in the example.
?- {5/6 = X/2 + 1/3}.
X = 1.


text:
Q: How to edit the imageField label text "Currently, ... ect"
here i have a form i did find were to control label and input field of the imagefield but label only controls the Avatar text not the "currently ....ect",
is there a way to access it i want to add a class to style it and cant find its object in python ?
this my attempt and it is not working only gives me the "avatar" ext only
class ProfileUpdateModelForm(ModelForm):
    class Meta:
        model = Profile
        fields = ('first_name', 'last_name', 'bio', 'avatar')

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['avatar'].label = False #hides "avatar" text and the rest of text still there

A: These are defined in ClearableFileInput:
class ClearableFileInput(FileInput):
    clear_checkbox_label = _('Clear')
    initial_text = _('Currently')
    input_text = _('Change')
    # ....

So you would have to subclass this widget, override the class attributes, and use it in the form field. Alternatively, you can override the template forms/widgets/clearable_file_input.html for total control over the display of the generated markup of the field.


text:
Q: Force Login to use APP Force log-in to use my APP? Can I do this like the following example?
When someone not logged in go into your app, eg:
https://apps.facebook.com/gmteste/
They can see your entirely app without login, can I force they to login? eg:
https://apps.facebook.com/ruaevolution/
Also, I didn't found any question answered like this in here. or on Facebook itself.

A: Just parse the signed_request, and see if it has the oauth_token property set – if so, the user has authorized your app, otherwise not.
https://developers.facebook.com/docs/authentication/signed_request/


text:
Q: Problem compiling Bibliography on Gummi I am trying to create cites and bibliography,in ApJ style, using the tex commands below using Gummi.
\documentclass[12pt]{article}

\usepackage{ natbib}
\citestyle{aa}
\begin{document}

\section{Introduction}

\cite{texbook}

\section{Conclusion}

\cite{Narendra_1990}

\bibliography{Bib2}{}
\bibliographystyle{apj}

\end{document}

However, I keep getting the following error:
/tmp/.LatexEssay.tex.bbl:8: Undefined control sequence.
l.8 {Worthey}, G. 1994, \apjs
                         , 95, 107
/tmp/.LatexEssay.tex.bbl:8:  ==> Fatal error occurred, no output   PDF          file    produced!
Transcript written on /tmp/.LatexEssay.tex.log.

My Bibtex file is:
    @Article{Narendra_1990,
    author =       {K.S.Narendra and K.Parthsarathy},
    title =        {Identification and Control of Dynamical System
                  using Neural Networks},
    journal =      "IEENN",
    year =         {1990},
    volume =    {1},
    number =    {1},
    month =     {},
    pages =     {4-27},
    note =      {},
    annote =    {}
    @BOOK{texbook,
    author = "Donald E. Knuth",
    title= "The {{\TeX}book}",
    publisher = "Addison-Wesley",
    year = 1984
    }
    @ARTICLE{1994ApJS...95..107W,
    author = {{Worthey}, G.},
    title = "{Comprehensive stellar population models and the disentanglement  of age and metallicity effects}",
   journal = {\apjs},
   year =  1994,
   month = nov,
   volume = 95,
   pages = {107-149},
   doi = {10.1086/192096},
   adsurl = {http://adsabs.harvard.edu/abs/1994ApJS...95..107W},
  adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

If I cite the texbook and Narendra_1990 references I have no problem. It is only when I include the 1994ApJS...95..107W reference that the error occurs.
Any help appreciated!

A: As you can read in the given error message
/tmp/.LatexEssay.tex.bbl:8: Undefined control sequence.
l.8 {Worthey}, G. 1994, \apjs
                         , 95, 107

you have an undefined control sequence \apjs that causes the error. I guess it should contain the name of a journal. So add the line @string {apjs  = {The correct name of the journal}} (add the correct name please) to your bib file. With a little pretty printing it could look like this:
@string {apjs  = {The correct name of the journal}}
@ARTICLE{1994ApJS...95..107W,
  author  = {{Worthey}, G.},
  title   = {{Comprehensive stellar population models and the disentanglement
    of age and metallicity effects}},
  journal = apjs,
  year    = {1994},
  month   = nov,
  volume  = {95},
  pages   = {107--149},
  doi     = {10.1086/192096},
  adsurl  = {http://adsabs.harvard.edu/abs/1994ApJS...95..107W},
  adsnote = {Provided by the SAO/NASA Astrophysics Data System},
}

Did you recognised the -- in field pages?


text:
Q: RegEx how to insert text in a previous line of searched text in notepad++ I am searching for an regular expression to insert text in previous line  below is the example how i need to insert in notepad++
submit...
action..
method=post

I would like to search with method=post and then insert a text "Post" like below
Always it should be two lines up of method=post
Post
Submit
action
method=post

Could you please suggest any regular expression I can use in notepad++?

A: If I understand what you want :
Use the Find & Replace Dialog Box.
In Find What, add "method=post" and in Replace With add "Post^^submit^^action^^method=post"
And then Replace All.

A: This how I'd do the job:
Find what: (.+\R.+\R.*method=post)
Replace with: Post\n$1
Make sure you've selected Regular Expression and NOT checked . matches newline.


text:
Q: Showing error when trying to create pop in transition I am new to WPF and am trying to create a simple pop in effect. But I get the following error "The attachable property Triggers was not found in type newwindow. Below is the XAML code:
<Window x:Class="WpfApplication6.newwindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="newwindow" Height="295" Width="371">
<Grid Height="257" Width="349">
    <Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="115,0,0,112" Name="label1" VerticalAlignment="Bottom" Width="127" />
    <newwindow.Triggers>
        <EventTrigger RoutedEvent="newwindow.Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:2" FillBehavior="HoldEnd" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </newwindow.Triggers>
    </Grid>
</Window>

I am using VS 2010 with .net 3.5 framework.
Thank you.

A: Replace newwindow.Triggers through Window.Triggers and newwindow.Loaded through Window.Loaded.
The programm knows that you want to refer to your newwindow because its in the xaml of your newwindow-Window (And consider renaming your "newwindow")^^.
(You could have edited your old Question...)


text:
Q: Azure Active Directory - How to give an http redirectUri for my registered app under tenant I have created a tenant under my organization and registered an app for my testing react application. I have deployed my react application in one of the kubrnetes http server. Is there a way to add http url (react application uri which deployed in kubernetes) in Redirect URI in app registration.

*

*I have given SPA during app registration

*Account type - Single tenant

*Checked both access token and ID token

A: The Redirect URIs must begin with the scheme https.
The HTTPS scheme (https://) is supported for all HTTP-based redirect URIs.
The HTTP scheme (http://) is supported only for localhost URIs and should be used only during active local application development and testing.
Please check this for more information
There is no other option available to use Http Schema.


text:
Q: Contour add to map conditional I have correlation map then I wan to add contour line on it taking into consideration
(i). for positive correlation enclosed with solid line
(ii). for negative correlation enclosed with dotted line
Here is my scrip just to modify contour line as per mentioned criteria
image.plot(lons,lats,cor5FMAM,zlim=c(-0.6,0.6))
contour(lons,lats,cor5FMAM,add=T,at=c(-0.6,0.6,0.2),lwd=0.2)

enter image description here

A: A reproducible example would be nice, but I would guess you're looking for
contour(lons,lats,cor5FMAM,add=TRUE,at=-0.6,lwd=2,lty=3)
contour(lons,lats,cor5FMAM,add=TRUE,at=c(0.2,0.6,lwd=2,lty=1)

?  You could embed this in a looping/lapply construct, but it might not be worth it for a one-off plot ...


text:
Q: Некорректная работа функции Некорректная работа блока кода:
do {
    b = F[i];
    if (b.find(G)) {
        N++;
        b.clear();
        i++;
    } else {
        b.clear();
        i++;
    }
} while (i < F.length());

N++ делается для каждого символа из string F; хотя в string G; таких символов не существует. В чем может заключаться проблема?
A: std::string::find
If the content is not found, the member value npos is returned.
Т.е. сравнение должно выглядеть так:
if (b.find(G) != std::string::npos)


text:
Q: Does MVVMCross PictureChooserTask work on Windows Phone 8.1 I have done as the youtube video on PictureChooserTask (https://www.youtube.com/watch?v=Dyy6U67ouQI&list=PLR6WI6W1JdeYSXLbm58jwAKYT7RQR31-W&index=16) shows, and it all compiles, but when i push the "Take picture" button that calls the TakePicture-command the app crash and returns to the home screen.
My commands and methods:
private MvxCommand _takePictureCommand;
public ICommand TakePictureCommand
{
    get
    {
        _takePictureCommand = _takePictureCommand ?? new MvxCommand(DoTakePicture);
        return _takePictureCommand;
    }
}

private void DoTakePicture()
{
    _pictureChooserTask.TakePicture(400, 95, OnPicture, () => { });
}

private void OnPicture(Stream pictureStream)
{
    var memoryStream = new MemoryStream();
    pictureStream.CopyTo(memoryStream);
    Bytes = memoryStream.ToArray();
}

A: It means Wpf 8.1 RT, thats the new standard for Windows Phone dev i have learned. I get this message: "This object needs to be initialized before the requested operation can be carried out." When i click the button that is bound up against the TakePicture

A: I believe this was fixed in https://github.com/MvvmCross/MvvmCross/pull/818 - so it should be in the 3.2.2 release of MvvmCross


text:
Q: Проблема с запуском flask приложения на Centos 7 httpd.conf:
<VirtualHost *:88>
ServerName <myserver.com>

WSGIDaemonProcess feedlerbot user=apache group=apache threads=5
WSGIScriptAlias / /var/www/feedler/feedler_bot/bot.wsgi

<Directory /var/www/feedler/feedler_bot/>
    WSGIProcessGroup feedlerbot
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

bot.wsgi:
#!/usr/bin/env python
import sys

# activate virtualenv
activate_this = '/var/www/feedler/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

# path to flask app
sys.path.insert(0, '/var/www/feedler/feedler_bot')

from bot import app as application

bot.py:
app = flask.Flask(__name__)

# Empty webserver index, return nothing, just http 200
@app.route('/', methods=['GET', 'HEAD'])
def index():
    return 'Feedler Bot using webhooks works fine!'

# Process webhook calls
@app.route(WebhooksSetting.WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
    if flask.request.headers.get('content-type') == 'application/json':
        json_string = flask.request.get_data().decode('utf-8')
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return ''
    else:
        flask.abort(403)

"""Start of the bot logic"""
<bot_logic>
"""End of the bot logic"""

# Remove webhook, it fails sometimes the set if there is a previous webhook
bot.remove_webhook()

time.sleep(1)

# Set webhook
bot.set_webhook(url=WebhooksSetting.WEBHOOK_URL_BASE + WebhooksSetting.WEBHOOK_URL_PATH,
                certificate=open(WebhooksSetting.WEBHOOK_SSL_CERT, 'r'))

# Start flask server
if __name__ == '__main__':
    app.run(host=WebhooksSetting.WEBHOOK_LISTEN,
            port=WebhooksSetting.WEBHOOK_PORT,
            ssl_context=(WebhooksSetting.WEBHOOK_SSL_CERT, WebhooksSetting.WEBHOOK_SSL_PRIV),
            debug=True)

Порт 88 открыт, но при попытке открыть в браузере https://myserver.com:88/ - connection refused. В логах /etc/httpd/logs/error_log пусто. Где я мог ошибиться? Причем на этом же сервере запущен и корректно работает телеграм бот ровно по такой же схеме, но только на порту 8443.


text:
Q: preg_match return all parts in array I've got following php code:
$match = array();
if (preg_match("%^(/\d+)(/test)(/\w+)*$%", "/25/test/t1/t2/t3/t4", $match))
    print_r($match);

I'm getting this result:
Array ( [0] => /25/test/t1/t2/t3/t4 [1] => /25 [2] => /test [3] => /t4 )

What do i need to change in my regexp to get this result:
Array ( [0] => /25/test/t1/t2/t3/t4 [1] => /25 [2] => /test [3] => /t1 [4] => /t2 [5] => /t3  [6] => /t4)

A: you need preg_match_all
preg_match_all( '~(/\w+)~', $str, $matches );

in your situation you can use explode too

A: <?php

    $str = '/a/b/1/2/3/4';
    if(preg_match('/^(\/\w+)*$/', $str) && preg_match_all('/\/\w+/', $str, $matches)) {
        $matches = $matches[0];
        print_r($matches);
    }

?>

Prints:
Array
(
    [0] => /a
    [1] => /b
    [2] => /1
    [3] => /2
    [4] => /3
    [5] => /4
)

A: Using your original example, you could use a recursive expression:
"%(/\w+)(?>[^(/\w+)]?|(?R))%"

This works my matching (/\w+) subexpressions in turn. Therfore the match for
"/a/b/1/2/3/4"

Would be:
Array
(
[0] => Array
    (
        [0] => /a [1] => /b [2] => /1 [3] => /2 [4] => /3 [5] => /4
    )
...

However your later examples complicate things. A simple 0 or more match will only return the last (greedy) or first (ungreedy) match - not all submatches. preg_match_all won't be able to handle your dynamic expression.
You will have to clarify what you're trying to achieve in more detail before a suitable solution can be provided.


text:
Q: Text in CardView is overlapping Android In my android app I have created two TextView inside CardView layout. The first TextView will show the description of one item and second TextView will show a link of that item. but whenever I run my app, the second text is overlapping with the first one. I want to implement in such a way that after finishing the first text the second one with start. but I fail to implement that.
Here is my code for CardView layout.
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp">

        <android.support.v7.widget.CardView
            android:id="@+id/cardView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
            <TextView
                android:id="@+id/news_description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/large_text"/>

            <TextView
                android:id="@+id/webLink"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/link"
                android:layout_gravity="bottom"
                android:textAppearance="?android:attr/textAppearanceSmall" />

        </android.support.v7.widget.CardView>
    </RelativeLayout>

A: <RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:padding="20dp">

 <android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <TextView
        android:id="@+id/news_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/large_text"/>

    <TextView
        android:id="@+id/webLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/link"
        android:layout_gravity="bottom"
        android:textAppearance="?android:attr/textAppearanceSmall" />
    </LinearLayout>

 </android.support.v7.widget.CardView>
</RelativeLayout>

A: make your layout like this
<RelativeLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:padding="20dp">

 <android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:id="@+id/news_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/large_text" />

        <TextView
            android:id="@+id/webLink"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:text="@string/link"
            android:textAppearance="?android:attr/textAppearanceSmall" />

    </LinearLayout>
</android.support.v7.widget.CardView>

</RelativeLayout>

A: Use the RelativeLayout or LinearLayout inside the CardView like this:
     <android.support.v7.widget.CardView
                android:id="@+id/cardView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/news_description"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="dklfjkdsjfsd"
                        />

                    <TextView
                        android:id="@+id/webLink"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="bottom"
                        android:layout_marginLeft="5dp"
                        android:layout_toRightOf="@+id/news_description"
                        android:textAppearance="?android:attr/textAppearanceSmall" />
                </RelativeLayout>

            </android.support.v7.widget.CardView>

Hope this will help you out.....

A: You have put two TextViews inside CardView. The super class of CardView is FrameLayout. Putting your TextVeiws inside a LinearLayout or Relative Layout can solve your problem.
<android.support.v7.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
<TextView
    android:id="@+id/news_description"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/large_text"/>

<TextView
    android:id="@+id/webLink"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/link"
    android:layout_gravity="bottom"
    android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</android.support.v7.widget.CardView>


text:
Q: How to iterate mongodb database in node.js to send to Algolia? In the documentation of Algolia, for the node.js part they specified to use MySQL for indexing but not MongoDB, I have another question regarding this issue but it is more a general question , check here
Some folks ask me to use mongo-connector but tried it and I got some unknown error, which got me to square one
My real question is, how do i iterate a list of collections in mongodb to algolia?
This is the Algolia's version of MySQL in Node.js
var _ = require('lodash');
var async = require('async');
var mysql = require('mysql');

var algoliasearch = require('algoliasearch');
var client = algoliasearch("RQGLD4LOQI", "••••••••••••••••••••••••••••••••");
var index = client.initIndex('YourIndexName');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'mysql_user',
  password: 'mysql_password',
  database: 'YourDatabaseName'
});

connection.query('SELECT * FROM TABLE_TO_IMPORT', function(err, results, fields) {
  if (err) {
    throw err;
  }

  // let's use table IDS as Algolia objectIDs
  results = results.map(function(result) {
    result.objectID = result.id;
    return result;
  });

  // split our results into chunks of 5,000 objects, to get a good indexing/insert performance
  var chunkedResults = _.chunk(results, 5000);

  // for each chunk of 5,000 objects, save to algolia, in parallel. Call end() when finished
  // or if any save produces an error
  // https://github.com/caolan/async#eacharr-iterator-callback
  async.each(chunkedResults, index.saveObjects.bind(index), end);
});

function end(err) {
  if (err) {
    throw err;
  }

  console.log('MySQL<>Algolia import done')
};

To be specific I'm using mongoose as my ORM, so I have no experience in other libraries. Please help me on this, so that I could some searching interface already :(.

A: You can use the following code to iterate over the whole MongoDB mydb.myCollection collection + create batches that will be sent to the Algolia index:
var Db = require('mongodb').Db,
    Server = require('mongodb').Server,
    algoliasearch = require('algoliasearch');

// init Algolia index
var client = algoliasearch("*********", "••••••••••••••••••••••••••••••••");
var index = client.initIndex('YourIndexName');

// init connection to MongoDB
var db = new Db('mydb', new Server('localhost', 27017));
db.open(function(err, db) {
  // get the collection
  db.collection('myCollection', function(err, collection) {
    // iterate over the whole collection using a cursor
    var batch = [];
    collection.find().forEach(function(doc) {
      batch.push(doc);
      if (batch.length > 10000) {
        // send documents by batch of 10000 to Algolia
        index.addObjects(batch);
        batch = [];
      }
    });
    // last batch
    if (batch.length > 0) {
      index.addObjects(batch);
    }
  });
});


text:
Q: Dotnet Return Url Missing Parameter Here's a head-scratcher:
I have a Dotnet Application which signs a user out after a certain inactive time period. A JavaScript function using an action defined in the relevant CSHTML sends the user to a certain controller method which will sign them out.
When the JavaScript code decides that the user should be signed out, it uses the following line to do so:
location.href = settings.actions.expireSession + '?returnUrlString=' + currentUrl;

where settings.actions.expireSession is defined as:
expireSession: '@Url.Action("Expire", "Session")'

and the return url string getting into the location.href looks like this:
http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84&caseId=173

which is correct, and the entire string assembled together with the url action looks like this:
"/Session/Expire?returnUrlString=http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84&caseId=173"

I set up a breakpoint at the point of entry in the relevant method, but what arrives in the string parameter named "returnUrlString" there is missing the "caseId":
http://localhost:49574/?returnUrl=http%3A%2F%2Flocalhost%3A49574%2FReport%2FReportWithUserIdAndCaseId%3FuserId%3D84

consequently, when I enter my username and password to log back in, I get redirected to the following url:
http://localhost:49574/Report/EntrySummaryReportWithPatientIdAndVisitId?userId=84

which fails because it's missing a crucial parameter.
Have I missed anything obvious? Is there something else in the automated background of Dotnet's addressing/redirection system that could be contributing to this mysterious disappearance?
A huge thanks to everyone for reading this, and a gargantuan thanks for contributors!
 - Ilia

A: You need to escape the Url before it is sent to the Session/Expire page.
See this previous question for information on encoding it in Javascript:
Encode URL in JavaScript?
Once you have returnUrlString on your Session Expire page, you should then unescape it and direct the user to it.
The problem is that the Url to the Session/Expire page would be:
"/Session/Expire?returnUrlString=http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84&caseId=173"
What the server sees is:
Page: "/Session/Expire?, QueryString ReturnUrlString: returnUrlString=http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84, QueryString CaseId: &caseId=173"
It is interpreting your &caseId as part of the /Session/Expire URL. This is why it disappears.


text:
Q: I am geting a recurring error as "permission denied" on opening psql in Postgresql.Why am i getting this error?How to solve it? I am new to Postgresql,i installed pgdAdmin4 and all, but now on opening psql i am getting the following errors:
Server [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:
find: /c/$Recycle.Bin/S-1-5-18: Permission denied
find: /c/$Recycle.Bin/S-1-5-21-1126570350-378795617-2859373091-1000: Permission denied
find: /c/$Recycle.Bin/S-1-5-21-1126570350-378795617-2859373091-500: Permission denied
find: /c/Config.Msi: Permission denied
find: /c/hiberfil.sys: Permission denied
find: /c/MSOCache: Permission denied
find: /c/pagefile.sys: Permission denied
find: /c/PerfLogs: Permission denied

A: Run the shell as administrator. I had the same problem. Worked for me.


text:
Q: How to get rounded value without fraction error when using numberFromString to generate NSDecimalNumber? I am trying to parse out a NSDecimalNumber from a String, but whatever attributes i set on numberFormatter, I can't get it to stop making a fraction error when getting numberFromString
let numberFormatter = NSNumberFormatter()
numberFormatter.maximumFractionDigits = 1
numberFormatter.decimalSeparator = "."
numberFormatter.generatesDecimalNumbers = true
numberFormatter.roundingMode = .RoundDown
numberFormatter.roundingIncrement = 0.01
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let number = numberFormatter.numberFromString("93.9")

number gets set to 93.9000000000001, not 93.9. How can I get it to set the correct value for number?

A: There is a factory method defined on NSDecimalNumber that takes a string:
+ (NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString
Example:
$ swift
Welcome to Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81). Type :help for assistance.
  1> import Foundation
  2> NSDecimalNumber(string: "93.9")
$R0: NSDecimalNumber = 93.9
  3>

A: Replace the last line with
let number = numberFormatter.numberFromString("93.7")?.floatValue


text:
Q: Swift: Creating a csv file in Documents Directory I am creating a registration form application. The registration form data will be saved in a CSV file. I need to create a csv file in the documents directory and be able to write to it. I'm pretty new to Swift so I'm having a bit of trouble. This is what I've got so far.
var fileManager = NSFileManager.defaultManager()
var fileHandle: NSFileHandle

@IBAction func submitForm(sender: AnyObject) {
    mySingleton.filename = mySingleton.filename + ".csv"
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let filePath = documentsPath + mySingleton.filename

    if !fileManager.fileExistsAtPath(mySingleton.filename) {
        fileManager.createFileAtPath(filePath, contents: nil, attributes: nil)
        fileHandle = ...
    }

}

Obviously the code I'm having trouble with is the FileHandle which is what allows to to modify the file. In objective-c it would look something like this:
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];

Then obviously if I wanted to write to the file I could do something like this:
[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

So I'm really only struggling with that one part. Thanks for the help!

A: In Swift, fileHandleForUpdatingAtPath has become an initializer of NSFileHandle, adopting the Swift naming convention of avoiding repetition and taking the end of the Objective-C method name, making it the parameter name:
let fileHandle = NSFileHandle(forUpdatingAtPath: yourPath)

A: Make sure to add these two keys in info.plist and set them to "YES"
Supports opening documents in place
Application supports iTunes file sharing


text:
Q: How to plot absolute value function? To preface this, I just started learning LaTeX today as my professor wants us to complete homework assignments in it from now on. I've attached all my code, but the problem area is the very bottom. I'm trying to plot the absolute value of \phi (t) - \phi_n (t) (only done the first one so far), but as far as I can tell, there's no common package that has a built in absolute value function that actually does math instead of just formatting the bars. Is there some functionality or package I've missed?
\documentclass[12pt]{article}
\usepackage{fullpage,mathpazo,amsfonts,nicefrac,amsmath,amssymb,enumitem, geometry, pgfplots, physics}
\pgfplotsset{compat = newest}
\geometry{top = 20mm, bottom = 20mm, left = 20mm, right = 20mm}

\begin{document}
\section*{2.8}
\begin{enumerate}[start = 2]
  \item Transform the given initial value problem
into an equivalent problem with the initial point at the origin.
    \begin{gather*}
      \frac{dy}{dt} = 1 - y^3, \quad \quad y(-1) = 3 \\
      T = t + 1 \Longrightarrow y(0) = 0 \\
      \frac{dy}{dt} = \frac{dy}{dT} * \frac{dT}{dt} = \frac{dy}{dT} \\
      \frac{dy}{dT} = 1 - y^3 \\
      Y = y-3 \\
      \frac{dy}{dT} = 1 - (Y + 3)^3 \\
      \frac{dY}{dT} = 1 - (Y + 3)^3, \quad \quad Y(0) = 0 \\
    \end{gather*}
\end{enumerate}
    \begin{enumerate}[start = 4]
      \item Let $\phi _0 (t) = 0$ and define $\{\phi _n (t)\}$ by the method of successive approximations.
      \[
      y' = -\frac{y}{2} + t, \quad \quad y(0) = 0
      \]
        \begin{enumerate}
            \item Determine $\phi _n (t)$ for an arbitrary value of n.
            \begin{gather*}
                \int_{0}^{t} \,dy = \int_{0}^{t} -\frac{y}{2} + s \,ds \\
                \begin{align*}
                     \phi (t) &= \int_{0}^{t} -\frac{y}{2} + s \,ds \Longrightarrow \phi_{n+1} (t) = \int_{0}^{t} -\frac{\phi_n}{2} + s \,ds \\
                    \phi_1 (t) &= \int_{0}^{t} -\frac{y_0}{2} + s \,ds = \frac{t^2}{2} \\
                    \phi_2 (t) &= \int_{0}^{t} -\frac{s^2}{4} + s \,ds = -\frac{t^3}{12} + \frac{t^2}{2}\\
                    \phi_3 (t) &= \int_{0}^{t} -\frac{s^3}{24} + \frac{s^2}{4} + s \,ds = \frac{t^4}{96} - \frac{t^3}{12} + \frac{t^2}{2}\\
                    \phi_4 (t) &= \int_{0}^{t} \frac{s^4}{192} -\frac{s^3}{24} + \frac{s^2}{4} + s \,ds = -\frac{t^5}{960} + \frac{t^4}{96} - \frac{t^3}{12} + \frac{t^2}{2}
                \end{align*} \\
                \phi_n (t) = 4 \sum_{i=0}^{n} \frac{ (-\frac{t}{2})^i }{ i! } + 2t -4 \\
            \end{gather*}
            \item Plot $\phi_n (t)$ for $n = 1\ldots4$. Observe whether the iterates appear to be converging.
                \begin{tikzpicture}
                    \begin{axis}[
                        grid = both,
                        width = .75 * \textwidth,
                        height = .5 * \textwidth,
                        legend pos = north west,
                        xlabel = t, ylabel = $\phi_n (t)$,
                        xmin = 0, xmax = 10,
                        ymin = 0, ymax = 20]
                    \addplot[domain = 0:10, samples = 100, smooth, thick, blue,] {(x^2)/2};
                    \addplot[domain = 0:10, samples = 100, smooth, thick, red,] {-x^3/12 + (x^2)/2};
                    \addplot[domain = 0:10, samples = 100, smooth, thick, green,] {x^4/96 -x^3/12 + (x^2)/2};
                    \addplot[domain = 0:10, samples = 100, smooth, thick, pink,] {-x^5/960 + x^4/96 -x^3/12 + (x^2)/2};
                    \addplot[domain = 0:10, samples = 200, smooth, thick, black,] {4*exp(-x/2) + 2*x - 4};

                    \legend{$\phi_1 (t)$, $\phi_2 (t)$, $\phi_3 (t)$, $\phi_4 (t)$, $\phi (t)$}
                    \end{axis}
                \end{tikzpicture}
                \\ The iterates do appear to be converging as $n$ increases.

            \item Express $\lim_{n\to\infty} \phi_n (t) = \phi (t)$ in terms of elementary functions; that is, solve the given initial value problem.
                \begin{align*}
                    \lim_{n\to\infty} \phi_n (t) &= \lim_{n\to\infty} 4 \sum_{i=0}^{n} \frac{ (-\frac{t}{2})^i }{ i! } + 2t -4\\
                    &= 4e^{-\frac{t}{2}} + 2t -4 \\
                    \phi_n (t) &= 4e^{-\frac{t}{2}} + 2t -4
                \end{align*}
                \[ \phi (t) =  4e^{-\frac{t}{2}} + 2t -4 , \quad \quad \phi (0) = y (0) = 0 \]
            \item Plot $|\phi (t) - \phi_n (t)|$ for each value of $n$. Estimate the interval in which each is a reasonably good approximation to the actual solution. \\
                \begin{tikzpicture}
                    \begin{axis}[
                        grid = both,
                        width = .75 * \textwidth,
                        height = .5 * \textwidth,
                        legend pos = north west,
                        xlabel = t, ylabel = $\phi_n (t)$,
                        xmin = 0, xmax = 10,
                        ymin = 0, ymax = 10]
                    \addplot[domain = 0:10, samples = 100, smooth, thick, blue,] {{4*exp(-x/2) + 2*x - 4 - (x^2)/2}};
                    \addplot[domain = 0:10, samples = 100, smooth, thick, red,] {-x^3/12 + (x^2)/2};
                    \addplot[domain = 0:10, samples = 100, smooth, thick, green,] {x^4/96 -x^3/12 + (x^2)/2};
                    \addplot[domain = 0:10, samples = 100, smooth, thick, pink,] {-x^5/960 + x^4/96 -x^3/12 + (x^2)/2};
                    \addplot[domain = 0:10, samples = 200, smooth, thick, black,] {4*exp(-x/2) + 2*x - 4};

                    \legend{$\phi_1 (t)$, $\phi_2 (t)$, $\phi_3 (t)$, $\phi_4 (t)$, $\phi (t)$}
                    \end{axis}
                \end{tikzpicture}

        \end{enumerate}
    \end{enumerate}

\end{document}

A: Is this what you mean?

\addplot[domain = 0:10, samples = 100, smooth, thick, blue,] {{abs((4*exp(-x/2) + 2*x - 4)-(4*exp(-x/2) + 2*x - 4 - (x^2)/2))}};
\addplot[domain = 0:10, samples = 100, smooth, thick, red,] {abs((4*exp(-x/2) + 2*x - 4)-(-x^3/12 + (x^2)/2))};
\addplot[domain = 0:10, samples = 100, smooth, thick, green,] {abs((4*exp(-x/2) + 2*x - 4)-(x^4/96 -x^3/12 + (x^2)/2))};
\addplot[domain = 0:10, samples = 100, smooth, thick, pink,] {abs((4*exp(-x/2) + 2*x - 4)-(x^5/960 + x^4/96 -x^3/12 + (x^2)/2))};
\addplot[domain = 0:10, samples = 200, smooth, thick, black,] {4*exp(-x/2) + 2*x - 4};

\legend{$|\phi (t)-\phi_1 (t)|$, $|\phi (t)-\phi_2 (t)|$, $|\phi (t)-\phi_3 (t)|$, $|\phi (t)-\phi_4 (t)|$, $\phi (t)$}


text:
Q: Javascript KeyboardEvent in IE 8 I got 2 problems with my function, because it displays "Missing part 'Keyboard Event'". I'm working in IE 8 and have no idea, what to change here. Second thing is i would like to change key: 'n' to spacebar, so i would appreciate help for that too. I've tried using keyCode, but maybe i'm doing it wrong.
function myFunction () {
  var event = new KeyboardEvent('keydown', {
    key: 'n',
    altKey: true
  });
  document.dispatchEvent(event);
}

document.attachEvent('keydown', function (e) {
  if (e.altKey && e.key == "n") {
    // alt or ctrl is pressed
    document.getElementById("blok").innerHTML = "OOHHHH!";
  }
});

Thanks in advance for help.


text:
Q: I cant update an object in Django? Ive created a Django application where you add jobs and Im fully able to add new jobs but I can update them for some reason? The update feature isn't working and I don't know why??
<form action='/update_job/{{job.id}}' method="POST">

    {% for message in messages %}

{{message}}

    {% endfor %}

    {% csrf_token %}
    Title: <input type='text' value="{{job.job}}" name='job'>
    Description: <input type='text' value="{{job.description}}" name='description'>
    Location: <input type='text' value="{{job.location}}" name='location'>
    <input type='submit'>
</form>

def update_job(request, job_id):
    errors = Job.objects.job_validator(request.POST, job_id)
    if job.creator.id != request.session['user_id']:
        messages.error(request, "This isn't yours to edit!")
    if len(errors):
        for key, value in errors.items():
            messages.error(request, value)
        return redirect(f'/edit_job/{job_id}')
    job = Job.objects.get(id=job_id)
    job.job = request.POST['job']
    job.description = request.POST['description']
    job.location = request.POST['location']
    job.save()
    return redirect('/main')

Page not found (404)
Request Method: POST
Request URL:    http://localhost:8000/update_job/2
Using the URLconf defined in Python_Exam.urls, Django tried these URL patterns, in this order:
register
login
logout
main
job_link
job/create
jobs/<int:job_id>/view
jobs/<int:job_id>/delete
jobs/<int:job_id>/edit
jobs/<int:job_id>/update_job
The current path, update_job/2, didn't match any of these.

A: You swapped the primary key and the update_job, it is:
<form action="/jobs/{{ job.id }}/update_job" method="POST">
     …
</form>
You however might want to use the {% url … %} template tag [Django-doc] to determine the URL.


text:
Q: Link component with nextjs doesnt work (not clickable ?) Working on some web site draft,
I have an issue that I dont understand
None of my < Link > are clickable. I use nextjs link component,
by inspecting my page I seems that everything is generate as expected
<Link href={`/about/about-dark`}>

      Discover

</Link>

It's even more weird because the link in my menu works, but none of my buttons does.
here a demo: https://main.d3jahvwbjvsmfk.amplifyapp.com/

A: Hi @xif
As you can see in <canvas> tag. There are many !important which are important to you, I don't know why. Maybe it's important . That why.

The !important keyword in CSS it is generally considered bad practice to use it excessively in CSS. This is because it can make your CSS code harder to read and maintain, and it can also make it difficult to override or change the rules that are marked as !important. Instead of using the !important` keyword, it is generally better to use a more specific selector or a more organized CSS structure to give the desired rule a higher priority.

it is best to avoid using !important whenever possible, and to use more maintainable and scalable CSS techniques instead.

So, remove all your !important on that canvas. then its work fine.


text:
Q: Datatable works fine on local but on production i have error? I have an issue when I put Laravel app on production server with Yajra Datatables. I have strange issue Invalid JSON response with status code 200 in my debug. This extension works fine on my local Linux server but in production I have this error and i can't find any solution. Please any help.
This is my code.
   var table = $("#excel_table").DataTable({
        "processing": true,
        "bSort": false,
        "serverSide": true,
        "paging": false,
        "scrollX": true,
        "scrollY": "500px",
        "paging": "true",
        'dom': 'Rlfrtip',
        'colReorder': {
            'allowReorder': false
        },
        "ajax": {
            "url": "{{ route('admin.getdata') }}",
            "type": "POST",

        },

        "columns": [
            {
                'data': 'id',
                'name': 'id',
                'visible': false
            },
            {
                'data': 'action',
                'name': 'action'
            },
            {
                'data': 'kw',
                'name': 'kw'
            },
            {
                'data': 'startdatum',
                'name': 'startdatum'
            },
            {
                'data': 'enddatum',
                'name': 'enddatum'
            }]
          )}

A: Try to Debug from the console and network tab from your browser.
1. Check the Yajra Datatables script loaded properly or not on the production
2. Check the Yajra Datatables needs any extra extension or not. Debug this on the network section on chrome debug.
3. Check the response on the network see what is the response on this request (Please APP Debug TRUE from .env before debugging)

A: I solved my issue when i changed my hosting. I was on shared hosting and when I changed to VPS everything works fine.


text:
Q: Counting how many times a number appear in a pandas dataframe I have a data frame and a dictionary of lists. The dataframe looks like:
Name     begin    stop    ID
Peter     30       150    1
Hugo     4500     6000    2
Jennie    300      700    3

The dictionary looks like:
dictionary = {'0':[30,60,4650],'1':[100,5971]}

I want to create a new dataframe where I go through each of the list in a dictionary and see which interval (specified by begin column and stop column) does the value fall. For example 30, 60, and 100 falls in the the first row and 4650 and 5971 in dictionary falls in second row. But none of the values fall in third row. So I want to create a new dataframe such that I add the count as well. So the new dataframe looks like:
Name     begin    stop    ID    count
Peter     30       150    1      3
Hugo     4500     6000    2      2
Jennie    300      700    3      0

How can I achieve this? Insights will be appreciated.

A: df["count"] = df.apply(
    lambda x: sum(
        x["begin"] <= i <= x["stop"] for v in dictionary.values() for i in v
    ),
    axis=1,
)
print(df)

Prints:
     Name  begin  stop  ID  count
0   Peter     30   150   1      3
1    Hugo   4500  6000   2      2
2  Jennie    300   700   3      0

EDIT: Alternative solution using bisect:
from bisect import bisect_left

dictionary = {"0": [30, 60, 4650], "1": [100, 5971]}
values = sorted([v for lst in dictionary.values() for v in lst])

df["count"] = df.apply(
    lambda x: bisect_left(values, x["stop"]) - bisect_left(values, x["begin"]),
    axis=1,
)
print(df)

Prints:
     Name  begin  stop  ID  count
0   Peter     30   150   1      3
1    Hugo   4500  6000   2      2
2  Jennie    300   700   3      0


text:
Q: library not found for lcrypto I'm trying to build the iOS AllJoyn project, but I'm having trouble with the OpenSSL integration.
I've been looking at these directions: https://allseenalliance.org/docs-and-downloads/documentation/configuring-build-environment-ios-and-osx#unique_16
I've followed the directions all the way up to Xcode IDE Build, but now I'm getting an error that says: "library not found for lcrypto".
Looking online it looks like there might be something to do with the Makefile, but I'm not really sure what lcrypto is and what library I'm supposed to be referencing.
EDIT
I noticed that it says it is a Shell Script Invocation Error
Also here is the trace:
ld: warning: directory not found for option '-L/PATH/alljoyn/alljoyn/common/crypto/openssl/build/Debug-iphoneos'
ld: library not found for -lcrypto
clang: error: linker command failed with exit code 1 (use -v to see invocation)
scons: *** [build/darwin/arm/iphoneos/debug/obj/test/bbcclient] Error 1
scons: building terminated because of errors.
Command /usr/local/bin/scons failed with exit code 2

A: In order to successfully use the AllJoyn SDK you need to have a compiled version of the openssl library available (i.e. libcrypto.a).
The details to build the openssl library can be found in the README-INSTALLING.txt file under /alljoyn_objc in the SDK, I have copied the relevant instructions below. Once you have created the openssl library you need to place it in a directory accessible to your project (in your case "/PATH/alljoyn/alljoyn/common/crypto/openssl/build/Debug-iphoneos").
Most of this information is contained in the AllJoyn Programming Guide for Objective-C
Relevant text from the README-INSTALLING.txt file:

*

*OpenSSL is required for iOS development and is available at the following web
  address: www.openssl.org
  AllJoyn has been tested with version 1.0.1 of OpenSSL.

*Download the Xcode project that can be used to build OpenSSL for iOS from GitHub,
  at the following web address: https://github.com/sqlcipher/openssl-xcode/
Installation

*

*Copy the OpenSSL source into a separate folder on your development system, not
  under the AllJoyn SDK.

*Navigate to the OpenSSL source top folder in Finder, and copy the openssl.xcodeproj
  folder you downloaded from GitHub into this folder.

*Open the openssl.xcodeproj in Xcode.

*In Xcode, build the crypto target (libssl.a and libcrypto.a) for each
  combination of configuration (debug|release) and platform (iphoneos|iphonesimulator) that you
  need for your iOS project by selecting Product->Build For->(your desired configuration).


text:
Q: PHP echo In a while Loop for Multiple variable i am trying to echo some results
here $aditya is a array which contains multiple value
and $var3 also contains multiple value
but when i am echoing it it showing only one value
please figure out what wrong i am doing
$query1= mysql_query("SELECT * FROM table WHERE col2 in ($aditya)");

while($var1=mysql_fetch_array($query1))
{

$var2=$var1['col1'];
$var3=$var1['col2'];
$var4=$var1['col3'];

 $name=mysql_query("SELECT f_name FROM table2 WHERE f_id=$var2");
$tname=mysql_fetch_array($name);

   echo "
"."
"."".$name['f_name'].""." "."$var3"." "."("."$var4".")";

}

A: Most probably the problem comes from your query.
Put echo $query1; exit; and try it in phpmyadmin if u have such.
Other approach to see what you get from the query is to place:
echo $var1['col1'].", ".$var1['col2'].", ".$var1['col3'];

in the while() to see what u get from the query.
The problem isn't in the echo for sure.
UPDATE 2
$query1 = ("
    SELECT unique_ids, GROUP_CONCAT( whatuwant )
    FROM table
    WHERE col2 in ($aditya)
    GROUP BY unique_ids
");

A: If $aditya really is an array then it's impossible to use it the way you are in your query. MySQL expects a comma separated list of elements, so you could implode the PHP array and feed it to the query:
$query1= mysql_query("SELECT * FROM table WHERE col2 in (" . implode(',', $aditya) . ")");

Besides that you might wanna consider giving your variables more meaningful names, because you'll only confuse yourself and other coders working on your projects if you name them $var1, $var2 etc. Just a hint.

A: So many things might be wrong here
A. $aditya was not properly defined. If its an array then you need to combine it with implode if noy make sure its properly formatted
Expected Output should be like this
 SELECT * FROM table  WHERE col2  IN ( 250, 220, 170 );

B. $name is not an array so $name['f_name'] would not work. You use use $tname['f_name'] instead
C.  I think you need to update your question with the exact error you are having your code as so many things that can go run that we can not test remotely eg. Does a table name table even exist in the first place


text:
Q: Mul255 - what is it? Some days ago I downloaded sources of SumatraPDF and started exploring it. I found that library MuPDF сontains on interesting function, but not understand it.
static inline int fz_mul255(int a, int b) {
    int x = a * b + 128;
    x += x >> 8;
    return x >> 8;
}

In some other sources I found another definition of mul255 function:
(a+1)*b >> 8

What is it? Help.

A: In graphics we often use scaled integer values (range 0 to 255) to represent color values in the range of 0.0 to 1.0.
The mul255 function multiplies two such scaled integers, such that 255 * 255 = 255.
The implementation in MuPDF is based on Jim Blinn's accurate scaling method from the book "Dirty Pixels" by Jim Blinn. The other implementation you quoted (a+1)*b >> 8 is a faster, but less accurate, approximation.

A: If it weren't for the second line (x += x >> 8) I'd know exactly what the method does. If we remove it, for purpose of discussion:
static inline int fz_mul255(int a, int b) {
    int x = a * b + 128;
    // x += x >> 8;
    return x >> 8;
}

The method now multiples a * b, which are fixed-point numbers with 8 fractional bits, rounding to the nearest result. Specifically, the a * b is the multiple, the + 128 rounds to the nearest (remember that this gets shifted out, so it only has an effect if it causes a carry to the next most significant bit position after bit 7), and the >> 8 corrects the position of the point (because multiplying two fixed-point values with 8 fractional bits using integer arithmetic yields a fixed-point value with 16 fractional bits).
The only question then is what that 'x += x >> 8' is for, and that I'm afraid I do now know. In effect it multiplies the result by (1 + 1/256).


text:
Q: Xcode4 : custom task for copying resources to the bundle Folks, is it possible to create a custom task for copying resources in Xcode?
I'd like to use rsync instead of Xcode's built-in resource copy tasks. From time to time Xcode for some reason doesn't copy modified resources to the bundle so I'd like to have a better control over this task.
I think I need some magic variable which points to the destination bundle directory, so I could create the following task:
rsync -a ${SRCROOT}/resources ${PATH_TO_THE_BUNDLE}/
...but I have no idea if there is such a variable.
Update: I tried ${BUILT_PRODUCTS_DIR} variable and it points to some intermediate directory while during the runtime [[NSBundle mainBundle] pathForResource: my_path ofType: nil] returns something completely different. Is there any Xcode variable which which returns the same result as NSBundle does?

A: Yes... it sounds like you already know how to add a "Run Script" action to a build scheme, and the magic variables you may want are either:
$SRCROOT -- the source tree's root directory
$BUILT_PRODUCTS_DIR -- the convoluted path to the destination where the built product eventually arrives at (i.e. and yes, this variable's contents changes slightly depending on whether you are building a Mac app, or an iPhone app targeting the simulator or the device)
So... it sounds like what you want is "$BUILT_PRODUCTS_DIR/Contents/Resources" in your build script?

A: To do this on a per-directory basis:

*

*Add a 'Run Script Build Phase' (Editor > Add Build Phase > Add Run Script Build Phase)

*Copy/paste the following script into the build phase (don't forget to set the actual paths on line 1):

dirsToCopy=("path1/directory1","path2/directory2")

for INPATTERN in "${dirsToCopy[@]}"; do
    INDIR=$PROJECT_DIR/$INPATTERN/*
    OUTDIR=$TARGET_BUILD_DIR/$CONTENTS_FOLDER_PATH/$INPATTERN
    cp -R $INDIR $OUTDIR
done

For those not used to working with shell scripts:

*

*paths on line 1 of the script are relative to the project directory (where the .xcodeproj file resides)

*you can add more (or less) paths to the array dirsToCopy if you want

*you can change the pattern of files to copy where variable INDIR is defined

*you can change how the copying is done (currently, recursive due to -R) by changing the flags to cp in the last line of script within the for block.


text:
Q: XmlWriter unknow error when execute html file A weird error is occuring when I execute my test HTML file.
My code is below:
<html>
 <head>
   <title>PHP Test</title>
 </head>
 <body>
 <?php
mysql_connect('myip', '----', '----');
mysql_select_db('test');

$sql = "SELECT 1st, 3rd FROM test";
$res = mysql_query($sql);

$xml = new XMLWriter();

$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);

$xml->startElement('dataset');

while ($row = mysql_fetch_assoc($res)) {
  $xml->startElement("data");

      $xml->writeAttribute('unit', $row['1st']);
  $xml->writeAttribute('value', $row['3rd']);

  //$xml->writeRaw($row['country']);

  $xml->endElement();
}

$xml->endElement();

header('Content-type: text/xml');
$xml->flush();
?>
 </body>
</html>

After I executed it, it went error after $xml = new XMLWriter(); like this:
http://i.imgur.com/oALlSmX.png
It only shows pure text after I newed an XmlWriter object.
If I made any mistake please let me know and sorry for my bad English.

This is the error shows when I try to access php file from localhost. Imgur


text:
Q: Save complexa data using entity framework Hi every one I want to save complex data using Entity Framework and C#. I have 2 classes Product and Order defined as follows
Product Class
public class Product
    {
        [Key]
        public int Id { get; set; }
        public string SKU_Code { get; set; }
        public string Product_Name { get; set; }
        public string Quantity { get; set; }
        public string Price { get; set; }
        public string Image { get; set; }
        public DateTime Created_Date { get; set; }
        public DateTime Modified_Date { get; set; }
    }

Order Class
public class Order
    {
        [Key]
        public long ID { get; set; }
        public string Order_Id { get; set; }
        public string Payment_Type { get; set; }
        public string Customer_Name { get; set; }
        public string Shipping_Address { get; set; }
        public DateTime Order_Date { get; set; }
        public DateTime Modified_Date { get; set; }
        public bool Flag { get; set; }
        public List<Product> ProductDetails { get; set; }
    }

And I want to save data Order details and my piece of code is as follows.
public Order Add(Order odrerDetails)
{
    using (var context = new EcommerceDBContext())
    {
        var MyOrder_Id = Helper.Random(7); //Generate random orderID from my class
        foreach (var detail in odrerDetails.ProductDetails)
        {
            odrerDetails.Order_Id = MyOrder_Id;
            odrerDetails.Quantity = Convert.ToInt32(detail.Quantity);
            odrerDetails.Amount = Convert.ToDouble(detail.Price);

           //Other Details
            context.objOrderListing.Add(odrerDetails);
        }
        context.SaveChanges();
        return odrerDetails;
    }
}

This gives me perfect data but when it comes to context.SaveChanges(); it return's me error.

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.

A: To me you domain model seems all wrong. The order should just be used for grouping, its a typical e-commerce scenario.
When you get a receipt of your purchases, you get one receipt with every Item and price listed next to it. Its considered as one order of multiple things, not multiple orders of multiple things.
Reading your last comment, you cant have multiple orders with the same order id. Try to understand the domain first before trying to solve it with code. Also,you have no notion of a Customer with an Order.
public class Product
{
    [Key]
    public int Id { get; set; }
    public string SKU_Code { get; set; }
    public string Product_Name { get; set; }
    public string Price { get; set; }
    public string Image { get; set; }
    public DateTime Created_Date { get; set; }
    public DateTime Modified_Date { get; set; }
}

public class Order
{
    [Key]
    public long ID { get; set; }
    public string Order_Id { get; set; }
    public string Payment_Type { get; set; }
    public string Customer_Name { get; set; }
    public string Shipping_Address { get; set; }
    public DateTime Order_Date { get; set; }
    public DateTime Modified_Date { get; set; }
    public bool Flag { get; set; }
    public List<OrderLineItem> Items { get; set; }
}

public class OrderLineItem
{
    [Key]
    public long ID { get; set; }
    public long Order_Id { get; set; }
    public long Product_Id {get; set;}
    public int Quantity {get; set;}
}


text:
Q: Javascript error yet the code still works Ok I am really confused. Right now I am working on getting a datagrid to focus on a cell by selecting a point on a map. Below is the javascript that controls the election. I added cell.elements.focus() and it DOES focus on the cell I want it to but it also gives me an error at the same time saying "Microsoft JScript runtime error: 'element' is null or not an object" Any idea why it would give me an error but still work? Is there a way I can get rid of this error?
function selectRowByID(sIDField, sID) {
var bSelectionFound = false;
var grid = igtbl_getGridById(_gridID);
if (grid != null) {
    var rows = grid.Rows;
    for (var x = 0; x < rows.length; x++) {
        var row = rows.getRow(x);
        var cell = row.getCellFromKey(sIDField);
        if (cell != null) {
            cell.scrollToView(true);
            if (cell.getValue() == sID) {
                row.setSelected(true);
                cell.element.focus();
                bSelectionFound = true;
            }
        }
    }
}
return bSelectionFound;

A: The error says 'element' is not set. Try skipping the .element in this sentence
cell.element.focus();

so it becomes
cell.focus();

A: Just a guess but try replacing
cell.element.focus();
with
if (cell.element) cell.element.focus();

that might get rid of the error.


text:
Q: Visual Studio dynamic javascript reference intellisense from localhost It appears that Visual Studio 2010 will skip references that are not formatted http://x.x... I'm trying to use
/// <reference path="http://localhost:12946/js/fancytest" />

to generate intellisense for a dynamic javascript result without going through the hassle of setting up a subdomain.
I've used fiddler and found that Visual Studio is entirely ignoring my reference if I don't include a subdomain. No request to my script controller is attempted.
Does anyone know if there is a workaround for this?

A: You can use lvh.me which points to 127.0.0.1.
It works in VS2012


text:
Q: Set focus on a NSTextField in an NSMenu? I have an NSMenu in the Mac statusbar, inside it I have a load of NSMenuItems and a custom view. Inside the custom view I have an NSTextField. I want to set the focus on the NSTextField when the menu is opened as in the Spotlight menu so the user can type straight away.
I have tried quite a few methods including:
    [myTextField becomeFirstResponder];

and
    [myTextField selectText: self];
    [[myTextField currentEditor] setSelectedRange:NSMakeRange([[myTextField stringValue] length], 0)];

but none of them work.
Thanks
Alex

A: You were on the right track with the first one, but -becomeFirstResponder doesn't actually make your view the first responder--you have to call -[NSWindow makeFirstResponder:] for that.
Google suggests that NSMenus actually have an attached window.  You have to use it very carefully, but it is safe to call makeFirstResponder: on it.
More information about this and how to take advantage of it here: https://web.archive.org/web/20171113100008/http://www.cocoabuilder.com/archive/cocoa/195835-set-focus-on-nsview-in-an-nsmenuitem.html


text:
Q: Receiving Error: Invalid hook call in functional component I'm trying to create a simple component and publish it to npm. Before publishing, I want to test the component out; however, whenever I consume my component in my test application, I'm getting the following: Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
Here is the offending component:
MyComponent.tsx:
import React, { useState } from 'react';

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (

      <button onClick={increment} name='test1'>
        Increment
      </button>
      <button onClick={decrement} name='test2'>
        Decrement
      </button>

  );
};

export default MyComponent;

index.ts:
import MyComponent from './MyComponent';

import './index.css';

export { MyComponent };

And this is the test application:
import React from 'react';
import './App.css';
import { MyComponent } from 'one-select';

function App() {
  return (

        <MyComponent />

  );
}

export default App;

MyComponent is imported into the test app via npm install /path/to/mycomponent-project
I've created other react apps before (but not a stand-alone component) and I've never had this issue. Any advice would be greatly appreciated.


text:
Q: Read NumPy 4d int array from python to C# So I have a 4d 61x41x61x41 numpy integer array in python which I want to read in Unity. Which is the best way to do it and with what data format should I work with?
I have tried with JSON but JSONUtility has trouble reading it as it is not an object. What would you suggest?
EDIT: When using JSON I tried this:
class TransitionClass
    {
        public List<List<List<List<int>>>> transitionMatrices = new List<List<List<List<int>>>>();
    }

TransitionClass transition;
        using (StreamReader r = new StreamReader(transitionJsonPath))
        {
            string json = r.ReadToEnd();
            transition = JsonUtility.FromJson<TransitionClass>(json);
        }

But I get an empty list returned.
The JSON file right now looks like this:
{"transitionMatrices":[[[[8,3,12,0,2,0,0,5 ... 2,4,1,0]]]]}

I even tried using simple arrays and without using classes but got the error 'JSON must represent an object type'

A: If you change transitionMatrices to be an int [][][][] it works with the built in JsonSerializer in c#
        public void JsonTest()
        {
            var result = JsonSerializer.Deserialize<TransitionClass>(@"{""transitionMatrices"":[[[[8,3,12,0,2,0,0,5,4,1,0]]]]}");
        }

        public class TransitionClass
        {
            public int [][][][] transitionMatrices { get; set; }
        }


text:
Q: Mann Whitney U and ROC AUC relationship I've been learning about the relationship between Mann-Whitney U.
Supposedly, the area under the ROC curve should be
$\text{AUC} = \frac{U}{n_0 n_1}$, where $U$ is the Mann-Whitney statistic, $n_0$ is the number of negative examples, and $n_1$ is the number of positive examples.
I attempted to test this using python's scipy and scikitlearn library and found some unaccounted discrepancies.
Unfortunately, I can't share the data, but here's the code and output.
U = mannwhitneyu(preds['score'], preds['truth'])[0]
vc = preds['truth'].value_counts()
n0n1 = vc.loc[0] * vc.loc[1]

print('U: %d' % U)
print('n0n1: %d' % n0n1)
print('U/n0n1: %0.3f' % (U/n0n1))
print('AUC: %0.3f' % roc_auc_score(preds['truth'], preds['score']))

output:
U: 26899093155
n0n1: 40496604804
U/n0n1: 0.664
AUC: 0.674

However, when I using the implementation described in the above link:
def calc_U(y_true, y_score):
    n1 = np.sum(y_true==1)
    n0 = len(y_score)-n1

    ## Calculate the rank for each observation
    # Get the order: The index of the score at each rank from 0 to n
    order = np.argsort(y_score)
    # Get the rank: The rank of each score at the indices from 0 to n
    rank = np.argsort(order)
    # Python starts at 0, but statistical ranks at 1, so add 1 to every rank
    rank += 1

    # If the rank for target observations is higher than expected for a random model,
    # then a possible reason could be that our model ranks target observations higher
    U1 = np.sum(rank[y_true == 1]) - n1*(n1+1)/2
    U0 = np.sum(rank[y_true == 0]) - n0*(n0+1)/2

    # Formula for the relation between AUC and the U statistic
    AUC1 = U1/ (n1*n0)
    AUC0 = U0/ (n1*n0)

    return U1, AUC1, U0, AUC0

gives me the correct equality $\text{AUC} = \frac{U}{n_0 n_1}$.
I've attempted applying the solution described here, but this is not resolving my issue.  I'm wondering if it could have anything to do with these particular implementations with the functions.

A: I believe Lukas Roberts is correct that this is an open issue in scipy. The current implementation reverses the definitions of U1 and U2.
The problem is in these lines:
u1 = n1*n2 + (n1*(n1+1))/2.0 - np.sum(rankx, axis=0)  # calc U for x
u2 = n1*n2 - u1  # remainder is U for y

When we place the definition of u1 in u2, we see that the formula for u2 used here is in fact the formula for u1 from Wikipedia:
u2 = n1*n2 - n1*n2 + (n1*(n1+1))/2.0 - np.sum(rankx)

There is an complete revision in the works, but the pull request seems to be stuck for now.

A: Please check the case where it has the tied value.
=======================================
Assign numeric ranks to all the observations (put the observations from both groups to one set), beginning with 1 for the smallest value. Where there are groups of tied values, assign a rank equal to the midpoint of unadjusted rankings. E.g., the ranks of (3, 5, 5, 5, 5, 8) are (1, 3.5, 3.5, 3.5, 3.5, 6)
(the unadjusted rank would be (1, 2, 3, 4, 5, 6)).
from https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test#Calculations


text:
Q: LAContext evaluatePolicy:localizedReason:reply: errors with LAErrorUserCancel when user doesn't cancel I am trying to implement Touch ID on my app:
LAContext *ctx = [[LAContext alloc] init];
[ctx evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"Authenticate to access." reply:^(BOOL success, NSError *error) {
    if(success){
       ...
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (error.code) {
                case LAErrorTouchIDNotAvailable:
                case LAErrorUserFallback:
                    self.passwordPanel.hidden = NO;
                    break;

                default:
                    //we hit here with error code -2
            }
        });
    }
}];

This is an in-house app that is currently used by 5 users. Four people including me (with a mix of iPhone 6 and iPhone 5s devices), have no problems. The last user (also having an iPhone 6) constantly hits the default case and their error code is -2, which is set to LAErrorUserCancel. The problem is that, they are hitting it instantly when evaluatePolicy is called, without even being able to scan their finger or tap cancel.
Why would this happen?


text:
Q: Hypothesis testing, chance To find out whether the inhabitants of two South Pacific islands may be regarded as having the same racial ancestry, an anthropologist determines the cephalie indices of six adult
males from each island, getting $x_1$ = 77.4 and $x_2$ = 72.2 and the corresponding standard
deviation $s_1 = 3.3$ and $s_2 = 2.1$. Test at $0.01$ level of significance whether the difference between the two sample means can reasonably be attributed to chance. Assume that the
populations sampled are normal and have equal variances.
I am confused on what the hypotheses should be: should it be $H_0: \mu_1 - \mu_2 = 0$ and $H_1: \mu_1-\mu_2 \neq 0$?

A: Pooled 2-sample t test. Minitab is one of the relatively few statistical packages
that will perform a pooled 2-sample t test on summarized data
(that is, without seeing the 12 actual data values). You
have correctly used 6 + 6 -2 = 10 degrees of freedom to get
your critical value 3.169. Also, Minitab gets $T = 3.26$ for the test
statistic, which agrees with your result.
Here is Minitab output.
Two-Sample T-Test and CI

Sample  N   Mean  StDev  SE Mean
1       6  77.40   3.30      1.3
2       6  72.20   2.10     0.86

Difference = μ (1) - μ (2)
Estimate for difference:  5.20
95% CI for difference:  (1.64, 8.76)
T-Test of difference = 0 (vs ≠):
  T-Value = 3.26  P-Value = 0.009  DF = 10
Both use Pooled StDev = 2.7659

Welch 2-sample t-test. However, as a matter of statistical practice, I would not be willing
to assume the two population variances are equal. (If the population
means might be different, why not also the population variances?)
The Welch version of the 2-sample t test does not assume equal
population variances. Standard statistical practice is not to assume
equal variances unless you have strong prior evidence of equality. (In this
situation, that might come from measuring cephalic indexes for many other
Pacific islands and having found that means vary, but that variances don't.)
Typically the Welch 2-sample t test uses a reduced degrees of freedom
to compensate for possibly unequal variances. A formula involving sample
sizes and sample standard deviations is used to find the adjusted degrees
of freedom. Here is Minitab output for the Welch 2-sample t test.
Two-Sample T-Test and CI

Sample  N   Mean  StDev  SE Mean
1       6  77.40   3.30      1.3
2       6  72.20   2.10     0.86

Difference = μ (1) - μ (2)
Estimate for difference:  5.20
95% CI for difference:  (1.52, 8.88)
T-Test of difference = 0 (vs ≠):
  T-Value = 3.26  P-Value = 0.012  DF = 8

Notice that df = 8 here instead of 10 for the pooled test.
Also, notice that there is no note at the end about using
a pooled standard deviation. The P-value is a little larger
for the Welch test, but is still below 0.05, so $H_0$ is
rejected here as well.