text:
Q: Calling a scope function in different controller I have a function defined in a controller , I want to call it in another controller.
I tried to attach it to the $rootscope so I can see in the other controller , but I couldn't .
Is there a way for calling it, without attaching it to the $rootscope?

A: As far as I know in AngularJS you can share info between controllers in 3 ways:
1 - Creating a Service.
2 - Creating a function linked to $rootScope.
3 - Using events ($broadcast and $on). I use a lot this method in my projects.
I think your problem is that you don't instantiate the controllers in
the proper order or one of them is never instantiated, therefore the
function you want to link to $rootScope in that controller or the broadcast event never fires.
E.G If you want to call a function linked to $rootScope in the 2 controller from the
first one, it is impossible because the 2 controller is instantiated after the first one.
This case happens when you make calls on application runtime.
I will implement your method with some changes:
HTML:

     <button ng-click="send()">Send Mess</button>

JS:
var myApp = angular.module('myApp',[]);

function MyCtrl_1($scope, $rootScope) {

   $scope.$on('RenderPage', function (event, PageId) {
      $scope.RenderPage = PageId;
      alert($scope.RenderPage);
   });

};

function MyCtrl_2($scope, $rootScope) {

   $scope.MasterPageId = 10;
   $scope.send = function(){
      $rootScope.$broadcast('RenderPage', $scope.MasterPageId);
   }

};

Use carefully $broadcast and $emit, because has different behavior each one.
Try here: http://jsfiddle.net/1ypkb4s9/
Otherwise, post your error.

A: if you want to use the same function in two or more controllers you might need a service.
or use events
function firstCtrl($scope)
{
    $scope.$broadcast('someEvent', [1,2,3]);
}

function secondCtrl($scope)
{
    $scope.$on('someEvent', function(event, mass) { console.log(mass); });
}

A: Simply wrap them with a "father controller":
HTML:

        <button ng-click="outerClick()">Outer Click</button>

        <button ng-click="innerTwoClick()">Inner Click</button>

JS:
angular.module('myApp', []).
controller('myOuterCtrl', function ($scope) {
    $scope.outerClick = function () {
        console.log('outer click');
    }
}).
controller('myInnerCtrl1', function ($scope) {
    // nothing here!!
}).
controller('myInnerCtrl2', function ($scope) {
    $scope.innerTwoClick = function () {
        console.log('inner two click');
    }
});

JSFIDDLE.


text:
Q: Solve the Euler–Lagrange equation? For $x=(x_1,x_2) \in \mathbb R^2$, we denote by  $$L(x,\dot{x})= \dot{x_{1}}^{2}+x_{1}\, \dot{x_{1}}\, \dot{x_{2}}+\dot{x_{2}}$$
the Lagrangian associated to an Hamiltonian for an unbounded operator $L$.
I would like solve the Euler–Lagrange equation given by
$$\frac{d}{ds}\frac{\partial L}{\partial \dot{x}} = \frac{\partial L}{\partial x} .$$
Thank you in advance

A: Let us go step by step:
1) the term $\dot x_2$ is a total time-derivative, thus unimportant for the equations of motion. So I will consider the Lagrangian $\tilde L = \dot x_1^2 + x_1 \dot x_1 \dot x_2$
2) $x_2$ is cyclic and thus $$p_2 = \frac{\partial \tilde L}{\partial \dot x_2} = x_1 \dot x_1$$ is conserved
3) as the Lagrangian does not depend explicitly on time, we have that the "energy"
$$ H = \sum_{j=1}^2\frac{\partial \tilde L}{\partial \dot x_j} \dot x_j - \tilde L = \dot x_1 (\dot x_1 + x_1 \dot x_2) = \dot x_1^2 +p_2 \dot x_2 $$
is conserved
Now we solve:
2) $$p_2 = x_1 \dot x_1$$
has the solution $$x_1 = \pm\sqrt{p_2 t + \alpha}. \tag{1}$$
Inserting into the expression 3) for $H$, we have the equation
$$ H= \frac{p_2^2}{2 (p_2 t +\alpha)} + p_2 \dot x_2$$
with the solution
$$ x_2 = \frac{H t} {p_2} + \beta -\frac12 \ln\left(p_2 t + \alpha \right) \tag{2} =\frac{H t} {p_2} + \beta - \ln x_1 .$$
The general solution is given by (1) and (2) where $\alpha,\beta,p_2,H$ are the 4 constants of integration.
Edit: in order that $x_2$ remains reals, we have to choose the `+' sign in (1). Here is the orbit for $H=p_2=1$ and $\alpha=\beta=0$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stop a counter running in a loop on the basis of index in React I am running a counter in a loop and that counter starts on a click of a         button for every loop. But I am unable to stop counter for a particular         loop using index. Stopping the counter for one index stops all other         counters because of I an using SetInetrval and ClearInterval.
Please suggest me the best possible way to achieve that.
Thank you in advance.
I tried stopping the counter via clearInterval which calls setInterval
        but due to index access behavior, I am not able to attach that.
I am a newbie in complex looping in js. Your assistance would be highly appreciated. Thank you
        class RecordDuration extends Component {

            constructor(props) {
                super(props);
                this.state = {
                    patientId: props.patientId ? props.patientId : null,
                    FromDate: new Date(),
                    time: null,
                    isStart: [],
                    isSave: [],
                    secondsElapsed: [] // this tha array for the value of the counter
                }
            }

            renderLoading() {
                if (this.state.isLoading) {
                    return (

                    );
                }
            }

            componentWillMount = () => {
                this.props.PatientRecordDurationDataList(this.state.patientId)
            }

            componentWillReceiveProps = (nextProps) => {
                if( nextProps.recordDurationDataList.data !== undefined) {
                    let clikcedData = this.state.isStart
                    let saveData = this.state.isSave
                    let counterData = this.state.secondsElapsed
                    let patientBehaviorsReductionData = nextProps.recordDurationDataList.data.PatientBehaviorsReductionData;
                    patientBehaviorsReductionData.map((obj, index) => {
                        return saveData[index] = false;
                    })
                    patientBehaviorsReductionData.map((obj, index) => {
                        return clikcedData[index] = false;
                    })
                    patientBehaviorsReductionData.map((obj, index) => {
                        return counterData[index] = 0;
                    })
                    this.setState({
                        isStart: clikcedData,
                        isSave: saveData,
                        secondsElapsed: counterData
                    })
                }
            }

            componentWillUnmount = () => {
                clearInterval(this.incrementer)
            }

           // This method is for start counter
            handleStart = (index) => {
                var _this = this;
                const isStart = this.state.isStart
                isStart[index] = true
                _this.setState({
                    isStart: isStart
                });
    //this particular incrementer is the issue
                this.incrementer = setInterval(() => {
                    let secondsElapsed = _this.state.secondsElapsed
                    secondsElapsed[index] = secondsElapsed[index] + 1
                    _this.setState({
                        secondsElapsed : secondsElapsed
                    })
                }, 1000)

            }

            // This method is for Stop Counter
            handleStop = (index) => {
                let isStart = this.state.isStart
                let isSave = this.state.isSave
                isStart[index] = false
                isSave[index] = true
                this.setState({
                    isStart: isStart,
                    isSave: isSave
                });
                clearInterval(this.incrementer)
            }

            // This method is for Cancel the counter.
            handleCancel = (index) => {
                if(this.props.recordDurationDataList.data !== undefined) {
                    let counterData = this.state.secondsElapsed
                    let patientBehaviorsReductionData = this.props.recordDurationDataList.data.PatientBehaviorsReductionData;
                    patientBehaviorsReductionData.map((obj, index) => {
                        return counterData[index] = 0;
                    })
                    this.setState({
                        secondsElapsed: counterData
                    })
                    clearInterval(this.incrementer)
                }
                let clikcedData = this.state.isStart
                let isSave = this.state.isSave
                clikcedData[index] = false
                isSave[index] = false
                this.setState({
                    isStart: clikcedData,
                    isSave: isSave,
                });
            }

            handleSave = (index) => {

            }

            getSeconds = (index) => {
                return ('0' + this.state.secondsElapsed[index] % 60).slice(-2)
            }

            getMinutes = (index) => {
                return Math.floor(this.state.secondsElapsed[index] / 60)
            }

            // this functiomn will be called by the parent render function
            renderData = (dataList) => {
                let PatientRecordFrequencyData = dataList || [];
                if (!PatientRecordFrequencyData.length) {
                    return (

{this.props.loading ? 'Loading please wait...' : 'No record found.'}

                    );
                }
                return PatientRecordFrequencyData.map((Obj, index) => {
                    return (

                                {Obj.behaviorName}

                                        {(this.state.isStart[index] === false && this.state.isSave[index] === false) &&
                                            <RaisedButton
                                                label="START"
                                                primary={true}
                                                onTouchTap={() => this.handleStart(index)} />
                                        }
                                        {(this.state.isStart[index] === true && this.state.isSave[index] === false) &&

                                                    <RaisedButton
                                                        label="STOP"
                                                        primary={true}
                                                        onTouchTap={() => this.handleStop(index)} />

                                                    <RaisedButton
                                                        label="CANCEL"
                                                        primary={true}
                                                        onTouchTap={() => this.handleCancel(index)} />

                                        }
                                         {this.state.isSave[index] === true &&

                                                    <RaisedButton
                                                        label="SAVE"
                                                        primary={true}
                                                        onTouchTap={() => this.handleSave(index)} />

                                                    <RaisedButton
                                                        label="CANCEL"
                                                        primary={true}
                                                        onTouchTap={() => this.handleCancel(index)} />

                                        }

                                {Obj.description}

                                {this.getMinutes(index)}:{this.getSeconds(index)}

                    )
                })
            }
        }

A: I solved this issue by managing state for the index, Please look at the code now
class RecordDuration extends Component {

    constructor(props) {
        super(props);
        this.state = {
            patientId: props.patientId ? props.patientId : null,
            FromDate: new Date(),
            time: null,
            isStart: [],
            isSave: [],
            secondsElapsed: [],
            incrementer: [],
        }
    }

    renderLoading() {
        if (this.state.isLoading) {
            return (

            );
        }
    }

    componentWillMount = () => {
        this.props.PatientRecordDurationDataList(this.state.patientId)
    }

    componentWillReceiveProps = (nextProps) => {
        if( nextProps.recordDurationDataList.data !== undefined) {
            let clikcedData = this.state.isStart
            let saveData = this.state.isSave
            let counterData = this.state.secondsElapsed
            let patientBehaviorsReductionData = nextProps.recordDurationDataList.data.PatientBehaviorsReductionData;
            patientBehaviorsReductionData.map((obj, index) => {
                return saveData[index] = false;
            })
            patientBehaviorsReductionData.map((obj, index) => {
                return clikcedData[index] = false;
            })
            patientBehaviorsReductionData.map((obj, index) => {
                return counterData[index] = 0;
            })
            this.setState({
                isStart: clikcedData,
                isSave: saveData,
                secondsElapsed: counterData
            })
        }
    }

    componentWillUnmount = () => {
        this.state.incrementer.map((obj, index) => {
            return clearInterval(this.state.incrementer[index]);
        })
    }

    handleStart = (index) => {
        var _this = this;
        const isStart = this.state.isStart
        isStart[index] = true
        _this.setState({
            isStart: isStart
        });

        let incrementer = this.state.incrementer

        incrementer[index] = setInterval(() => {
            let secondsElapsed = _this.state.secondsElapsed
            secondsElapsed[index] = secondsElapsed[index] + 1
            _this.setState({
                secondsElapsed : secondsElapsed
            })
        }, 1000)

        _this.setState({
            incrementer: incrementer
        });

    }

    handleStop = (index) => {
        let isStart = this.state.isStart
        let isSave = this.state.isSave
        let counterData = this.state.secondsElapsed
        isStart[index] = false
        isSave[index] = true
        counterData[index];
        this.setState({
            isStart: isStart,
            isSave: isSave,
            secondsElapsed: counterData
        },clearInterval(this.state.incrementer[index]));
    }

    handleCancel = (index) => {
        let clikcedData = this.state.isStart
        let isSave = this.state.isSave
        let counterData = this.state.secondsElapsed
        clikcedData[index] = false
        isSave[index] = false
        counterData[index] = 0;
        this.setState({
            isStart: clikcedData,
            isSave: isSave,
            secondsElapsed: counterData
        }, clearInterval(this.state.incrementer[index]));

    }

    handleSave = (index) => {

    }

    getSeconds = (index) => {
        return ('0' + this.state.secondsElapsed[index] % 60).slice(-2)
    }

    getMinutes = (index) => {
        return Math.floor(this.state.secondsElapsed[index] / 60)
    }

    renderData = (dataList) => {
        let PatientRecordFrequencyData = dataList || [];
        if (!PatientRecordFrequencyData.length) {
            return (

{this.props.loading ? 'Loading please wait...' : 'No record found.'}

            );
        }
        return PatientRecordFrequencyData.map((Obj, index) => {
            return (

                        {Obj.behaviorName}

                                {(this.state.isStart[index] === false && this.state.isSave[index] === false) &&
                                    <RaisedButton
                                        label="START"
                                        primary={true}
                                        onTouchTap={() => this.handleStart(index)} />
                                }
                                {(this.state.isStart[index] === true && this.state.isSave[index] === false) &&

                                            <RaisedButton
                                                label="STOP"
                                                primary={true}
                                                onTouchTap={() => this.handleStop(index)} />

                                            <RaisedButton
                                                label="CANCEL"
                                                primary={true}
                                                onTouchTap={() => this.handleCancel(index)} />

                                }
                                 {this.state.isSave[index] === true &&

                                            <RaisedButton
                                                label="SAVE"
                                                primary={true}
                                                onTouchTap={() => this.handleSave(index)} />

                                            <RaisedButton
                                                label="CANCEL"
                                                primary={true}
                                                onTouchTap={() => this.handleCancel(index)} />

                                }

                        {Obj.description}

                        {this.getMinutes(index)}:{this.getSeconds(index)}

            )
        })
    }

    renderRecordDuration = () => {
        const tableClass = classNames({
            'table': true,
            'table-striped': this.props.condensed,
            'table-bordered': this.props.bordered,
            'table-hover': true,
            'table-condensed': this.props.condensed,
            'customtable': true,
        });
        const { recordDurationDataList } = this.props;
        let PatientRecordDurationList = (recordDurationDataList && recordDurationDataList.data) || [];
        return (

                            Duration

                        {this.renderData(PatientRecordDurationList.PatientBehaviorsReductionData)}

        )
    }

    render() {

        return (

                {this.renderLoading()}

                            {this.renderRecordDuration()}

        )
    }
}


text:
Q: Spring webflux ReactiveMongoOperations find by elemMatch I have a collection like this:
{"type": "bbb", "category": "aaa", "from": "eee", "INTERLOCUTOR": ["test1", "test2"]}

and I want to find INTERLOCUTOR have test1 ;
how to use by ReactiveMongoOperations?

A: db.collection.find({"INTERLOCUTOR" : "test1"})

A: Using ReactiveMongoOperations and processing the returned reactor.core.publisher.Flux to print the query returned documents:
ReactiveMongoOperations ops = new ReactiveMongoTemplate(MongoClients.create(), "test");
Criteria c = Criteria.where("INTERLOCUTOR").is("test1");
Query qry = new Query(c);

Flux<Document> flux = ops.find(qry, Document.class, "coll")
flux.subscribe(doc -> System.out.println(doc), throwable -> throwable.printStackTrace());

Note the query actually executes when the subscribe method runs. Since the subscribe runs as an asynchronous operation, when you run this add the following to the current thread (for blocking it until the async operation completes).
try {
  Thread.sleep(1000);
} catch(InterruptedException e ) {}


text:
Q: Click event handler not persisting for dynamically created checkboxes I have a Javascript script in which I define a class called a "Layer". I put code in the Layer constructor, so that each time a new Layer object is created a checkbox associated with that layer is added to the HTML document. I also created a JQuery event handler within the constructor so that when the new checkbox is clicked, the layer is either shown or hidden within the document depending on the state of the checkbox. For some reason however, the event handler only works for the most recently created layer. Somehow the old event handlers are getting overwritten. I searched on here for similar questions, and saw that using the on function from JQuery rather than click is the way to go, but I'm still having the same issue. Here's my code...
Layer2D.prototype.addToUI = function() {
    if (this.firstLayer()) {
        var layerDiv = document.createElement('div');
        layerDiv.className = 'content';
        layerDiv.id = 'layerNames';
    }
    else {
        var layerDiv = document.getElementById('layerNames');
    }

    layerDiv.innerHTML += '
' +
                          '
' +
                          '<input type="checkbox" name="' + this.name + '" checked>' +
                          '</input>' +
                          '' + this.name + '' +
                          '
';

    if (this.firstLayer()) {
        var parentDiv = document.getElementById('layerMenu');
        parentDiv.appendChild(layerDiv);
    };
    $('#layer' + this.name).after('
');

    var This = this;
    $('#layer' + this.name).on('click', ':input', function(e) {
        checked = $(this).is(':checked');
        console.log(This);
        if (checked === true) {
            This.show();
        }
        else {
            This.hide();
        }
    });
};

A: You should use $(document).on('click', '#layer' + this.name, function(){...}) it usually works with dynamically added HTML.

A: innerHTML has this issue.  If you create the dynamic elements using Document.create methods, I think the listener will be attached.  In any case you can put your evenListener(s) in a function like addEventListenerToBeer() and call it after the innerHTML call.
var d = document.createElement("div")
var t = document.createTextNode("i like beer");
d.id = "myId";
d.appendChild(t);

A: You need to replace:
layerDiv.innerHTML += '
' +
                      '
' +
                      '<input type="checkbox" name="' + this.name + '" checked>' +
                      '</input>' +
                      '' + this.name + '' +
                      '
';

for:
let element="";
//****
element = '
' +
                      '
' +
                      '<input type="checkbox" name="' + this.name + '" checked>' +
                      '</input>' +
                      '' + this.name + '' +
                      '
';
$(element).appendTo(layerDiv);

appendTo inserts the elements and make them part of the DOM to be query...


text:
Q: Rails: How to look for project time expiration? I have a project which has set end (datetime). After this time is reached I want to disable some buttons on a project page and show it is finished.
My idea is to add a boolean flag finished and change it when end reaches time.now.
The question is, is there any better way than run a cron job each minute and watch for projects end datetime, compare it with actual time and when it is over, change the flag?
I am not sure if running cron job each minute is the most efficient way how to do that.
Thanks

A: If it is just a matter of displaying or not some buttons, this could be done at UI level and you could update your records once a day with a cron job, without running it every minute.
Another approach could be update the records just when an user asks for them. Like:

*

*User requested the specific project

*You fetch the project

*Before serving the project information you check the end time and updates the record

*Your program then serves the freshly update record

But, then again, this depends on the requirements.
And finally, you may join these two ideas. You may have a once|twice a day cron job to update records and also check and update things 'on the fly' as I suggested above.
Maybe you could post some more info to receive a more specific answer.


text:
Q: How to create a socket that listens a localhost port in Android Before explain my doubt I want to mension that there're three "actors" in this enviorement:

*

*A desktop program executed in some server

*A person who uses this program remotely through a computer

*And an Android tablet application that is connected with the computer via USB

When the person clicks on a link bar in this program that he is using remotely there's a shell script that sends a string to the person's computer port(e.g 1100). The requirement is: After recive this string from the desktop send it to the tablet.
So, what is the best way to recive this string from the desktop to the tablet?
Now there's a java daemon that is running in the desktop computer who is listening the 1100 port. This java app is working as a intermidiate between the desktop computer and the tablet, but I think that maybe there's a way to delete this daemon and just using the tablet to recive the computer data creating a socket.

A: You can also implement Java Sockets in Android. Like wise on Desktop Sockets in Android listens on ports but this will be accessed locally as there is no such way to assign static usable IP to an Android device.
There is another solution which is socket.io
Socket.io is one of the best socket library i have ever used. Implement socket.io on Node.js server and on Android simply connect to Node.js server and you can send same string to all connected users whether it is a Desktop or Android.

A: private class ServerThread extends Thread {

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(portNumber);

            while (true) {
                try {
                    clientSocket = serverSocket.accept();
                } catch (IOException e) {
                    LOGGER.error("Error on accept!");
                }
                // new thread for a client
                new EchoThread(clientSocket).start();
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

public class EchoThread extends Thread {
    protected Socket clientSocket;
    BufferedReader br = null;

    public EchoThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void run() {
        try {
             br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (IOException e) {
            ...
        }

        isConnected = true;

        while (isConnected) {
            try {
                receivedMessage = br.readLine();
                if (!Strings.isNullOrEmpty(receivedMessage)) {
                    ....
                }
                else {
                    //sleep 0,1s
                    //TODO (ver): Thread.sleep(100);
                }
            } catch (Exception e) {
                if (e instanceof IOException) {
                }
                else if (e instanceof JsonSyntaxException){
                }
                else {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException inte) {
                        inte.printStackTrace();
                    }
                }
            }

            if (//yourmessagecondition){
                isConnected = false;
            }
        }
        if (!isConnected){
            try {
                br.close();
                clientSocket.close();
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
    }
}

Hope this helps, it is working here... You probably find easier/simple examples on the Internet.
PS: If you are using a USB cable to communicate with the computer app, you can use the "adb forward" command, just google for some examples and accept this answer if it helped ;)


text:
Q: Metadata file not be found in csx file with VS 2019 I have researched the other answers to this question for couple of days and none of the solutions seem to work for my situation.

*

*Error message: "error CS0006: Metadata file 'Newtonsoft.Json.dll' could not be found"

*Visual Studio 2019

*.NET Core c# console project

*Coding included in .csx files for scripting. Note the "Newtonsoft.Json" can be found in a .cs file.

A: The issue was resolved by providing the full path to the dll file:
replacing
     #r "Newtonsoft.Json.dll"
with
     #r "c:\full_path\Newtonsoft.Json.dll"
It appears with VS 2019, the CSX file does not know the path of dll added through NuGet, though it does recognize .NET libraries such as System.


text:
Q: making text files containing list of files in different directories with random name in bash I have a script which makes some files in pair (all the resulting files have either R1 OR R2 in the file name) and then put each pair in a separate directory with random name (every time will be different and I cannot predict). for example if I have 6 files, 3 files would be file_R1.txt or file_R2.txt but in pair like this example:
s1_R1.txt and s1_R2.txt
s2_R1.txt and s2_R2.txt
s3_R1.txt and s3_R2.txt

In this example I will have 3 directories  (one per pair of files). I want to make 2 text file (d1.txt  and. d2.txt) containing above file names. In fact, d1.txt will have all the files with R1 and d2.txt will contain all the files with R2. To do so, I made the following short bash code but it does not return what I want. Do you know how to fix it?
For file in /./*R*.txt;
do;
    touch "s1.txt"
    touch "s2.txt"
    echo "${fastq}" >> "s1.txt"

done

A: Weird question, not sure I get it, but for your d1 and d2 files:
#!/bin/bash

find . -type f -name "*R1*" -print >d1.txt
find . -type f -name "*R2*" -print >d2.txt

*

*find is used since you have files under different sub-directories.

*Using > ensures the text files are emptied out if they already exist.

Note the code you put in your question is not valid bash.


text:
Q: Remove record from Store without causing server call on DS.Store#commit I'm developing a push application and need to remove items from a DS.Store without invoking any actions. I'm able to insert objects using load(), but need to be able to "unload" an object after it has been deleted on another client.
Thanks

A: Rather than remove a record from the store I just need to change the record state.
record.get('stateManager').goToState('deleted.saved');

For ember-data V ~1.0 use:
record.transitionTo('deleted.saved');

A: record.unloadRecord();

This clears belongsTo and hasMany relationships on the record and then transitions the record to the deleted.saved state, all without sending anything to the server.


text:
Q: Leaving validation on empty email address with jquery regex I am using jquery regex to validate an email address, but i don't want this validation to be applied on empty field, please tell me how can i solve it
(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i)

A: Try this:
if($.trim($('textEmail').val()).length == 0){
    //show some error
}
else{
    //do your regex here
}

A: I just found this regex, and it doesn't validate any empty field for email address but checks if email entered in invalid, this worked for me
/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/

A: You can also try as
if($("#textEmail").val() == "" || $("#textEmail").val() == undefined)
{
  alert("Please enter email");
}
else
{
   //Regex Validation
   //Other call as want
}

A: It's simple --
if($('#textEmail').val().trim() != ""){
  //validate your Email
}


text:
Q: Filter dictionary with arrays as value I have dictionary  [String: [Object]]. Each object has .name
Is it possible to use .filter on dictionary to return dictionary with only keys that contain filtered value ?

A: If I understand your question, you want the keys of a [String: [Object]] dictionary where each Object has a name property and this property has a given value.
struct Obj {
    let name: String
}

let o1 = Obj(name: "one")
let o2 = Obj(name: "two")
let o3 = Obj(name: "three")

let dict = ["a": [o1, o2], "b": [o3]]

Now let's say you want the dictionary key where an object has "two" for its name:
Solution with filter
let filteredKeys = dict.filter { (key, value) in value.contains({ $0.name == "two" }) }.map { $0.0 }

print(filteredKeys)

Solution with flatMap and contains
let filteredKeys = dict.flatMap { (str, arr) -> String? in
    if arr.contains({ $0.name == "two" }) {
        return str
    }
    return nil
}

print(filteredKeys)

Solution with a loop
var filteredKeys = [String]()

for (key, value) in dict {
    if value.contains({ $0.name == "two" }) {
        filteredKeys.append(key)
    }
}

print(filteredKeys)

A: Yes, but since you got a Dictionary with an array as value:
dictionary.flatMap({ $0.1.filter({ $0.name == "NameToBeEqual"}) })


text:
Q: Linux Mint 18 - connecting a bluetooth headset disables USB mouse I'm trying to get a bluetooth headset to work on my Mint 18 Cinnamon. I can connect to the headset in the normal mode, but most of the time when switching to A2DP mode for better quality, my USB mouse stops working. It is still powered on, and recognized in lsusb, but does not react to clicks or movement. I can use my wireless mouse as normal in this case.
Sometimes the connection works, and sometimes I get an error from pulseaudio "Failed to change profile to a2dp_sink". I don't know if this error is in any way related.
The problem did occur on a clean Live-USB version of LM18 as well, so I don't think it's due to any updates gone wrong. When I have the USB mouse unplugged, then connect to the headset and then reconnect the mouse, it works normally.
Any pointers on where to start debugging this?
Dmesg doesn't show anything exiting, except for a few lines of
Bluetooth: hci0 SCO packet for unknown connection handle 6

EDIT: The mouse also freezes when sending files to mobile phone through BT. Seems like high activity causes the issue?

A: Well, the answer is a bit of a lackluster. I updated my BIOS to the newest version and the mouse now works as it should.
Motherboard: Gigabyte Z87-D3H
Previous BIOS: F7
New working BIOS: F9


text:
Q: Connect to computer audio source through JavaScript I would like to use my computer's audio as a source for an online music streaming project I'm working on. How would I go about, via JavaScript, accessing my computer's audio output/speakers?

A: You could setup your computer to output its audio to its microphone input and then use the getUserMedia API to capture the audio from your "microphone".


text:
Q: does atomic operation (c++) freeze cpu If we perform a atomic operation on a multi core cpu, does the atomic instruction freeze operations on all other cores?
Example if we do a increment on a atomic variable:
++atomicInteger;
Does this freeze all other operations on other cores?
I am focused on x86 processors.
I know that reading or writing to memory aligned native type is atomic and does not impact any other cores execution.

A: x86 allows writing unaligned data that spans across two cache lines (i.e. across two 64 byte chunks), but the result is not guaranteed to be atomic. This means you may read 8 Byte from addr 0x1003c for e.g., requiring the CPU to fetch 2 lines (0x10000 and 0x10040), taking the relevant 4-byte chunks and stitching them together. However, these two lines may be stored in different locations - one could be cached, the other could be in the main memory. In extreme cases (page splits), one could in theory even be swapped out. As a result, you might get 2 data chunks from different times (a better term is observation points), where a store from some other process could have changed one in the middle.
On the other hand, once you add the lock prefix (or add an std::atomic definition, which should include that for you), x86 does guarantee that the result comes from a single observation point, and is consistent with observations from all other threads. To achieve this, it's quite possible that the CPU will enforce a complete block of all cores (for e.g. bus lock) until both lines are secured in the requesting core. If you don't you're risking a livelock where you constantly get one line, and lose it to another core by the time you got the second.
p.s. - user3286380 raised a good point, ++atomicInteger is not atomic, even if you declared it as such. std::atomic guarantees an atomic read and an atomic write (each on its own observation point), but it doesn't guarantee atomic read-modify-write unless you explicitly state that.

A: An atomic operation is an operation that cannot be done by multiple processors at the same time. If you want to do an addition atomically only one thread can be doing that operation.

If we perform a atomic operation on a multi core cpu, does the atomic
  instruction freeze operations on all other cores?

No. Not necessarily, if you happen to have multiple threads trying to do the same atomic operation, than they will be halted except the first one to reach that atomic statement.

I know that reading or writing to memory aligned native type is atomic
  and does not impact any other cores execution.

Where did you read this? It does not sound correct to me. The result of this operation might depend on the architecture. But if you have multiple threads on x86 for example, and those threads try to write to the same location, the operation is not atomic by default. So the final value of the address that is being edited by threads can be anything.
Here is a similar discussion you might be interested in : pthreads: If I increment a global from two different threads, can there be sync issues?


text:
Q: Knockout.js mapping. How to update only part of view model? I want to build simple page where user can select one photo from list and modify some properties, so i had built the model:
model = {
            newPhotos: [],
            currentPhoto: {
                id: 0,
                description: ""
            },
            setCurrent: function (photo, e) {
                ko.mapping.fromJS(ko.mapping.toJS(photo), viewModel.currentPhoto);
            }
      }

and markup:

            <canvas id="image-edit" />
            <textarea class="multi-line" name="PhotoDesc" data-bind="value: description"></textarea>

Main idea is that when user click on photo, setCurrent function called and there i can update currentPhoto with view model that click binding pass into setCurrent, but there is problem ko.mapping.fromJS(jsObj, viewModel) (as i can see from source) expecting that viewModel will be root model.
I know that i can manually go through all observables and refresh their values, or unmap rootModel, set property and then update root, but i belive that there is more complex and elegant way to do this.
Thank you.

A: Set up your current photo as an observable, and then you can use map to load the observable with JSON details.
  self.currentPhoto(ko.mapping.fromJS(data));

Here's a working JSFiddle to demonstrate:
http://jsfiddle.net/jearles/wgZ59/7/


text:
Q: Setting up djangoappengine I'm trying to setup djangoappengine.  I've cloned the code from git / bitbucket per here (following a number of links from Google), copied over django-testapp and renamed it for my own application.
But python manage.py runserver runs into this:
  Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_manager(settings)
  File "/Users/gimli/sandbox/iAgri/whipple/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/Users/gimli/sandbox/iAgri/whipple/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/gimli/sandbox/iAgri/whipple/django/core/management/__init__.py", line 261, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/Users/gimli/sandbox/iAgri/whipple/django/core/management/__init__.py", line 67, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/Users/gimli/sandbox/iAgri/whipple/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/Users/gimli/sandbox/iAgri/whipple/djangoappengine/management/commands/runserver.py", line 5, in <module>
    from django.db import connections
  File "/Users/gimli/sandbox/iAgri/whipple/django/db/__init__.py", line 78, in <module>
    connection = connections[DEFAULT_DB_ALIAS]
  File "/Users/gimli/sandbox/iAgri/whipple/django/db/utils.py", line 94, in __getitem__
    conn = backend.DatabaseWrapper(db, alias)
  File "/Users/gimli/sandbox/iAgri/whipple/dbindexer/base.py", line 54, in DatabaseWrapper
    return Wrapper(merged_settings, *args, **kwargs)
  File "/Users/gimli/sandbox/iAgri/whipple/dbindexer/base.py", line 37, in __init__
    super(BaseDatabaseWrapper, self).__init__(*args, **kwargs)
  File "/Users/gimli/sandbox/iAgri/whipple/djangoappengine/db/base.py", line 290, in __init__
    self.ops = DatabaseOperations(self)
TypeError: __init__() takes exactly 1 argument (2 given)

I've google around, the project seems to have errors of this sort over time but none of the solutions seem up-to-date.
Any help would be appreciated.

A: Do not use the code from bitbucket or the docs from allbuttonspressed!
They are both old and out of date. The new home for the project is:
http://django-nonrel.org/
There, you'll find decent documentation and current download links.

A: To run djangoappengine get the following modules & copy in your apps root:
1.autoload
2.dbindexer
3.djangoappengine
4.djangotoolbox
5.django (I think its optional)
You can get the django-testapp

A: The allbuttonspressed docs are pretty old and need to be updated, particularly with respect to install.  Fortunately someone built an installer (which I haven't tried):
https://groups.google.com/forum/?fromgroups=#!topic/django-non-relational/Nlkh-zldQ6w


text:
Q: How to read a InputStream with UTF-8? Welcome all
I'm developing a Java app, that calls a PHP from internet that it's giving me a XML response.
In the response is contained this word: "Próximo", but when i parse the nodes of the XML and obtain the response into a String variable, I'm receiving the word like this: "Pr& oacute;ximo".
I'm sure that the problem is that i'm using different encoding in the Java app then encoding of PHP script. Then, i supose i must set encoding to the same as in your PHP xml, UTF-8
This is the code i'm using to geat the XML file from the PHP.
¿What should i change in this code to set the encoding to UTF-8? (note that im not using bufered reader, i'm using input stream)
        InputStream in = null;
        String url = "http://www.myurl.com"
        try {
            URL formattedUrl = new URL(url);
            URLConnection connection = formattedUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();
            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
                in = httpConnection.getInputStream();

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(in);
            doc.getDocumentElement().normalize();
            NodeList myNodes = doc.getElementsByTagName("myNode");

A: When you get your InputStream read byte[]s from it. When you create your Strings, pass in the CharSetfor "UTF-8". Example:
byte[] buffer = new byte[contentLength];
int bytesRead = inputStream.read(buffer);
String page = new String(buffer, 0, bytesRead, "UTF-8");

Note, you're probably going to want to make your buffer some sane size (like 1024), and continuously called inputStream.read(buffer).

@Amir Pashazadeh
Yes, you can also use an InputStreamReader, and try changing the parse() line to:
Document doc = db.parse(new InputSource(new InputStreamReader(in, "UTF-8")));


text:
Q: sql auth vs nt auth in SQL server Ok, so everything I read says best practice is to us NT authentication in SQL server. And I can see some advantages to that but using NT auth how do I force users to access the data using only my application and not some other tool such as SSMS? It would seem to me that it would be better to allow only my application to connect to SQL server using SQL auth and password the user does not know and controlling security through the application. Am I missing something here? Is there a way to block SSMS and other database tools from connecting to my application's database?

A:
Ok, so everything I read says best practice is to us NT authentication in SQL
  server

Read more. Please. Because while there are good reasons to do that in certain scenarios, there are good reasons NOT to do it in other scenarios.

And I can see some advantages to that but using NT auth how do I force users
  to access the data using only my application and not some other tool such as
  SSMS?

Since maybe 25 years or so a standard approach to program applications is to have a SERVER. The user connects to the SERVER and ONLY the server connects to the database. Problem solved.

Am I missing something here?

Stating the obvious: A lot more reading than you did so far.

Is there a way to block SSMS and other database tools from connecting to my
  application's database?

Your reading did not get to application passwords in the documentation (https://msdn.microsoft.com/en-us/library/ms181491.aspx is titled CREATE APPLICATION ROLE) which would allow an application to post-authenticate with a password. Not that this is a good approach - but it sis AN approach that was introduce some versions back. This way rights could be on an application, and unless the user knows the role password of the application - out of luck.
But really, the standard approach is to use an application server and only the app server can connect. And often this does not use NT authentication as the connection password is coded in a server config file.


text:
Q: variable is not accessible in angular.forEach I have a service
app.service('myService', function() {
    this.list = [];
    this.execute = function() {
        //this.list is reachable here
        angular.forEach(AnArrayHere, function(val, key) {
           //this.list is not reachable here
        });
    }
}

even in controller its accessible
function Ctrl($scope, myService) {
    $scope.list = myService.list;
}

Can someone explain me why "this.list" is not reachable within the angular.foreach and how can I access to "this.list" ?

A: The reason this.list is not accessible in the foreach is because the context for that function call has changed. It works inside the execute method as that method is part of the same context as list.
Due to all the closures I would assign the this context to another variable that you can then call later on. Something like this:
app.service('myService', function() {

    var self = this;
    self.list = [];

    self.execute = function() {
        //this.list and self.list are reachable here
        angular.forEach(AnArrayHere, function(val, key) {
           //self.this == this.list
        });
    }
}

This is a slightly more general solution than passing the context as part of the foreach method call and would work in other closure related situations.

A: The last parameter in the angular.forEach (See http://docs.angularjs.org/api/angular.forEach) function is the context for this. So you'll want something like this:
app.service('myService', function() {

    this.list = [];

    this.execute = function() {

        //this.list is reachable here

        angular.forEach(AnArrayHere, function(val, key) {
           //access this.list
        }, this);

    }
}


text:
Q: error ';' expected in array defining, ; already used public class AssignmentChapter8
{
    public static void main(String[] args)
    {
        int randomNumbers = new int[100];
        int counter = 0;

        while(counter < randomNumbers.length)
        {
            randomNumbers[counter] = (int)(Math.random() * 25);
            counter++;
        }

        int oddNumbers[] = new int[100];
        oddNumbers[] = getOddNumbers(randomNumbers);
        int evenNumbers[] = new int[100];
        evenNumbers[] = getEvenNumbers(randomNumbers);

        System.out.println("The odd numbers are:");

        for(int k = 0; k < oddNumbers.length; k++)
            System.out.print("\t" + oddNumbers[k]);

        System.out.println("The even numbers are:");

        for(int l = 0; l < evenNumbers.length; l++)
            System.out.print("\t" + evenNumbers[l]);
    }
    public static int getOddNumbers(int randomNumbers)
    {
        int oddNumbers[] = new int[100];
        int counterA = 0;
        int counterB = 0;
        int counter = 0;
        int placeholder;

        while(counter < randomNumbers.length)
        {
            if(randomNumbers[counterA] % 2 > 0)
            {
                oddNumbers[counterB] = randomNumbers[counterA];
                counterB++;
            }

            counterA++;
            counter++;
        }

        return oddNumbers;
    }
    public static int getEvenNumbers(int randomNumbers)
    {
        int evenNumbers[] = new int[100];
        int counterA = 0;
        int counterB = 0;
        int counter = 0;
        int placeholder;

        while(counter < randomNumbers.length)
        {
            if(randomNumbers[counterA] % 2 > 0)
            {
                evenNumbers[counterB] = randomNumbers[counterA];
                counterB++;
            }

            counterA++;
            counter++;
        }

        return evenNumbers;
    }
}

I have been trying to execute a program to sort variables in arrays, but I keep getting a ';' expected error in the line after declaration of the array where the program is supposed to retrieve an array from a function. Any help would be appreciated.

A: This is bad syntax (which causes the  ';' expected error ):
oddNumbers[] = getOddNumbers(randomNumbers);

The brackets are not needed.  You can do this:
oddNumbers = getOddNumbers(randomNumbers);

Besides that, you have plenty of errors:
int randomNumbers[] = new int[100]; // you need the brackets

Your return value in the method declaration is wrong (you are returning an array, not an int):
public static int[] getEvenNumbers(int randomNumbers)

A:    int oddNumbers[] = new int[100];

By initializing oddNumbers become an array. when you want to assign values,
    oddNumbers={elements of array}

Both left and right hand side both should arrays.
May be you should use IDE for coding then it may help you to understand some issues like this.


text:
Q: How to move from activity to fragment I wrote this code for login and for chatting;
login is an activity where is chatting is a fragment; here is my activity :
public class Consultant extends AppCompatActivity {

    private FirebaseAuth auth;
    private Button loginbtn;
    private EditText email;
    private EditText pass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consultant);

        auth = FirebaseAuth.getInstance();

        loginbtn = (Button) findViewById(R.id.loginbtn);
        email = (EditText) findViewById(R.id.email);
        pass = (EditText) findViewById(R.id.pass);

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkEmailandpassword();
            }
        });
    }

    public boolean checkEmailandpassword() {
        if (validate()) {
            String CEmail = email.getText().toString().trim();
            String CPass = pass.getText().toString().trim();

            auth.signInWithEmailAndPassword(CEmail, CPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    if (task.isSuccessful()) {
                        Toast.makeText(Consultant.this, "welcome", Toast.LENGTH_LONG).show();
                        Intent i = new Intent(Consultant.this,Consultant_Home_Chatting.class);
                        startActivity(i);
                    } else {
                        Toast.makeText(Consultant.this, "wrong ", Toast.LENGTH_LONG).show();
                    }

                }
            });
        }
        return false;
    }
            private boolean validate() {
                boolean result = false;

                String CPass = pass.getText().toString();
                String CEmail = email.getText().toString();

                if (CPass.isEmpty() || CEmail.isEmpty()) {
                    Toast.makeText(Consultant.this, "all fields required", Toast.LENGTH_LONG).show();
                } else {
                    result = true;
                }

                return result;
            }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_nav, menu);
        return true;
    }
        }

and here my fragment :
   public class Consultant_Home_Chatting extends Fragment {
private ViewPager mViewP ;
private FirebaseAuth mAuth ;
private TabLayout mTab ;
private TabsPagerAdapter mAdapter ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_consultant__home__chatting, container, false);
}

public  Consultant_Home_Chatting() {

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    mAuth = FirebaseAuth.getInstance();
    mViewP = (ViewPager) getView().findViewById(R.id.main_tabs_pager);

    mAdapter = new TabsPagerAdapter(getFragmentManager());
    mViewP.setAdapter(mAdapter);
    mTab = (TabLayout) getView().findViewById(R.id.main_tabs);
    mTab.setupWithViewPager(mViewP);
}

I tried to add a new class holding these liens then make a constructor in my fragment and onCreatOptions method in my activity but it does not work!
I think the solution is to use the Bundle but I don't know how to use it or can I use it and what can I send inside put extra, can you please help?
   if (savedInstanceState == null){
            getFragmentManager().beginTransaction()
                    .add(android.R.id.content, new Consultant_Home_Chatting ()).commit();}

A: to use bundle simple create the instance of your fragment and then create bundle add all data you want and add this bundle to the fragment.
Here is example:
In activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TestFragment testFragment = new TestFragment();
    Bundle bundle = new Bundle();
    bundle.putString("name", "John");
    bundle.putInt("age", 24);
    testFragment.setArguments(bundle);

    getSupportFragmentManager()
       .beginTransaction()
       .add(R.id.content, testFragment).commit();

}

In your fragment:
public class TestFragment extends Fragment {

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = getArguments();
    if(bundle != null){
        String name = bundle.getString("name");
        int age =`enter code here` bundle.getInt("age");
    }
  }
}


text:
Q: Emails not being delivered to server from certain mail servers: "domain has no valid mail exchangers" I'm having trouble with a server that I administer.
I've been told that a number of emails aren't coming through. These are consistently from certain people. Here's the bounce error that they receive:

This message was created automatically by mail delivery software.
A message that you sent could not be delivered to one or more of its recipients. This is a permanent error. The following address failed:
"example@fish-thecompany.com":
domain has no valid mail exchangers

I don't know how to approach this. Obviously I have mail exchangers as we can send and receive email (usually) without a problem.
Is there anything I can do on our end or do I need to should I contact the postmaster for the domain that can't find the mail exchanger?

A: Assuming that's your real domain (for which, many thanks), you have a problem with your MX record:
[me@lory ~]$ dig mx fish-thecompany.com
[...]
;; ANSWER SECTION:
fish-thecompany.com.    86313   IN      MX      20 mail.fish-thecompany.com.
[me@lory ~]$ dig mail.fish-thecompany.com
[...]
;; ANSWER SECTION:
mail.fish-thecompany.com. 86300 IN      CNAME   fish-thecompany.com.
fish-thecompany.com.    86300   IN      A       109.228.0.95

But RFC2181 is very clear on the subject:

10.3. MX and NS records
The domain name used as the value of a NS resource record, or part
of    the value of a MX resource record must not be an alias.  Not
only is    the specification clear on this point, but using an alias
in either    of these positions neither works as well as might be
hoped, nor well    fulfills the ambition that may have led to this
approach.  This    domain name must have as its value one or more
address records.    Currently those will be A records, however in the
future other record    types giving addressing information may be
acceptable.  It can also    have other RRs, but never a CNAME RR.

My guess is that some of your senders are using mail servers that are intolerant of violations of this particular RFC; as far as their servers are concerned, you really don't have any valid mail exchangers.  Fix that, make your MX-referenced host an A record, and this may well improve.

A: Most likely your mail server, or dns setup does not correspond to the accepted rules.
http://mxtoolbox.com/diagnostic.aspx


text:
Q: Loop that finds a word in a string So, i'm working on a 'for' loop that will identify my name, Andrew, and push it into an array, but there's something wrong with it
/*jshint multistr:true */

var text = ("Andrew is really awesome and Andrew should be working on the project, but there is honestly nothing for Andrew to do.");
var myName = ("Andrew");
var hits = [];
for (var i = 0; i < text.length; i ++) {
    if (text[i] === "A") {
        for (var j = i; i + nyName.length; i ++) {
            hits.push(text[j]);
        }
    }
}

Also, the second loop is supposed to stop when it reaches the end of myName.

A: You're using JSHINT, so just read the error messages and it'll tell you exactly what's wrong.

Errors:

*

*Line 7: for (var j = i; i + nyName.length; i ++) {
'nyName' is not defined.

*Line 3: var myName = ("Andrew");
'myName' is defined but never used.

JSHINT isn't much good if you don't pay attention to what it's telling you.

Also, your inner loop looks odd.
for (var j = i; i + nyName.length; i ++) {

Seems like it'll cause an infinite loop. You're perhaps wanting j with a different condition.

A: You misspelled myName in your for loop syntax and typed nyName instead, so chances are the script dies as soon as it hits that line.

A: A typo in the for loop that wants to refer to myName would appear to be a big problem:
for (var j = i; i + nyName.length; i ++)
                    ^

A: The misspelled myName isn't the only part that fails. You for loop will never end the loop because i + myName.length will always evaluate to true. You also need to increase the value of j or it will always get the character at index i.
Here's the corrected loop.
for (var i = 0; i < text.length; i ++) {
    if (text[i] === "A") {
        for (var j = 0; j < myName.length; i++, j++) {
            hits.push(text[i]);
        }
    }
}


text:
Q: Convert rows to columns like pivot I have a data like:
formid  formownerid approverid
1       100         102
1       100         103
1       100         104
2       200         107
2       200         103
2       200         109
2       200         105
3       400         201
3       400         210

I want to convert it to:
formid  formownerid approverid  approverid  approverid  approverid
1       100         102         103         104         NULL
2       200         107         103         109         105
3       400         201         202         NULL        NULL

Wherever I looked at I saw pivot/unpivot but it looks unrelated since we don't need aggregation.

A: The aggregate is a necessary part of the pivot, but it's simple to apply here; you don't want sum but a max aggregate works fine:
select *
from (
  select t.*,
    row_number() over (partition by formid, formownerid
      order by approverid) as rn
  from t42 t
)
pivot (max(approverid) as approverid for (rn) in (1, 2, 3, 4));

    FORMID FORMOWNERID 1_APPROVERID 2_APPROVERID 3_APPROVERID 4_APPROVERID
---------- ----------- ------------ ------------ ------------ ------------
         1         100          102          103          104
         2         200          103          105          107          109
         3         400          201          210

Or you can specify the column name prefix explicitly to make them valid identifiers:
pivot (max(approverid) as approverid
  for (rn) in (1 as a, 2 as b, 3 as c, 4 as d));

The inner query is adding a pseudocolumn rn to the table results to give you a fixed value to pivot against, since the actual approver IDs aren't going to be known in advance.
The manual approach might make this a bit clearer:
select formid, formownerid,
  max(case when rn = 1 then approverid end) as approverid_1,
  max(case when rn = 2 then approverid end) as approverid_2,
  max(case when rn = 3 then approverid end) as approverid_3,
  max(case when rn = 4 then approverid end) as approverid_4
from (
  select t.*,
    row_number() over (partition by formid, formownerid
      order by approverid) as rn
  from t42 t
)
group by formid, formownerid
order by formid, formownerid;

    FORMID FORMOWNERID APPROVERID_1 APPROVERID_2 APPROVERID_3 APPROVERID_4
---------- ----------- ------------ ------------ ------------ ------------
         1         100          102          103          104
         2         200          103          105          107          109
         3         400          201          210

The inner query is the same. The case statement produces each column as above, but without the max and grouping you get multiple rows with lots of extra blanks:
select formid, formownerid,
  case when rn = 1 then approverid end as approverid_1,
  case when rn = 2 then approverid end as approverid_2,
  case when rn = 3 then approverid end as approverid_3,
  case when rn = 4 then approverid end as approverid_4
from (
  select t.*,
    row_number() over (partition by formid, formownerid
      order by approverid) as rn
  from t42 t
);

    FORMID FORMOWNERID APPROVERID_1 APPROVERID_2 APPROVERID_3 APPROVERID_4
---------- ----------- ------------ ------------ ------------ ------------
         1         100          102
         1         100                       103
         1         100                                    104
         2         200          103
         2         200                       105
         2         200                                    107
         2         200                                                 109
         3         400          201
         3         400                       210

Notice that there's only a value in (at most) one column for each formid/formownerid combination, but that they appear in different rows. The max suppresses those multiple rows; and the pivot version does something similar under the hood.
SQL Fiddle showing the manual approach with the intermediate step, and the pivot version.

A: One possible Approch:
SELECT FROMID, FROMOWNERID, APPROVERID, NULL APPROVERID, NULL APPROVERID, NULL APPROVERID
FROM   yourtable
WHERE  FROMID = 100
AND    APPROVERID =  102
UNION ALL
SELECT FROMID, FROMOWNERID, NULL APPROVERID, APPROVERID APPROVERID, NULL APPROVERID, NULL APPROVERID
FROM   yourtable
WHERE  FROMID = 100
AND    APPROVERID =  103
UNION ALL
SELECT FROMID, FROMOWNERID, NULL APPROVERID, NULL APPROVERID, APPROVERID APPROVERID, NULL APPROVERID
FROM   yourtable
WHERE  FROMID = 100
AND    APPROVERID =  104
----
-------
And So On


text:
Q: why ajax return the error response message in a laravel project ? what the possible reasons? Before anything , I have searched for a solution for my issue here in SOF and in the internet but I didn't found the useful solution for my code :/
I write a code for getting products prices in an e-commerce laravel project depends on a product size ,
just for testing I want to (alert) the size id , and that is my js code where I use ajax :
edited
  $(document).ready(function(){
   $("#selSize").change(function(){
     var idSize = $(this).val();
     var arr = idSize.split('/');
     var productID = arr[0];
     var sizeID = arr[1];
     //alert(productID);
     $.ajax({
        type:'get',
        data: {sizeID:sizeID},
        dataType: 'application/json' ,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        contentType: "application/json; charset=utf-8",
        url:productID+'/get-products-price',
        success:function(resp){
            alert(resp);
        },error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
          }
     });
   });
});

and that is my html code where I browsing the product possible sizes :

Product Sizes

   @if(count($sizes) > 0)
   <select id="selSize" name="size"style="width:180px;margin-bottom:40px;height:30px;">
         <option>Select size</option>
         @foreach($sizes as $size)
             <option value="{{$product->id}}/{{$size->id}}">({{$size->width}},
                                            {{$size->height}},
                                            {{$size->length}},
                                            {{$size->thickness}})
                                           (cm)
             </option>
         @endforeach
    </select>
    @endif

and that is my controller function that I used :
public function getProductPrice(Request $request)
{
    $data = $request->all();
    echo "
"; print_r($data); die;
}

and that where I do the routing :
Route::get('{id}/get-products-price' , 'SizesController@getProductPrice');

finally the alert it shown to me says : (localhost says  undefined) , mean return the error alert from ajax , why ?
the url shown in network console is (http://localhost/AishaStore/public/details/11/get-products-price?sizeID=2)
I hope I found the solution by your help

A: In your ajax parameters add :
dataType: 'json'

Let me know if it worked but i think this is the part you are missing cause you don't define the dataType of your variables you are sending to the backend. Happened to me also sometimes that i forgot it.
Also you can add:
 contentType: "application/json; charset=utf-8",

Edit:
error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

Print your error message so you know what's the error of the ajax in order to debug.
New Edit:
Based on the feedback from the comments you are missing the id in your url:
Route::get('{id}/get-products-price' , 'SizesController@getProductPrice')->name('get-products-price');

A: I think the error is here:
url:'/get-products-price',

change it to:
url: "{{ url('/get-products-price') }}",  // url() function will generate the right url for the application

and try again and open the console to check the exact response.

A: In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">

Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})

;
Try add this in your controller
 return response()->json(['success'=>'Record is successfully added']);


text:
Q: accent characters crash IE9 I'm working on a multilingual site using Umbraco CMS.  When testing IE9, I found several pages that force IE9 to close (and only certain versions or builds of IE9). I've narrowed it down to accented characters.  However, the pages that work have accented characters as well. To figure out what the difference is, I copied the offending text into Notepad from both working and non-working pages. I am unable to add a screenshot from notepad b/c I'm new so I'll have to describe it:
The first word with 'í' crashes IE9. The 'í' character does not look correct; there is no kerning, it's smaller, just looks like it is not rendering as part of the font.  The second word with 'í' does not crash IE9. It renders correctly as part of the font. I get the same, correct character by typing (alt/option+e)+i.
I apologize if there is a term for this difference but I'm having a difficult time searching for such a specific problem without knowing what to search for. The editor who is adding the data to the site copies content from multiple sources so I'm assuming that is the source of the problem, but I would like to control this and keep it from happening again. Can I validate this kind of problem on input? What is the technical difference between these two characters?
MORE INFORMATION
IE9 Version: 9.0.8112.16421
Update Versions: 9.0.15 (KB2817183)
I did more digging and I've found that when pasting the bad character 'í' in this ASCII converter: http://slayeroffice.com/tools/ascii/ it returns an ASCII value of 105 (which is the same as the letter 'i'.  When I paste the correct character 'í' in the converter, I get an ASCII value of 237.
I've also found the source of the problem. The bad character comes from a pdf.  When an editor copies from a particular pdf and pastes it into the CMS I get the bad character. So far, any character with an accent mark is breaking my version of IE9.
Below is a snippet of code used to display the content on the front-end of the site. I'm using Umbraco CMS version 6.1, Microsoft ASP.NET MVC, my views are .cshtml:
@{

   XmlDocument xd = new XmlDocument();
   xd.LoadXml(Model);

}

@foreach(XmlNode widget in xd.SelectNodes("//widget")){
   <h4>@widget.SelectSingleNode("title").InnerText</h4>
}

To reiterate, is there a way to 'protect' or validate against these types of character problems? I'm assuming no, since the ASCII converter recognizes the bad character as an 'i', but I'm concerned that the editor adding information could add a bad character and no one would know unless they happened to look at the site in IE9...
Thanks!


text:
Q: Why do colons not work in pandas iloc if slicing on the basis of both rows & columns df.iloc[[1,4], [1,6]] works, but what if I want rows
[1:4] inclusive, and columns [1:6] inclusive?
I know I can list the rows/columns that I want eg df.iloc[[1,2,3,4],[1,2,3,4,5,6]]
but what if the quantity of rows/columns makes this impractical, say, it was [7:50]?

A: df.iloc[[1,2,3,4],[1,2,3,4,5,6]] is equivalent to df.iloc[1:5, 1:7], or df.iloc[1:4+1, 1:6+1]


text:
Q: Angular js - Disable toggle switch (using angular and typescript)
I have a toggle switch directive as:
    return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            onText: '@',
            offText: '@',
            title: '@',
        },
        template:
        '' +
        '  <input type="checkbox" ng-model="ngModel">' +
        '  ' +
        '    {{title}}' +
        '    {{offText}}' +
        '    {{onText}}' +
        '  ' +
        '  ' +
        ''
    };

In my html I am using this as:
toggle-switch ng-model="myValues" on-text="Enabled" off-text="Disabled"

Now I want to disable the above one. How can I do so.
I am pretty new to angular so any inputs would be appreciated.
Thanks

A: Use:
<toggle-switch
   ng-model="switchStatus"
   is-disabled="true">
</toggle-switch>

http://jumplink.github.io/angular-toggle-switch/

A: try adding the link code to your directive :
link: function ($scope, element, attrs) {
           $scope.somethingDisabled = true;
        };

and in your html part ng-disabled = somethingDisabled
then all you have to do is just add to the link function how and when you want to disabled either by passing it as an directive attr value or in the controller scope.
makes sense?
EDIT2
as per request I did something that would just show a proof of concept...
here is the plunker..
plunker
 link: function ($scope) {
$scope.myclick = function(elem){
 setTimeout(function(){$scope.disabled = true;},0);
  setTimeout(function(){
    $scope.disabled=false;
    alert('db call done');
  },2000);
};

}
I fixed the buggyness code might still be kinda ugly but Ill leave it to you to prettify it... the second timeout is the db call... first on is pushing the disable to the end of the stack so you'll see the animation.
if you want you can also just use !ngModel in the ng-disabled and then change the value of the ngModel when the db call come back..
good luck

A: I have the same issue and I used disabled attribute:
<toggle-switch  label-text="'Enable Internet Cash'" label-position="'top-center'" disabled="MyBankAccount.HasMoney"></toggle-switch>

the disabled attribute receive a Boolean expression. If the disabled attribute has true value it will disable the toogle-switch , in other case it will enable the toggle-switch.
consider that in js file there is $scope.MyBankAccount and $scope.MyBankAccount is json object with HasMoney property.


text:
Q: FluentValidation require one out of three values Using fluent validation and verifying if at least one variable out of three is > 0. I have tried verifying with a when otherwise statement but I can't add another otherwise statement.
        When(c => c.var1!= null || c.var2!= null || c.var3!= null, () =>
        {
            RuleFor(c => c.var1).GreaterThan(0)
            .WithMessage("One of these fields, var1, var2, or var3, are required.");
        }).Otherwise(() =>
        {
            RuleFor(c => c.var2).GreaterThan(0);
        });
// I would like to verify a third var but can't stack otherwise statements

If I would like to verify that one of var1, var2, var3 is > 0 what changes should I make?

A: If you use a when statement you can verify all 3 variables with only one validation message sent. There is such thing as dependent rules but that is more complicated.
RuleFor(c => c.var1).NotNull()
  .WithMessage("At least one is required");

RuleFor(c => c.var2).NotNull()
  .When(c => c.var2!= null)
  .WithMessage("At least one is required");

RuleFor(c => c.var3).NotNull()
  .When(c => c.var1!= null && c.var2!= null)
  .WithMessage("At least one is required");


text:
Q: How does one find the PyQt6 version of PyQt5 class QAbstractTransition I'm trying to convert this PyQt5 example to PyQt6 but it has some modules that are not available through QtCore. I've been taking a PyQt6 class and working through examples but I'm not yet at the point where I can understand the documentation very well. I found qrand and qsrand in QObject. How can I find how or where to import QAbstractTransition? Could this be something that is not yet implemented in PyQt6?
"""https://github.com/baoboa/pyqt5/blob/master/examples/animation/moveblocks.py"""
"""
from PyQt5.QtCore import (QAbstractTransition, QEasingCurve, QEvent,
        QParallelAnimationGroup, QPropertyAnimation, qrand, QRect,
        QSequentialAnimationGroup, qsrand, QState, QStateMachine, Qt, QTime,
        QTimer)
"""
from PyQt6.QtCore import (QEasingCurve, QEvent,
        QParallelAnimationGroup, QPropertyAnimation, QRect,
        QSequentialAnimationGroup, Qt, QTime, QTimer)
# from PyQt6.   can't find QAbstractTransition
from PyQt6.QtCore import QObject

A: QAbstractTransition has been moved to the new module called QtStateMachine so ideally you should import it using from PyQt6.QtStateMachine import QAbstractTransition. Unfortunately PyQt6 hasn't implemented it (maybe it's a bug), PySide6 has instead.


text:
Q: A dominant (?) rational map on space of matrices... A rational map $\varphi:X\dashrightarrow Y$ (written with a dashed arrow because it is not defined at every point) between two (irreducible) algebraic varieties over $\mathbb{C}$, is said to be dominant if $\varphi(X)$ is dense in $Y$ for the Zariski's topology.
For an integer $n\geqslant 2$ identify the space of all $n\times n$ matrices $A=(a_{i,j})$ with $\mathbb{C}^{n^2}$. Denote by $\Delta_{j,k}$ the determinant of the $(n-1)\times(n-1)$-matrix obtained from $A$ deleting its $j$-th row and $k$-th column. I'm trying to prove (or disprove) the following proposition:
For all $k=1,\ldots,n$ the association $A=(a_{i,j})\mapsto \Big(a_{k,i}\frac{(-1)^{k+j}\Delta_{j,k}}{\det A}\Big)_{i,j}$ defines  $\pi_k:\mathbb{C}^{n^2}\dashrightarrow \mathbb{C}^{n^2}$, which is a dominant rational map.
The obvious strategy of equating the coordinates of $\pi_k$ to an element $(\alpha_{i,j})$ of $\mathbb{C}^{n^2}$ and eliminating $\det\, A$ leads in too many relations ($n^4-n^3$, I'd say) involving the $a's$, $\Delta's$ and $\alpha's$ that cannot be obviously reduced. Hence it is not clear to me how to identify the open set (if any) on the target at which $\pi_k$ surjects.
Any idea? Thank you.

A: I just realized that the above maps are not dominant. In the case $n=2$ already, say for $k=1$: $$\pi_1\Big(\begin{equation*}
\begin{pmatrix}
a_{1,1} & a_{1,2} \\
a_{2,1} & a_{2,2} \\
\end{pmatrix}
\end{equation*}\Big)=
\frac{1}{\det A}\begin{pmatrix}
a_{1,1}\Delta_{1,1} & -a_{1,1}\Delta_{2,1} \\
a_{1,2}\Delta_{1,1} & -a_{1,2}\Delta_{2,1} \\
\end{pmatrix} =
\frac{a_{1,1}a_{1,2}}{\det A}\begin{pmatrix}
\Delta_{1,1} & -\Delta_{2,1} \\
\Delta_{1,1} & -\Delta_{2,1} \\
\end{pmatrix}.
$$
Hence the image of $\pi_1$ is contained in the hypersurface of $\mathbb{C}^{2^2}=\mathbb{C}^{4}$ determined by the equation $\det=0$. It follows that the image is not dense for the Zariski topology.
Similar reasoning shows that for higher $n$ and all $k=1,\ldots,n$ that the $\pi_k$ are not dominant.


text:
Q: Mr. Smith is the president of the corporation who will not accept our proposal My professor holds that this is a good sentence, since who agrees with the subject, Mr. Smith.  It sounds horrible to me.

Mr. Smith is the president of the corporation who will not accept our proposal.

Is this a good sentence?

A: Well, let's start with a rhetorical question. Would you consider the following to be a "good" English sentence?

Mr. Smith is the executive who will not accept our proposal.

I definitely consider this to be a "good" English sentence. It relies on the fact that there are multiple executives of which Mr. Smith is the one who's not impressed with the proposal.
Similarly, your sentence,

Mr. Smith is the president of the corporation who will not accept our proposal.

is a "good" English sentence if the following sentence holds true,

Mr. Smith is the president of the corporation, among all of the presidents of the corporation, who will not accept our proposal.

A: The OP is right that it's a horrible sentence.
Consider some alternatives, starting with the original.

Mr. Smith is the president of the corporation who will not accept our proposal

The sentence as given is grammatical if it is interpreted to mean:

Mr. Smith is the corporation president who will not accept our proposal.

But it sounds more like an ungrammatical attempt to say:

Mr. Smith is the president of the corporation that will not accept our proposal

Since the original sentence is ambiguous, it would be a mistake to describe it as "good." It is a poorly written grammatical sentence.

A: Fun sentence!
The disquiet here is because of the use of determiners with a preposition in the middle:

the president of the corporation

We expect the relative pronoun who to describe the noun that immediately precedes it. The sentence is grammatical if the president of the corporation is understood to be a noun phrase with president as the headword.
Writing the sentence as:

Mr. Smith is the president of the corporation that will not accept our proposal.

gives the corporation (and strips Smith of) agency, changing the meaning.
N.B.
I've only given this a little thought, and would love to have problems with my logic pointed out, but this pattern (det n prep det n) isn't uncommon when it comes to titles:

*

*the head of the committee

*a man of the cloth

The first shows how changing the relative pronoun changes agency; the second can illustrate how important it is to recognize the first noun as the headword of the NP.

Sharon is the head of the committee who closed the deal.

is different to

Sharon is the head of the committee that closed the deal.

In the first case, Sharon did it; in the second, it was the committee. From this I'd argue that the OP's sentence is a grammatical construction that conveys a precise meaning.
Similarly,

Savonarola was a/the man of the cloth who was burned at the stake.

is grammatical.

Savonarola was a/the man of the cloth that was burned at the stake.

is also grammatical, but almost nonsensical as it sounds like Savonarola was made of cloth.


text:
Q: Unbiased estimator from two SRS less duplicates Suppose I take two independent random samples from a population of size $N$: the first is a simple random sample of size $n$ and the second is a simple random sample of size $m$. Let set $S$ contain all of the records selected from the two samples of size $n$ and $m$ less any duplicates.  Thus, $S$ should consist of $n_s$ records where $n_s$ $\le ($$m$+$n$) since $S$ does not contain duplicates.
I am trying to create an unbiased estimator for the population total that only depends on the records in $S$ in terms of only all $y_i$, $n$, $m$, and $N$.
I tried to mimic the unbiased Horvitz Thompson estimator $\hat{t} = \sum_{iϵS}y_i/\pi_i$, where $\pi_i$ is the probability that $y_i$ is in $S$.  Here, I believe $\pi_i$  is the probability of the union of the event that $y_i$ is selected in the first sample of $n$ people and the event that $y_i$ is selected in the second sample of $m$ people.  However, I am unsure of how to express the upper limit of the sum without using $n_s$.
Is there a way to mimic the Horvitz Thompson estimator in terms only of all $y_i$, $n$, $m$, and $N$?  Or should I be taking a different approach to creating an unbiased estimator?

A: An option is to derive two independent HT estimates from each sample: $s_1$ and $s_2$:
$\hat{t}_1 = \sum_{i \in s_1} \frac{y_i}{\pi_i} = \frac{N}{n} \sum_{i \in s_1} y_i$,
$\hat{t}_2 = \sum_{i \in s_2} \frac{y_i}{\pi_i} = \frac{N}{m} \sum_{i \in s_2} y_i$.
And then you can use average of both estimates to derive another unbiased estimate of $t$:
$\hat{t} = \frac{1}{2} \left( \hat{t}_1 + \hat{t}_2 \right) =
 \frac{N}{2} \left( \frac{1}{n} \sum_{i \in s_1} y_i + \frac{1}{m} \sum_{i \in s_2} y_i \right)$.

A: There is other solution.
You can compute the sampling probability for each individual to be sampled in combined sample $S$ by
$$\pi_i = \frac{n}{N} + \frac{m}{N} - \frac{mn}{N^2} = \frac{n + m - \frac{mn}{N}}{N}$$
You can apply the standard HT-estimator for the population total now:
$$\hat{t} = \sum_{i \in S} \frac{y_i}{\pi_i} = \frac{N}{n + m - \frac{mn}{N}} \sum_{i \in S} y_i$$


text:
Q: How to Upgrade Oracle VirtualBox 4.1.12 to to 4.2.10 I installed Oracle VirtualBox 4.1.12 in my Ubuntu 12.04.
Now I want upgrade from 4.1.12 to 4.2.10 version.
How can I upgrade the Oracle VirtualBox in command line

A: Try this:
Add this line to /etc/apt/sources.list:
deb http://download.virtualbox.org/virtualbox/debian precise contrib

Add PGP keyring:
wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- \
| sudo apt-key add -

Update source list:
sudo apt-get update

Then install virtualbox-4.2:
sudo apt-get install virtualbox-4.2


text:
Q: Fast file search algorithm for IP addresses Question
What is the fastest way to find if an IP address exists in a file that contains IP addresses sorted as:

219.93.88.62
219.94.181.87
219.94.193.96
220.1.72.201
220.110.162.50
220.126.52.187
220.126.52.247

Constraints

*

*No database (e.g., MySQL, PostgreSQL, Oracle, etc.)

*Infrequent pre-processing is allowed (see possibilities section)

*Would be nice not to have to load the file each query (131Kb)

*Uses under 5 megabytes of disk space

*No extra PHP modules

File Details

*

*One IP address per line

*9500+ lines

Possible Solutions

*

*Create a directory hierarchy (radix tree?) then use is_dir() (sadly, this uses 87 megabytes)

A: Since your file stores the IP addresses in sorted order already you can quickly find a specific IP address in O(log(n)) time by using a binary search.
If you want to speed this up even further you can cache for example every 100th row in memory and use an in-memory binary search first, then you know which part of the file you need to read in to finish the search.
Having said that 131kB is really not that much, so the simplest and fastest solution is to buy more memory and cache the entire file in memory in a hash table.

A: EDIT I didn't notice the php tag, I don't know if the following type of thing is possible in that language.  But I'll leave it for the idea anyway.
An IPv4 address is representable as a 32-bit number, so I'd just make an array of int32, translate your addresses into the 'ints` with the following Python-ish psuedocode:
x = 0
i = 24
s = '111.222.333.444'
for part in s.split('.'):
    x += part.toint() << i
    i -= 8
IPlist.append(x)

Then you can get the input address, convert it to an int the same way, and do binary search on the array.
For ~10 k lines, the array will take ~40 kBytes.

A: Scanning the file line by line to find an IP seems like a pain if you have 9,000 non-matches to check before you get to 232.0.17.1
Is your file constrained to a single file?  e.g. lets say this list is banned IPs and you just want to see if one is "in" the list.
What if you made a DIR to contain multiple files:
BannedIPs
  +- 0.ips
  +- 1.ips
  +- 37.ips
  +- 123.ips
  +- 253.ips
  +- 254.ips

Each file only contains IP addresses that start with that number.
If you were lucky enough to have even distribution... you'd have 256 files, but each would only have ~37 entries.
Thus when you want to test: 232.0.17.1 you look in the 232.ips file and scan for it.

A: Might not be fast, but I'd try this out: If the IP address file doesn't change much, read the file into an array and cache it (maybe Memcache) and search from there on every request.


text:
Q: Including jar files into library project I am developing small library for android application. My library having some dependencies for that i want to include some external jar file into my library project so that user of library need not be worry about library dependencies. I know how to include external jar files in normal android project. But i don't know how to include external jar files into my android library. Can any one to do this.
What is the proper way to do that. Need help. Thank you..

A: Each jar file is a zipped file and can be opened by winrar application. Extract the content of those jar files ( Folders and *.class files ) and add them into your jar file.

A: It's very simple. You can select the files that you want to export as jar. Check following image


text:
Q: Swift - why can't I append one Double array with another Double array I want to append this array
var rates  = [1.00, 0.98, 0.97, 0.90, 0.86, 0.84, 0.80, 0.79, 0.78, 0.77, 0.76, 0.76, 0.68, 0.66, 0.63, 0.61, 0.60, 0.60, 0.59, 0.57, 0.57, 0.55, 0.53, 0.53, 0.51, 0.51, 0.49, 0.48, 0.47, 0.46, 0.46, 0.46, 0.44, 0.44, 0.44, 0.43, 0.43, 0.43, 0.43, 0.43, 0.43, 0.43, 0.43, 0.43, 0.43, 0.43, 0.42, 0.42, 0.42, 0.42, 0.42, 0.42]

with this one
var ratesone  = [2.00, 1.98, 1.97, 0.99, 0.89]

under certain conditions
This code does not work
rates.append(ratesone)
This is error message - I have Googled this for days without satisfactory answer

'Cannot convert value of type '[Double]' to expected argument type
  'Double''

These are both Double arrays so why on earth is it trying to convert

A: Just join arrays using rates += ratesone

A: You're trying to append the entire array as a single entity ([2.00, 1.98, 1.97, 0.99, 0.89], of type [Double]), into an array whose members are Double (not [Double]).
You're looking for Array.append(contentsOf:), or more popularly, the += operator.


text:
Q: Laravel get an error when i try to upload image by ajax simply i can upload image with below codes. but after try to use the controller's action to upload image by ajax i get error:
Error:
Call to a member function move()

My codes:
{!! Form::open(['url' => 'registerToBuyCard', 'id' => 'register_to_buy_card','style'=>'text-align:left;','enctype'=>"multipart/form-data"]) !!}

    Passport Image
    {!! Form::file('passport') !!}

<button type="submit" class="btn btn-default">Submit</button>
</fieldset>
{!! Form::close() !!}

Ajax:
$("#register_to_buy_card").submit(function (event) {
    event.preventDefault();
    var $this = $(this);
    var url = $this.attr('action');

    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: $this.serialize(),
        success: function (data) {
            if (data.code == '1') {
                alert('thanks');
            } else
                apprise("" + data.message + "");
        },
        error: function (data) {
            apprise("" + data.message + "");
        }
    });
});

Controller action:
public function registerToBuyCard(Request $request)
{
    $file = $request->file('passport');
    $filename = $this->upload_image($file);
}
public function upload_image($filename)
{
    $destinationPath = base_path() . '/upload/';
    if ($filename->move($destinationPath, $filename))
        return $filename;
    else
        return false;
}

A: Problem Solved:
$("#register_to_buy_card").submit(function (event) {
    event.preventDefault();
    var $this = $(this);
    var url = $this.attr('action');
    var formData = new FormData(this);
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: formData,
        contentType:false,
        processData:false,
        success: function (data) {

        },
        error: function (data) {

        }
    });
});


text:
Q: Binding a usercontrol to SQL datatable I have a user control that is supposed to view some data from a SQL datatable. My database class is called DBManager it has a property called ResTable which is of type Datatable. It has data that is relevant to what is in my user control. Upon retrieval of the Table i want to instantiate a number of controls as the number of rows in the Datatable and bind each field with the corresponding one in the table. I know how to bind comboboxes but not usercontrols.
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Menupedia"
mc:Ignorable="d"
x:Class="Menupedia.RestaurantViewer"
x:Name="UserControl"
d:DesignWidth="640" d:DesignHeight="480" Width="330" Height="150">
<Grid x:Name="LayoutRoot" Width="330">
    <Label x:Name="label_Name" Content="" HorizontalAlignment="Left" Height="30" Margin="16,0,0,7" VerticalAlignment="Bottom" Width="72" FontFamily="Public Enemy NF" FontSize="14.667" Foreground="#FFEF7B54"/>
    <Image x:Name="image_Logo" HorizontalAlignment="Left" Margin="16,13,0,37" Width="100"/>
    <Label x:Name="label_Phone" Margin="0,61,122,59" FontFamily="Public Enemy NF" FontSize="14.667" Foreground="#FFEF7B54" HorizontalAlignment="Right" Width="42" Content="{Binding Hotline}"/>
    <ComboBox x:Name="combobox_Branch" Height="30" Margin="0,21,29,0" Style="{DynamicResource MPComboBox}" VerticalAlignment="Top" HorizontalAlignment="Right" Width="135"/>
    <Image Margin="126,55,0,59" Source="Images/Phone.png" Stretch="Fill" HorizontalAlignment="Left" Width="36"/>
    <Image Margin="120,13,164,0" Source="Images/Branch.png" Stretch="Fill" Height="46" VerticalAlignment="Top"/>
    <Label x:Name="label_labelCuisines" Content="Cuisine:" Height="30" Margin="125,0,150,25" VerticalAlignment="Bottom" FontFamily="Public Enemy NF" FontSize="14.667" Foreground="#FFEF7B54"/>
    <Label x:Name="label_Cuisines" Height="48" Margin="0,0,29,7" VerticalAlignment="Bottom" FontFamily="Public Enemy NF" FontSize="14.667" Foreground="#FFEF7B54" HorizontalAlignment="Right" Width="117"/>
</Grid>

The corresponding object of this usercontrol has no properties. I though have a class called Restaurant that have the same format as that of the Datatable i am using but i don't know how to fill it either.

A: You can make constructor of the user control take in parameters. You can then bind the controls of user controls to the passed parameters. Example:
 public partial class TestControl : UserControl
 {
    public TestControl()
    {
        InitializeComponent();
    }

    public TestControl(string name)
    {
        lblName.Content = name;
        InitializeComponent();
    }
 }

Use it as:
TestControl tc = new TestControl("Austin");


text:
Q: How does Google Drive (or other services) capture the Ctrl+F or Command+F input for a custom search box? Is it possible to create a custom "find" box similar to what Google Drive does upon pressing Command+F or Ctrl+F? I'm a complete noob and I'm not sure how to phrase this question better, I'm sorry!

A: They capture the keydown event on document and prevent the default action from occurring, doing their own thing instead:
document.addEventListener("keydown", function(e) {
    if (e.ctrlKey && (e.which || e.keyCode) == 70) {
        e.preventDefault();
        alert("Search!");
    }
}, false);

Live Example:

document.addEventListener("keydown", function(e) {
    if (e.ctrlKey && (e.which || e.keyCode) == 70) {
        e.preventDefault();
        alert("Search!");
    }
}, false);

Click here to focus the snippet's document, then press Ctrl+F

The event object the handler receives has a ctrlKey property which will have a truthy value if the ctrl key is down. On most browsers, it will also have a which property to say which key, but on some it's keyCode, so in the above I used the curiously-powerful || operator to use whichever one the browser provided.


text:
Q: How to change string of ^ type to char* type in vc++ CLR window application? I'm working on a vc++ CLR window application.In this application when I browse the local file system for file selection, the input file path is coming in string^ type ...now I want to change this ^ type to char* type. Help me. Thank you.

A: You probably want Marshal::StringToHGlobalAnsi
IntPtr p = Marshal::StringToHGlobalAnsi(managedString);
char* c = (char*)p.ToPointer();
...
Marshal::FreeHGlobal(p);

See msdn for more.


text:
Q: How to copy file and run script based on current date? Every day after midnight I have to copy log file from day before.
Log names are in format exYYMMDD.log. So today (22.10.2011) I would have to copy file named ex111021.log into some directory.
Is it possible to do it in batch script? If not I could use powershell but would prefer not as it is not installed on my server.
Edit:
With help of Siva Charan I created this (polish win7 - echo %date% prints YYYY-MM-DD)
set /a yest_Day = %date:~8,2%-%var:~-2,1%
copy ex%date:~2,2%%date:~5,2%%yest_Day%.log targetDir

A: Implement this way in Batch file.
Syntax of Copy Command:
copy sourcefilepath destinationfilepath

Example:
For today's date:
copy ex%date:~12,10%%date:~4,2%%date:~7,2%.log D:\

For yesterday's date:
set /a yest_Day = %date:~7,2%-%var:~-2,1%
copy ex%date:~12,10%%date:~4,2%%yest_Day%.log D:\

You have to provide proper file path before the file name ex111022.log / ex111021.log and destination too.
You can make a schedule for this batch file, which will run on daily basis.

A: In powershell :
$YesterdayfileName = [string]::format("{0:yyMMdd}", ((Get-Date).adddays(-1)))+".log
# today 22/20/2011 gives 111021.log

Copy-Item $YesterdayfileName c:\temp

A: are you looking for something like this?
http://www.pcreview.co.uk/forums/do-schedule-automatic-file-copy-t493716.html


text:
Q: Calling Octave interpolation function within function body I'm trying to wrap Octave interpolation function in a function body,
function FUN = inter(p);
    FUN = interpn (x1, x2, x3, x4, x5, A, p(1), p(2), p(3), p(4), p(5), "spline");
end

The reason why I'm doing this is because I'm using a package which function needs a string name function which would be in this case packageFunction("inter", argument1);
The issue is calling now for instance like,
  disp("value = "), inter([10 2 4 3 4])

doesn't work; Doesn't see the vectors error: 'x1' undefined ,
Of course the vectors xi and matrix A are defined above the function body. Would appreciate advice on this,
thanks, Damir
------------- in file example1.m
[a b c] = fminuit('gaussian','mnplot',[10 166 33],[x;y;dy])

------------- in file gaussian.m
function f = gaussian(par,data);
%theoretical function
f = par(1)/(sqrt(2*pi)*par(3)) * exp(-.5*((data(1,:)-
par(2))./par(3)).^2);
if (size(data,1)==2),    %chi-square, error = 1
  f = sum((data(2,:) - f).^2);
 elseif (size(data,1)>2), %chi-square, error = 3rd row of data
 f = sum(((data(2,:) - f)./data(3,:)).^2);
end

A: Given you are using an old function that requires a string as the function, the first solution below will not work. This is, however, the right way to do it. Changing the old function to use function handles instead of strings would be my preferred solution. However, you can also use an alternative solution further down below, which uses global variables. This is not the recommended approach (we should strive to avoid globals), but will solve your near-term problems.
Correct approach: use an anonymous function
You should use an anonymous function, these can capture variables when they're defined:
inter = @(p)interpn (x1, x2, x3, x4, x5, A, p(1), p(2), p(3), p(4), p(5), "spline");

Now inter(p) works just as if inter had been declared as a normal function. But the values of x1, x2, etc as they were defined when inter was defined will be stored inside inter.
As stated, the function you pass inter to must be written to accept function handles.
Bad, quick solution: use global variables
First, create a file inter.m with the following contents:
function FUN = inter(p);
    global x1 x2 x3 x4 x5 A
    FUN = interpn (x1, x2, x3, x4, x5, A, p(1), p(2), p(3), p(4), p(5), "spline");
end

Next, in your function of script that calls inter, again declare the global variables (currently MATLAB warns that you should declare them as globals before giving them a value, in future versions this will be required):
global x1 x2 x3 x4 x5 A
x1 = ...
x2 = ...
% etc

inter([10 2 4 3 4])
% or:
fminuit('inter',...)