text:
Q: How to build a Gray-code generator in Picat? Encouraged by the knowledge I've gained from the answer to my previous post, I aim to generate Gray-codes of given length. The procedure hamming seems to work correctly, however, the Picat system finds no solution. Where's the mistake here?
import cp.
main => gray(2).

gray(CodeLen) =>
    CodeNr is 2**CodeLen,
    Codes = new_array(CodeNr, CodeLen),
    Codes :: 0..1,

    foreach(CodeNr1 in 1..CodeNr)
        CodeNr2 = cond(CodeNr1 == CodeNr, 1, CodeNr1 + 1),
        hamming(Codes[CodeNr1], Codes[CodeNr2], 0, H),
        H #= 1
        % the Hamming distance between 2 consecutive codes is 1
    end,

    solve(Codes),
    printf("%w\n", Codes).

hamming([], [], A, H) ?=> H #= A.
hamming([H1|T1], [H2|T2], A, H) ?=>
    H1 #!= H2,
    A1 #= A + 1,
    hamming(T1, T2, A1, H).
hamming([H1|T1], [H2|T2], A, H) ?=>
    H1 #= H2,
    A1 #= A + 0,
    hamming(T1, T2, A1, H).

A: The reason that the model don't print anything is that you are using list constructs ([H|T]) on the array matrix Code which is not allowed. You have to convert the rows of the matrix (which are arrays) to lists. This can be done in two ways:

*

*Convert the array matrix Code matrix to a list matrix with array_matrix_to_list_matrix() (requires that the util package is loaded):

import util.

% ....

gray(CodeLen) =>
    CodeNr is 2**CodeLen,
    Codes = new_array(CodeNr, CodeLen).array_matrix_to_list_matrix, % <--
    Codes :: 0..1,
    % ....

*Convert the array parameters in the call to hamming/4 to lists with theto_list() function. E.g.:

    % ...
    foreach(CodeNr1 in 1..CodeNr)
        CodeNr2 = cond(CodeNr1 == CodeNr, 1, CodeNr1 + 1),
        % hamming(Codes[CodeNr1], Codes[CodeNr2], 0, H), % Original
        hamming(Codes[CodeNr1].to_list, Codes[CodeNr2].to_list, 0, H), % <---
        H #= 1
        % the Hamming distance between 2 consecutive codes is 1
    end,
    % ...

Update.
Here's a constraint model that solves the problem of generating different rows that was indicated in the comment. It uses a simpler version of hamming_distance by just counting the number of different bits with sum. Also, for symmetry, I require that the first and last row also have a Hamming distance of 1.  (This was in the original code.)
To require different rows, the constraint to_num/3 is used to converts a number to digits in an array (given a base, here 2). These numbers (which must be distinct) are in the CodesNum list.
import cp,util.
main =>
   go.

go ?=>
  gray(5),
  nl,
  % fail,
  nl.
go => true.

% First solution for N=2..10
go2 ?=>
  foreach(N in 2..10)
    println(n=N),
    if time(gray(N)) then
      true
    else
      println(nope)
    end,
    nl
  end,
  nl.
go2 => true.

gray(CodeLen) =>
    CodeNr is 2**CodeLen,
    println(codeNr=CodeNr),
    Codes = new_array(CodeNr, CodeLen).array_matrix_to_list_matrix,
    Codes :: 0..1,
    CodesNum = new_list(CodeNr), % array -> integer
    CodesNum :: 0..CodeNr,

    foreach(CodeNr1 in 1..CodeNr)
        to_num(Codes[CodeNr1],2,CodesNum[CodeNr1]),
        CodeNr2 = cond(CodeNr1 == CodeNr, 1, CodeNr1 + 1),
        hamming_distance(Codes[CodeNr1], Codes[CodeNr2], 1),
    end,
    % around the corner
    % hamming_distance(Codes[1], Codes[CodeNr],1),

    all_different(CodesNum),
    CodesNum[1] #= 0, % symmetry breaking
    Vars = CodesNum ++ Codes.vars,
    solve($[ff,updown],Vars),
    printf("%w\n", Codes),
    println(codesNum=CodesNum),nl.

% Hamming distance of As and Bs
hamming_distance(As, Bs,Diff) =>
   Diff #= sum([(A #!= B) : {A,B} in zip(As,Bs)]).

% Convert Num to/from a list of digits in List (base Base)
to_num(List, Base, Num) =>
        Len = length(List),
        Num #= sum([List[I]*Base**(Len-I) : I in 1..Len]).

to_num(List, Num) =>
       to_num(List, 10, Num).

It solves N=4 in 0s:
n = 4
codeNr = 16
[[0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0],[1,1,1,1],[1,1,0,1],[1,0,0,1],[1,0,1,1],[1,0,1,0],[0,0,1,0],[0,1,1,0],[0,1,1,1],[0,0,1,1],[0,0,0,1],[0,1,0,1],[0,1,0,0]]
codesNum = [0,8,12,14,15,13,9,11,10,2,6,7,3,1,5,4]

CPU time 0.0 seconds.

The model solves N=2..7 (first solution) quite fast, but it struggles with N=8, and I don't have the time to test different search heuristics to make it faster.
Here's some another approach for solving the gray code but without constraint modelling and it's much faster: http://hakank.org/picat/gray_code.pi
Update2 Here's a much faster version of hamming/4. It use a reification (boolean) variable B to check if H1 and H2 are different and can then be used as the value to add to A0.
hamming2([], [], A, A).
hamming2([H1|T1], [H2|T2], A0, H) :-
    B :: 0..1,
    H1 #!= H2 #<=> B #= 1,
    A1 #= A0 + B,
    hamming2(T1, T2, A1, H).


text:
Q: JSTree Prevent drag from class Afternoon,
I am having a few issues with JSTree 3.0. What I would like to do is on the load of the page prevent all nodes from being dragged using the dnd plugin. I then want to be able to click an edit button to enable the drag and drop functionality on all nodes. I think the best way to achieve this would be to set a class on all nodes and prevent the drag if it contains this class. When the edit is clicked the class is removed.
I have found a way to get the class of the node on move_node using data.node.li_attr.class. This returns the class but I cannot work out how to stop the drag operation. Please see the below code so far:
$tree.on("move_node.jstree", function(e, data){
            var NodeClass = data.node.li_attr.class;
            if(NodeClass == "noMove")
            {
                $.jstree.defaults.dnd_is_draggable(false);
            }else{
                $tree.jstree("open_all");
                var nodeId = data.node.id;
                var nodeParent = data.parent;
                var level = data.node.parents.length;
                getChildren(data.node.id, level);
                var url = window.location.origin + window.location.pathname.replace(regexp, "/ajaxSaveCaseFamily");

                $.ajax({
                    type:"POST",
                    url:url,
                    data:{
                        "_token":token,
                        "nodeId":nodeId,
                        "nodeParent":nodeParent,
                        "depth":level
                    },
                    success:function(data){
                        var query = data;
                        if(query.RESULT == "FAIL"){
                            $("#errMsg").html(query.REASON);
                        }
                    }
                })
            }
        });

Any help would be greatly appreciated!
Thanks in advance!!

A: You are approaching this wrong - when the event is triggered the drag has already begun - there is a function that gets called to determine if nodes are draggable (even before dragging has started):
http://www.jstree.com/api/#/?q=is_dra&f=$.jstree.defaults.dnd.is_draggable
Here is an example on how to use it:
var is_dragging_allowed = false;
$('#edit_button').on('click', function () {
  is_dragging_allowed = true;
});
$('#tree').jstree({
  dnd : {
    is_draggable : function () {
      return is_dragging_allowed;
    }, ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ebean ORM auto create table structure in SQLite I have a following model class. It's just for testing.
@Entity
public class Quest {

    public static final Find<Long, Quest> find = new Find<Long, Quest>() {};

    @Id
    Long id;

    @Column(length=100)
    String name;

    //... Constructors/getters/setters
}

And in main method trying to connect to database:
public static void main(String[] args) {
    if(!AgentLoader.loadAgentFromClasspath(
        "avaje-ebeanorm-agent",
        "debug=1;packages=com.package.mmohelper.model.**")
    ) {
        throw new RuntimeException("Agent loader exception");
    }

    DataSourceConfig ds = new DataSourceConfig();
    ds.setDriver("org.sqlite.JDBC");
    ds.setUrl("jdbc:sqlite:data");
    ds.setUsername("");
    ds.setPassword("");
    ds.setIsolationLevel(Connection.TRANSACTION_SERIALIZABLE);

    ServerConfig config = new ServerConfig();
    config.setName("Sqlite");
    config.setDdlGenerate(true);
    config.setDdlRun(true);
    config.setAutoCommitMode(true);
    config.setDefaultServer(true);
    config.setDatabasePlatform(new SQLitePlatform());
    config.getDatabasePlatform().getDbDdlSyntax().setIdentity("");
    config.setDataSourceConfig(ds);

    EbeanServer server = EbeanServerFactory.create(config);

    Quest q = new Quest(0L, "Quest1");
    q.save(); // !!! Fails here !!!
}

When I run it, it fails with following exceptions:
Exception in thread "main" javax.persistence.PersistenceException: ERROR executing DML bindLog[] error[[SQLITE_ERROR] SQL error or missing database (no such table: quest)]

Caused by: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: quest)

So, question is: what's wrong? Why does table won't create automatically? What if I want to create database 'on-the-fly'? I should use plain JDBC for creating table structure?

A: @Entity
@Table(name = "quest")
public class Quest


text:
Q: Highchart x-axis shuffle randomly even the data is proper
We have implemented ppt download feature with python-pptx including highcharts init.
But the X-axis values are shuffling randomly, Even the data encountered is proper.
Current output X-axis: 29-feb, 31-jan, 31-dec
Required output X-axis: 31-Oct, 30-Nov,31-Dec,..and so on
(data is dynamic, we cant make axis values fix)
def create_column_clustered_comparison_payload(slide_layout, input_chart_data, chart_width, chart_height, enable_3d):
column_clustered_comparison = { "infile": {
        "title": {
            "text": None
        },
        "chart": {},
        "xAxis": {
            "lineColor": "#000000",
            "lineWidth": 1,
            "tickLength": 0,
            "gridLineWidth": 0,
            "title": {
                "text": None
            },
            "labels": {
                "style": {
                    "fontSize": "9px",
                    "color": "#000000"
                },
                "padding": 0
            }
        },
        "yAxis": [{
            "title": {
                "text": None
            },
            "lineColor": "#000000",
            "lineWidth": 1,
            "gridLineWidth": 0,
            "labels": {
                "style": {
                    "fontSize": "9px",
                    "color": "#000000"
                },
                "padding": 0,
                "format": "{value}%"
            }
        }, {
            "title": {
                "text": None
            },
            "lineColor": "#000000",
            "lineWidth": 1,
            "opposite": True,
            "gridLineWidth": 0,
            "labels": {
                "style": {
                    "fontSize": "9px",
                    "color": "#000000"
                },
                "padding": 0
            }
        }],
        "plotOptions": {
            "column": {
                "grouping": True,
                "shadow": False,
                "dataLabels": {
                    "enabled": True,
                    "style": {
                      "fontSize": "10px",
                      "fontWeight": False
                    }
                }
            }
        },
        "legend": {
            "enabled": True,
            "itemStyle": {
                "color": "#000000",
                "fontSize": "9px",
                "fontWeight": None
            },
            "itemMarginTop": 5,
            "itemMarginBottom": 20
        },
        "credits": {
            "enabled": False
        },
        "series": [{
            "type": "column",
            "borderWidth": 0,
            "color": "#29336a"
        }, {
            "type": "column",
            "borderWidth": 0,
            "color": "#b8c4ff"
        }, {
            "type": "spline",
            "color": "#ffab3d",
            "lineWidth": 2,
            "marker": {
                "lineWidth": 2,
                "lineColor": "#747578",
                "fillColor": "white",
                "radius": 2.5
            }
        }]
    }
}

chart_keys = list(input_chart_data.keys())
categories = [category for category in input_chart_data[chart_keys[0]]['data'].keys()]
column_clustered_comparison['infile']['xAxis']['categories'] = categories

index = 0
for key in chart_keys:

    chart_type = input_chart_data[key]['type']
    if chart_type == 'bar':

        index += 1
        if index == 2:

            column_clustered_comparison['infile']['series'][1]['name'] = key
            column_clustered_comparison['infile']['series'][1]['data'] = \
                [input_chart_data[key]['data'][category] for category in categories]
            continue

        column_clustered_comparison['infile']['series'][0]['name'] = key
        column_clustered_comparison['infile']['series'][0]['data'] = \
            [input_chart_data[key]['data'][category] for category in categories]

    elif chart_type == 'line':
        column_clustered_comparison['infile']['series'][2]['name'] = key
        column_clustered_comparison['infile']['series'][2]['data'] = \
            [input_chart_data[key]['data'][category] for category in categories]
        column_clustered_comparison['infile']['series'][2]['yAxis'] = 1

if chart_width:
    column_clustered_comparison['infile']['chart']['width'] = 570
if chart_height:
    column_clustered_comparison['infile']['chart']['height'] = 280

return column_clustered_comparison


text:
Q: Grouping lat/lng into grid of 1 km squares We have a lot of lat/lng that we would like to group into a grid of ~1 km squares.
1) Grouping lat isn't difficult. That's just grouping them by lat +/- 0.02, i.e. 14.X will be grouped like this:
14.00-14.02
14.02-14.04
14.04-14.06
etc.

2) Problem is lng, since the length of each lng varies depending on where you are looking.
Does anyone know a formula for converting lng to km that handles the varying length of lng?
I know this is not 100% precise 1 km squares, for it's good enough for our purpose.

A: Using Google, approximated length (kilometers) per 1 degree of longitude can be calculated as below. (This sample formula is assuming latitude= 14.02. Please change it as necessary.)
(6378000*2*pi*(cos(14.02/180*pi))/360)/1000

If you prefer Excel
A1:    14.02
B1:    = (6378000 * 2 * PI() * COS(A1/180*PI()) / 360) / 1000


text:
Q: Second Variations of Functionals Let $\displaystyle J[y]=\int_{\alpha}^{\beta}f[x,y(x),y'(x)]dx$, where $y(\alpha)=a$, $y(\beta)=b$. Consider a small perturbation $\delta y$. To second order, we have
$$J[y+\delta y]-J[y]=\int_{\alpha}^{\beta}\left\{\delta y\frac{\partial f}{\partial y}+(\delta y)'\frac{\partial f}{\partial y'}\right\}dx+\frac{1}{2}\int_{\alpha}^{\beta}\left\{(\delta y)^2\frac{\partial^2 y}{\partial y^2}+2\delta y(\delta y)'\frac{\partial^2 f}{\partial y\partial y'}+(\delta y)'^2\frac{\partial^2 f}{\partial y'^2}\right\}dx$$
where $\delta y(\alpha)=\delta y(\beta)=0$. Integrating the first term ("first variation" $\delta J[y,\delta y]$) by parts we get
$$\int_{\alpha}^{\beta}\left\{\delta y\frac{\partial f}{\partial y}+(\delta y)'\frac{\partial f}{\partial y'}\right\}dx=\int_{\alpha}^{\beta}\delta y\left\{\frac{\partial f}{\partial y}-\frac{d}{dx}\left(\frac{\partial f}{\partial y'}\right)\right\}dx$$
For the second term, note that $\delta y(\delta y)'=(\delta y^2)'/2$, so, integrating by parts, we can rewrite this "second variation" $\delta^2 J[y,\delta y]$ as
$$\frac{1}{2}\int_{\alpha}^{\beta}\left\{(\delta y)^2\frac{\partial^2 y}{\partial y^2}+2\delta y(\delta y)'\frac{\partial^2 f}{\partial y\partial y'}+(\delta y)'^2\frac{\partial^2 f}{\partial y'^2}\right\}dx=\frac{1}{2}\int_{\alpha}^{\beta}\left\{(\delta y)^2\left[\frac{\partial^2 f}{\partial y^2}-\frac{d}{dx}\left(\frac{\partial^2 f}{\partial y\partial y'}\right)\right]+(\delta y)'^2\frac{\partial^2 f}{\partial y'^2}\right\}dx$$
Hence, to second order
$$J[y+\delta y]-J[y]=\delta J[y,\delta y]+\delta^2 J[y,\delta y]=\int_{\alpha}^{\beta}\delta y\left\{\frac{\partial f}{\partial y}-\frac{d}{dx}\left(\frac{\partial f}{\partial y'}\right)\right\}dx+\frac{1}{2}\int_{\alpha}^{\beta}\left\{(\delta y)^2\left[\frac{\partial^2 f}{\partial y^2}-\frac{d}{dx}\left(\frac{\partial^2 f}{\partial y\partial y'}\right)\right]+(\delta y)'^2\frac{\partial^2 f}{\partial y'^2}\right\}dx$$
Suppose that $\delta^2 J[y,\delta]\geq 0$ for all sufficiently differentiable functions $y(x)$ and $\delta y$ satisfying $\delta y(\alpha)=\delta y(\beta)=0$ and $y(\alpha)=a$, $y(\beta)=b$. Assume that $y_0(x)$ satisfies $\displaystyle \frac{\partial f}{\partial y_0}-\frac{d}{dx}\left(\frac{\partial f}{\partial y_0'}\right)\equiv 0$. How can one show that $J[y]$ has an absolute minimum  for $y=y_0$?


text:
Q: How to position an absolute element on the top of the screen in react-native I want to position a Pressable to detect presses all over my Screen, but I can only place it inside the parent when I use top: 0, left: 0 as the style.
I use it inside a Component to create a pop-up menu, so I can't just put it inside the top View.
How can I make it fill the whole screen?


text:
Q: "Check" or "check out" or "check on"?
Mary was very busy. That, however, didn't stop her from checking
  (on/out) Mrs. Johnsons' research.

Is it necessary to add on or out in cases like this? If so, why?

A:
Mary was very busy. That, however, didn't stop her from checking Mrs. Johnson's research.
  Mary was very busy. That, however, didn't stop her from checking out Mrs. Johnson's research.

These both mean that Mary reviewed Mrs. Johnson's research.
But when you say:

Mary was very busy. That, however, didn't stop her from checking on Mrs. Johnson's research.

this means Mary checked on the status/progress of Mrs. Johnson's research, but not the contents of it.


text:
Q: Display whole objects in Vue.js Problem is that:
I need to display and possible to change JSON. I want to display it as a tree of directory. I don't know how object will be look. It can be like this:
"buttons": {
    "login": "LOGIN",
    "register": "REGISTER",
    "next": "Next",
},
"nav": {
    "account": "Acount",
    "login": "Login"
},

But sometimes it can be like this:
"register": {
    "user": "User",
    "email": "E-mail",
    "language": {
        "en": "English",
        "de": "German",
        "es": "Spanish",
    }
},
"blog": {
    "search": "SEARCH",
    "comments": "COMMENTS"
},

The problem is i don't know how nested it will be. I already wrote parser and i parse it into object, but i have no idea how to display it on site.

A: You can use a textarea with a computed property (with getter and setter) as v-model.
Something like this:
<textarea v-model="my_JSON_model"></textarea>

<script>
    export default {

        data() {
            return {
                my_JSON: {} // import here your json
            }
        },

        computed: {

            my_JSON_model: {

                get() {

                    return JSON.stringify( this.my_JSON , null , '\t' )

                },

                set(val) {

                    this.my_JSON = JSON.parse(val);

                }

            }

        }

    }
</script>

A: Can you use a library?
To display a JSON with a view. I use the very good library
https://leezng.github.io/vue-json-pretty/
.
It takes as a parameter a json of any form.
Good continuation.


text:
Q: Including and referring to jQuery as a file in an iNotes-form in Domino Designer We are trying to use jQuery in Domino Designer. When I create a library, post the code of jQuery in the editor and try to save, Domino designer complains about compile errors, which turns out to be a reported bug!
Our clients are using old versions of Domino and we can't expect such a bug to be fixed on their machiens.
Anyway, there seems to be some solutions.
In my case, I have to go for adding jQuery as a file. The problem is that the old application we are modifying is forms-based. In XPages, one could refer to the lib like this:
<xp:script src="/jquery-1.4.2.min.js" clientSide="true"></xp:script>

Where the js-library would reside in the resources/files folder in the iNotes application.
However, in a form, I can only refer to libraries included explicitly in the libraries folder.
Is there a way to include the js-file, whose path is reachable, in a form?

A: Using jQuery in forms is as almost easy as in XPages: Just go to the HTML- header- section of the form and do exactly the same, but with a "script"- Tag:
Here is the formula I used for jquery, jquery,cookie and jquery-ui:
"<script type=\"text/javascript\" src=\"/" + @WebDbName +
    "/jquery.js\"></script>" +
"<script type=\"text/javascript\" src=\"/" + @WebDbName +
    "/jquery.cookie.js\"></script>" +
"<script type=\"text/javascript\" src=\"/" + @WebDbName +
    "/jquery-ui.js\"></script>"

Usually It should work without the @WebDbName as well, but I found out, that there might be conditions (e.g. Form embedded in a frameset in another app) where this is not safe.


text:
Q: Рисование графика на Panel или PictureBox Здраствуйте! Нужно нарисовать график функции y=(1-х^2)(x-2) (-2<x<2). При этом нужно использовать Radiobutton и RadioGroup для выбора цветов и шрифтов надписей, а также для построения осей координат. График должен выводится в анимационном режиме с использованием компонента Timer. Я новичок в этом деле и не совсем понимаю как это делать. Сделал, что-то вроде такого, но при этом если я нажима на Radiobutton, ничего не рисует. Как только я сворачиваю окно и открываю заново, уже нарисовано. Может ли кто-то помочь в этом разобраться? Я очень много прошу, но хотел бы что-бы мне подсказали как правильно нарисовать график с использованием RadioButton и Timer. Буду очень признателен!
namespace WindowsFormsApp5
{
    public partial class Form1 : Form
    {

        private int xMin = -15;
        private int xMax = 15;
        private int yMin = -15;
        private int yMax = 15;

        private int dx, dy;
        private int x0, y0;

        bool shouldPaint = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void panel1_Resize(object sender, EventArgs e)
        {
            panel1.Refresh();
            panel1.Refresh();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            dx = panel1.Width / (xMax - xMin);
            dy = panel1.Height / (yMax - yMin);
            x0 = -dx * xMin;
            y0 = dy * yMax;
            //panel1.Controls.Add(radioButton10);

            for (int x = xMin; x <= xMax; x++)
            {
                e.Graphics.DrawLine(Pens.LightBlue, x0 + x * dx, 0, x0 + x * dx, panel1.Height);
            }
            //panel1.Refresh();

            if (radioButton10.Checked)
            {
                shouldPaint = true;
                //if (!RenderOk) { return; }
                Pen p = new Pen(Color.Blue, 2);
                // ось абсцисс
                e.Graphics.DrawLine(p, 0, y0, panel1.Width, y0);
            }
        }
    }
}

A: Новичкам давать такие задачи...
RadioGroup - панель для Radiobutton, чтобы когда нажимаешь на один Radiobutton - с другого снималась отметка в том-же RadioGroup. Сам по себе выбор Radiobutton не должен запускать никаких процессов, это настройка.
Должна быть отдельная кнопка, запускающая процесс рисования.
Что с таймером, что без таймера - вариантов ка это сделать - много, какая задача - такое решение, целенаправленно ищем самый тупой вариант.
Xmin и Xmax у вас в диапазоне [-2,2]
Pen p = new Pen(Color.Black, 1);
List<Point> points = new List<Point>(); //для хранения точек
int y(int x) => (1 - x * x)*(x - 2);

void Start(Control panel) //(-2 < x < 2)
{
    if (paintactive) return;
    paintactive = true;
    //y=(1-х^2)(x-2) (-2<x<2)
    points.Clear();
    Timer timer = new Timer();
    timer.Interval = 1000;
    int x = -2;
    timer.Tick += (s, a) =>
    {
        if (x <= 2)
        {
            var point = new Point(x, y(x));
            //WriteLine(point);
            points.Add(point);
            x++;
            panel.Invalidate();
        }
        else
        {
            timer.Enabled = false;
            paintactive = false;
        }
    };
    timer.Start();
}

void Panel_Paint(object s, PaintEventArgs a)
{
   a.Graphics.DrawLines(p, points.ToArray());
}

Запуск рисования происходит командой:
Start(panel);


text:
Q: To call the adapter is there a way to set it or bypass in web browser? I mean to bypass wl_antiXSRFRealm when I try to hit in browser? I created a simple custom login module for mobilefirst java adapter.
authentication-config.xml
<customSecurityTest name="DummyAdapter-securityTest" AccessTokenExpirationSec="15">
<test isInternalUserID="true" realm="CustomAuthenticatorRealm"/></customSecurityTest>

<realm name="CustomAuthenticatorRealm" loginModule="CustomerLoginModule">           <className>com.mbanking.customauthenticator.CustomerAuthenticator</className>
</realm>

<loginModule name="CustomerLoginModule">            <className>com.mbanking.customauthenticator.CustomerLoginModule</className>
</loginModule>

Defined the following in application-descriptor.xml
<userIdentityRealms>CustomAuthenticatorRealm</userIdentityRealms>

I am authenticating a hard coded username and password in the CustomerAuthenticator and CustomerLoginModule as given in the IBM tutorials.
    @Override
    public AuthenticationResult processRequest(HttpServletRequest request, HttpServletResponse response,
            boolean isAccessToProtectedResource) throws IOException, ServletException {
        if (request.getRequestURI() != null){

         String username = "Prabhu";
         String password = "polo11";

if (null != username && null != password && username.length() > 0 && password.length() > 0){
                authenticationData = new HashMap<String, Object>();
                authenticationData.put("username", username);
                authenticationData.put("password", password);
                return AuthenticationResult.createFrom(AuthenticationStatus.SUCCESS);
            } else {
                response.setContentType("application/json; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache, must-revalidate");
                response.getWriter().print("{\"authStatus\":\"required\", \"errorMessage\":\"Please enter username and password\"}");
                return AuthenticationResult.createFrom(AuthenticationStatus.CLIENT_INTERACTION_REQUIRED);
            }
        }

        if (!isAccessToProtectedResource){
            return AuthenticationResult.createFrom(AuthenticationStatus.REQUEST_NOT_RECOGNIZED);
        }
        response.setContentType("application/json; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        response.getWriter().print("{\"authStatus\":\"required\"}");
        return AuthenticationResult.createFrom(AuthenticationStatus.CLIENT_INTERACTION_REQUIRED);
}

Login Module
@Override
    public boolean login(Map<String, Object> authenticationData) {
          USERNAME =(String) authenticationData.get("username");
          PASSWORD = (String) authenticationData.get("password");

          if ("Prabhu".equals(USERNAME) && "polo11".equals(PASSWORD)){
          return true;
          }else{
              throw new RuntimeException("Invalid credentials");
              }
    }

Java Adapter code
@GET
    @Path("/mobile")
    @Produces(MediaType.APPLICATION_JSON)
    @OAuthSecurity(scope="CustomAuthenticatorRealm")
    public JSONObject generate(){
        JSONObject responseValue = new JSONObject();
        responseValue.put("data", "Secret Data From Adpter");
        return responseValue;
    }

Authorization is failing
[ERROR   ] FWLSE0059E: Login into realm 'CustomerLoginModule' failed. null. [project JIB]
java.lang.NullPointerException
[ERROR   ] FWLSE0117E: Error code: 4, error description: AUTHENTICATION_ERROR, error message: An error occurred while performing authentication using loginModule CustomerLoginModule, User Identity {wl_antiXSRFRealm=(name:lbgo1f8edsjvsjgfv8i9umdneb, loginModule:WLAntiXSRFLoginModule), wl_authenticityRealm=null, CustomAuthenticatorRealm=(name:Prabhu, loginModule:CustomerLoginModule), CustomRealm=null, wl_directUpdateRealm=null, wl_remoteDisableRealm=null, SampleAppRealm=null, myserver=(name:ac09d1e7-71a6-47da-bbb8-e6c2f48651f3, loginModule:WeakDummy), wl_deviceNoProvisioningRealm=null, wl_anonymousUserRealm=(name:ac09d1e7-71a6-47da-bbb8-e6c2f48651f3, loginModule:WeakDummy), wl_deviceAutoProvisioningRealm=null}. [project JIB] [project JIB]

and When I tried debugging, I get internal exception.
CLIENT_INTERACTION_REQUIRED{"challenges":{"wl_antiXSRFRealm":{"WL-Instance-Id":"lr0tsjecoeghhrf670oc8hu17v"}}}

There is lot of caching, even after restarting, mobile first server is picking up old values.
Can anyone please help?
Its a one way authorization, why wl_antiXSRFRealm is called in between, I dont get any references related to this.


text:
Q: ColorWithPatternImage and constraints I have a image I need to tile as a background for a UIView:
UIView *buttonView = [UIView new];
[buttonView setTranslatesAutoresizingMaskIntoConstraints:NO];
[buttonView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[buttonBar(100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(buttonView)]];
[buttonView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bottomBar-bg-100.png"]]];

The image is 200x200 but I need it to be 100. If I add the image as:
imageView.image = [UIImage imageWithName:@"bottomBar-bg-100.png"]

It will be compress to 100. But when I use the colorWithPatternImage: method, it doesn't compress the 200 tall image to be 100 tall.
Is there some goofyness going on with colorWithPatternImage: and using constraints, or is that just how the colorWithPatternImage: works?

A: Do you know about resizableImageWithCapInsets:resizingMode:? This is the best way to turn an image into something that you can stretch or tile into an available size.


text:
Q: SQL Homework - "IN" Subquery yes this is a homework question, but I'm giving it honest effort and I'm not asking you to do it for me, just point me in the right direction! :)
So I have a set of questions concerning the SQL IN subquery, and while I understand what it does I'm having trouble applying it in these situations.
The first question:

1) Use the In subquery technique to list the customer number, customer name and  phone for customers who have paid either by visa or mc. Sort
  by customer name.

This one I believe I got:
SELECT DISTINCT
   tblCust.CustomerNum, CustomerName, Phone
FROM
   tblCust
INNER JOIN tblOrd ON
   tblCust.CustomerNum=tblOrd.CustomerNum
WHERE
   tblOrd.PayMethod IN ("visa", "mc")
ORDER BY CustomerName;

But the next one just makes no sense to me:

2) Use the In subquery technique to list from tblCust the customer number, customer  name and state for customers who have a state
  description that begins with "co".

Shouldn't I be using the LIKE operator for this instead of IN?
So far I have:
SELECT
   CustomerNum, CustomerName, StateProv
FROM
   tblCust
INNER JOIN tblState ON
   tblCust.StateProv = tblState.StateProv
WHERE
   tblState.StateProvDesc IN

And I don't know what to put after the IN, if I were using LIKE I would say

...StateProvDesc LIKE "co%"

and be done with it, but I don't think that's what my teacher wants.
Finally, the third question:

3) Use the In subquery technique to list from tblCust the customer
  name, country for  customers who have at least one order in the range
  of $90,000-$120,000. Sort by  country then customer name.

Shouldn't between be used for a range of numbers?
Thanks for anything you guys can think of!
using microsoft access by the way

A: I think what the prof wants you to do is write a subquery within the IN clause. You can actually put a select statement within IN() like this:
SELECT
   CustomerNum, CustomerName, StateProv
FROM
   tblCust
WHERE StateProv IN(SELECT StateProv FROM tblState WHERE StateProvDesc LIKE 'co%')

A: I think the instructor wants you to change the query to use ... IN (SELECT ... FROM ...) style instead of the inner join.
You can work on these queries from the back of the description, like this:

...a state description that begins with "co".

-- Inner query
SELECT StateProv
FROM tblState
WHERE StateProvDesc LIKE `co%`

Now that you have this, you can compose the outer query:

list from tblCust the customer number, customer name and state for customers who have...

SELECT
   CustomerNum, CustomerName, StateProv
FROM
   tblCust
WHERE tblCust.StateProv IN (
-- Your inner query goes here
)


text:
Q: Git post-receive hook not working We're using git with a central repo (using Gitosis). I've created a post-receive hook to generate an email to the dev mailing list whenever changes are pushed to the central repo, and to generate documentation from the documentation folder in the git repo.
Therefore, in ~git/ I've got a directory, we'll call it 'a' that contains a clone of the git repo. The post-receive hook looks like:
#!/bin/bash
cd ~git/repositories/a.git
. ~git/post-receive-email &> /dev/null
( cd ~git/a && git pull &> ~git/pull_log.log && php ~git/a/scripts/generate_markdown_documentation.php &> ~git/doc_log.log )

The email script is working, but the documentation generation is not. The content of pull_log.log is:
fatal: Not a git repository: '.'

Which makes me think that it's not changing to the correct directory in line 5 of the above script. Am I wrong? How can I get this to work?
Edit: I've updated the post-receive hook as suggested in the responses. The script is now:
#!/bin/bash
function die {
  echo "$*" >&2; exit 1
}

function checkgit {
  [ -d "$1/.git" ] || die "$1 could not possibly be a git repo; $1/.git is not a dir"
}

cd ~git/repositories/a.git
. ~git/post-receive-email &> /dev/null
( set -x
checkgit ~git/a
cd ~git/a
checkgit .
pwd
git pull
php ~git/a/scripts/generate_markdown_documentation.php )

And I get the following output from git push:
+ checkgit /var/git/a
+ '[' -d /var/git/a/.git ']'
+ cd /var/git/a
+ checkgit .
+ '[' -d ./.git ']'
+ pwd
/var/git/a
+ git pull
fatal: Not a git repository: '.'
+ php /var/git/a/scripts/generate_markdown_documentation.php

Any more help?
Oh, and if I run the script myself, it works (I run it by saying hooks/post-receive)
Discovered the problem, thanks to serverfault -- basically, environment variables GIT_DIR and GIT_WORK_TREE are set when the hook runs, and these affect git pull adversely.  Unsetting the variables fixes the problem.

A: You need more diagnostics, e.g.,
function die {
  echo "$*" >&2; exit 1
}

function checkgit {
  [ -d "$1/.git" ] || die "$1 could not possibly be a git repo; $1/.git is not a dir"
}

At this point, in the subshell right after the parenthesis, you can try stuff like
set -x # show exactly what's executed (writes to stderr)
checkgit ~git/a
cd ~git/a && checkgit . && git pull ...

You might also consider redirecting the whole stderr of the subshell, e.g.,
( ... ) 2>/tmp/mydiagnosis$$.log

(This is a temporary measure and is OK only if there's no confidential info in the logs.)

OK Silas, your additional info rules out a lot of awkward possibilities.  I'm nearing the end of my git fu, but here are some more things to try:

*

*Go into ~git/a and see if you can make it git pull by hand.  This should fail.

*Got into ~git/a and run git status.  This should also fail.  If it doesn't, then git is giving you a very bad error message.

If both steps fail, ~git/a is not the clone you thought it was.  Rename it, make a new clone, and see if you can get the problem to persist.
If the first step succeeds by hand, then something strange is going on and I'm baffled.
If the first step fails but the second succeeds, you may have a problem with branches:

*

*Perhaps repo ~git/a is set to the wrong branch, and your repo needs a branch it doesn't have.   Try git branch -a and see if you see something unexpected.

*Perhaps you have the branch, but it's not properly associated with a remote repository.  At this point you have to dive into ~git/a/.git/config, and I don't really know how to explain what you should expect to find there.  At that point you will need a real git expert; I just play one on TV.

A: I recently ran into a similar problem and I think it is related to the environment variables that git sets, specifically the $GIT_DIR variable. If you have that set, all git commands on other repos start to act weirdly. Basically I think that running your git pull inside the hook must be invoked in a neutral shell environment that does not have those odd variables and leads to git confusion, though I haven't figured out how to do that just yet.

A: unset GIT_DIR is a solution which works for the fatal error you are seeing.
This applies to all scripts in hooks (post-update is another common one), which uses the git command inside it. git command uses the GIT_DIR from env instead of pwd.
See https://stackoverflow.com/a/4100577 for further explanation.


text:
Q: Lucene Standard Analyzer vs Snowball Just getting started with Lucene.Net.  I indexed 100,000 rows using standard analyzer, ran some test queries, and noticed plural queries don't return results if the original term was singular.  I understand snowball analyzer adds stemming support, which sounds nice.  However, I'm wondering if there are any drawbacks to gong with snowball over standard?  Am I losing anything by going with it?  Are there any other analyzers out there to consider?

A: The snowball analyzer will increase your recall, because it is much more aggressive than standard analyzer. So you need to evaluate your search results to see if for your data you need to increase recall or precision.

A: I just finished an analyzer that performs lemmatization. That's similar to stemming, except that it uses context to determine a word's type (noun, verb, etc.) and uses that information to derive the stem. It also keeps the original form of the word in the index. Maybe my library can be of use to you. It requires Lucene Java, though, and I'm not aware of any C#/.NET lemmatizers.

A: Yes, by using a stemmer such as Snowball, you are losing information about the original form of your text. Sometimes this will be useful, sometimes not.
For example, Snowball will stem "organization" into "organ", so a search for "organization" will return results with "organ", without any scoring penalty.
Whether or not this is appropriate to you depends on your content, and on the type of queries you are supporting (for example, are the searches very basic, or are users very sophisticated and using your search to accurately filter down the results). You may also want to look into less aggressive stemmers, such as KStem.


text:
Q: More Elegant LINQ Alternative to Foreach Extension This is purely to improve my skill. My solution works fine for the primary task, but it's not "neat". I'm currently working on a .NET MVC with Entity framework project. I know only basic singular LINQ functions which have sufficed over the years. Now I'd like to learn how to fancy.
So I have two models
public class Server
{
    [Key]
    public int Id { get; set; }
    public string InstanceCode { get; set; }
    public string ServerName { get; set; }
}

public class Users
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int ServerId { get; set; } //foreign key relationship
}

In one of my view models I was asked to provide a dropdown list for selecting a server when creating a new user. The drop down list populated with text and value Id as an IEnumerable
Here's my original property for dropdown list of servers
public IEnumerable<SelectListItem> ServerItems
{
    get { Servers.ToList().Select(s => new selectListItem { Value = x.Id.ToString(), Text = $"{s.InstanceCode}@{s.ServerName}" }); }
}

Update on requirements, now I need to display how many users are related to each server selection. Ok no problem. Here's what I wrote off the top of my head.
public IEnumerable<SelectListItem> ServerItems
{
    get
    {
        var items = new List<SelectListItem>();
        Servers.ToList().ForEach(x => {
            var count = Users.ToList().Where(t => t.ServerId == x.Id).Count();
            items.Add(new SelectListItem { Value = x.Id.ToString(), Text = $"{x.InstanceCode}@{x.ServerName} ({count} users on)" });
        });

        return items;
    }
}

This gets my result lets say "localhost@rvrmt1u (8 Users)" but thats it..
What if I want to sort this dropdown list by user count. All I'm doing is another variable in the string.
TLDR ... I'm sure that someone somewhere can teach me a thing or two about converting this to a LINQ Query and making it look nicer. Also bonus points for knowing how I could sort the list to show servers with the most users on it first.

A: OK, we have this mess:
    var items = new List<SelectListItem>();
    Servers.ToList().ForEach(x => {
        var count = Users.ToList().Where(t => t.ServerId == x.Id).Count();
        items.Add(new SelectListItem { Value = x.Id.ToString(), Text = $"{x.InstanceCode}@{x.ServerName} ({count} users on)" });
    });
    return items;

Make a series of small, careful, obviously-correct refactorings that gradually improve the code.
Start with: Let's abstract those complicated operations to their own methods.
Note that I've replaced the unhelpful x with the helpful server.
int UserCount(Server server) =>
  Users.ToList().Where(t => t.ServerId == server.Id).Count();

Why on earth is there a ToList on Users? That looks wrong.
int UserCount(Server server) =>
  Users.Where(t => t.ServerId == server.Id).Count();

We notice that there is a built-in method that does these two operations together:
int UserCount(Server server) =>
  Users.Count(t => t.ServerId == server.Id);

And similarly for creating an item:
SelectListItem CreateItem(Server server, int count) =>
  new SelectListItem
  {
    Value = server.Id.ToString(),
    Text = $"{server.InstanceCode}@{server.ServerName} ({count} users on)"
  };

And now our property body is:
    var items = new List<SelectListItem>();
    Servers.ToList().ForEach(server =>
    {
        var count = UserCount(server);
        items.Add(CreateItem(server, count);
    });
    return items;

Already much nicer.
Never use ForEach as a method if you're just going to pass a lambda body! There's already a built-in mechanism in the language that does it better!  There is no reason to write items.Foreach(item => {...}); when you could simply write foreach(var item in items) { ... }.  It's simpler and easier to understand and debug, and the compiler can optimize it better.
    var items = new List<SelectListItem>();
    foreach (var server in Servers.ToList())
    {
        var count = UserCount(server);
        items.Add(CreateItem(server, count);
    }
    return items;

Much nicer.
Why is there a ToList on Servers? Completely unnecessary!
    var items = new List<SelectListItem>();
    foreach(var server in Servers)
    {
        var count = UserCount(server);
        items.Add(CreateItem(server, count);
    }
    return items;

Getting better. We can eliminate the unnecessary variable.
    var items = new List<SelectListItem>();
    foreach(var server in Servers)
        items.Add(CreateItem(server, UserCount(server));
    return items;

Hmm.  This gives us an insight that CreateItem could be doing the count itself. Let's rewrite it.
SelectListItem CreateItem(Server server) =>
  new SelectListItem
  {
    Value = server.Id.ToString(),
    Text = $"{server.InstanceCode}@{server.ServerName} ({UserCount(server)} users on)"
  };

Now our prop body is
    var items = new List<SelectListItem>();
    foreach(var server in Servers)
        items.Add(CreateItem(server);
    return items;

And this should look familiar. We have re-invented Select and ToList:
var items = Servers.Select(server => CreateItem(server)).ToList();

Now we notice that the lambda can be replaced with the method group:
var items = Servers.Select(CreateItem).ToList();

And we have reduced that whole mess to a single line that clearly and unambiguously looks like what it does. What does it do? It creates an item for every server and puts them in a list.  The code should read like what it does, not how it does it.
Study the techniques I used here carefully.

*

*Extract complex code to helper methods

*Replace ForEach with real loops

*Eliminate unnecessary ToLists

*Revisit earlier decisions when you realize there's an improvement to be made

*Recognize when you are re-implementing simple helper methods

*Don't stop with one improvement!  Each improvement makes it possible to do another.

What if I want to sort this dropdown list by user count?

Then sort it by user count! We abstracted that away into a helper method, so we can use it:
var items = Servers
  .OrderBy(UserCount)
  .Select(CreateItem)
  .ToList();

We now notice that we're calling UserCount twice.  Do we care? Maybe. It could be a perf problem to call it twice, or, horrors, it might not be idempotent! If either are a problem then we need to undo a decision we made before.  It's easier to deal with this situation in comprehension mode rather than fluent mode, so let's rewrite as a comprehension:
var query = from server in Servers
            orderby UserCount(server)
            select CreateItem(server);
var items = query.ToList();

Now we go back to our earlier:
SelectListItem CreateItem(Server server, int count) => ...

and now we can say
var query = from server in Servers
            let count = UserCount(server)
            orderby count
            select CreateItem(server, count);
var items = query.ToList();

and we are only calling UserCount once per server.
Why go back to comprehension mode? Because to do this in fluent mode makes a mess:
var query = Servers
  .Select(server => new { server, count = UserCount(server) })
  .OrderBy(pair => pair.count)
  .Select(pair => CreateItem(pair.server, pair.count))
  .ToList();

And it looks a little ugly.  (In C# 7 you could use a tuple instead of an anonymous type, but the idea is the same.)

A: The trick with LINQ is just to type return and go from there. Don't create a list and add items to it; there is usually a way to select it all in one go.
public IEnumerable<SelectListItem> ServerItems
{
    get
    {
        return Servers.Select
        (
            server =>
            new
            {
                Server = server,
                UserCount = Users.Count( u => u.ServerId = server.Id )
            }
        )
        .Select
        (
            item =>
            new SelectListItem
            {
                Value = item.Server.Id.ToString(),
                Text = string.Format
                (
                    @"{0}{1} ({2} users on)" ,
                    item.Server.InstanceCode,
                    item.Server.ServerName,
                    item.UserCount
                )
            }
        );
    }
}

In this example there are actually two Select statements-- one to extract the data, and one to do the formatting. In an ideal situation the logic for those two tasks would be separated into different layers, but this is an OK compromise.


text:
Q: Trapezoid rule error analysis How can I prove that the max error of the trapezoid rule for the integral $\int_{a}^{b}{f(x)\, \mathrm{d}x} $ is: $$\Delta=-\frac{1}{12n^2}f''(c)(b-a)^3 \text{for } c \in (a,b) \ ?$$
I know that to obtain that result first you have to prove that $$\exists \;c \in (a,b); \int_{a}^{b}f(x)\,dx = \frac{b - a}{2}\{f(a) + f(b)\} - \frac{1}{12}f''(c)(b-a)^3$$ But I'm stuck here, I tried using the mean value theorem but got nowhere. Anyone got any ideas?
If it helps: $\forall x_0 \in (a,b) \;\exists\;\xi_0 \in (a,b);\; f(x_0) - p(x_0) = f''(\xi_0)\frac{(x_0 - a)(x_0 - b)}{2}$, where p(x) is the linear function that interpolates f(x) in the points a and b ($p(x) = f(a) + \frac{f(b) - f(a)}{b-a}(x-a)$)

A: Let $p = (a + b)/2$ and $2h = b - a$ so that $a = p - h, b = p + h$. We further define the functions $g(t)$ and $r(t)$ by $$g(t) = \int_{p - t}^{p + t}f(x)\,dx - t\{f(p - t) + f(p + t)\},\,\, r(t) = g(t) - \left(\frac{t}{h}\right)^{3}g(h)$$ Then we can see that $$g'(t) = -t\{f'(p + t) - f'(p - t)\},\,\, r'(t) = g'(t) - \frac{3t^{2}}{h^{3}}g(h)$$ By Mean Value theorem we can see that $$ g'(t) = -2t^{2}f''(t')$$ for some $t' \in (p - t, p + t)$. Thus we have $$r'(t) = -t^{2}\left(2f''(t') + \frac{3}{h^{3}}g(h)\right)$$ Clearly we can see that $r(0) = r(h) = 0$ so that (by Rolle's Theorem) there is some point $t_{0} \in (0, h)$ such that $r'(t_{0}) = 0$. This means that $$-t_{0}^{2}\left(2f''(t') + \frac{3}{h^{3}}g(h)\right) = 0$$ and therefore we have $$g(h) = -\frac{2h^{3}}{3}f''(t')$$ where $t' \in (p - t_{0}, p + t_{0}) \subset (p - h, p + h) = (a, b)$. We finally arrive at (by putting values of $h = (b - a)/2,\, p - h = a,\, p + h = b$ and definition of $g(t)$) $$\int_{a}^{b}f(x)\,dx = \frac{b - a}{2}\{f(a) + f(b)\} - \frac{(b - a)^{3}}{12}f''(t')$$ where $t' \in (a, b)$
Note: This is based on an exercise problem in G. H. Hardy's "A Course of Pure Mathematics". Compared to all the usual proofs given on Numerical Analysis books (primarily based on various interpolation formulas and Taylor series) I find this proof by Hardy to be the simplest one.

A: In standard numerical analysis courses, numerical integration comes after polynomial interpolation. The trapezoidal rule amounts to consider the approximation
$$
\int_a^b f(x) dx \approx \int_a^b p_1(x) dx,
$$
where $p_1(x)$ is the first degree interpolant at $x=a,b$. In this sense, the integration error is given by
$$
\Delta = \int_a^b f(x) dx -\int_a^b p_1(x) dx = \int_a^b(f(x)-p_1(x)) dx = \int_a^b \frac{f''(\xi_x)}{2!} (x-a)(x-b) dx
$$
Since $(x-a)(x-b)$ does not change sign in $[a,b]$, we can use the mean value theorem for integrals obtaining
$$
\Delta = \frac{f''(\xi)}{2!} \int_a^b(x-a)(x-b)dx = -\frac{f''(\xi)}{12}(b-a)^3.
$$
As for the composed rule, if we are dividing $[a,b]$ in $n$ intervals of equal length,
$$
\Delta = \sum_{i=0}^{n-1}\int_{x_i}^{x_{i+1}} (f(x)-p_{1,i}(x))dx,
$$
where $p_{1,i}(x)$ is the linear interpolant of $f$ in at $x = x_i, x_{i+1}$, so using the previous result,
$$
\Delta = \sum_{i=0}^{n-1} -\frac{f''(\xi_i)}{12} \left(\frac{b-a}{n}\right)^3=-\frac{(b-a)^3}{12 n^3} n \cdot \underbrace{\frac{1}{n}\sum_{i=0}^{n-1} f''(\xi_i)}_{=f''(\xi)} = -\frac{f''(\xi)}{12 n^2} (b-a)^3.
$$
The last factor  is an average of values of $f''$, therefore comprised between the min and max of $f''$. By the mean value theorem it corresponds to the value of $f''$ in some $\xi \in [a,b]$, which yields the final result.

A: Hint: Use the Lagrange Remainder  of the Taylor Expansion:
$$f(x)\sim f(x_1) +f'(x_1)(x-x_1)+f''(x^*)\frac{(x-x_1)^2}{2!}$$
For some $x^*$ in $[x_1,x]$, and integrate the error term over $[x_1,x_2]$.


text:
Q: Scriptella - Unable to instantiate driver for class scriptella.driver.xls.Driver My second question: I'm very newbie with Linux/Java/Scriptella and I'm trying a jdbc connection with scriptella on a xls local file, but I'm receiving the following errors:
4-dic-2013 0.41.46 <GRAVE> Script /home/maurizio/Scrivania/JATROPHA/applicazioni/prova_per_scriptella.etl execution failed.
Unable to instantiate driver for class scriptella.driver.xls.Driver
JDBC provider exception: Couldn't find appropriate jdbc driver : net.pcal.sqlsheet.XlsDriver. Please check class path settings
Error codes: []
4-dic-2013 0.41.46 <GRAVE> Scriptella bug report. Submit to issue tracker.
Scriptella version: 1.1
Exception:
scriptella.execution.EtlExecutorException: Unable to instantiate driver for class scriptella.driver.xls.Driver
JDBC provider exception: Couldn't find appropriate jdbc driver : net.pcal.sqlsheet.XlsDriver. Please check class path settings
Error codes: []
    at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:190)
    at scriptella.tools.launcher.EtlLauncher.execute(EtlLauncher.java:276)
    at scriptella.tools.launcher.EtlLauncher.launch(EtlLauncher.java:193)
    at scriptella.tools.launcher.EtlLauncher.main(EtlLauncher.java:321)
Caused by: java.lang.IllegalStateException: Unable to instantiate driver for class scriptella.driver.xls.Driver
    at scriptella.core.DriverFactory.getDriver(DriverFactory.java:98)
    at scriptella.core.DriverFactory.getDriver(DriverFactory.java:58)
    at scriptella.driver.auto.Driver.getConnection(Driver.java:96)
    at scriptella.driver.auto.Driver.connect(Driver.java:77)
    at scriptella.core.ConnectionManager.getConnection(ConnectionManager.java:81)
    at scriptella.core.Session.<init>(Session.java:57)
    at scriptella.execution.EtlExecutor.prepare(EtlExecutor.java:248)
    at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:178)
    ... 3 more
Caused by: scriptella.jdbc.JdbcException: Couldn't find appropriate jdbc driver : net.pcal.sqlsheet.XlsDriver. Please check class path settings
    at scriptella.jdbc.GenericDriver.loadDrivers(GenericDriver.java:87)
    at scriptella.driver.xls.Driver.<init>(Driver.java:33)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:534)
    at java.lang.Class.newInstance(Class.java:374)
    at scriptella.core.DriverFactory.getDriver(DriverFactory.java:96)
    ... 10 more
Caused by: java.lang.NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFWorkbook
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:190)
    at scriptella.jdbc.GenericDriver.loadDrivers(GenericDriver.java:67)
    ... 17 more
Caused by: java.lang.ClassNotFoundException: org.apache.poi.xssf.usermodel.XSSFWorkbook
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
    ... 20 more

I'm using Ubuntu 10.04 Lucid Lynx.
I start scriptella via console in directory /home/maurizio/Scrivania/JATROPHA/applicazioni/ with the command scriptella/scriptella-1.1/bin/scriptella.sh -debug "prova_per_scriptella.etl" My ETL file prova_per_scriptella.etl contains the following rows:
<!DOCTYPE etl SYSTEM "http://scriptella.javaforge.com/dtd/etl.dtd">
<etl>
  <description>Prova connessione Firebird e XLS</description>
  <connection
    id="fb_destination"
    driver="org.firebirdsql.jdbc.FBDriver"
    url="jdbc:firebirdsql:localhost/3050:jatropha"
    user="SYSDBA"
    password="jatro201"
    classpath="/home/maurizio/Scrivania/JATROPHA/applicazioni/jaybird/Jaybird-2.2.3JDK_1.6/jaybird-2.2.3.jar"
  />
  <connection
    id="xls_source"
    url="jdbc:xls:file:prova_per_scriptella.xls"
    classpath="/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/sqlsheet-6.5.jar"
  />
</etl>

The env var $_SCRIPTELLA_CP of batch command scriptella/scriptella-1.1/bin/scriptella.sh results in
:/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/commons-jexl.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/commons-logging.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/jaybird-2.2.3.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/jsqlparser-0.8.0.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/mini-j2ee.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/scriptella-core.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/scriptella-drivers.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/scriptella-tools.jar:
/home/maurizio/Scrivania/JATROPHA/applicazioni/scriptella/scriptella-1.1/lib/sqlsheet-6.5.jar

My scriptella lib directory contains the following files:
commons-jexl.jar
commons-logging.jar
jaybird-2.2.3.jar
jsqlparser-0.8.0.jar
mini-j2ee.jar
scriptella-core.jar
scriptella-drivers.jar
scriptella-tools.jar
sqlsheet-6.5.jar

Any help would be very appreciated. Thanks in advance.

A: This was asked a while ago but I thought I may answer this anyway as I just had the same issue.
The key to the answer is at the end of the stack trace Caused by: java.lang.ClassNotFoundException: org.apache.poi.xssf.usermodel.XSSFWorkbook.
This can be fixed by including all the libs included in the latest poi download found here.

A: I also had problems getting this to work. Rather than downloading the latest version as suggested by otty, it seems like a better idea to look at the pom.xml file for the net.pcal.sqlsheet.XlsDriver (which is what scriptella.driver.xls.Driver tries to instantiate. This way we are using the correct dependencies.


text:
Q: get the id of a new record in SavingChanges event on the entityframework Im tring to implement some generic logging in the entityframework 4.0 using the SavingChanges event in the entity context.
I want to record details about any create/ update and deleted records including the id of the record being changed (which is always an int identity field). During the update and delete processes I can get the id for the record using
    Dim AddedItems = Statemanager.GetObjectStateEntries(EntityState.Added)
    For Each entry As ObjectStateEntry In DirectCast(sender, ObjectContext).ObjectStateManager.GetObjectStateEntries(EntityState.Added)

        NewLogItem.RecordId = CInt(entry.EntityKey.EntityKeyValues(0).Value.ToString())
    Next

But I obviously cannot get the id of the about to be inserted record during an insert becuase it hasn't been written to the database yet, is there a simple way around this?

A: One option you can do is override the SaveChanges method and call SaveChanges to the base with not accepting changes to the objectcontext. this way you can audit the changes on the ObjectStateManager.
 override void SaveChanges(SaveOptions)
 {
context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
//query the object statemanager

 }

The key is calling the savechanges to the base with right saveoptions. The default would accept all the changes to the ObjectStateManager so all entries would then be in unchaged state and you won't be able to know what got added or deleted or modified. after looping through the statemanager you can then call AcceptChanges explicitly.
I cover this concept in my book as well.
12-1 Executing Code When SaveChanges() Is Called

A: I think there is no way to get the ID of a new inserted record in the SavingChanges event since the event is simply called before the database gets touched at all and the ID is created. Unfortunately there is no SavedChanges event which gets called after the data are saved.
A possible option might be to leverage the fact that one of the overloads of the ObjectContext's SaveChanges method is virtual (or overridable in VB), namely:
public virtual int SaveChanges(SaveOptions options)

(Note: It's virtual only in EF 4, not in the earlier version! And only this overload is virtual, the other two overloads of SaveChanges are not!)
So you could override this method in your model's ObjectContext. In this overridden method you call SaveChanges of the base class and after that your new entities should have the created IDs from the database which you could log then.
(It's just a rough idea, I never tested or used this virtual overload. I've built a similar logging mechanism in SavingChanges as you're just implementing and had the same problem. But this was in EF 3.5 where this virtual method didn't exist yet. Finally I had logged Inserts only at the important places after calling SaveChanges, but that wasn't then "generic" of course. Perhaps the new virtual method is a good chance to improve that now.)
Edit
A bit more precise what I meant (in C# syntax):
public partial class MyEntitiesContext : ObjectContext
{
    // ...

    public override int SaveChanges(SaveOptions options)
    {
        // Log something BEFORE entities are stored in DB

        int result = base.SaveChanges(options);

        // Log something AFTER entities are stored in DB, especially new entities
        // with auto-incrementing identity key which have been inserted in the DB
        // should have the final primary key value now

        return result;
    }

    // ...
}

Important is to call base.SaveChanges(options). (Calling only SaveChanges(options) without base. ends with a StackOverflow of course.)

A: This is what I ended up with, not ideal in the fact that I ended up with two saveChanges calls and therefore two transactions but cant see any other way around it, if we dont log the deleted items before the save then we cannot access them correctly after the savechanges() (the entities will no longer exist and this is reflected in the State Entry for deleted items)
Public Function SaveAndLogChanges() As Integer
    Dim Statemanager As ObjectStateManager = Me.ObjectStateManager

    Dim AddedItems As IEnumerable(Of ObjectStateEntry) = Statemanager.GetObjectStateEntries(EntityState.Added)
    Dim UpdatedItems As IEnumerable(Of ObjectStateEntry) = Statemanager.GetObjectStateEntries(EntityState.Modified)
    Dim DeletedItems As IEnumerable(Of ObjectStateEntry) = Statemanager.GetObjectStateEntries(EntityState.Deleted)

    For Each entry As ObjectStateEntry In UpdatedItems
        ' dont do anything for any of the log file entries or we will end up in an infinate loop
        If (Not entry.EntitySet.Name = "LogItem" And Not entry.EntitySet.Name = "LogTransaction") Then
            createLogEntry(LogItemType.ItemType.Modify, entry)
        End If
    Next

    ' deleted entities
    For Each entry As ObjectStateEntry In DeletedItems
        ' dont do anything for any of the log file entries or we will end up in an infinate loop
        If (Not entry.EntitySet.Name = "LogItem" And Not entry.EntitySet.Name = "LogTransaction") Then
            createLogEntry(LogItemType.ItemType.Delete, entry)
        End If
    Next

    ' need to save changes here to ensure we have ids for the inserted records
    Me.SaveChanges()

    ' inserted enties
    For Each entry As ObjectStateEntry In AddedItems
        ' dont do anything for any of the log file entries or we will end up in an infinate loop
        If (Not entry.EntitySet.Name = "LogItem" And Not entry.EntitySet.Name = "LogTransaction") Then
            createLogEntry(LogItemType.ItemType.Insert, entry)
        End If
    Next

    Me.SaveChanges()

    Return iRet
End Function


text:
Q: Django modelform - when errors in the form it is showing excluded fields and losing translations? Im seeing a weird behaviour with my modelform. If I submit and a field has errors, when I re display it with the errors, excluded fields are appearing. Also its happening that the fields were translated into spanish and I m getting the labels in the original English.
I m using django 1.6.10, does anyone know if this is a bug or I m doing something wrong?
I'm not doing anything fancy with the rendering, I'm just doing {{ form }} in the template.
For instance this is a normal form

But if I submit the field empty I get the extra excluded field "notes" and the original field's name in English "plate number":

Here is the model code:
class Operation3Domain(models.Model):
    operation    = models.ForeignKey(Operation, unique=True)
    date         = models.DateTimeField(auto_now_add=True)
    update_date  = models.DateTimeField(auto_now=True)
    notes        = models.TextField(blank=True, null=True)
    #this one is the only one I want to show:
    plate_number = NumberPlateField()
    class Meta:
        app_label = "operation"

and the model form:
class Operation3DomainForm(forms.ModelForm):
    class Meta:
        model   = Operation3Domain
        labels  = { 'plate_number': 'Dominio/Patente'}
        exclude = ['operation', 'notes']

I appreciate any help! Thanks!!

A: Let me answer my own question!
So the problem to excluded fields was that in the creation of the form I had an outdated exclude parameter (sorry!), which is overriding the form's exclude.
form_class = modelform_factory(step_model, exclude=('operation',))
form = form_class(request.POST, instance=instance)

BUT! I still don't know why the form appears in English instead of spanish, which doesn't happen if I use the form class directly:
form = Operation3DomainForm(request.POST, instance=instance)

Thanks!


text:
Q: SharpDX: Content Assets not found what could be the problem if my assets are not found when using the sharpdx toolkit contentpipeline.
sf = Content.Load<SpriteFont>("Arial16ClearType");

they are in a subdirectory called "Content" and it is set in the application:
Content.RootDirectory = "Content";

the buildaction is set correctly to Toolkitfont.
"Copy to output directory" is "do not copy".
i imported the buildactions by adding this to my csproj
<Import Project="f:\work\github\SharpDX\SharpDX.targets" />

and it is always throwing this exception
SharpDX.Toolkit.Content.AssetNotFoundException was unhandled
  HResult=-2146233088
  Message=Content\Arial16ClearType
  Source=SharpDX.Toolkit
  StackTrace:
       at SharpDX.Toolkit.Content.ContentManager.FindStream(String assetName) in ..\..\Source\Toolkit\SharpDX.Toolkit\Content\ContentManager.cs:line 330
       at SharpDX.Toolkit.Content.ContentManager.Load(Type assetType, String assetName, Object options) in ..\..\Source\Toolkit\SharpDX.Toolkit\Content\ContentManager.cs:line 201
       at SharpDX.Toolkit.Content.ContentManager.Load[T](String assetName, Object options) in ..\..\Source\Toolkit\SharpDX.Toolkit\Content\ContentManager.cs:line 163
       at glyphrenderer.GlyphGame.LoadContent() in GlyphGame.cs:line 78
       at SharpDX.Toolkit.Game.InitializeBeforeRun() in ..\..\Source\Toolkit\SharpDX.Toolkit.Game\Game.cs:line 326
       at SharpDX.Toolkit.GameWindowDesktop.RunRenderLoop() in ..\..\Source\Toolkit\SharpDX.Toolkit.Game\Desktop\GameWindowDesktop.cs:line 340
       at SharpDX.Toolkit.GameWindowDesktop.Run() in ..\..\Source\Toolkit\SharpDX.Toolkit.Game\Desktop\GameWindowDesktop.cs:line 302
       at SharpDX.Toolkit.GamePlatform.Run(GameContext gameContext) in ..\..\Source\Toolkit\SharpDX.Toolkit.Game\GamePlatform.cs:line 133
       at SharpDX.Toolkit.Game.Run(GameContext gameContext) in ..\..\Source\Toolkit\SharpDX.Toolkit.Game\Game.cs:line 378
       at glyphrenderer.Program.Main(String[] args) in Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

A: Not sure what you meant by "the buildaction is set correctly" but you have to use the build action ToolkitFont and not Content and without specifying "Copy to output directory", as it is done by the ToolkitFont task. Check the projects in Toolkit samples that are configured this way. The Toolkit tasks are responsible to compile the xml/source files into a binary form that will be loaded at runtime.


text:
Q: How can I subtract tuples in a list? Let's say I have a list with tuples in it.
Something like this:
listnum = [(18,12),(12,20)]

Is there a way I can subtract what is in the tuples and make listnum into:
listnum = [6,8]

As you can see It takes the biggest of the numbers in the tuple and subtracts it by the other.

A: Use list comprehension:-
>>> listnum = [(18,12),(12,20)]
>>> [(i-j) for i,j in listnum]
[6, -8]
>>> listnum = [(18,12),(12,20),(32,54),(2,43)]
>>> [(i-j) for i,j in listnum]
[6, -8, -22, -41]

And as you asked for bigger number - smaller; use abs() to calculate it.
>>> listnum = [(18,12),(12,20),(32,54),(2,43)]
>>> [abs(i-j) for i ,j in listnum]
[6, 8, 22, 41]

A: Just a list comprehension works fine.
listnum = [(18,12),(12,20)]
listnum = [x[0] - x[1] for x in listnum]
# [6, -8]

Edit: For subtracting the bigger number from the smaller one, you can do something like this instead.
listnum = [max(x[0],x[1]) - min(x[0], x[1]) for x in listnum]
# [6, 8]

Or you can be a bit more cheeky about it
listnum = [abs(x[0] - x[1]) for x in listnum]
# [6, 8]

A: You can do it as following, using the map function:
listnum = [(18,12),(12,20)]
listnum = list(map(lambda x: abs(x[0]-x[1]),listnum))
print(listnum)

Result:
[6, 8]

A: You can loop through the list and append each answer to a new list, and output the list.
Code
y=[]
listnum = [(18,12),(12,20)]
for a,b in listnum:
    x=abs(a-b)
    y.append(x)
print (y)

Output
[6, -8]


text:
Q: Merge two dataframe based on the unique (first) value I have two dataframes. I want to merge these dataframe based on the first values. Here is a simple example:
I have this df:
df = pd.DataFrame()
df['id'] = [1, 2, 3, 4, 5]
df['x'] = [3, 4, 7, 8, 9]

   id   x
0   1   3
1   2   4
2   3   7
3   4   8
4   5   9

I want to get the value of 'y' from the following df1 based on the first values.
df1 = pd.DataFrame()
df1['id'] = [1, 1, 2, 3,3]
df1['y'] = [ 10, 100, 200, 500, 100]
   id   y
0   1   10
1   1   100
2   2   200
3   3   500
4   3   100

For id=1, we have two values in df1, but we only want the first one which is 10.
The desired output is:
   id   y
0   1   10
1   2   200
2   3   500

Thank you so much for your help

A: here is one way to do it
df1.groupby('id').first().merge(df, on='id', how='left').drop(columns='x')

    id    y
0   1    10
1   2   200
2   3   500

A: Although this is not an ideal solution, as I am new to programming (2 months old), I could only manage this.
merged_df = pd.merge(df1, df, on='id', how='left')
merged_df.drop(columns='x', index=[1,4], inplace= True)
merged_df.reset_index()

Found another way (the common way)
df1.groupby("id").first().reset_index()


text:
Q: elasticsearch parent/children aggregation performance I am just an elasticsearch newbie. According to the following elasticsearch document,

*

*join datatype

The join field shouldn't be used like joins in a relation database. In Elasticsearch the key to good performance is to de-normalize your data into documents. Each join field, has_child or has_parent query adds a significant tax to your query performance.

*has_child query

Note that the has_child is a slow query compared to other queries in the query dsl due to the fact that it performs a join.

*has_parent query

Note that the has_parent is a slow query compared to other queries in the query dsl due to the fact that it performs a join.

I can understand these query types are slow and should be avoided. But what about parent and children aggregations ? I can not find any document or performance test result which says these aggregations are slow or not so bad.
I have to test it though, can someone give me some advice ?

A: Parent and Child Aggregations are definitely slower compared to other Aggregations. I have tested it in my applications and found it much slower than normal ones.


text:
Q: Where to put the image file in node.js? I have the following directory structure in Linux with just 3 files in it:
/home/nikhil/test_img/

*

*server.js

*page.html

*pic.jpg

This is a simple node.js hello world setup without using express or any other library
Code for server.js
var http = require("http"), fs = require('fs');
var path = require('path');
var root = path.dirname(require.main.filename);
var filePath = path.join(root + '/page.html');

var port = 8889;

function onRequest(request, response) {
    fs.readFile(filePath, function (err, html) {
        if (err) {
            throw err;
        }
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(html);
        response.end();
    });
}

http.createServer(onRequest).listen(port, function () {
  console.log("Server has started at port " + port);
});

This simply creates the server which displays page.html on any request to localhost:8889
Code for page.html

<title>Page</title>

 Hello World

This is a simple webpage with Hello World heading and an image.
Now, the error is that the image does not get displayed when the page is loaded when I hit localhost:8889 on my browser. But, the image is displayed when I simply open the webpage through my browser (not via node).
I have also tried changing the src to

*

*"/home/nikhil/test_img/page.html"

*"file:///home/nikhil/test_img/page.html"

*"localhost:8889/page.html"
But, none of these work

Also, I tried printing my location in javascript using
The path printed was

/

Whereas, when I ran the page directly in my browser (without node), it was

/home/nikhil/test_img/page.html

Where do I need to put the image file for this to work?

A: Your code says that each request should serve the file that corresponds to filePath i.e. the  html file page.html. This is fine for the page request itself, but the img tag in your html page creates a separate request for the image pic.jpg which should exist in the same path as the page. But instead of serving the img file, which means your request handler would return something with header Content-type: image/jpg, your request handler again responds with the html page's contents and header Content-Type:text/html.
You need to differentiate what to serve, based on what is being requested.


text:
Q: How is the size of the StatusBar (in the Toolbar) set? In my app, on iphone as well as in the iPhoneX skin on the simulator, the size of StatusBar (inside the Toolbar) is for some reason too small/thin, so the title of the Form is shown partially hidden by the iPhoneX notch.
I've tried to understand how to fix this, but I simply can't figure out how the size of the StatusBar is set. I don't change the size of the StatusBar UIID in my css file, nor in my code and yet it is smaller than if I create a fresh Hello World example with the iPhoneX.skin.
I first thought it could be the SafeArea which changed the size, but it doesn't seem so. Then I thought the default theme (or the values of the Default UIID in the css) could change the size, but it doesn't seem to be that either. I probably miss something obvious, but I'm stuck so any help would be greatly appreciated.
PS. I could of course force the size of the StatusBar in css myself, but then I'm not sure it will work on the various devices, so I prefer rely on the default value defined by CN1.

A: The StatusBar UIID is defined internally and is generally hard coded to a value that fits for most themes. This very much depends on the padding in your Title UIID which is often large and works in tandem with the status bar. Assuming your title has 0 padding you might need more padding to the StatusBar.
Assuming you're using CSS you can use something like:
@media platform-ios {
    StatusBar {
        padding: 7mm;
    }
}


text:
Q: Is there any other function similar to slic() function of python? I am working on a project about applying the method of superpixels in python. I used the slic() function, but because the images are very big, the program takes SEVERAL MINUTES to run all the code. I noted that that slic() function just uses 1 CPU. When I used MATLAB to do the same that I do in python, I use the function called superpixels() and that function uses all the resources of my computers (GPU also), so that means that it takes FEW SECONDS to run all the code.
So, I would like to know how can I improve that slic() function of python in order to make it faster. Where can I get the codes of the slic() function?
Or maybe I was making something wrong?

A: well i don't have a solution but i do have a few suggestions:

*

*if you really want to see the code for the function it can be found here in the git-hub repository. but you should probably look at other implementations that already do this algorithm in parallel since converting the single threaded one to be parallel would probably take more time than translating an existing algorithm from another language to python

*alternatively you can take an implementation in c/c++ and just write a wrapping module for it to use in python.

*no matter what pure python would always run slower so even if you decide to write your own implementation you should do it with cython


text:
Q: How to write a comparison result correctly in simple sentence I have two methods. The first method needs 30 steps to be done. The second method needs only 10-15 steps. I would like to compare the steps that each method needed to be done.
Here is my sentence:

*

*1- The number of iterations is reduced to (almost) the half of the
iterations that the EM-method needed to converge when not using the second method.

or

*The number of iteration of the second method was (almost) the half of the iteration that was required for the first method.

Which one is correct?
Another sentence:
All models show poor fit, where the first model is the poorest one.
Is this a correct comparison in English?
Any help, please?

A: Your constructions are unnecessarily complex, which makes them hard to follow.
Note that steps and iterations are not the same thing. But if you prefer iterations, you might say:

The first method requires more than twice as many iterations as the second.

or

The second method requires less than half as many iterations as the first.

Your sentence regarding the models is also awkward.
I would suggest:

All models fit poorly (or badly); the first model fits worst.

https://www.merriam-webster.com/dictionary/iteration


text:
Q: Is there a way to apply multiple method by one liner in ruby? There is an array like this:
a = [1,2,3,4]

I want to get the return values of size and sum like this.
size = a.size
sum = a.sum

Is there a way to get both values by a one-liner like this?
size, sum = a.some_method(&:size, &:sum)

A: In Ruby, you can do multiple assignments in one line:
size, sum = a.size, a.sum

It doesn't make it more readable, though.

A: You could do this:
a = [1,2,3,4]
methods = [:size, :max, :min, :first, :last]

methods.map { |m| a.send m }
  #=> [4, 4, 1, 1, 4]

A: Another possible solution:
size, sum = a.size, a.reduce { |a,b| a = a + b }

A: Previous answers are correct, but if OP was actually concerned about walking the array multiple times, then array.size does not walk the array, it merely returns the length, thus there is no saving from a oneliner in that regard.
On the other hand, if size was just an example and the question is more about making multiple operations on an array in one go, then try something like this:
arr = [1,2,3,4,5,6]

product,sum = arr.inject([1,0]){|sums,el| [sums[0]*el, sums[1]+el]}
# => [720, 21]

That is, inject the array with multiple initial values for the results and then calculate new value for every element.


text:
Q: Updating user profile details in meteor not working How can I edit the user details in users collection in my meteor app.My code is
 Meteor.users.update({_id:this._id}, { $set:{"profile.name":pname}} )

This is working only for the 1st user in the list. How can I do this for all users listed ?

A: I found that the only way to update a Meteor user was to set the criteria using the _id with the Meteor.userId():
Meteor.users.update( { _id: Meteor.userId() }, { $set: { 'oauth.token': token }} );

I do this on the server side so it will block the client until success/failure from Mongo.

A: The problem was that you are referencing something that doesn't exists
Replace:

Meteor.users.update({_id:this._id}, { $set:{"profile.name":pname}} )

by:

Meteor.users.update({_id:this.userId}, { $set:{"profile.name":pname}} )

Or Use Meteor.userId() as @occasl suggested before.
Just happened to me

A: As per http://docs.meteor.com/#update, set the "multi" option to "true":
Meteor.users.update({_id:this._id}, { $set:{"profile.name":pname}}, {multi: true} )


text:
Q: How to relate traffic to a Banner even thought they didn`t click on it and just searched the site afterwords I will like to know if there is a way to relate a user to a publicity banner on a  3rd party site that came to my site not directly by clicking on it, but they search for my site afterwords. FYI - I use Google analytic to track my traffic.
An example flow is as described bellow:

*

*The user saw the banner on a site that I promote trough. (The user don`t click on the banner)

*The user sometime after remembers that he saw the banner and search for my site on Google/Bing.

*The user becomes a client in my site.

*Here is the problem, I thought that the user came from an add-words search instead the real reason that was the banner in the other site.
Hope you can help me resolve this issue.
Thanks!
FYI - I use Google analytic to track my traffic.

A: Unfortunately no, you won't be able to track these kinds of visitors with just Google Analytics. If the site you're advertising on uses an ad server like DoubleClick, they've developed technology for just this use case (though you'll need to place the DC javascript tracking on your site in order for it to work correctly).


text:
Q: C# WPF Resource Image (Visual Studio) I have a picture in my Resource of a project.
Now, which source do I have to set in the image properties?
Should I use this one i.e. C:\Users\user\Docs\Project\Resources\image.jpg
(I'm using Visual Studio and have a C# WPF project)

A: Set the resources buildaction to resource and don't copy to Output Directory
I made a Folder in my Project called Images where i put the Image into
In my code, I put the Picture in a picturebox, so I load it into a BitmapImage
BitmapImage BI = new BitmapImage();
BI.BeginInit();
BI.UriSource = new Uri("pack://application:,,,/Images/ImageName.png");
BI.EndInit();


text:
Q: I can't see the elements by their id in Android Studio I'm a new Kotlin Programmer. I tried to change the app icon by deleting the ic_launcher.png files and replacing my own images. As i see that is ridiculous what i'm trying to do, i copied the "Main Activity.kt" and "main_activity.xml" files and created a new project. As i tried to copy the files into the new project, the program throws a lot of errors:

It didn't imported the "kotlinx" packet and didn't perceive the elements in the xml file. As i tried to create an another new project to try whether the problem is only for this project, i realized that Android Studio doesn't perceive the xml elements anymore.

Here are some important infos about my project:
The Android Manifest XML File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ihdovanay.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

The Build Gradle File of The Project
buildscript {
    ext.kotlin_version = "1.4.10"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

The Build Gradle File of the Module
plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.ihdovanay.myapplication"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

I would be very happy if you could solve my problem.

A: Revised answer after the deprecation of view synthetics.
You're missing the kotlin-android-extensions plugin in your build.gradle. It's responsible for generating synthetic view references.
kotlin-android-extensions is now deprecated, so it is no longer included by default and should no longer be added to projects. You should use findViewById or View Binding.
You can make it work by doing the following, but I don't recommend adding and relying on a deprecated library. Add the line to your plugins block at the top:
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

A: In Android Studio 4.1.1, the following code is missing in build.gradle (module: yourAppName)
id 'kotlin-android-extensions'


text:
Q: how can calling of admin controller of custom module be done How can I call admin controller of custom module using the following code. I have tried to search on Google but was unable to find anything
Here is the code of Mynamespace/TypeChanger/Block/Adminhtml/Catalog/Product/Grid.php
class Mynamespace_TypeChanger_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid
{
        protected function _prepareMassaction()
    {
        parent::_prepareMassaction();

        // Append new mass action option
        $this->getMassactionBlock()->addItem(
                'typechanger',
                array('label' => $this->__('Change Type'),
                        'url'   => $this->getUrl('abc'),
        //this should be the url where there will be mass operation

            'additional' => array(
                        'visibility' => array(
                                'name' => 'type',
                                'type' => 'select',
                                'class' => 'required-entry',
                                'label' => Mage::helper('catalog')->__('Type'),
                                'values' => array('simple' => 'simple','grouped' => 'grouped' , 'configurable' => 'configurable' ,'virtual'=> 'virtual', 'bundle'=> 'bundle', 'downloadable'=>'downloadable')
                            )

            )

            )
            );
    }
}

here is the code for config.xml
 <?xml version="1.0"?>
    <config>
        <modules>
            <Mynamespace_TypeChanger>
                <version>1.0</version>
            </Mynamespace_TypeChanger>
        </modules>

        <admin>
            <routers>
                <typechanger>
                    <use>admin</use>
                    <args>
                        <module>Mynamespace_TypeChanger</module>
                        <frontName>abc</frontName>
                    </args>
                </typechanger>
            </routers>

        </admin>

       <global>
            <blocks>
                <adminhtml>
                    <rewrite>
                        <catalog_product_grid>Mynamespace_TypeChanger_Block_Adminhtml_Catalog_Product_Grid</catalog_product_grid>
                    </rewrite>
                </adminhtml>
            </blocks>

        <helpers>
                <typechanger>
                    <class>Mynamespace_TypeChanger_Helper</class>
                </typechanger>
        </helpers>

        </global>

    </config>

A: you can add url tag in your Grid.php like below
 $this->getMassactionBlock()->addItem(
                'typechanger',
                array('label' => $this->__('Change Type'),
                      'url'  => $this->getUrl('*/*/massChangeType', array('_current'=>true)),
        //this should be the url where there will be mass operation

            'additional' => array(
                        'visibility' => array(
                                'name' => 'type',
                                'type' => 'select',
                                'class' => 'required-entry',
                                'label' => Mage::helper('catalog')->__('Type'),
                                'values' => array('simple' => 'simple','grouped' => 'grouped' , 'configurable' => 'configurable' ,'virtual'=> 'virtual', 'bundle'=> 'bundle', 'downloadable'=>'downloadable')
                            )
                 )
               )
            );

where your controller name should be like
Mynamespace_TypeChanger_Adminhtml_Catalog_ProductController

anb path should be like
\Mynamespace\TypeChanger\controllers\Adminhtml\Catalog\ProductController.php

in that you have to define function massChangeType or your custom name.
And use below rewrite admin controller in config.xml
<admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <Mynamespace_TypeChanger before="Mage_Adminhtml">Mynamespace_TypeChanger_Adminhtml</Mynamespace_TypeChanger>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>


text:
Q: Facebook post thumbnail size I have a next problem. In web site i have "like" facebook button. And when I comment page and shared link in small reso I see all good:
good
but in big reso (1680x1050 and more) its not good like:bad.
I try different size, different proportions and different type. I saw that some post always see good. Can I say Facebook that always show post thumbnail as first variant for all reso???


text:
Q: How is antimatter produced? In Star Trek, the fundamental concept of warp drive requires anti-matter and matter combinations to produce the needed energy.  Yet, despite this importance, I haven't come across any reference to how antimatter is produced (Memory Alpha contained no hints).  So how is antimatter produced in the 23rd or 24th centuries?

A: The semi-canonical Star Trek: The Next Generation Technical Manual is deliberately vague on this, just referring to some unknown form of "charge reversal devices" on p. 67, but they do at least specify that Starfleet has special facilities for antimatter production:

As used aboard the USS Enterprise, antimatter is first generated at
  major Starfleet fueling facilities by combined solar-fusion charge
  reversal devices, which process proton and neutron beams into
  antideuterons, and are joined by a positron beam accelerator to
  produce antihydrogen (specifically antideuterium). Even with the added
  solar dynamo input, there is a net energy loss of 24% using this
  process, but this loss is deemed acceptable by Starfleet to conduct
  distant interstellar operations.

A: Today, very small amounts of antimatter are produced. Most are in the form of positrons, some are produced in the form of anti-protons, and there are a few labs making anti-hydrogen (a full positron/anti-proton pair).
It takes more energy to make it than would be released if it was utilized. This is a basic principle of physics, after all.
There is a nuclear fission principle though, that of the "breeder reaction". They experimented with this sort of nuclear reactor until the 1980s or so. It exploited some weird side reactions, such that as you cooked the uranium (plutonium? I'm not familiar with the details) it also cooked the other radioactive elements in the fuels rods turning them into more fuel.
Hypothetically, if there were a similar reaction for antimatter, such that annihilating it with matter caused nearby particles to convert into antimatter, then you would be able to make more of the stuff easily. It would be sort of like if when using gasoline in a internal combustion engine it caused the air to spontaneously turn into gasoline. Only, with antimatter there might be some formulation of this that didn't necessarily violate entropy.
I've also read other theories that suppose that you might "rotate" normal matter through higher dimensions, such that when it reappeared to us in our dimension it would have become antimatter. Of course, every few weeks someone is claiming that there are 30 higher dimensions or none, so this might be bunk too.
Star Trek itself has mostly been silent on the details of its own process, for the same reason that we never see the cops on Law and Order ever bother to fill up the gas tanks of their department-issued vehicles.

A: I think we must assume starships regularly hang in close orbit around stars, there converting solar energy into matter and antimatter (and storing the antimatter).  Stars have loads of energy.  But the trick is carrying this compact form of energy between stars.  Between stars, one can't just convert a natural and close source of solar energy into antimatter since the nearest source of energy is often many light years away.  Between stars, the energy is too weak and it would take too long to gather sufficient energy to make any appreciable amount of antimatter.
Thus, starships (not shown actually doing this since it's boring, like filling up at a gas station) collect solar energy whenever they are low on antimatter and close to a star and they have time, and thus produce and store antimatter for later use between stars.  How long this takes, we do not know, but we must further assume it does not take too long and they have highly efficient solar energy converters.  Otherwise, you'd have to account for huge time lags in the story while they did this.

A: In Star Trek, they have devices which reverses the quantum numbers.
To be clear, quantum numbers are a conserved quantity in the standard model just like energy is. Matter, known as fermions, are separate from antimatter, known as antifermions, based on these quantum numbers:
Electric charge.
Color charge.
Baryon number.
Lepton number.
Lepton family number.
Spin.
Angular momentum.
These numbers must not change in either sign or magnitude in any quantum interaction. This is the case, which prevents the creation of antimatter and matter in unequal quantities.
"Quantum charge reversal devices," therefore, would violate conservation of baryon number, electric charge, etc. " flipping" matter into antimatter.

A: Definitely in the original series a reference is dropped in i believe "The Mark of Gideon" that the Enterprise regenerates its own power.
I always thought it was canon that once initially fueled, Federation starships used their own power and equipment to keep making more anti matter, obviously using less energy to make it than it eventually produced.


text:
Q: How to fix "ConnectionResetError: [Errno 104] Connection reset by peer" error? I'm trying to download MNIST dataset on GPU of google colaboratory. But it is showing me "ConnectionResetError: [Errno 104] Connection reset by peer" error message.
from sklearn.datasets import fetch_mldata
dataset = fetch_mldata('MNIST original')
data = dataset.data

And the following error I'm getting:
/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:85: DeprecationWarning: Function fetch_mldata is deprecated; fetch_mldata was deprecated in version 0.20 and will be removed in version 0.22. Please use fetch_openml.
  warnings.warn(msg, category=DeprecationWarning)
/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:85: DeprecationWarning: Function mldata_filename is deprecated; mldata_filename was deprecated in version 0.20 and will be removed in version 0.22. Please use fetch_openml.
  warnings.warn(msg, category=DeprecationWarning)
---------------------------------------------------------------------------
ConnectionResetError                      Traceback (most recent call last)
<ipython-input-8-8ae517e9a088> in <module>()
      1 from sklearn.datasets import fetch_mldata
----> 2 dataset = fetch_mldata('MNIST original')
      3 data = dataset.data

11 frames
/usr/lib/python3.6/socket.py in readinto(self, b)
    584         while True:
    585             try:
--> 586                 return self._sock.recv_into(b)
    587             except timeout:
    588                 self._timeout_occurred = True

ConnectionResetError: [Errno 104] Connection reset by peer

It is taking too long to show this error message. How to resolve this?

A: Take a look at this response, it is very similar SO answer
But, you can simply wrap the dataset = fetch_mldata('MNIST original') in a try-except block.
try:
     dataset = fetch_mldata('MNIST original')
except ConnectionResetError as exc:
     print('Oh no, conection error', str(exc))
     raise

This will catch the exception, print a statement, and then reraise the original exception.
This is the exception being raised socket.py You can try calling socket.settimeout with a larger timeout value to give your request time to complete. To be clear, this will make the exception take even longer to appear (60 seconds in the code below). If it still occurs, there may be an issue with your network that is causing a disconnect.
from sklearn.datasets import fetch_mldata
import socket

socket.settimeout(60) # sets the socket timeout to 60 seconds.
dataset = fetch_mldata('MNIST original')
data = dataset.data

Another caveat, take a look at the first line of the error response you provided.
/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:85: DeprecationWarning: Function fetch_mldata is deprecated; fetch_mldata was deprecated in version 0.20 and will be removed in version 0.22. Please use fetch_openml.

warnings.warn(msg, category=DeprecationWarning)
You may want to try using fetch_openml since fetch_mldata is being deprecated.

A: The MNIST dataset is removed from the sklearn. That is why I was facing that problem. Following is an alternate solution to load MNIST data:
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')