Q:

Flutter: build error when adding "image_cropper" and "contacts_service" packages

I can successfully build and run a fresh new flutter project. But when I add both image_cropper: ^1.0.0 and contacts_service: ^0.2.4 packages to pubspec.yaml and run flutter packages get, I cannot build the project anymore, and get this build error:
D8: Program type already present: android.support.v4.app.INotificationSideChannel

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\2.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\3.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\4.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\5.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\6.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\7.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\8.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\9.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\10.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\11.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\12.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\13.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\14.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\15.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\16.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\17.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\18.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\19.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\20.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\21.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\22.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\23.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\24.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\25.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\26.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\27.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\28.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\29.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\30.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\31.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\32.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\33.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\34.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\35.jar, E:\Projects\flutter\hello\build\app\intermediates\transforms\dexBuilder\debug\36.jar
  Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.
  Program type already present: android.support.v4.app.INotificationSideChannel

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 19s
*******************************************************************************************
The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See https:///CP92wY for more information on the problem and how to fix it.
*******************************************************************************************
Finished with error: Gradle task assembleDebug failed with exit code 1

I do not understand this error very well, but it seems that there is a naming conflict between these two packages (because of duplicate_classes in the error text). Is there any workaround for this?
Note that this error does not happen with any other pair of packages for me.

A:

This was an Android X compatibility issue. I could get it fixed by following the steps mentioned here, but in summary:

First make sure that compileSdkVersion is at least 28 in app/build.gradle. This property controls the version of the Android SDK that Gradle uses to build your APK. It doesn’t affect the minimum SDK version that your app can run on.
Right click on android directory of flutter project and open it using this menu: Flutter > Open android module in android studio
In the newly opened project, from menus select Refactor > Migrate to AdnroidX
Close the project and open your flutter project again.


Q:

How to choose database management system?

Basic requirements

Fault tolerant (ex. has to work even when an entire data center goes down)
Maximum number of records are about 1-5 billion
Has to work properly and comparatively fast under high load
Compatible with JavaEE
Prefer relative DB but in general it doesn't matter
Free of charge

Do you have any ideas?

A:

Wikipedia has an extensive list that compares many RDBMSs - take a look.
PostGresSql is a good free option.


Q:

Where can I find a good tutorial on how to program a keyboard/mouse macro (emulating keyboard and mouse guestures repeatedly) with C#?

Where can I find a good tutorial on how to program a keyboard/mouse macro (emulating keyboard and mouse guestures repeatedly) with C#?

A:

No tutorial, but the API function is MSDN - SendInput.
To use it from C#, you have to declare the function as DllImport. Bot don't worry, someone else already did all the typing for you: pinvoke.net: SendInput (user32).


Q:

Can Kendo TimezoneEditor be disabled?

Some controls (widgets?) in Kendo UI can be disabled using data-bind="disabled:boundfield", some need to set this option manually (yes, it's about multiselect).
But I can't find a good way to do this with TimezoneEditor — it not reacts on both.
In Scheduler editor template I want to turn timezones to readonly state for some cases (a.e. occurrence events), but can't find a proper solution.

A:

No, TimezoneEditor can't be disabled in current version, so we just replaced it with custom selector.


Q:

3-labelled automaton

I need to draw a (kind of) automaton with every arc having:

a "letter label" at the midpoint of the arc,

and (some) having

a "number label" at the beginning of the arc,
a "number label" at     the end of the arc.

I thought that, instead of using plain tikz, it will be more confortable to use some existing library or package (say tikzcd, automata, tkzgraph...). But in every case I find some issues that I can not properly solve.
For example, using tikzcd I obtained the following (quite satisfactory) result
\documentclass{article}

\usepackage{tikz,tikz-cd}
\usetikzlibrary{arrows.meta,bending}

\tikzcdset{
    arrow style=tikz,               % Latin Modern, math font, tikz
    diagrams={>=stealth},            % to, stealth, latex, space
    diagrams={nodes={inner sep=1pt}},
    }

\begin{document}

\begin{tikzcd}[column sep = 50,row sep = 40]
    \odot \arrow[loop left,distance=3em,
     out=145,in=215,
     "y" description,
     blue]
     \arrow[r,bend left=90,red,"x" description]
    & \bullet
    \arrow[l,red, "x" description,
    "\scriptscriptstyle{(0,2)}"' very near start,
    "\scriptscriptstyle{(1,2)}"' very near end]
    \arrow[loop right,distance=3em,
     out=35,in=-35,
     "y" description,
     "\scriptscriptstyle{(0,2)}"' very near start,
    "\scriptscriptstyle{(1,2)}"' very near end,
     blue]\\
    &\bullet \arrow[lu,red,"x" description,
    "\scriptscriptstyle{(1,0)}" very near end]
    \arrow[u,blue,"y" description]
  \end{tikzcd}

\end{document}

The problem is, of course, the "number labeling" of the loops. Is there a way to correctly position this labels (to appear in the start and end of the edge loop)?
I have also tried with the automata library (which I suppose is more appropriate for drawing automata, right?) with the following result:
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\usetikzlibrary{arrows.meta,bending}

\tikzset{every state/.style={
    inner sep=2pt,
    minimum size=4pt,
    %fill=black
    }}

\tikzset{every edge/.append style={
    font=\tiny    %\scriptsize  \tiny
}}

\tikzset{>=stealth}  %latex, to, stealth

\begin{document}

\begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid,auto]
   \node[state,accepting] (1) {1};
   \node[state] (4) [right=of 1] {4};
   \node[state] (3) [below=of 4] {3};
   \path[->]
        (1) edge[red,bend left,in=90,out=90]
            node {$a$}(4)
            edge[loop left,blue,min distance=10mm]
            node {$b$}(1)
        (3) edge[red]
            node {$a$}
            node[very near end] {${(1,0)}$}(1)
            edge[blue]
            node {$b$}(4)
        (4) edge[red]
            node {$a$}
            node[near end,swap] {${(1,2)}$}
            node[very near start,swap] {${(0,2)}$} (1)
            edge[loop right,blue,min distance=10mm]
            node {$b$}
            node[pos=0] {${(0,2)}$}
            node[pos=1] {${(1,2)}$}(4);
\end{tikzpicture}

\end{document}

Here, the problems are more. At least:

positioning of "number labels" in loops (as before),
simulating the "description" effect to position "letter labels" like in the tikcd example,
bad spacing in "number labels" (probably caused by the \tiny font size).

Do you know how to fix these problems?
Which option do you think is better for drawing this kind of automata?
Of course, I am not an expert. Sorry if I am asking something trivial o easy to find.

A:

Instead of auto you can fix where you want your labels. By default auto place labels above or below the path. Without auto they are placed on the path and if you want they cut the path, use fill=white.
Just an example:

\documentclass[tikz,border=3mm]{standalone}

\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\usetikzlibrary{arrows.meta,bending}

\tikzset{every state/.style={
    inner sep=2pt,
    minimum size=4pt,
    %fill=black
    }}

\tikzset{every edge/.append style={
    font=\tiny
}}

\tikzset{>=stealth}  %latex, to, stealth

\begin{document}

\begin{tikzpicture}[shorten >=1pt, node distance=2cm, on grid]
   \node[state,accepting] (1) {1};
   \node[state] (4) [right=of 1] {4};
   \node[state] (3) [below=of 4] {3};
   \path[->]
        (1) edge[red,bend left,in=90,out=90]
            node[fill=white] {$a$}(4)
            edge[loop left,blue,min distance=10mm]
            node[fill=white] {$b$}(1)
        (3) edge[red]
            node[fill=white] {$a$}
            node[near end, below left=-1mm] {(1,0)}(1)
            edge[blue]
            node[fill=white] {$b$}(4)
        (4) edge[red]
            node[fill=white] {$a$}
            node[pos=.8,above=-1mm] {(1,2)}
            node[pos=.2,above=-1mm] {(0,2)} (1)
            edge[loop right,blue,min distance=10mm]
            node[fill=white] {$b$}
            node[pos=0.1, above] {(0,2)}
            node[pos=0.9, below] {(1,2)}(4);
\end{tikzpicture}

\end{document}


Q:

AngularJS Ng-Repeat not iterating items in $Scope

I'm currently trying to read a Json array of objects from my Employees API, which is returning the following,
 [
            {
                "Id": "00162c3a-2b70-4f50-80e8-6fee463cffdb",
                "EmployeeNumber": 123,
                "FirstName": "John",
                "Surname": "Smith",
                "JobTitle": "Developer",
                "Email": "jsmith@company.co.uk",
                "PhoneNumber": "89345 242397",
                "ExtensionNumber": "2895",
                "MobileNumber": "12343451234"
            },
            {
                "Id": "048b73e7-a84d-439b-97c2-0c611a076eb0",
                "EmployeeNumber": 125,
                "FirstName": "Billy",
                "Surname": "Smith",
                "JobTitle": "Developer",
                "Email": "bsmith@company.co.uk",
                "PhoneNumber": "89345 242397",
                "ExtensionNumber": "2896",
                "MobileNumber": "12343451223"
            }
 ]

In my AngularJs application I have a controller as follows,
'use strict';
app.controller('directoryController', ['$scope', 'Page', function ($scope, Page) {
    Page.setTitle('Employee Directory');

    $.ajax({
        url: 'http://localhost:8080/SGIntranetService/api/employee/',
        type: 'GET',
    }).success(function (data) {
        $scope.employees = data;

    //console.log($scope.employees);
    });
}]);

When returning to the console all of the objects appear to be there. Also to note, for some reason at the moment my Ajax call is making two requests to the Web API. (Not sure why this is)
Finally I am trying to use this in a partial view (ng-view), Only using one of the properties for testing until it starts working, then ill add the rest in.

{{employee.FirstName}}

On my index.html (master page) I have the following.

{{Page.title()}}

A:

You do call in controller, so maybe you twice insert controller, so there are two ajax calls.
Look here for comparision of ajax and http calls.
When using $http instead of ajax, you can rewrite your code like this:
app.controller('directoryController', ['$scope', 'Page','$http', function ($scope, Page,$http) {
    Page.setTitle('Employee Directory');

$http({
    url: 'http://localhost:8080/SGIntranetService/api/employee/',
    method: 'GET',
}).success(function (data) {
    $scope.employees = data;
});
}]);

You can use both ajax and $http calls.
Pros for $http are:

it is simple to write $http call - you don't have to precise headers
and javascript objects are converted to JSON automatically
$http have success method and error method
$http can be used with $httpbackend service, to mockup calls for testing. I didn't check if $.ajax would work with this, but i see here, that people are asking about this.
$http returns result as promise, so you can use this mechanism in
your angular app.

There is one pros for ajax call, you can set async: true in this call and $http doesn't provide this.
In general it is better to migrate from JQuery Ajax, to Angulars $http, when working with Angularjs. But if you want for more deeper calls(like using REST), use $resource service.
Here is $http documentation.


Q:

Iphone:Split a string seperated by comma and print each in row of pickerview

I got a string as mild,medium,hot.I  split the string with comma as separator.I need to print it in a pickerView too.
I used the following code and got List count as 3 successfully.
    NSString *spList=[mdict objectForKey:@"spicinesstype"];
    NSArray *list = [spList componentsSeparatedByString:@","];
    NSLog(@"List count:%d",[list count]);
    return [list count];

But how could I display all 3 items in pickerview

A:

You should set your class as the delegate of the picker view, Then implement these 3 delegate methods for your picker
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
    return [array count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [array objectAtIndex:row];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
    return 1;
}


Q:

importar csv a python SIN usar rutas absolutas

Explico paso por paso.

Creo un repo en github con readme y gitignoreVScode.
Creo una carpeta vacia en mi escritorio a la que llamo x y dentro otra a la que llamo x1 también vacía.
Navego a través de la terminal hasta x2 y hago git clone de mi repo.ahi se crea otra carpeta que se llama Sharkattack.
Creo dos directorios dentro de Shark... input y output
Me descargo un csv de kaggle.
Copio el csv en input.
Abro vscode y me voy a gitignore escribo el nombre del csv.
Desde output abro un jupyter notebook,e importo pandas y otros modulos.

Cuando intento abrir el csv con pandas no me deja.¿Por qué?
Mi codigodf = pd.read_csv('input/attacks.csv', encoding='cp-1252')
Me da el siguiente error:
FileNotFoundError: [Errno 2] No such file or directory: 'input/attacks.csv'
¿Qué está pasando?

A:

Puedes usar os.path.join que une uno o más componentes de ruta de format inteligente:
excel = os.path.join(os.getcwd(), "ejemplo.xlsx")


Q:

How to convert a array of strings to an array of symbols?

I want to convert the elements of the string array below to symbols, and output them
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

look at what I'm doing:
strings.each { |x| puts x.to_sym }

No success. What am I doing wrong?

A:

Use map rather than each:
>> strings.map { |x| x.to_sym }
=> [:HTML, :CSS, :JavaScript, :Python, :Ruby]

For Ruby 1.8.7 and later or with ActiveSupport included, you can use this syntax:
>> strings.map &:to_sym
=> [:HTML, :CSS, :JavaScript, :Python, :Ruby]

The reason your each method appears to not work is that calling puts with a symbol outputs the string representation of the symbol (that is, without the :). Additionally, you're just looping through and outputting things; you're not actually constructing a new array.

A:

Clean one-liner:
%w(HTML CSS JavaScript Python Ruby).map(&:to_sym)

& tells argument should be treated as a block, i.e. build up array and apply to_sym to each element.

A:

I'd do something like
strings.map! &:to_sym


Q:

How to get list row item(textview) id and text in onScroll of Listview in android?

I have used base adapter in to create a custom listview. There is an ImageView and TextView in each row of listview. What I want to do is that when I scroll listview I want to get the text of textview in firstvisible row of listview and then I want to make the textview invisible of firstvisible row of listview. How can I get Id and data of a view in onScroll method of listview.
@Override
        public View getView(int arg0, View convertView, ViewGroup arg2) {
            // TODO Auto-generated method stub

            convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_row, arg2, false);
            TextView tv = (TextView)convertView.findViewById(R.id.textViewrow);
            tv.setText("position " + arg0);
            tv_item = tv;
//          tv.setTag("position " + arg0);

            return convertView;
        }

@Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub
//              ViewGroup viewGroup = (ViewGroup) view.getAdapter()
//                        .getView(firstVisibleRow, null, view);//
                int post = lv.getFirstVisiblePosition();
                TextView tv = (TextView)lv.findViewWithTag("position " + post);
                System.out.println("position " + post);
//              View v= lv.findViewWithTag("position " + post);
//              v.findViewById(R.id.textViewrow).gett
//              System.out.println("position text" + tv.getText());

                /*tv_item.getHitRect(rect2);
                if (Rect.intersects(rect1, rect2)) {
                    Toast.makeText(getApplicationContext(), "intersected", Toast.LENGTH_LONG).show();
                }*/

            }

A:

I guess this problem is connected with this :)
To resolve your problem I searched a little and I found this
Now to fix your problem you have to follow these steps:
You have to get the View of your first visible row like this:
    ....
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        View view = mListView.getAdapter().getView(firstVisibleItem, null, mListView);
        TextView mTextView = (TextView) view.findViewById(R.id.textViewrow);
        mTextView.setVisbility(View.GONE);

I hope it helps you,


Q:

How to stop 'drop' speed increase?

The issue is that every time a new drop is added by pressing the 'Space' key, the speed of all the drops increases, the speed is determined by the movepi function in the Drop Constructor. Any Help would be appreciated. Thanks.
The Code Snippet below can be tested by pressing the SpaceBar.

// Get Random //
function rand(min, max) {
    "use strict";
    return Math.floor((Math.random() * max) + min);
}

// Setup Canvas //
var canvas = document.querySelector("#make"),
    ctx = canvas.getContext("2d");

// Create Drop //
function Drop(x, y) {
    'use strict';
    // Set X and Y Position //
    this.x = x;
    this.y = y;
    // Show Drop //
    this.showpi = function () {
        ctx.fillStyle = 'red';
        ctx.fillRect(x, y, 10, 10);
    };
    // Move Drop //
    this.movepi = function () {
        y = y - 3;
    };
}

// Setup Canvas Size //
function setCanvasWidth() {
    "use strict";
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
}

// Paint Over Canvas For Animation Illusion //
function paintover() {
    'use strict';
    ctx.fillStyle = "rgba(0, 0, 0, 0.4)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    window.requestAnimationFrame(paintover);
}

// Variables //
var dropi = [];
//var drop = new Drop(window.innerWidth / 2, window.innerHeight);

// Get New Drops //
function drop() {
    'use strict';
    var newdrops = new Drop(window.innerWidth / 2, window.innerHeight);
    return newdrops;
}

// Draw //
function draw() {
    'use strict';
    var i;
    for (i = 0; i < dropi.length; i = i + 1) {
        dropi[i].showpi();
        dropi[i].movepi();
    }
    window.requestAnimationFrame(draw);
}

// Listen For "SpaceBar" Key Press //
window.addEventListener('keydown', function pressed(x) {
 'use strict';
 var code = x.keyCode;
        //soundfile = new Audio('blop.wav');
 if (code === 32) {
        //soundfile.play();
        dropi.push(new Drop(window.innerWidth / 2, window.innerHeight));
        draw();
    }
});

// Run //
setCanvasWidth();
paintover();
canvas {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
}
<html>
    <body>
        <canvas id="make"></canvas>
    </body>
</html>

A:

My Friend helped me out, i made the mistake of calling draw() everytime i pressed space. he put it in a conditional statement so i only had to call it once. Thanks to all...

// Get Random //
function rand(min, max) {
    "use strict";
    return Math.floor((Math.random() * max) + min);
}

// Setup Canvas //
var canvas = document.querySelector("#make"),
    ctx = canvas.getContext("2d");

// Create Drop //
function Drop(x, y) {
    'use strict';
    // Set X and Y Position //
    this.x = x;
    this.y = y;
    // Show Drop //
    this.showpi = function () {
        ctx.fillStyle = 'red';
        ctx.fillRect(x, y, 10, 10);
    };
    // Move Drop //
    this.movepi = function () {
        y = y - 3;
    };
}

// Setup Canvas Size //
function setCanvasWidth() {
    "use strict";
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
}

// Paint Over Canvas For Animation Illusion //
function paintover() {
    'use strict';
    ctx.fillStyle = "rgba(0, 0, 0, 0.4)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    window.requestAnimationFrame(paintover);
}

// Variables //
var dropi = [];
//var drop = new Drop(window.innerWidth / 2, window.innerHeight);

// Get New Drops //
function drop() {
    'use strict';
    var newdrops = new Drop(window.innerWidth / 2, window.innerHeight);
    return newdrops;
}

// Draw //
function draw() {
    'use strict';
    var i;
    for (i = 0; i < dropi.length; i = i + 1) {
        dropi[i].showpi();
        dropi[i].movepi();
    }
    window.requestAnimationFrame(draw);
}

// Listen For Key Press //
window.addEventListener('keydown', function pressed(x) {
 'use strict';
 var code = x.keyCode;
        //soundfile = new Audio('blop.wav');
 if (code === 32) {
        //soundfile.play();
        dropi.push(new Drop(window.innerWidth / 2, window.innerHeight));
        if (dropi.length === 1) {
            draw();
        }
    }
});

// Run //
setCanvasWidth();
paintover();
canvas {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
}
    <body>
        <canvas id="make"></canvas>
    </body>


Q:

How can I fill under a function in a plot just to right of a specified vertical line?

How do I plot a normal curve with filling under the curve and to the right of a vertical line. I would prefer that the vertical line starts at the x-axis and stops at the plotted curve.
Basically trying to shade the area under the curve for a specific region.

A:

Maybe you could use something like this as a start point:
Manipulate[
    dist=PDF[NormalDistribution[5,1],#]&;
    p1=Plot[dist@x,{x,0,l}
        ,Filling->Axis
        ,PlotRange-> {{0,10},All}
        ];
    p2=Plot[dist@x,{x,l,10}
        ,Filling->None
        ,PlotRange-> {{0,10},All}
        ];
    Show[p1,p2,Epilog->{Orange,Line[{{l,0},{l,dist@l}}]},PlotLabel->Style[#,20]&@Row[{"l=",NumberForm[dist@l,{\[Infinity],2}]}]],
{{l,5.},0,10}
]

A:

Murta's solution works nicely, but there is a way to do what is desired without the fuss of using Show[] and separate instances of Plot[]. Witness the following:
With[{dist = PDF[NormalDistribution[5, 1]], l = 5},
     Plot[{ConditionalExpression[dist[x], x < l], dist[x]}, {x, 0, 10},
          Epilog -> {Orange, Line[{{l, 0}, {l, dist @ l}}]},
          Filling -> {1 -> Axis}, PlotRange -> {{0, 10}, All},
          PlotLabel -> Style[StringForm["l=`1`", NumberForm[dist @ N @ l, {∞, 2}]], 20],
          PlotStyle -> ColorData[1, 1]]]

The key here is the tandem use of the specifications in the Filling option to restrict the filling to a single curve, and ConditionalExpression[] to restrict the filling domain.

The Wizard reports the following variation that is useful to people who don't have ConditionalExpression[] handy:
With[{dist = PDF[NormalDistribution[5, 1]], l = 5},
     Plot[{If[x < l, dist[x]], dist[x]}, {x, 0, 10},
          Epilog -> {Orange, Line[{{l, 0}, {l, dist @ l}}]}, Filling -> {1 -> Axis},
          PlotLabel -> Style[StringForm["l=`1`", NumberForm[dist @ N @ l, {∞, 2}]], 20],
          PlotRange -> All, PlotStyle -> ColorData[1, 1]]]


Q:

An urn containing numbered balls probability

An urn containing numbered balls 1, 2, 3 and 4, respectively. Two balls are selected, one at a time and at random of the casket. Let X be a va denoting the sum of the numbers of the selected balls.
Guys, how can I get the probability distribution, the expected value, variance and standard deviation of X for example?

A:

By a simple grid, we have the probability of all 5 possible results
$\begin{array}{c|cccc} \sum & 1 & 2 & 3 & 4 \\ \hline 1 & ~ & 3 & 4 & 5 \\ 2 & 3 & ~ & 5 & 6 \\ 3 & 4 & 5 & ~ & 7 \\ 4 & 5 & 6 & 7 &~\end{array}$
So $\mathsf P(X=x)= \begin{cases}\boxed{?} & : x\in \{3,4,6,7\} \\ \boxed{?} & : x=5 \\ 0 & :\text{otherwise}\end{cases}$
From this find $\mathsf E(X) = \boxed{?}\cdot(3+4+6+7)+\boxed{?}\cdot 5$
Likewise you can find $\mathsf{Var}(X) = \mathsf E((X-\mathsf E(X))^2)$


Q:

How to access a new browser tab

Watir noob here. I'm attempting to connect to and manipulate a newly spawned browser tab, but am a little confused about how to recognize the new tab. Here's what I have:
Windows 7 (32 bit) IE 10
Ruby 1.9.3-p392/TDM-32.4.5.2
LOCAL GEMS
watir (4.0.2 x86-mingw32)
watir-classic (3.6.0)
watir-webdriver (0.6.3)
Basic gist of the Script:
require 'rubygems'
require 'Watir'
ie=Watir::Browser.new

... First part of the script on the original browser tab is completed. The original browser tab generates a second browser tab, which I need to access.
I've read a response somewhere that I need to link to the browser tab prior to attaching to it, but I'm having a hard time recognizing the link by the href, url or title: (where 'path...' = http url)
ie.link(:href, "path...").click

--Uncaught exception: Unable to locate element, using {:tag_name=>["a"], :href=>"path..."
ie.link(:url, "path...").click

--Uncaught exception: Unable to locate element, using {:tag_name=>["a"], :url=>"path..."
ie.a(:href, "path...").click

--Unable to locate element, using {:tag_name=>["a"], :url=>"path..."}
However, if I try the following:
ie2 = Watir::IE.attach(:title, 'New_Tab_Title')

--"Unable to locate a window with title of New_Tab_Title"
Firstly, how do I point to the new url or browser tab?  If I do a ie.close after the second tab opens, the first tab closes, so clearly I don't recognize this new tab (even if it appears to have focus).
Secondly, am I correct in assuming that I need to connect to the link/url first, then attach to the browser tab, then I can continue with populating fields?
Lastly, is there a short name url I can use, as the url generated is very long, or do we need to insert the entire url?

A:

I would recommend using watir-webdriver on tab handling:
Try the following
MEDBEDbs-iMac:~ medbedb$ irb
1.9.3p392 :001 > require 'watir-webdriver'
 => true
1.9.3p392 :002 > b = Watir::Browser.new :chrome
 => #<Watir::Browser:0x..f87e94a30e87e1e60 url="about:blank" title="about:blank">
1.9.3p392 :003 > b.goto "http://www.w3schools.com/html/html_links.asp"
 => "http://www.w3schools.com/html/html_links.asp"
1.9.3p392 :004 > b.title
 => "HTML Links"

Here a new window is opened in a new tab.
1.9.3p392 :005 > b.a(:text, 'HTML links').click
 => []
1.9.3p392 :006 > b.windows.count
 => 2

But watir-webdriving is still handling the previous page..
1.9.3p392 :007 > b.title
 => "HTML Links"

Switching to recently opened tab.
1.9.3p392 :008 > b.windows.last.use
 => #<Watir::Window:0x..fd949289f2b083062 located=true>
1.9.3p392 :009 > b.title
 => "Tryit Editor v1.7"

From here you can do whatever you need in a new tab.
1.9.3p392 :010 > b.windows.last.close
 => #<Watir::Window:0x..fd949289f2b083062 located=true>

After closing the new tab watir will switch back to initial tab.
1.9.3p392 :011 > b.title
 => "HTML Links"
1.9.3p392 :012 > b.close
 => true

Show us the code or url to the web-pate to get more detailed results...


Q:

Adding an element to a singly linked list in Java

I'm implementing a singly linked list in Java. What I don't like about this code is that I need to check if (head.next == null) every time I add an element. But the condition is met only once, when adding the first element.
Is there a way to implement a singly linked non-circular list without such a condition?
package sample;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class SinglyLinkedList<T> implements Iterable<T> {

    private Node<T> head = new Node<T>(null);
    private Node<T> last = null;

    public SinglyLinkedList(T... elements) {
        addAll(elements);
    }

    public void add(T element) {
        if (head.next == null) {
            head.next = new Node<T>(element);
            last = head.next;
        } else {
            Node<T> newNode = new Node<T>(element);
            last.next = newNode;
            last = last.next;
        }
    }

    public void addAll(T... elements) {
        for (T element : elements) {
            add(element);
        }
    }

    @Override
    public String toString() {
        Iterator<T> iterator = iterator();
        if (!iterator.hasNext()) {
            return "[]";
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        while (iterator.hasNext()) {
            T element = iterator.next();
            builder.append(element);
            if (!iterator.hasNext()) {
                return builder.append("]").toString();
            }
            builder.append(", ");
        }
        return builder.toString();
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {

            Node<T> current = head;

            @Override
            public boolean hasNext() {
                return current.next != null;
            }

            @Override
            public T next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                Node<T> temp = current;
                current = current.next;
                return temp.next.element;
            }

        };
    }

    private static class Node<T> {

        private Node<T> next;
        private T element;

        Node(T element) {
            this.element = element;
        }

        @Override
        public String toString() {
            return element.toString();
        }
    }
}

A:

You could initialize last to be pointing to head and then your if is redundant:
private Node<T> head = new Node<T>(null);
private Node<T> last = head;

public void add(T element) {
        Node<T> newNode = new Node<T>(element);
        last.next = newNode;
        last = last.next;
}


Q:

Why object's attributes are not there when the class is instantiated?

Why instantiating a class does not instantiate all its attributes ? I think a very simple example could explain my problem better:
class Example:
    def example(self):
        self.var=10

if __name__=='__main__':
    E=Example()
    # In this case, the attribute  var is not instantiated
    try:
        attr=getattr(E,"var")
        print(attr) # <-- it does not exist even if E instantiated Example class
    except AttributeError:
        print("Object not having this attribute") # <-- This is the output

Why the object E does not have all its attributes instantiated (namely the attribute var) ?

A:

in your class if you need to initialize var you need to call it explicitly by calling the example method in the example class
but if if you write __init__ method it it automatically initialize the variable at the time of object creation

The init method (init for initialise) is called when the object is instantiated. Instantiation is done by (effectively) calling the
  class.Here a new instance is created. Then its init method is called .it call the example method to initialize  var in the exapme

class Example:
    def __init__(self):
        self.var=0 # or you can directly give self.var=10
        self.example()
    def example(self):
        self.var=10

if __name__=='__main__':
    E=Example()
    # In this case, the attribute  var is not instantiated
    try:
        attr=getattr(E,"var")
        print(attr) # <-- it does not exist even if E instantiated Example class
    except AttributeError:
        print("Object not having this attribute")

other way of doing is
when you intalized class object call the method in it
E=Example()
E.example()#explicitly call example method in the class


Q:

Reputation by graph bug

On the reputation page, if you choose to view the reputation by graph, two graphs show up. Beneath the lower one it says:

select an area by dragging across the lower chart

I can't seem to understand what to do here. I click and drag, I drag parts of the higher graph to the lower one, and all kinds of clicking and dragging. Nothing happens. What does it want me to do?

A:

What it means is that you should hold the left mouse button down while the mouse pointer is  on the lower graph and drag along the graph to select which part of your reputation you wish to see. See the below image

The area I have highlighted in red is the one I selected by dragging.

A:

I solved the problem, thanks to @Matt Эллен's comment. In Chrome, if you're zoomed in (by pressing 'Control' & '+') you can't highlight any part of the graph. On Firefox you can. So I un-zoomed and all was good.


Q:

Canvas - Clear Circular Gradient

I have a canvas that sits above some content and is filled completely with black to allow the users to reveal things below the canvas. I would like to clear a circle at a predetermined location, but I'd like the circle fade into the fill color. I've found how to clear circles, but I am unable to locate anything that lets me clear a circle that fades to the background color.

Current Code - Clears a Circle, But Does not Fade to Black
    context.fillStyle = "black";
    context.fillRect(0, 0, this.width, this.height);

    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI, false);
    context.clip();
    context.clearRect(x - radius - 1, y - radius - 1, radius * 2 + 2, radius * 2 + 2);

Code Tried - Doesn't Work
    var radGrd = context.createRadialGradient(x, y, r1, x, y, r2);
    radGrd.addColorStop(0, "rgba( 0, 0, 0,  0 )");
    radGrd.addColorStop(1, "rgba( 0, 0, 0,  1 )");

    //Doesn't Work; Nothing Draws On Screen
    context.fillStyle = radGrd;
    context.clip();
    context.clearRect(x - r2, y - r2, r2 * 2, r2 * 2);

Q: What is the correct way to clear a circle that fades into the background color?

A:

You almost have it: after the clearRect, add a fillRect command with the same parameters. You should remove arc or clip commands, since you're filling a rectangle with a circular gradient.


Q:

Hiding classes - but unable to unit test

I am writing a project in C# using Visual Studio 2010 but wanted to use NUnit for unit testing.
I am quite new to oop but tried to go as far with information hiding and exposing only the minimum of interfaces required. This means that I have a couple classes which are entirely internal to the library - they can handle some internal state while the user only needs to be aware of a couple of public classes which provide an interface.
This seems to hide as much as possible, providing a minimal interface to the user.
However, if I want to unit test, I can't see a way to test these classes. So my question is what is best practice? Having to expose them purely for the sake of unit testing seems a shame.. or is there a better tool for the job?
It seems a trade off between encapsulating as much as possible and exposing as many methods as possible to allow them all to be tested - surely it would be best for unit testing to test the internal workings and let integration testing test the public interface?
--
I realise that normally, you would only worry about unit testing the public interface, but in this case that would lead to a lot of very convoluted tests - it is surely better to have everything broken down into small chunks to test?

A:

I won't go into discussions whether it makes sense to test internal classes or not, but what you want can be achieved using InternalsVisibleTo attribute
Add following to your library:
[assembly:InternalsVisibleTo("MyTest")]

and all internal classes will be accessible from MyTest.dll


Q:

Use Tomcat Library in Webapp project

I have a web application that uses the Tomcat library. I have not copied the jars from the Tomcat library into the web-inf/lib directory.
Now when I run an ant build / testNG class, it throws an error since the concerned jars are not present under the web-inf/lib directory.
Is there any way (configuration) that I can use the Tomcat library for the running the ant build  / testNG classes.
Thanks in advance,
Vivek

A:

In the <testng> task, just provide the tomcat libraries as additional classpath elements.
<TestNG>
    <classpath>
        <pathelement path="${classpath}"/>
        <pathelement location="path/to/tomcat/lib.jar"/>
    </classpath>
</TestNG>


Q:

does flex use frames?

I'm looking into developing a game using the flex SDK instead of flash. I'm kind of not sure how to start.
One question I have - does Flex have a timeline like Flash, with frames etc? Is there a main/root timeline?

A:

From my experience with Flex it is event-based and does not use a timeline for development. That is not to say that you cannot implement timelines using state transitions. I'm not sure what the performance would be like compared to Flash.


Q:

How to change EXIM mail server to send to new mx record?

Our website uses the wordpress contact forms 7 plugin to send emails.  These are for people who want us to contact them.
This just uses the default MTA on our server which is exim.
Everything worked great and then we migrated our mail servers to exchange on a different server.
Our MX record is pointing to the new server and incoming and outgoing email works great.
But the contact forms on the website still send the emails to the localhost.
Which makes sense.  That is what it did in the past.  But I need to change it so users still get their emails.
How do I change exim to not accept mail locally but just relay it on to the mx record for the domain?
I tried adding the text at Exim: how to deliver locally and send a copy to another server but it gives me an error
Exim configuration error in line 1343 of /etc/exim.conf missing error type.

do I need to put the text
smarthost:
            driver = manualroute
            domains = currentdomain.com
            transport = remote_smtp
            route_data = "mxrecordofdomain"

at a certain place in the file.

A:

Exim is delivering locally because the destination domain matches one that you've configured Exim to consider local.  Smarthosting doesn't come into it, because that only kicks in once Exim's decided to route the e-mail somewhere else, and that's not what's happening.
The easiest way to handle this just to grep through your Exim config for your domain, and remove them.  I can't remember the exact name of the option(s) involved; I got rid of my last Exim server in favour of Postfix some years ago.


Q:

Are these consecutive prepositions?

If Gryffindor won, they would move (1) up into second place in the
  house championship.  (Harry Potter book1)
They follow him (2) out into the farmyard, and (3) on into
  the old flint barn. (The Secret Intensity of Everyday Life)

Are those examples of (1), (2) and (3) the same consecutive prepositions as the case in J.R.’s reply?

A:

The first example of “move up into second place” is a phrasal verb, to move up followed by a preposition.
There is nothing “wrong”, nor even uncommon, with stacking prepositions in English. You can lean out of a second-storey window, or ask someone to come on up out of the cellar — or even, and somewhat famously, ask them what they brought that book that you don’t want to be read to out of up for.


Q:

Who controls the StackLinguist's tweeting?

There is a twitter account which regularly tweets questions from this site. Who controls this tweeting? Is it random, automatic, or controlled by some moderator? If automatic, what determines which question gets tweeted?

A:

Twitter.com/StackLinguist tweets interesting questions every so often automatically. I emphasize interesting because Twitter is not meant to be an arbitrary RSS Feed.
The feed is designed to publish the most interesting questions from this site every three hours — without ever repeating themselves.
Twitter Question Feeds for Stack Exchange
The Twitter account currently tweets:

per-site blog posts (if you create one)
chat events, if started by a moderator
interesting questions on the site
bountied questions
interesting answers of +3 or better
unanswered questions of +3 or better
particularly hot meta questions (not support or bug though)


Q:

Topological proof that a continuous injective real function on an interval has a continuous inverse

The text Topology and Groupoids by Brown states the following on page 8 in Chapter 1:

1.2.4 (Inverse rule.) Let $f \colon A \to \mathbb{R}$ be a real function which is injective, so that $f$ has an inverse $f^{-1} \colon f[A] \to A$. If $A$ is an interval and $f$ is continuous, then $f^{-1}$ is continuous.
For a proof see many books on a first course in analysis. This result
is also a consequence of general theorems on connectivity and compactness [cf. Chapter 3]. The assumption that $A$ is an interval is essential [cf.
Exercise 4 of Section 1.2].

Chapter 1 of this book is mostly about preparing the reader for a study of topological spaces in general beginning in Chapter 2. In that spirit, I am wondering if there is a topological proof of 1.2.4, i.e. one using neighborhoods.
I have checked the following books:

Analysis I, by Tao
Elementary Analysis, by Ross
Real Analysis and Foundations, by Krantz
Real Mathematical Analysis, by Pugh
Understanding Analysis, by Abbott
Introduction to Analysis, by Bartle and Sherbert
Principles of Mathematical Analysis, by Rudin
Analysis I, by Amann and Escher
Real Analysis, by Carothers

and I didn't see any neighborhood-style proofs of a result like 1.2.4. (Maybe I missed it?) I've also searched StackExchange but haven't found what I'm looking for.
Questions:
Does anyone know of a proof of result 1.2.4 using neighborhoods? Should I just wait until result 1.2.4 falls out as a special case of more general theorems later in the book?
Thank you.

A:

The intermediate value theorem is all that you need to show that $f$ is either strictly increasing or strictly decreasing, and that $f[A]$ is order-convex, meaning that whenever $x<y<z$, and $x,z\in f[A]$, then $y\in f[A]$. This means that $f[A]$ must be all of $\Bbb R$, a ray, or an interval, i.e., that it must have one of the following forms: $\Bbb R$; $(\leftarrow,a)$, $(\leftarrow,a]$, $(a,\to)$, or $[a,\to)$ for some $a\in\Bbb R$; or $(a,b)$, $[a,b)$, $(a,b]$, or $[a,b]$ for some $a,b\in\Bbb R$. The intermediate value theorem is also all that you need to show that if $[a,b]\subseteq A$, then
$$f\big[[a,b]\big]=\begin{cases}
[f(a),f(b)],&\text{if }f\text{ is increasing}\\
[f(b),f(a)],&\text{if }f\text{ is decreasing.}
\end{cases}$$
Now suppose that $(a,b)\subseteq A$. Note that $a$ and $b$ need not belong to $A$. However,
$$(a,b)=\bigcup_{a<c<d<b}[c,d]\;,$$
so
$$\begin{align*}
f[(a,b)]&=\bigcup_{a<c<d<b}f\big[[c,d]\big]\\
&=\begin{cases}
\left(\inf_\limits{a<c<b}f(c),\sup_\limits{a<c<b}f(d)\right),\text{ if }f\text{ is increasing}\\
\left(\inf_\limits{a<c<b}f(c),\sup_\limits{a<c<b}f(c)\right),\text{ if }f\text{ is decreasing}\;.
\end{cases}
\end{align*}$$
(It’s possible that $\inf_\limits{a<c<b}f(c)=-\infty$ or $\sup_\limits{a<c<b}f(c)=+\infty$; in that case $f\big[(a,b)\big]$ is $\Bbb R$ or an open ray.)
If $a=\min A$, a basic open nbhd of $a$ has the form $[a,b)$ for some $a<b\in A$, and
$$f\big[[a,b)\big]=\begin{cases}
\big[f(a),f(b)\big),&\text{if }f\text{ is increasing}\\
\big(f(b),f(a)\big],&\text{if }f\text{ is decreasing.}
\end{cases}$$
A corresponding result holds for intervals of the form $(a,b]$ if $b=\max A$, so $f$ is open as well as bijective, and the inverse of an open bijection is continuous.


Q:

Gwt compiling error: unable to find entry point when it's not in src/main/java

I have an error compiling my app:
[INFO] Compiling module com.mycompany.myapp.MyAppMocked
[INFO]    Finding entry point classes
[INFO]       [ERROR] Unable to find type 'com.mycompany.myapp.client.mock.MockEntryPoint'
[INFO]          [ERROR] Hint: Check that the type name 'com.mycompany.myapp.client.mock.MockEntryPoint' is really what you meant
[INFO]          [ERROR] Hint: Check that your classpath includes all required source roots

In my .gwt.xml, I have:
<entry-point class="com.mycompany.myapp.client.mock.MockEntryPoint" />

The problem occurs when I put MockEntryPoint.java in src/mocked/java instead of src/main/java.
I need to have both directories to exclude everything in src/mocked/java when compiling the "no-mock" version.
If I move MockEntryPoint.java to src/main/java, the compilation will succeed with no error. In both cases, the class MockEntryPoint is in the package "com.mycompany.myapp.client.mock".
How can I tell gwt to look for my entry class in src/mocked/java?

A:

Assuming this is a Maven project, you need to add src/mocked/java as a source folder. In Maven, it has to be done using the build-helper-maven-plugin's add-source mojo.

But there's little to no reason to have that src/mocked hierarchy:

you can put everything in src/main and just compile the GWT module you need/want (set the module or modules configuration property for the gwt-maven-plugin accordingly)
if you want them clearly separated, Maven wants you to use distinct Maven modules/projects. You don't want to fight against Maven.


Q:

javascript dropdown onclick change element attribute

For some reason, attribute value is not changing. I have a limited knowledge of JavaScript. Any help would be appreciated.

function change(amount) {
  document.getElementsByName("sold_amount").value = amount;
}
<input type="hidden" name="sold_amount">

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Sold amount
        </button>

10000

20000

30000

A:

When you use getElementsByName, notice the elementS; its plural. This means the function returns a NodeList collection (similar to an array). You should use document.getElementsByName("sold_amount")[0].value=amount;.
You still don't see it as type="hidden", but its there. You can use your developer tools to inspect the input to see the change.


Q:

Parsing a string?

So I have the following string:
String text = "\t\t\torder #168\n\t\t\tpaid\n\t\t\tview 4 items\n\t\t\tpicked up\n\t\t\tcomplete pickup\n\t\t\t2 stops";

How do I parse this string so that I always get the 2 in front of stops? I have tried the following, but it always returns 2 stops.
String substr = "complete pickup";
String numberOfStops = text.substring(text.indexOf(substr) + substr.length());
numberOfStops = numberOfStops.replaceAll("^\\s+","").replaceAll("\\s+$","");

A:

The short way:
numberOfStops = numberOfStops.replaceAll("^\\s+","").replaceAll("\\s+$","").replace("stops","");

The flexible way is using Regex, and Pattern and Match classes. Let me know if you need it


Q:

what's a RESTful way to save draft posts?

I have a posts controller on a small test website I'm making. I want to have a 'save draft'/combo-auto-save function to the site, as the site will have long posts that users may want to leave and come back to finish. However, I've never built an autosave/save function into a Rails app before (or any app). What is a good, RESTful way to do so?
Here is my current controller action:
posts_controller.rb
 def create

 @post = params[:post]
 if @post.save
     flash.now[:success] = "Post created!"
 else
     render_errors_now(@post)
 end
     respond_to do |format|
           format.html {redirect_to Discussion.find(session[:discussion_id])}
           format.js
     end
 end

As you can see, users post remotely.
Here is the current post.rb model:
 attr_accessible :content, :title
 validates :title, :presence => true
 validate :title_character_length

 validates :content, :length => { :maximum => 10000 }
 validates :user_id, :presence => true
 validates :discussion_id, :presence => true
 belongs_to :user
 belongs_to :discussion
 default_scope :order => 'posts.created_at ASC'

 def title_character_length
    #some code that checks length
 end

I would need to accomplish the following things from this code..

Auto-save periodically (1 min intervals, perhaps)
Give option to save draft
Choose which validations to run: I would want to allow users to, for example, save a draft with a title that exceeds the allowed length, while not allowing them to actually post  a post with that title.

I also am curious what is a good Rails practice for saving drafts: should I add an attribute "draft" to the post model? Or create a draft posts model?
OK please comment if I need to provide more info. I'm interested to hear people's input! Thanks everyone!

A:

Auto-save:
application.js
$(document).ready(function() {
  setInterval(function() {
    $('form[data-remote]').submit();
  }, 1000*60); // 1000ms * 60s = 1m
});

You'll then need to have an update.js.erb to handle the messages ("Saved", for example).
For drafts, I would make a separate model, PostDraft. The auto-save will be saving the PostDraft object, and then once they click "Publish" or whatever, it will create a new Post and delete the PostDraft. This method will also allow the user to have titles longer than the limit, just by not putting that validation on the PostDraft model. This would be a lot more difficult if you did it all from within the Post model with a "draft" boolean.


Q:

Reduce data usage in an application supports offline-mode

I am working with an application which has offline mode. In order to do that we store the information in a local SQLite Database and using Content Provider which provides a wrapper around the SQLite, and sync it every once in a while with the data from the web service.
We are also keeping the images which are taken by user on the sdcard and send them to the server during the sync service.
The problem is bandwidth and data usage. In Android 4.0+, we have a section in device setting named Data usage. It is showing too much data usage and it annoyed the users.
My first question is : Do you think using ProGaurd which is a tool to shrink the code, can have any impact on reducing the Data Usage?
I would appreciate if you share any experience and suggestion with me in order to reduce the Data usage in such an app.
Addenda:
1 - User login to the system and during first sync sqlite file generated and transferred from REST (initialization).
2 - We have sync-status flag for entries in database. If record(using json string for data) or picture is not synced, it will transfer to the REST during sync and status-flag get updated.
3 - An updated database file receives from REST and merge with the current database on the phone in the sync service (if initialization is already done).

A:

ProGuard has nothing to do with the amount of data you send/receive from a server. ProGuard can shrink and obfuscate code (thus making your APK smaller).
You need to analyze the data you send and receive. There is no silver bullet here that will magically solve any bandwidth issues you may come across in an app. You need to ask yourself several questions and take action depending on your answers:
What kind of numbers are we talking about?
In 2011 the average bandwidth use of an app was around 10MB per hour. There are probably more recent surveys if you search a bit. Are you far above the average number? If not, then I don't think you have to worry too much.
How often do you send and receive data?
If it's a real-time app that absolutely require live data then there's little you can do. If it's not a real-time app maybe you can reduce the frequency of send/receive or wait and collect more data before sending it to reduce overhead? If you're sending many small chunks of data you'll get a lot of overhead in HTTP headers and so on. Hold on to the small chunks a while longer and send them in one go to change the data to overhead ratio.
Can you change the protocol?
Maybe you can send data over a socket instead of HTTP to reduce overhead? By your description it doesn't sound like this would work in your case.
Can you compress data before sending it?
Make sure that your server GZips data before sending it to the client. There is a lot to gain by doing this.
Can you use another data format (binary, json, xml, custom)?
You mention that you use JSON. JSON usually/always perform better than XML, so you're already good there, but maybe you can send data in another format that is even more compact?


Q:

Bernoulli trials (n,p) - probability for even/odd number of successes

I came across this problem. It asks what is the probability of even number of successes in a series of $n$ Bernoulli trials with probability of success in each trial equal to $p \neq \frac{1}{2}$.
Knowing the formula for $k$ number of successes I was able to immediately write down this:
$$ p_{\ even} = \sum_{k=0}^{\lfloor\frac{n}{2}\rfloor}{n \choose 2k} p^{2k}(1-p)^{n-2k} $$
I think that is correct, right?
But after that when I saw the solution which they give in the book, I found (as I suspected by the way) that there's a closed form formula and it goes.
$$ p_{\ even} =  \frac{1}{2} + \frac{1}{2} (1-2p)^{n}$$
The proof is simple, one basically argues inductively over $n$.
This made me think (and this is my question here)... Is there an algebraic way to prove the following equality? I mean some way which simply manipulates these binomial coefficients and uses some of their known properties.
$$ \sum_{k=0}^{\lfloor\frac{n}{2}\rfloor}{n \choose 2k} p^{2k}(1-p)^{n-2k} = \frac{1}{2} + \frac{1}{2} (1-2p)^{n} $$

A:

Case 1: $n=2m$, then:
$$\sum_{k=0}^{\lfloor\frac{n}{2}\rfloor}{n \choose 2k} p^{2k}(1-p)^{n-2k} = \sum_{k=0}^{m}{2m \choose 2k}p^{2k}(1-p)^{2m-2k} = \\
\frac12\left(((1-p)+p)^{2m}+((1-p)-p)^{2m}\right)=\frac12\left(1+(1-2p)^{2m}\right)=\frac{1}{2} + \frac{1}{2} (1-2p)^{n};$$
Case 2: $n=2m+1$, then:
$$\sum_{k=0}^{\lfloor\frac{n}{2}\rfloor}{n \choose 2k} p^{2k}(1-p)^{n-2k} = \sum_{k=0}^{m}{2m+1 \choose 2k}p^{2k}(1-p)^{2m+1-2k} = \\
\frac12\left(((1-p)+p)^{2m+1}+((1-p)-p)^{2m+1}\right)=\frac12\left(1+(1-2p)^{2m+1}\right)=\frac{1}{2} + \frac{1}{2} (1-2p)^{n}.$$


Q:

Avoid duplicated records in a key, value structure JS

An easy question from a noob.
I have this example where I create a list with a Key/Value structure, I use the Id as the Key and the rest of the content is the value so if I add more records they will be added to my list $scope.itemList [ ]
var data = [
              {
                id: 1,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }, {
                id: 2,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }
            ];

            $scope.itemList = [];
            angular.forEach(data, function(item){
                var obj = {};
                var valObj = {};

                valObj.name = item.name;
                valObj.lastname = item.lastname;
                valObj.age = item.age;

                obj[item.id] = valObj;
                $scope.itemList.push(obj);
            });

The thing is that I could have more records in my json with the same id and I want to avoid adding duplicated records, now this code will push everything it comes in it without matter if the id's are duplicated, but I dont know how to compare the var obj {} with the item.id, I tried different "options" but none of them work.
Some help on this will be great and I'll appreciate it a lot

A:

If you changed the itemList from a list to a dictionary, I think it would do what you need. Something like:
var data = [
              {
                id: 1,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }, {
                id: 2,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }
            ];

            $scope.itemDictionary = {};
            angular.forEach(data, function(item){
                var obj = {};
                var valObj = {};

                valObj.name = item.name;
                valObj.lastname = item.lastname;
                valObj.age = item.age;

                obj[item.id] = valObj;
                if(!$scope.itemDictionary[item.id]){
                     $scope.itemDictionary[item.id] = obj;
                }
            });


Q:

Angle math, normalize to [-180,180] and mod vs remainder()

I need to convert a double/float angle to the range of [-180,180] by adding or subtracting 360. The remainder function works, but I am not sure why.
x = remainder (x, 360);

Why does this produce a range of [-180,180] and not [0,359.99999...]?
I understand that remainder and mod are the same for positive numbers, but they work differently for negative numbers... I just have not seen a good explanation of what is happening.
I'm happy that this works of course, but I don't really understand why.

A:

Taken from cppreference:

The IEEE floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where the value n is the integral value nearest the exact value x/y. When |n-x/y| = ½, the value n is chosen to be even.
In contrast to fmod(), the returned value is not guaranteed to have the same sign as x.
If the returned value is 0, it will have the same sign as x.

What's happening here is the function remainder(x, y) rounds to the nearest integer value, times your y and then subtracts the result from x.
Example:
remainder(160.0f, 360.0f)

result = 160 - round(160.0f / 360.0f) * 360
result = 160 - round(0.44f) * 360
result = 160 - (0 * 360)
result = 160.0f

Example2:
remainder(190.0f, 360.0f)

result = 190 - round(190.0f / 360.0f) * 360
result = 190 - round(0.53f) * 360
result = 190 - (1 * 360)
result = -170.0f

Thus you could end up having negative numbers depending on your input variable.


Q:

Format Function returns wrong value

We have a field in a query that should be left-padded with zeroes if it is too short, and we accomplish this using the Format() function.  However, there are some values that produce bizarre results.
Format("14425112-8","00000000-00")

Returns the value "00019330-78"
For most inputs, the string gets formatted as expected, 8 digits, hyphen, two digits.  But in a few rare cases, the value is modified.  Is this repeatable for anyone else?  Does anyone have an explanation?
Thanks for your help.

A:

This is an example of access trying to be too helpful. It looks like it is interpreting these values as dates, but since you didn't use any date indicators in the format e.g: (dd,mm,yyyy), it converted 1-1 to a date, and then tried to display it in decimal form:
debug.print Format("1-1","000000-00")

returns 000427-36 which is the decimal value 42736 which, if you convert to a date, becomes 1/1/2017. This is what access interpreted "1-1" as.
it seems that access has reserved the - character as symbolizing a date format, despite what their website says. This function is only useful for formatting actual dates, or numeric values, such as prices. If you are set on using the format function, you will have to change you separator to a decimal point, which apparently is the only character that will get you what you want with the leading and trailing zeros.
Otherwise, you may have to build your own function for this.


Q:

Security groups not allowing domain admin to view files

This should be very simple.  I have my Documents folders redirected to a share called //dc/documents.  It creates a folder under this share for each person and then creates a folder under that for My Documents.  The security permissions on this //dc/documents share are as follows:

Share Permissions:

Everyone - Full Control

NTFS Permissions:

Everyone (This Folder Only) - List Folder/Read Data, Read Attributes, Read Extended Attributes, Read Permissions
CREATOR OWNER (Subfolders and files only) - Full Control
SYSTEM (This folder, subfolders and files) - Full Control
Administrators (This folder, subfolders and files) - Full Control
Domain Admins (This folder, subfolders and files) - Full Control

My problem arises when I sign into the in-built administrator account on the PDC.  Though that account is part of the Domain Admins and Administrator groups, I do not have permission to view the subfolders and files. I don't see any inherited permissions that should prevent me from doing anything I want inside of these folders.  Is there some magical button I have to hit when opening the folders?  This is becoming increasingly frustrating.

A:

You have the "Grant the user exclusive rights..." box ticked on the "Settings" tab of the folder redirection settings. Turn that off and the Folder Redirection client-side extension (CSE) will add "Administrators" to the permissions on the folders it creates.
Pesonally, I pre-create the subfolders for the users because the Folder Redirection CSE disables inheritance on the subfolders it creates (which I consider a Bad ThingTM). If you pre-create the folders and add "The User / Full Control" to the subfolder the Folder Redirection CSE will be happy and will leave the inheritance hierarchy on your folders intact.
If you want to "repair" the folders you already have you can use something like the icacls utility in a script to clean up the permissions. Assuming the subfolders are all named for the users' samAccountNames you could do something like the following:
FOR /D %%d in (E:\Home Directories\*) DO (
  TAKEOWN /f "E:\Home Directories\%%d" /r /d y
  ICACLS "E:\Home Directories\%%d" /reset /T
  ICACLS "E:\Home Directories\%%d" /grant:r "MYDOMAIN\%userDir%":(OI)(CI)F
  ICACLS "E:\Home Directories\%%d" /setowner "MYDOMAIN\%userDir%" /T
)

That'll give you a nice, clean inheritance hierarchy again w/ the user specified w/ "Full Control" permission at each subfolder.


Q:

Sizeof string literal

The following code
#include <iostream>
using namespace std;

int main()
{
    const char* const foo = "f";
    const char bar[] = "b";
    cout << "sizeof(string literal) = " << sizeof( "f" ) << endl;
    cout << "sizeof(const char* const) = " << sizeof( foo ) << endl;
    cout << "sizeof(const char[]) = " << sizeof( bar ) << endl;
}

outputs
sizeof(string literal) = 2
sizeof(const char* const) = 4
sizeof(const char[]) = 2

on a 32bit OS, compiled with GCC.

Why does sizeof calculate the length of (the space needed for) the string literal ?
Does the string literal have a different type (from char* or char[]) when given to sizeof ?

A:

sizeof("f") must return 2, one for the 'f' and one for the terminating '\0'.
sizeof(foo) returns 4 on a 32-bit machine and 8 on a 64-bit machine because foo is a pointer.
sizeof(bar) returns 2 because bar is an array of two characters, the 'b' and the terminating '\0'.

The string literal has the type 'array of size N of const char' where N includes the terminal null.
Remember, arrays do not decay to pointers when passed to sizeof.

A:

sizeof returns the size in bytes of its operand. That should answer question number 1. ;) Also, a string literal is of type "array to n const char" when passed to sizeof.
Your test cases, one by one:

"f" is a string literal consisting of
two characters, the character f and the terminating
NUL.
foo is a pointer (edit: regardless of qualifiers), and pointers seem to be 4 bytes long on your system..
For bar the case is the same as "f".

Hope that helps.


Q:

How to inherit default values from Parent class using super()

fairly new to python here, and to programming as general, i have the following example, in which i'm trying to inherit the default values from the Parent class, in a way that both the objects can be made.
How to do it nicely and clean? - Tried to experiment with *args and **kwargs, but it had different errors.
class Person(object):

def __init__(self, name="Jane Doe", age="30", gender="female"):
    self.name = name
    self.age = age
    self.gender = gender
    self.goal = "My goal is: Live for the moment!"

class Student(Person):

def __init__(self, name, age, gender, prev_org="The School of Life", skip_d=0):
    super(Student, self).__init__(name, age, gender,)
    self.prev_org = prev_org
    self.skip_d = skip_d
    self.goal = "Be a junior software developer."

 john = Student('John Doe', 20, 'male', 'BME')

 student = Student()

A:

I don't think this is possible. What I've seen instead is something like this:
class Person(object):

    def __init__(self, name=None, age=None, gender=None):
        if name is None:
            name = "Jane Doe"
        if age is None:
            age = "30"
        if gender is None:
            gender = "female"

        self.name = name
        self.age = age
        self.gender = gender
        self.goal = "My goal is: Live for the moment!"

class Student(Person):

    def __init__(self, name=None, age=None, gender=None, prev_org="The School of Life", skip_d=0):
        super(Student, self).__init__(name, age, gender)
        self.prev_org = prev_org
        self.skip_d = skip_d
        self.goal = "Be a junior software developer."

john = Student('John Doe', 20, 'male', 'BME')

student = Student()


Q:

VLC player cannot open files or directories out of "/home"

I'm using Ubuntu 20.04 with VLC player 3.0.11.
The player works well on files and directories within /home (for both /home/myname and /home/test), but cannot open files or directories located in other directories.
Some information about my environment:
Main output of mount:
/dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro)
/dev/sda3 on /work type ext4 (rw,relatime)
/dev/sda2 on /home type ext4 (rw,relatime)

I try to add the following two lines in /etc/apparmor.d/usr.bin.evince and reload apparmor, but it doesn't work:
/work/ r,
/work/** rw,

Thank you very much for your help.

A:

Snap packages are in containers which prevent them from "seeing" outside of those containers unless you give them permission.
For VLC, I'd recommend uninstalling the Snap package, and using the vanilla APT version:
sudo snap remove vlc

sudo apt update && sudo apt install vlc

A:

Snap applications can't guarantee the access of directories/files outside of current user's $HOME. From zyga's post:

The $HOME directory of the user must match /home/*. Other directories are not supported yet. In particular /home/subdir/user is also not supported.

any installation where the user’s home is not available if they're not logged in, is not yet supported. This includes:

installations using automount
ecryptfs and similar tech that unencrypt the $HOME directory (or partition) only while the user is logged in

Note here “not supported” does not mean “doesn’t work”. Some things might not work, but also some sequences of events might result in a user not being able to access their data.

So, it's better to switch to deb version of VLC provided by Ubuntu's official repositories. To install VLC, run
sudo apt install --no-install-recommends vlc

And remove VLC's snap package using
sudo snap remove vlc


Q:

WP migration, can't login to WP admin

I was in the middle of migrating a local WP site to a live server and came across a problem.
I edited my WP config file and uploaded it along with the rest of the WP files. I also uploaded the mysql database through phpMyAdmin.
Once i tried to test the site i got an error message "The page isn't redirecting properly". I then, mistakenly, logged in to the admin area and in the Settings > General tab I deleted the localhost part of the URL. Now I'm unable to log back in to the WP admin area.
EDIT
To clarify, my major problem is that i can no longer log in to the wp admin area because of something I've done. The steps i took to get to this point were:

Backed up WP using the BackUpWordpress plugin
Edited back up wp-config file with    define('WP_HOME','http://example.com'); define('WP_SITEURL','http://example.com');
Created mySQL database through DreamHost
Changed database info in wp-config file
Uploaded wp files (not including mySQL backup) to my url using Filezilla
Imported mySQL database backup to DreamHost
I then checked the site from my browser, an error message said too many redirects occurred
From the wp admin area i went to Settings > General and deleted the localhost part of the url that was displayed.
I believe it's due to the previous step I'm now unable to access the wp admin area at all.

I need a way of getting back into the admin area

A:

I believe the problem is that studiomed.co.uk is permanently redirected (301) to www.studiomed.co.uk and www.studiomed.co.uk is permanently redirected (301) to studiomed.co.uk
Login to your Dreamhost account go to Domains->Manage Domains and choose one of the three options there are in "Do you want the www in your URL?".
After that use an ftp program to download the .htaccess file that exists in your root installation of wordpress and open it with your favorite editor. Check if you have any kind of redirection in the .htaccess file.


Q:

On the GCD of a Pair of Fermat Numbers

I've been working with the Fermat numbers recently but this problem has really tripped me up. If the Fermat theorem is set as $f_a=2^{2^a}+1$, then how can we say that for an integer $b$ less than $a$ that $\gcd(f_b,f_a)=1$?

A:

Hint: Show that $f_b$ divides $f_a-2$.

A:

Claim. $f_n=f_0\cdots f_{n-1}+2$.
The result holds for $f_1$: $f_0=2^{2^0}+1 = 2^1+1 = 3$, $f_1=2^{2}+1 = 5 = 3+2$.
Assume the result holds for $f_n$. Then
$$\begin{align*}
f_{n+1} &= 2^{2^{n+1}}+1\\
&= (2^{2^n})^2 + 1\\
&= (f_n-1)^2 +1\\
&= f_n^2 - 2f_n +2\\
&= f_n(f_0\cdots f_{n-1} + 2) -2f_n + 2\\
&= f_0\cdots f_{n-1}f_n + 2f_n - 2f_n + 2\\
&= f_0\cdots f_n + 2,
\end{align*}$$
which proves the formula by induction. $\Box$
Now, let $d$ be a common factor of $f_b$ and $f_a$. Then $d$ divides $f_0\cdots f_{a-1}$ (because it's a multiple of $f_b$) and divides $f_a$. That means that it divides
$$f_a - f_0\cdots f_{a-1} = (f_0\cdots f_{a-1}+2) - f_0\cdots f_{a-1} = 2;$$
but $f_a$ and $f_b$ are odd, so $d$ is an odd divisor of $2$. Therefore, $d=\pm 1$. So $\gcd(f_a,f_b)=1$.

A:

${\bf Hint}\rm\quad\ \ \gcd(c+1,\,\ c^{\large 2\,k}\!+1)\ =\ gcd(c+1,\:2)$
${\bf Proof}\rm\ \ \ mod\ c+1\!:\,\  c^{\large 2\,k}\!+1\: \equiv\ (-1)^{\large 2\,k}\!+1\:\equiv\ 2,\ \ {\rm by}\ \ c\equiv -1\quad {\bf QED}$
Specializing $\rm\,\ c=2^{\Large 2^{B}},\ \ 2\,k = 2^{\large \,A-B}\ \Rightarrow\ c^{\Large\, 2\,k} = 2^{\Large 2^{A}}\ $ immediately yields your claim.
Remark $\ $ Aternatively, one could employ that $\rm\:c^{\large 2\,k}\!+1\, =\, (c^{\large 2\,k}-1) + 2\:\equiv\: 2\pmod{c+1}\ $
by $\rm\ c+1\ |\ c^{\large 2}-1\ |\ c^{\large 2\,k}\!-1.\, $ But this requires some ingenuity, whereas the above proof does not, being just a trivial congruence calculation using the modular reduction property of the $\rm\:gcd,\:$ namely $\rm\ \gcd(a,b)\, =\, \gcd(a,\:b\ mod\ a),\:$ a reduction which applies much more generally. $ $ Said equivalently, the result follows immediately by applying a single step of the Euclidean algorithm. Notice how abstracting the problem a little served to greatly elucidate the innate structure.


Q:

Parse the git index file and save to text file

How to read git index file and extract all paths to text file?
except

git ls-files > out.txt

I mean using other things like regex or something else?

A:

To see the content of the index file, use the command git ls-files.
Assuming you're on either Windows, Linux, or Mac, you can reroute the command's output into a text file by using git ls-files > out.txt.
See: What does the git index contain EXACTLY?


Q:

Program execution flow alternative to switch(){...} statement

I am trying to implement a program with the following functionality.

An SPI-Master sends 3 bytes of data to an SPI-Slave. For certain value of these data bytes, certain functions are to be called. For example FF FF FF    calls the function A, FF FF FE calls the function B, and so on.

One possible solution might be using switch case statement, however switching each possible case would be too long. Is there any other way to do this?
For example the last data byte has to set the PWM Dutycycle.
10 = 0000 1010
20 = 0001 0100
30 = 0001 1110
40 = 0010 1000
50 = 0011 0010
60 = 0011 1100
70 = 0100 0110
80 = 0101 0000
90 = 0101 1010

The Slave receives the last Byte and for each of these cases it has to set the duty cycle. The Second Byte determines prescaler. For example:

0000 00001 0000 1010 sets the prescaler to 1 and duty cycle to 10
0000 00010 0000 1010 would set prescaler to  8  and duty cycle to 10

and so on.
So there are like many different combinations possible, what is the best way to  handle all the possible cases?

A:

"...One possible solution might be using switch case statement, however switching each possible case would be too long. Is there any other way
  to do this?"

For each distinct but required functionality required by the process you are automating, you will need exactly one distinct method (or family of methods) to accomplish it.  100 distinct requirements will require 100 distinct methods implemented to satisfy the requirements.  The construct used is up to the developer.  A State Machine, ( such as a switch statement within a while loop ) is a common construct with which to control the execution flow through many distinct operations.  If using this construct, it will likely require 100 case: sections.
If a switch statement is not acceptable for whatever reason, a different option might be an array of function pointers.  Note however that this method, although it may be preferable over a switch/while combination, will still require a 1:1 correlation between  unique functions : requirements:
int op0(int b1, int b2, int b3);
int op1(int b1, int b2, int b3);
int op2(int b1, int b2, int b3);
int op3(int b1, int b2, int b3);
//.... and so on depending on how many operations needed

enum {  // mnemonics with which to call array of function pointers.
   OP0,
   OP1,
   OP2,
   OP3,
   ....
};

int (*op[4]) (int b1, int b2, int b3);

int main(void) //or (int argc, char *argv[])
{
   //initialize function pointer address to implementations:
   op[0] = &op0;
   op[1] = &op0;
   op[2] = &op0;
   op[3] = &op0;
   // and so on for every operation needed
   // other code in main
   return 0;
}

int op0(int b1, int b2, int b3)
{
    // code using b3 to set duty cycle
    // ...
    // code using b2 to set pre-scaler
    // ...
    // implement unique requirement of op0
    return 0;
}

int op1(int b1, int b2, int b3)
{
    // code using b3 to set duty cycle
    // ...
    // code using b2 to set pre-scaler
    // ...
    // implement unique requirement of op1
    return 0;
}

/// and so on...


Q:

I need to know why my counter variable is looping

So I have a method that receives a String[][] and a String(word).The method has to look for the word from the 2dArray and should display one of the other words in the same row. Also I need to ignore(not display) and count(++) the empty spots that are in the same row. I want to know why my counter is looping and it wont let me ignore those empty spaces.
public static void main(String[] args) {

    String[][] array2d = {{"joe", "slim", "ed", "george"},
                          {"soto", "", "", "" },
                          {"billy", "sanchez", "carlos", "fernando"}};

    sort(array2d, "soto");
}

public static void sort(String[][] matrix, String word) {
    int counterForArrayLength = 0;
    boolean random = true;
    boolean exit = true;
    String optionFromUser = "";
    do {
        random = true;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j].equals(word)) {
                    for (int k = 0; k < matrix[0].length; k++) {
                        while (random) {
                            String randomWord = matrix[i][(int) (Math.random() * matrix[0].length)];
                            String testRandom = "" + randomWord;

                            if (randomWord.equals(word)) {
                                random = true;
                            } else {
                                if (randomWord.equals("")) {
                                    counterForArrayLength++;
                                    System.out.println("" + counterForArrayLength);
                                } else {
                                    JOptionPane.showMessageDialog(null, randomWord);
                                    optionFromUser = JOptionPane.showInputDialog("Desea obtener otro sinonimo? si/no  \n Digite salir si asi lo desea.");
                                    optionFromUser = optionFromUser.toLowerCase();
                                    if (optionFromUser.equals("si") || optionFromUser.equals("s")) {
                                        random = true;
                                    } else {
                                        random = false;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (optionFromUser.equals("salir")) {
            exit = false;
        } else {
            word = JOptionPane.showInputDialog("Digite otra palabra");
        }
    } while (exit);
}

run:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10

etc.

A:

Your code sample missing essential information. However, the internal loop:
while(random)
{
   // . . .
}

can run forever because you don't guarantee to have random variable to be set to false.
It will work only if you call the method with a word that isn't part of the array.
Also if you call it with word = "soto" then a chance is 100% that never leave the loop since out of 4 words there is one that you found and other 3 are empty.


Q:

What game? Matching dice with two each of d4, d6, d8, and d10

I bought this game at gen con in 2015. It is not dissimilar to Yahtzee or Farkle. I'd given it to my grandmother as a gift, but she has misplaced it.
You have two four-sided dice, two six-sided dice, two eight-sided dice, and two ten-sided dice.
During your turn, you get 3 rolls. You can set aside dice to match or (re)roll them, with your goal being to get matching pairs or better.
For example, I think that two 8s would be eight points, but three 8s would be sixteen points.
I can't remember the name or the other rules.

A:

Ah-ha. I searched for the 2015 gen con convention map, looked up the booth number and found the associated store.
Lumps, by Continuum Games There are a couple of printings, with various packaging and dice colorings (I'm a bit partial to the coal-colored ones).
https://continuumgames.com/shop/lumps-non-seasonal-edition/
As mentioned in the question, a matched pair gives the face-value of those dice, with additional matching dice increasing the total by the face-value again (two 2s are two points, three 2s are four points, etc). First player to 100 points wins.
Later printings include additional rules, such as a solitaire mode, which is just a race to 100 points; a hard mode where you have to set aside dice every roll  instead of banking on the last roll to save you, and some other quirky optional rules, such as all even numbers granting a bonus (or odd numbers).


Q:

Vectors of references to objects

Is it legal to have a vector of references to objects, like the following?
vector<Agent&> seenAgents;

Which would for example be populated by some, but not all of the objects in the scene?
I have a vector of Agent objects, but the vector outlined above should hold references to only the ones each agent can currently see - meaning that the references will be being added and removed all the time.
Is this something the language will allow? And in addition, is there anything else I need to be aware of? If I remove a reference from the vector does it persist anywhere? Is it a memory leak?
I seem to be getting this error on the line declaring the vector:
error C2528: 'pointer' : pointer to reference is illegal

Is this something directly to do with the line or is it most likely occurring somewhere else? It's being initialised in the constructors initialiser list like this:
seenAgents(vector<Agents&>())

A:

You can't have vector of references, as a reference is not copyable assignable and all STL containers are supposed to store copyable assignable items.
But you can make the container to hold pointers. Like this:
vector< Agents* > seenAgents;

This is a little dangerous. You need to be sure that these pointers will remain valid. I mean - if someone deletes an object, pointed by a pointer in this container, the pointer becomes invalid. You need to be sure that this will not happen, because you can't check it (you can't check for NULL, because a pointer will not become NULL, if someone deletes the pointed object).
The best solution here (provided by container with pointers) would be to use some smart pointers - some with reference count, for example; they will guarantee you that the object will exist and that the pointer is valid. And in case that the object, pointed by the smart pointer, is destroyed, you can check it for NULL.

A:

You can't do it. Use pointers.
The Boost library provides PTR_VECTOR which is a better solution than:
vector<T*> foo;

A:

You can use std::reference_wrapper instead in C++11:

std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.

Example:
#include <functional>
#include <vector>
#include <iostream>

int main(int argc, char *argv[])
{

  int a = 5;
  int b = 6;
  std::vector<std::reference_wrapper<const int>> v;
  v.push_back(a);
  v.push_back(b);

  for (const auto& vi: v)
  {
    std::cout << vi << std::endl;
  }
  return 0;
}

https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper


Q:

Using "grep -n" and echo : : double backslash interpreted

I want to get the line number of the pattern "\label" with "grep -n" into a file.
The file content is :
\begin{equation}
(\beq{f'_{i}})_{3}-(\beq{e_{i}})_{3}=\text{d}\delta\,\beq{e_{i}}-\delta\,\text{d}\beq{e_{i}}
\label{r58}
\end{equation}

...

\begin{align}
&\beq{mm'_{3}}-\beq{mm_{3}}=\text{d}\delta\,\beq{m}-\delta\,\text{d}\beq{m}
\label{r59} \\
&(\beq{e'_{i}})_{3}-(\beq{e_{i}})_{3}=\text{d}\delta\,\beq{e_{i}}-\delta\,\text{d}\beq{e_{i}}
\label{r60}
\end{align}

...

\begin{equation}
(\beq{g'_{i}})_{3}-(\beq{e_{i}})_{3}=\text{d}\delta\,\beq{e_{i}}-\delta\,\text{d}\beq{e_{i}}
\label{r61}
\end{equation}

...

The command that I use :
for k in $(grep -n '\\label' test.tex); do echo $k; done

and I get :
...
    1366:\label{r58}
    1376:\label{r59}
    \\
    1378:\label{r60}
    1388:\label{r61}
...

and I want :
...
    1366:\label{r58}
    1376:\label{r59}
    1378:\label{r60}
    1388:\label{r61}
...

Given that I handle after the value of k variable, I would like to skip the line with a double backslash, it seems that "grep -n" interprets the double backslash.
I know that I could do a pipe command on k like "grep -v '\\\\' but can I directly skip this double backslash with grep -n (with an additional flag or with a more explicit pattern) ?
Thanks

A:

You can fix the issue with the newline with
$ for k in "$(grep -n '\\label' text.tex)"; do echo "$k"; done
3:\label{r58}
10:\label{r59} \\
12:\label{r60}
19:\label{r61}

i.e., quoting the command substitution. Which is a very complicated (and not recommended) way of just using
grep -n '\\label' test.tex

as it seems.
If you don't quote the command substitution, its result undergoes word splitting and the \\ is seen as a separate element to loop over, that's why it gets its own line.
To just get the parts you want, you can use
$ grep -on '\\label{[^}]*}' test.tex
3:\label{r58}
10:\label{r59}
12:\label{r60}
19:\label{r61}

-o to just retain the match, and the regex matches the braces after \label as well.


Q:

Object at point

In my imageview I create and add new imageviews as subview every time the image is tapped twice. Then I've added single tap gesture to the newly added subview. When that subview(the new imageview) is tapped once I get navigated to another view controller. But, my problem is I get the latter effect only with the latest added subview. So let's say I've added 5 imageviews. I get navigated away only when I tap the 5th imageview. How can I make this happen no matter which subview is tapped?

A:

Without seeing the code, I can guess that you are using a GestureRecognizer to detect the tap in the added UIImageView.  If that is the case, you can't reuse the recognizer since it can only be attached to one view.  You'll need to create a new recognizer for each UIImageView you add to your main view.


Q:

Why doesn't the shopkeeper in Harry Potter & the Prisoner of Azkaban use Accio to find the missing Invisibility books?

I have recently started reading through the Harry Potter series yet again and noticed something quite peculiar in Harry Potter and the Prisoner of Azkaban; while shopping at a wizarding book store (sorry, can't remember the name), the store owner cries out in frustration, obviously irritated by the newest book, The Monster Book of Monsters, yelling.

"I'm never stocking these again, never! This is worse than when we ordered over 200 copies of the Invisible Book of Invisibility; never could find them."

Couldn't the shopkeeper have used the Accio spell to summon the books, or was it implied at some point in the Harry Potter universe that this book owner is actually a Squib, and therefore cannot perform magic? I have not yet found any answer on this, and any help would be appreciated.

A:

It's entirely possible that the owner wasn't able to sufficiently distinguish between his copies of the books and others that may have been in the area - he'd certainly get into legal trouble if he Acciod other people possessions and tried to sell them!
That said, there's no indication that he's a squib - while he never does onscreen magic, neither do most of the other witches and wizards we see.
For myself, I've always taken that line as it was likely intended - a humorous throwaway that shows that there is a larger magical world, but was never intended to be explored in a deeper way.
The owner could also have been having some fun at the expense of the students - if he was a capable wizard, he could certainly have used any number of spells to retrieve the books, ranging from the levitating charm to the summoning charm, even up to something like Petrificus Totalis or Stupify.


Q:

Loop through Excel sheets in Python

I am trying to extract all data from one excel file (data is spread into different sheets from the same file ) into one new excel file
   import pandas as pd
   import glob as glob

appended_data = []
f_list = glob.glob(r'C:\Users\Sarah\Desktop\test\
               *.xlsx')
for f in f_list:
    data = pd.read_excel(f, sheet_name= ('May', 'April'))
    appended_data.append(data)
appended_data = pd.concat(appended_data)
appended_data.to_excel(r'C:\Users\Sarah\Desktop\test\appended.xlsx')

the problem is in the sheet_name if i try the code below :
   data = pd.read_excel(f, sheet_name= [0,1,2,3])

i get a Value Error : No objects to concatenate
the code only works when i type the name of one sheet  :
     data = pd.read_excel(f, sheet_name="April")

But it doesn't work when i try the name of two sheets or more :
        data = pd.read_excel(f, sheet_name= ('May', 'April'))

How to tell the code to loop through all the sheets?
Thank you

A:

you can read all sheets by providing sheet_name=None
dict_of_frames = pd.read_excel(f, sheet_name=None)

full example:
all_sheets = []
for f in glob.glob(r'C:\Users\Sarah\Desktop\test\*.xlsx'):
        all_sheets.extend(pd.read_excel(f, sheet_name=None).values())
data = pd.concat(all_sheets)
data.to_excel(r'C:\Users\Sarah\Desktop\test\appended.xlsx')


Q:

WPF recordset listbox databind?

how can i bind my records to the itemsource of a list box?

cn.ConnectionString = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\mvdata.accdb;"

cn.Open()

    If rs.State = True Then rs.Close()
    rs.Open("Select * from company", cn, ADODB.CursorTypeEnum.adOpenDynamic,ADODB.LockTypeEnum.adLockOptimistic)

    slistbox.ItemsSource = ?????

Hope someone cud help me. thanks.

A:

Fill DataTable by the data from recordset first, then set ListBox's ItemsSource to the DataTable. Something like this:
cn.ConnectionString = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\mvdata.accdb;"

cn.Open()

    If rs.State = True Then rs.Close()
    rs.Open("Select * from company", cn, ADODB.CursorTypeEnum.adOpenDynamic,ADODB.LockTypeEnum.adLockOptimistic)
    Dim oleDbAdapter As New OleDbDataAdapter()
    Dim dataTable As New DataTable()
    oleDbAdapter.Fill(dataTable, rs)

    slistbox.ItemsSource = dataTable

I didn't compile it, but I hope you got the idea


Q:

Django blog with picture

I have this in my database
paragraph1
paragraph2
paragraph2
I would like to place a picture in between paragraphs.
I tried this
<img src="where/photo/is">

class Post(models.Model):
STATUS_CHOICES = (
    ('draft','Draft'),
    ('published', 'Published'),
)

title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date ='publish')
author = models.ForeignKey(User, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='posts', default='path/to/my/default/image.jpg')
status = models.CharField(max_length=10, choices=STATUS_CHOICES,
    default='draft')
objects = models.Manager()
published = PublishedManager()
tags = TaggableManager()

class Meta:
    ordering = ('-publish',)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('blog:post_detail',
            args=[self.slug])

Note: This is the post table that takes the data in paragraphs, there is not picture in between, I would like to add it after getting this text body.
Here is my view
current_site = get_current_site(request)
namesite = current_site.name
domain = current_site.domain

post = Post.published.get(slug=post)

profile = Profile.objects.get(id=1)

if request.method == 'POST':
    comment_form = CommentForm(data=request.POST)
    if comment_form.is_valid():
        #create Comment object but do not say to database just yet
        new_comment = comment_form.save(commit=False)
        #Assigng the current post to the comment
        new_comment.post = post
        #save the comment to the database
        new_comment.save()
        comment_form = CommentForm()
else:
    comment_form = CommentForm()

return render(request, 'blog/detail.html',
                {'post': post, 'comments': comments,
                 'comment_form': comment_form, 'namesite': namesite, 'domain': domain, 'profile': profile })

in the database and I use the | safe filter, but that still prints the same as above.
Do you have any idea how to perform that acction?

A:

Hi If you want to create long description with image means you can go with django-ckeditor link, this package will provide you the RichTextField so you can create the bulk paragraphs with images.


Q:

Pivot SQL server results

My result set looks like:
ICount   Owners ProgramCount
1344     AA     1
408      AA     2
185      AA     3
87       AA     4
54       AA     5
644      EA     1
81       EA     2
18       EA     3
3        EA     4
2        EA     5
4419     JA     1
1461     JA     2
700      JA     3
375      JA     4
209      JA     5

and I'd like the results to be:
Owner Total  ProgramCount 1 ProgramCount 2 ProgramCount 3 ProgramCount 4 ProgramCount 5
AA    2078   1344           408            185            87             54
EA    748    644            81             18             3              2
JA    7164   4419           1461           700            375            209

where the Total column is the sum of ProgramCount 1 through 5.
How would I build my SQL to accomplish this?

A:

A simple pivot in concert with a sum() over()
Example
Select *
 From  (
        Select [Owners]
              ,Item = concat('Program Count ',[ProgramCount])
              ,[ICount]
              ,[Total] = sum([ICount]) over(partition by [Owners])
         from YourTable
        ) src
 Pivot (sum([ICount]) for [Item] in ([Program Count 1],[Program Count 2],[Program Count 3],[Program Count 4],[Program Count 5]) ) pvt
 Order By [Owners]

Returns

A:

select  v.Owners                                                    as  Owners,
        sum(v.ICount)                                               as  Total,
        sum(case when v.ProgramCount = 1 then v.ICount else 0 end)  as  ProgramCount1,
        sum(case when v.ProgramCount = 2 then v.ICount else 0 end)  as  ProgramCount2,
        sum(case when v.ProgramCount = 3 then v.ICount else 0 end)  as  ProgramCount3,
        sum(case when v.ProgramCount = 4 then v.ICount else 0 end)  as  ProgramCount4,
        sum(case when v.ProgramCount = 5 then v.ICount else 0 end)  as  ProgramCount5
from    (
            QUERY_WITH_YOUR_RESULT_SET
        ) as v(ICount, Owners, ProgramCount)
group by v.Owners


Q:

why does Solr not return any result on "suits" when there is a document that containing the word "Suits"

I have a little problem with my Solr search engine. It does not return any result when I search on the word "suits". I'm 100% sure that it exists a document that are containing the word "Suits". I can however search for the word "suit" and the result containing "suits" ends up.
My schema:
<schema name="hello" version="1.3">
    <types>
        <fieldType name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true"/>
        <fieldType name="text" class="solr.TextField" positionIncrementGap="100" autoGeneratePhraseQueries="true">
            <analyzer type="index">
                <tokenizer class="solr.WhitespaceTokenizerFactory"/>
                <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/>
                <filter class="solr.LowerCaseFilterFactory"/>
                <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
                <filter class="solr.PorterStemFilterFactory"/>
            </analyzer>
            <analyzer type="query">
                <tokenizer class="solr.WhitespaceTokenizerFactory"/>
                <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
                <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
                <filter class="solr.LowerCaseFilterFactory"/>
                <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
                <filter class="solr.PorterStemFilterFactory"/>
            </analyzer>
        </fieldType>
    </types>
    <fields>
        <field name="id" type="string" indexed="true" stored="true" required="true" />
        <field name="title" type="text" indexed="true" stored="true" required="true"/>
        <field name="description" type="text" indexed="true" stored="true" required="true"/>
        <field name="profileMiniature" type="string" stored="true" required="true"/>
    </fields>
    <uniqueKey>id</uniqueKey>
    <defaultSearchField>title</defaultSearchField>
</schema>

my query is "title:$q*^2 description:$q*".

A:

A search with wildcards disables the analysis (as described here).
To match suit with suits, you need stemming and not wildcards.  Using wildcards will anyway not work if your data has suit and the query is suits.
Could you provide some more information - maybe a use-case which explains why you need wildcards?  It will help us come up with a better solution to your problem.