text:
Q: detachable generic to generic in eiffel I have a feature with post-condition as follow:
checkValue (k: K): detachable V
do
...
end
ensure
some_post_condition:
    checkKey (Result)

And here is prototype of "checkKey":
checkKey (v: V): BOOLEAN

Since "Result" is type of "detachable V", and I try to pass that as parameter to "checkKey " which only accept type of "V" but not "detachable V", thus it cannot compile.
Here is what compile error says:
Argument name: v
Argument position: 1
Formal argument type: Generic #1
Actual argument type: detachable Generic #1

How can I convert detachable Generic to Generic?

A: There are several options:

*

*Change the type of checkValue from detachable V to V.

*Change the type of the argument of checkKey from V to detachable V.

*Change the postcondition to read

*

*if Result should always be attached
result_attached: attached Result
some_post_condition: checkKey (Result)

*if Result may be detachable (in which case it is considered valid):
some_post_condition: attached Result implies checkKey (Result)


text:
Q: CakePHP without mod_rewrite problems I've developed a website using CakePHP and I am now trying to host it on the live server. I couln't get much help from the hosting service, but I think they do not allow mod_rewrite (I get  500 server error whenever I try to turn it on).
So, I looked into using CakePHP without mod_rewrite. Now I can at least see the website, but I'm getting tons of errors, in particular:

*

*The css and js files are not found.

*There seems to be problems with the database, although it might be related to the problem above, I can't tell for sure.

The live website can be seen at new.enviro.lu.
The working website can be seen at enviro.webforall.be
Can anybody point me into the right direction to solve these problems?
I'm using CakePHP 1.3.4.

A: The problem with the CSS and JavaScript pages not showing is that you have Apache's DocumentRoot point to the wrong directory. The DocumentRoot should be /app/webroot, but you have it set to Cake's root directory. You can see that the paths work if you access http://new.enviro.lu/app/webroot/.
The database error on the page is:

Error: Database table content_pages for model ContentPage was not found.

This suggests that either the content_pages table has not been created as the error message says or the database configuration points at a wrong database.

A: Try contacting your hosting provider and ask them to turn mod_rewrite on for your account, or ask them how you can do it. CakePhp will not work without it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "config_get_device_record: failed to read blah-blah.plist" when iPhone is connected to Ubuntu I connect my iPhone to an Ubuntu computer just to charge it (without the need for any other actions), and my logs are spammed every second with
Apr 04 20:04:26 <user> usbmuxd[4610]: [20:04:26.345][1] config_get_device_record: failed to read '/var/lib/lockdown/<some long id>.plist': No such file or directory

I don't need to transfer any data, is there a way to stop this message from appearing whenever I charge my device?


text:
Q: ReactJS async rendering I am new with React and cannot write correct code for the situation. Let me explain in the code
class Test extends React.Component {
  render() {
    // IndexedDB indexes
    const ids = ['id1', 'id2', 'id3'];

    // fetch data and build a list
    const files = ids.map((id) =>
      localforage.getItem(id).then((entry) =>

      );
    );

    return (

{files}

    )
  }
}

What is the correct way to asynchronous load all data and display it?

A: You could do the asynchronous logic in the componentDidMount hook and use setState to put the entries in your state.
Example
class Test extends React.Component {
  state = { entries: [] };

  componentDidMount() {
    const ids = ["id1", "id2", "id3"];

    Promise.all(ids.map(id => localforage.getItem(id))).then(entries => {
      this.setState({ entries });
    });
  }

  render() {
    return (

        {this.state.entries.map(entry => (

        ))}

    );
  }
}


text:
Q: When pressure is exerted on parallel hydraulic pistons, do they start extending at the same time? If there are two hydraulic cylinders connected in parallel, each with a different load (shown in the picture below), will they start extending at the same time?
I'm having a disagreement with my tutor, he has told me that the cylinder with least resistance will fully extend, and only once it has fully extended will the other cylinder start to extend. I would have thought that both cylinders will start extending at the same time, and the cylinder with lower resistance will just extend faster. Much like parallel resistors in an electrical circuit.
The reason I think this is because there is still a net force on both cylinders. In the picture below, if the pressure of the system is 50000 Pa and the area of each cylinder is 0.03m^2, then there is a force of force of 1500N on the cylinders. Cylinder 1 has a load of 491N, and cylinder 2 has 981N, so cylinder 1 has a net force of 1009N, and cylinder 2 has 519N. So surely both cylinders will accelerate as there is a force on them?
Another reason I believe the tutor is wrong is that if the masses have very similar weights, say 50kg for cylinder 1 and 50.0000000000001Kg for cylinder 2, would they still only extend one at a time? If that is true then surely it is impossible for them ever to extend at the same time as no two weights will be exactly the same.
The only explanation I can think of to them extending one at a time is that the pressure relief valve (shown in the picture below, just to the left of the switch) plays some part. The pressure relief valve works exactly as the picture makes it look like it would. if the pressure of the fluid coming down the dotted pipe is enough to push the arrow so that it connect the above pipe and the reservoir, then water coming from the pump will flow straight to that reservoir. There is a spring that pushes the arrow to the right, so if that spring takes e.g 2000N to be compressed so that the arrow can connect to the reservoir, then this will prevent the system from ever having a higher pressure than 2000N. Everything else in the circuit is pretty self explanatory so I wont bother explaining what they do.
So please can somebody explain to me, in the diagram below If switch A is pressed down, will both cylinders start extending at the same time?

A: Based on your comments (that the exam question said "switch A is pressed"), the question can be answered - and the tutor was correct. The key is to look closely at the diagram, and observe that the lower halves of the compartments are connected together, as are the upper halves.

In this diagram, $p_1$ represents the driving pressure. Now across the piston on the left there is a pressure drop equal to the weight of the 50 kg mass divided by the area of the piston - let's call the pressure above the piston $p_2$. On the right, the same thing would lead to a pressure $p_3<p_2$ if the 100 kg object was getting lifted. But this pressure differential cannot exist while the two compartments are connected, so the right hand weight stays at the bottom - where it exerts a force of $50 g\ N$. This restores the balance of pressure and force.
Once the 50 kg weight reaches the top, the pressure against the end stop will result in a force of $50 g\ N$, and as that force increases, the force of the piston against the bottom of the right hand piston decreases until it, in turn, is lifted up.
All this assumes that the pressures at the top of both pistons are equalized by the tube joining them. It is hard to know from the diagram whether that is the case.
If the exit pipe represents essentially no resistance to fluid flow, then $p_2=p_3=1 atm$, and both pistons could be lifted at the same time.
However I'm pretty sure, given the way the diagram above is drawn, that this is not the case, and that my explanation above is the one your tutor had in mind.

A: Probably you have your question answered already, however, let me point out that:
You are incorrect.
You can't think of a hydrostatic system as it was an electric circuit. In an electric circuit what you (or the source) supply(ies) is the voltage and the result of that voltage acting upon the resistor of given resistance is the current. In hydrostatic systems what you (the source) supply(ies) is the fluid flow, not the pressure. If the hydrostatic pump is rated, say 200 bar what it really means that it can work with pressure (pressure difference really) up to 200 bar, it does not in any way mean that it supplies 200 bar of pressure.
As I said, what the pump supplies is flow, not pressure. If you had no cylinders in the system and the fluid would run directly back to the tank, the pressure would be, theoretically, 0 bar.
How it works is:
1. The pump pumps fluid into the system.
2. The flow is restricted due to the loads on the pistons.
3. Pressure rises up to the level required to move the piston with lower load up.
4. The first cylinder moves up.
5. The pressure is not enough to move the other piston, but it is not necessary to move at this point, because the first cylinder consumes all the flow that the pump provides.
6. The first cylinder reaches the top and it can move no more.
7. The fluid is still pumped into the system. The flow is restricted, so the pressure rises up to the leved required to move the cylinder with the bigger load.
8. The other cylinder moves up.
9. The other cylinder reaches the top
10. The pump still keeps pumping the fluid.
11. The flow is restricted, the pressure rises even higher up to the point at which...
12. The relief valve opens. The flow is redirected directly into the tank at this point.
In real world it works a bit different. There is no "0 bar" pressure. Everything is rescticting the flow, every piece of pipe or hose, every valve, fitting, etc creates what is called "pressure drop". There is also leakage. There is no cylinder, that will not let the fluid under pressure move from one chamber to another, it will always leak, the better the seal, the slower it will leak, of course, but you can never avoid that. There is also leakage in the pump. And also, the greater the pressure in the hydraulic system, the bigger the strain that is put on the motor that drives the pump and the RPM lowers (and since the flow supplied by the pump is directly proportional to its RPM, the flow lowers as well).
Hope that helped.
P.S. This probably will not help you at all, but if you wanted the pistons to move at once, you'd need what is called a proportional valve with load sensing function.

A: Initially, I agreed with Olaf Chujko's answer to this question; however, on further reflection, I think the most accurate answer is 'it depends':
Firstly, from the schematic that is given, when switch A is pressed, the cylinder volumes above the two cylinders will be vented to a reservoir at ambient pressure (trust me, I work in Oil & Gas and I look at schematics like this every day!).
The answer to the question will depend on the particular setup of the apparatus, specifically, it's a balance between how quickly the fluid can flow into the cylinder chambers (i.e. how restrictive the tubes/hoses are) and how fast the pistons can move.
The answer that Olaf gives is the situation where the pipes are very restrictive and the pistons have no friction: flow into the cylinders is small compared to the piston movement. Here, the cylinder pressure will increase relatively slowly. Once the pressure required to lift the smaller piston ($p_1$) is reached, that piston will start to lift and, as more fluid flows into the cylinder, the pressure will stay the same until the smaller piston has been completely lifted. The pressure will then continue to increase until the pressure required to lift the larger piston ($p_2$) is reached. Therefore, the larger piston will not start to move until the smaller one is fully lifted.
(btw, this is all assuming the piston diameters are equal).
The answer that Floris and Ross Millikan are supporting represents the other extreme, where the fluid will flow into the cylinders much more quickly than the pistons can move. For example, consider a high-pressure source with large, relatively smooth hoses and the case where the pistons have a large amount of friction, so their maximum speed is very limited. Here, the pressure in both cylinders will increase to be equal to the supply pressure very quickly, so (assuming $p_s>p_2$) both pistons will lift simultaneously. However, the smaller piston will always start to move a short time before the larger one, because in a real fluid system pressure has to increase at a finite rate - you can't have a step change.
tldr: either answer could be correct, depending on the exact setup of the system.

A: You are correct.  Each cylinder has a hydraulic force applied at the bottom that is sufficient to accelerate its mass upward.  The one with the lighter mass will accelerate more rapidly and reach the top of travel more quickly, but the other will already be moving.

A: piston with lesser resistance will move first. that is correct. because these two pistons are connected to same pressure source and pressure will build gradually and not spontaneous. i.e. the pressures inside both cylinders gradually increase from 0 to a value where less resistance piston starts move. once this moves pressure will not increase further until that piston reaches dead end. because if there is no resistance, there is no pressure.


text:
Q: Writing various implementations of Stack class in C++ I've recently taken a course in Data Structures in Java and I can write various structures and implement them in various ways in Java easily. I'm currently transferring this knowledge to the world of C++ which is a little different. I currently wrote a header file for a Stack interface (like you would writing an interface in Java for Stack) and I want to implement it in various ways (linked lists, array, vector, etc.) so I can master the idea of implementing structures in any language. The problem I'm currently having with C++ is understanding the notion of using pointers in my Stack and references (E&) plus making sure I can write various source implementations of Stack.h. Here is my current stack header...
/*
 * File: stack.h
 * -------------
 * Interface file of the Stack class. Follows a last-in/ first-out (LIFO) order. Includes contracts for the method bodies of Stack.
*/

#ifndef _stack_h
#define _stack_h

/*
 * declaration of Stack using template with type E for any data type or object using the Stack structure.
 *
 */

  template <typename E>
  class Stack {

    public:

    //constructor blank
    Stack();

    //destructor
    ~Stack();

    //constructor with integer size
    Stack(int);

    //number of items in stack.
    int size() const;

    //is stack empty?
    bool empty() const;

    //top element of stack
    const E& top() const throw(StackEmpty);

    //push e onto the stack.
    void push(const E& e);

    //remove top element from stack
    void pop() throw(StackEmpty);

    //pop and return.
    E popReturn();

    //returns a string form of stack.
    std::string toString();
};

// Error exception
class StackEmpty : public RuntimeException {
    public:
       StackEmpty(const std::string& err) : RuntimeException(err) {}
};

#endif

Sorry for the formatting! :)
Currently I'm working on the Array and Linked List implementation of this stack. I understand that a header file creates a link between files it is included in. I want to insure that when I create a stack for testing I can use both implementations I wrote with this header. I'm also not sure if I should use the keyword virtual or not to make an official interface. I know in java when you declare an implementation for Stack you would use
Stack test = new ArrayStack();

Is that the same for C++ to use a globalized header file and use different implementations of this Stack? Also this code is burrowed from a Data Structures book in C++ but sadly the authors do not say to make these interfaces a header file or not, and where to include that error checking exception for an empty stack. I just placed it in this file. C++ hasn't been a great language to me but I know that if I wanna build larger projects like Compilers, games, audio/ video players, OS, and writing an IDE for a new language that this and C are important to master. Please give me any insight to my current situation if possible I would greatly appreciate it. If anyone also can explain pointers and references in C++ I would greatly accept the knowledge. I believe the E& is a reference but the book didn't specify. Thank you! :)
P.S. this is what I thought would work for C++ for using different implementations of a header....
#include "stack.h"

Stack test = new ArrayStack();
Stack test2 = new LinkedStack();

A: Your code has a number of problems.
template <typename E>

Unless you honestly need run-time polymorphism (which you almost certainly don't in this case) you want to pass the underlying storage you're going to use as a template parameter instead of using inheritance:
template <typename E, typename Container = std::vector<E> >

This way, you can avoid (for example) virtual function calls for elementary operations that really don't need it.
//constructor blank
Stack();

You probably don't need to declare this default constructor at all. (See below in the comments about the other constructor you declared).
//destructor
~Stack();

If you're going to use Stack as a base class as you seem to be suggesting, then you want to make the destructor virtual.
//constructor with integer size
Stack(int);

Unless you really want to use an underlying container with a fixed size, there's no real need to specify the size here. If you want to specify a size anyway, I'd probably provide a default value (which is part of what renders the preceding default constructor declaration irrelevant) so you end up with something like this: Stack(int size = 20);
//top element of stack
const E& top() const throw(StackEmpty);

This is bad. Dynamic exception specifications like your throw(StackEmpty) turned out to be a mistake. They've been deprecated for a while now, and will probably disappear soon1. In addition, if you're going to use inheritance, most of these interface functions should probably be virtual (probably pure-virtual).
//push e onto the stack.
void push(const E& e);

This is all right, but if you want to get the most out of C++, you probably want to add an overload that takes an rvalue reference as well.
//remove top element from stack
void pop() throw(StackEmpty);

This dynamic exception specification has the same problem as above.
//pop and return.
E popReturn();

This has a serious design flaw--if E's copy constructor throws an exception, it will (unavoidably) destroy data. There are two fairly well-known ways to avoid this problem. One is to just eliminate it and require the user to write code like:
Foo f = myStack.top();
myStack.pop();

This way, if the copy constructor throws, myStack.pop() never executes. The other well known possibility is something like:
void pop(E &dest) {
    dest = top();
    pop();
}

Either way, we end up with exception safe code--either it completes (and the value is transferred from the top of the stack to the destination) or else it fails completely (and the data remains on the stack), so there was no effect.
//returns a string form of stack.
std::string toString();

In C++ this is normally named to_string.
// Error exception
class StackEmpty : public RuntimeException {
    public:
       StackEmpty(const std::string& err) : RuntimeException(err) {}
};

The standard already defines std::runtime_error. It's probably better to use that until/unless you know C++ well enough to know exactly what you want to do differently.
Also note: if you take the initial advice and make your stack a pure template instead of trying to use inheritance, many of the other comments become moot.
In the end, a stack class for C++ can end up more like this:
template <class T, class C = std::vector<T> >
class Stack {
    C data;
public:
    void push(T const &t) {
        data.push_back(t);
    }

    T top() const {  return data.back(); }

    void pop(T &d) {
        if (data.empty())
            throw std::runtime_error("Attempt to pop empty stack");
        d = data.top();
        data.pop_back();
    }

    bool empty() const { return data.empty(); }
};

You've indicated that you want to test it with different underlying containers. Here's how you'd do it with three standard containers:
#include "stack.h"
#include <vector>
#include <list>
#include <deque>
...
// These two are equivalent:
Stack<int, std::vector<int>> vs;
Stack<int> vs1;

Stack<int, std::list<int>> ls;
Stack<int, std::deque<int>> ds;

1. Yes, Java copied this mistake almost intact, then managed to actually make it even worse by adding tight coupling, which destroys one of the biggest advantages of exception handling to start with. About all I can say is: that hurts; don't do it any more.

A: I'm not going to comment on the quality, usability, correctness, or "C++-ness" of that stack. To any (C++) programmer, it'd be painfully obvious that a Java programmer wrote that stack class, which might be fine in Java, but there are far better ways in C++.
What I'm going to do is try and answer your question about interfaces and using them, in relation to include files. (Again, let me emphasize that the stack class itself is not good.)
What you might want to do is have a "stack.h", with content similar to this:
template <typename E>
class Stack
{
public:
    // These are *usually* useless in an abstract interface
    // Stack();
    // ~Stack();
    // Stack(int);

    // Every concrete class inheriting from this class must implement all these:
    virtual int size() const = 0;
    virtual bool empty() const = 0;
    virtual const E& top() const throw(StackEmpty) = 0;
    virtual void push(const E& e) = 0;
    virtual void pop() throw(StackEmpty) = 0;
    virtual E popReturn() = 0;
};

Now, you might have a "vector_stack.h" like this:
#include "stack.h"

template <typename E>
class VectorStack
    : public Stack<E>
{
public:
    VectorStack() {...}
    virtual ~VectorStack() {...}
    Virtual VectorStack(int) {...}

    virtual int size() const override {...}
    virtual bool empty() const override {...}
    virtual const E& top() const throw(StackEmpty) override {...}
    virtual void push(const E& e) override {...}
    virtual void pop() throw(StackEmpty) override {...}
    virtual E popReturn() override {...}
};

You'd do the exact same thing with any other implementation you want to do.
Now, in the code file that you want to use all these, you do this:
#include "VectorStack.h"
#include "ListStack.h"
#include "WhateverStack.h"

...
// I apologize to all C++ programmers, for not using unique_ptr<>!
Stack<int> * s1 = new VectorStack<int>;
Stack<int> * s2 = new ListStack<int>;
Stack<int> * s3 = new WhateverStack<int>;
...
...
// Don't forget to delete if you use raw pointers; you're
// not in Kansas anymore!
delete s3;
delete s2;
delete s1;

But this is not very "C++", not to mention flexible or efficient. Specially in this case, for containers like a stack. But if you insist on that interface (in the general sense,) this is probably what you have to do.
Oh, and don't forget to #include the headers that you use, such as <string>. And note that if you want those exception specifications (don't do it!) the declaration for your exception class must go before the declaration of your class.
(By the way, I'm pretty sure it's the popReturn method that throws, not pop.)


text:
Q: Three.js OBJLoader .obj model not casting shadows I'm working on a project where I wish to allow a .OBJ model loaded from OBJLoader.js to cast a shadow from a spotlight. The light will cast shadows from other normal objects, but the .OBJ will not seem to cast shadows.
A possible symptom to the problem is as follows:
When these normal objects are created when clicking on the floor, they are entered into the array Objects[], which in turn makes them clickable to add objects on top of themselves. The .OBJ model is also added to this array, however I cannot click it to add models on top of it; as if the raycaster is not detecting it.
I'll include all of the code, as the problem may lie somewhere unforeseen.
A working link is available HERE
http://www.powertrooper.com/3D/demos/issues/OBJShadows
Try Clicking on the floor to see how other objects do cast shadows.
Anyone have any ideas? Mr.Doob? Are you out there? :)
ps: I have no idea why in my browser, the link I have left is directing to a malware site called "4safe.in". Try copying and pasting the link I guess...
Just in case- here's a snippet of code that includes most of what is likely causing the problem.
    renderer.shadowMapEnabled = true;///////////////////////////////////////////// RENDERER /// <------------Renderer and lights set up to cast shadows
    light.castShadow = true;
    light.shadowDarkness = 1;
    renderer.shadowMapSoft = true;
    floor.receiveShadow = true;

    var texture = new THREE.Texture();
    var loader = new THREE.ImageLoader();
    loader.addEventListener( 'load', function ( event ) {

        texture.image = event.content;
        texture.needsUpdate = true;

    } );
    loader.load( 'modeltest/ash_uvgrid01.jpg' );

    // model

    var loader = new THREE.OBJLoader();
    loader.addEventListener( 'load', function ( event ) {

        var newModel = event.content;

         newModel.traverse( function ( child ) {

             if ( child instanceof THREE.Mesh ) {

                 child.material.map = texture;

            }

         } );

        newModel.position.set (200,30,0);
        newModel.castShadow = true;///////////////////////////// <------ This doesn't seem to be working.
        scene.add( newModel );
        objects.push( newModel );/////////////////////////////// <------ The other HINT: because of this, the raycaster SHOULD allow us to click the model and create a new block. But we can't.

    });

    loader.load( 'modeltest/male02.obj' );

A: Each child mesh of your object must have castShadow set to true.
newModel.traverse( function ( child ) {

    if ( child instanceof THREE.Mesh ) {

        child.material.map = texture;
        child.castShadow = true;

    }

} );

To get raycaster.intersectObjects() to work with your object, you need to set the recursive flag to true.
var intersects = raycaster.intersectObjects( objects, true );

three.js r.57


text:
Q: How can I detect keydown or keypress event in angular.js? I'm trying to get the value of a mobile number textbox to validate its input value using angular.js. I'm a newbie in using angular.js and not so sure how to implement those events and put some javascript to validate or manipulate the form inputs on my html code.
This is my HTML:

        Mobile Number
        <input type="text" id="mobile_number" placeholder="+639178983214" required
           ngcontroller="RegisterDataController" ng-keydown="keydown">

And my controller:
    function RegisterDataController($scope, $element) {
       console.log('register data controller');
       console.log($element);
       $scope.keydown = function(keyEvent) {
        console.log('keydown -'+keyEvent);
       };
    }

I'm not sure how to use the keydown event in angular.js, I also searched how to properly use it. And can i validate my inputs on the directives? Or should I use a controller like what I've done to use the events like keydown or keypress?

A: Update:
ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.

<input ng-keypress="count = count + 1" ng-init="count=0">

<input ng-keypress="changed($event)">

Read more here:
https://docs.angularjs.org/api/ng/directive/ngKeypress
https://docs.angularjs.org/api/ng/directive/ngKeydown
https://docs.angularjs.org/api/ng/directive/ngKeyup
Earlier solutions:
Solution 1: Use ng-change with ng-model
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController" ng-change="keydown()">

JS:
function RegisterDataController($scope) {
   $scope.keydown = function() {
        /* validate $scope.mobileNumber here*/
   };
}

Solution 2. Use $watch
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController">

JS:
$scope.$watch("mobileNumber", function(newValue, oldValue) {
    /* change noticed */
});

A: You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress
(also Enter key, backspace key, alter key ,control key)
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

A: JavaScript code using ng-controller:
$scope.checkkey = function (event) {
  alert(event.keyCode);  //this will show the ASCII value of the key pressed

}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />

You can now place your checks and other conditions using the keyCode method.

A: You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step.  Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it.  That's where "directives" come into play.  You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.
The following is an example of how you would do that.  We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):
var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
             // this next line will convert the string
             // function name into an actual function
             var functionToCall = scope.$eval(attrs.ngKeydown);
             elem.on('keydown', function(e){
                  // on the keydown event, call my function
                  // and pass it the keycode of the key
                  // that was pressed
                  // ex: if ENTER was pressed, e.which == 13
                  functionToCall(e.which);
             });
        }
    };
});

The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it.  In the html you would have the following:
<input type="text" on-keydown="onKeydown">

And then in your controller (just like you  already had), you would add a function to your controller's scope that is called "onKeydown", like so:
$scope.onKeydown = function(keycode){
    // do something with the keycode
}

Hopefully  that helps either you or someone else who wants to know


text:
Q: CMake error - Target foo INTERFACE_SOURCES property contains path which is prefixed in the source directory I'm trying to create a C++ library that can be re-used via CMake.  It's failing when I try to install the export files for the project.  I don't understand why.  Here's the error I get.
Target "Proj_LibA" INTERFACE_SOURCES property contains path:

  "C:/projects/cmake_temp/src/libA/include/liba.hpp"

which is prefixed in the source directory.

Reading the CMake documents and this other stackoverflow post imply that there's something wrong with how I setup source file paths and/or the include directory.  Here's a SSCE that reproduces my issue.
Folder structure
cmake_temp/
          /build
          /install
          /src/
              /CMakeLists.txt
          /src/libA/
                   /include/liba.hpp
                   /CMakeLists.txt
                   /liba.cpp
                   /LibAConfig.cmake.in

/src/CMakeLists.txt
cmake_minimum_required (VERSION 3.15)
project("TestProj")

set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)

set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")

set(include_install_dir ${CMAKE_INSTALL_PREFIX}/include/)
set(export_cmake ${CMAKE_INSTALL_PREFIX}/cmake)
set(lib_install_dir ${CMAKE_INSTALL_PREFIX}/lib)
set(bin_install_dir ${CMAKE_INSTALL_PREFIX}/bin)

add_subdirectory(libA)
#add_subdirectory(exec)

liba/include/liba.hpp
#ifndef liba
#define liba

#include "LibA_export.hpp"

class PROJ_LIBA_EXPORT Foo
{
public:
    Foo(const int bias);
    int add(int a, int b);
private:
    int mBias;
};

#endif //liba

src/liba/liba.cpp
#include "liba.hpp"
Foo::Foo(const int bias) : mBias(bias) {}
int Foo::add(int a, int b) { return a + b + mBias; }

src/liba/CMakeLists.txt
# Setup alias to support add_subdirectory, find_package, and fetchcontent usage
add_library(Proj_LibA SHARED)
add_library(proj::liba ALIAS Proj_LibA)
set_target_properties(Proj_LibA PROPERTIES
    EXPORT_NAME LibA
    POSITION_INDEPENDENT_CODE TRUE)

target_sources(Proj_LibA
    PUBLIC
        include/liba.hpp
    PRIVATE
        liba.cpp)

target_include_directories(Proj_LibA
   PUBLIC
      $<INSTALL_INTERFACE:${include_install_dir}>
      $<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>
      $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
   #PRIVATE
)

# Generate symbol export macros and add to source
include(GenerateExportHeader)
set(export_file "${CMAKE_CURRENT_BINARY_DIR}/LibA_export.hpp")
generate_export_header(Proj_LibA EXPORT_FILE_NAME ${export_file})
target_sources(Proj_LibA PUBLIC ${export_file})

# Install everything and mark it as part of the 'sdk' export package
install(TARGETS Proj_LibA
   EXPORT sdk
   ARCHIVE DESTINATION ${lib_install_dir}
   LIBRARY DESTINATION ${lib_install_dir}
   RUNTIME DESTINATION ${bin_install_dir}
)

# Install header files for package consumers
INSTALL(DIRECTORY include/ DESTINATION ${include_install_dir})

# Create the LibAConfig.cmake file for find_package
include(CMakePackageConfigHelpers)
configure_package_config_file(LibAConfig.cmake.in
  ${CMAKE_CURRENT_BINARY_DIR}/LibAConfig.cmake
  INSTALL_DESTINATION ${export_cmake}
  PATH_VARS include_install_dir)

# Create the LibAConfigVersion.cmake file for find_package
write_basic_package_version_file(
  ${CMAKE_CURRENT_BINARY_DIR}/LibAConfigVersion.cmake
  VERSION 1.2.3
  COMPATIBILITY SameMajorVersion )

# Install the LibAConfig*.cmake files
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/LibAConfig.cmake
              ${CMAKE_CURRENT_BINARY_DIR}/LibAConfigVersion.cmake
        DESTINATION ${export_cmake})

# Install the auto-generated export support/find_package scripts
install(EXPORT sdk
   DESTINATION ${export_cmake}
   NAMESPACE proj::)

# HELP: The above command triggers the following errors
#CMake Error in libA/CMakeLists.txt:
#  Target "Proj_LibA" INTERFACE_SOURCES property contains path:
#
#    "C:/projects/cmake_temp/src/libA/include/liba.hpp"
#
#  which is prefixed in the source directory.
#
#
#CMake Error in libA/CMakeLists.txt:
#  Target "Proj_LibA" INTERFACE_SOURCES property contains path:
#
#    "C:/projects/cmake_temp/build/libA/LibA_export.hpp"
#
#  which is prefixed in the build directory.

src/liba/LibAConfig.cmake.in
set(LibA_VERSION 1.2.3)

@PACKAGE_INIT@

set_and_check(LibA_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@")

check_required_components(LibA)

Does anyone have suggestions on what I should look at to troubleshoot this error when trying to export my library?

A: I also hit this problem yesterday. Reading through docs and a blog post of "co-maintainer of CMake" helped to shed some light on this (tldr; see the Complications For Installing paragraph).
The issue here comes from from your liba.hpp being added as a PUBLIC target source, which defines an absolute path to your header file. This is valid in your build tree on your local machine, but likely to be different when it is installed, using find_package() or copying your library into another source tree. I think a lot of people, including myself, make assumptions that PUBLIC or INTERFACE is associated with a public header file, which is not the case. Quote from the blog post above:

[...] do not confuse the PRIVATE , PUBLIC and INTERFACE keywords with whether a header is part of the public API for the library or not, the keywords are specifically for controlling which target(s) the sources are added to

Just like in the SO link that you gave (same as in your code) the answer points to BUILD_INTERFACE and INSTALL_INTERFACE generator expressions to fix this problem for an include directory. One possible solution is to be more explicit and use same expressions in your target_sources()
target_sources(Proj_LibA
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/liba.hpp>
        $<INSTALL_INTERFACE:include/liba.hpp>
    PRIVATE
        liba.cpp)

This is arguably not a very pretty solution as this has to be done for each header file. Another option is to simply move your headers into the PRIVATE scope. Yet another one is to use PUBLIC_HEADER target property to define your headers and specify an install destination, I haven't actually tried this, but see this SO.


text:
Q: JavaFX - Wait for user to click mouse on element I am implementing a game and I want to ask the player to click on a specific view.
I want my control thread to wait until I get a value back (I have clicked on the view and handled the result). Currently I am doing this by creating a thread, running a method that asks them to click and then entering a while loop that is terminated when the mouse click event changes a variable used in the while loop.
I am writing a game where I have a thread constantly receiving events. On a specific event, I want to prompt the user for a response, but to do this would require me to be on the JavaFX thread (to my knowledge).
Is there a better way of doing this in JavaFX? Thanks!

A: There are several tools "hidden" in the JDK documentation on threads that can help you resolve this type of issue. Usually when we make a routine code wait for some condition that can proceed we use threads synchronizers.

I want my control thread to wait until I get a value back [...]

CountDownLatch, CyclicBarrier and FutureTask may be classes that can solve your problem. The functionality of these is quite simple. They have the function of stopping threads and release them when some condition is met. The difference in each of these classes is just semantics applied for termination and release threads. Read the documentation of each and see which one is most comfortable to you.
You can also take a look at other sources of study. There is no better source of study in the world (in my opinion) than the content within the book "Java Concurrency In Practice" by Brian Goetz. I assure you that you will become able to easily manipulate threads if you buy this book (or at least gain an incredible knowledge on the subject). Make it clear that you do not need to buy the book to solve your current problem. Buying the book is just my suggestion for you to have more knowledge about threads. You probably will solve your problem by looking at the documentation of classes that synchronize threads I mentioned.
Good luck in your projects. ;)


text:
Q: Filtering data from one sheet to another in excel I need to have data stored on one sheet like a database, and then one displayed on another sheet based filtered by product. I am not familiar with visual basic at all, yet my boss tasked me with this project.
Basically we have a variable name, variable type, and a product that those will be associated with. New names, types, and even products will most likely be added in the future. I can't seem to find a solution online that will allow me to filter on one page while pulling data from another.
This is how the data sheet looks like at the moment. This was the best way we could think of for future expansion of the data sheet as multiple products would be associated with one new variable.
Name | Type | Product | Product | Product...|
test | var  | Product |         | Product   |
test2| txt  | Product |         |           |
test3| char |         | Product | Product   |

I hope this makes sense and if anyone can help that would be great. Below is some code we have found online and have tried to modify it to work with no luck.
Dim myButton As OptionButton
Dim MyVal As Long
Dim ButtonName As String
Dim sht As Worksheet
Dim myField As Long
Dim DataRange As Range
Dim mySearch As Variant

'Load Sheet into A Variable

  Set sht = ActiveSheet
  ThisWorkbook.Sheets("Sheet3").Activate

'Unfilter Data (if necessary)
  On Error Resume Next
    sht.ShowAllData
  On Error GoTo 0

'Filtered Data Range (include column heading cells)

  Set DataRange = sht.Range("A1:Z1000") 'Cell Range
  'Set DataRange = sht.ListObjects("Table1").Range 'Table

'Retrieve User's Search Input
  mySearch = sht.Shapes("UserSearch").TextFrame.Characters.Text 'Control Form
  'mySearch = sht.OLEObjects("UserSearch").Object.Text 'ActiveX Control
  'mySearch = sht.Range("A1").Value 'Cell Input

'Loop Through Option Buttons
  For Each myButton In ActiveSheet.OptionButtons
      If myButton.Value = 1 Then
        ButtonName = myButton.Text
        Exit For
      End If
  Next myButton

'Determine Filter Field
  On Error GoTo HeadingNotFound
    myField = Application.WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0)
  On Error GoTo 0

'Filter Data
  DataRange.AutoFilter _
    Field:=myField, _
    Criteria1:="=*" & mySearch & "*", _
    Operator:=xlAnd

'Clear Search Field
  sht.Shapes("UserSearch").TextFrame.Characters.Text = "" 'Control Form
  'sht.OLEObjects("UserSearch").Object.Text = "" 'ActiveX Control
  'sht.Range("A1").Value = "" 'Cell Input

Exit Sub

'ERROR HANDLERS
HeadingNotFound:
  MsgBox "The column heading [" & ButtonName & "] was not found in cells " & DataRange.Rows(1).Address & ". " & _
    vbNewLine & "Please check for possible typos.", vbCritical, "Header Name Not Found!"

End Sub

A: The closest that I've used was actually a kinda clunky equation:
Hidden_Sheet: Hidden table
B5978: Product Filter
$A$2:$A$5997: Full range on hidden table where 'Product filter' will look. I don't think you can make it simply $a:$a.
$E$2:$E$5997: Value you want to return
$A$2: This does need to change in each row of your final sheet (i.e. "$A$2," $A$3," etc.).
=IF(B5978=0,"",IFERROR(INDEX(Hidden_Sheet!$E$2:$E$5997,SMALL(INDEX((B5978=Hidden_Sheet!$A$2:$A$5997)*(MATCH(ROW(Hidden_Sheet!$A$2:$A$5997),ROW(Hidden_Sheet!$A$2:$A$5997)))+(B5978<>Hidden_Sheet!$A$2:$A$5997)*1048577,0,0),ROW(Hidden_Sheet!$A$2))),""))


text:
Q: How to pass the row and column instead of the value in a custom Google Sheets function? function calculateIntervall(note) {//The passing argument gives me the value of the cell with the note, NOT the column or row of particularly this cell
  var spreadsheet = SpreadsheetApp.getActive();
  var col = spreadsheet.getActiveCell().getColumn();//get the column of note anyhow?
  var row = spreadsheet.getActiveCell().getRow();//get the row of note anyhow?
  note = spreadsheet.getCurrentCell().offset(row, col).activate().getNote();//get the value of the note
  return col + row;
};

This is just an example program, that explains my question the best. The current program returns the sum of the row and the column of the active cell (the cell with the function). But I need the sum of the parameters of the cell with the note.
I just want to have the row and the column kinda like this (using the standard functions):
=ROW(note)
=COLUMN(note)

The functions usually look like this:
=ROW(A5) -> this returns 5
=COLUMN(C2) -> this returns 3

A: The typeof() parameters to custom functions varies. For example:
function custom_function(p) {
    return typeof(p);
}

=custom_function(A1:A1)   // returns "number" or "string" depending upon value is in the single cell A1.
=custom_function(B1:B2)   // returns "object" - a 2 dimenstional array representing the values in the cells in the range.
=custom_function("C1:C1") // returns "string" - representing "C1:C1"

As the last shows, you can pass in a string, representing a range, which you can then process as you require within the function:
function custom_function(cell) {
    if(!cell.map && (typeof(cell === "string"))) { // not an array or a number
       var range = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(cell);
       var column = range.getColumn();
       var row = range.getRow();
       return "c: "+column+" r: "+row;
    }
    else {
      return "Invalid Parameter";
    }
}

There is a fuller discussion about passing range values into custom functions at https://webapps.stackexchange.com/questions/10629/how-to-pass-a-range-into-a-custom-function-in-google-spreadsheets
Including solutions to the problem that if a range reference is passed in as a string your can't then copy the cell containing =custom_function("C1:C1") and have the cell references automatically updated.
Update to address the comment: a fairly simple way to be able to copy a custom function around with automatically updated cell references is shown below.
=custom_function(A1:C3; ROW(A1); COLUMN(A1); ROW(C3); COLUMN(C3))

So in the actual GAS script function now has 5 parameters: parameter-1 is a 2-dimensional array of the cell values, p2 and p3 are the row and column of the top left hand side of the array and p4 and p5 are the row and column of the bottom right hand side of the array.
Or if you don't actually care about the values, or are happy to re-create the range in the custom function using the co-ordinates simply:
=custom_function(ROW(A1); COLUMN(A1); ROW(C3); COLUMN(C3))


text:
Q: Error 18456 loggin on a SQL Server 2016 I had an unexpected system crash and had to setup SQL Server 2016 again. I can connect to the server from SSMS if I use a Windows authentication account, but not via any login created. I keep getting an error 18456:

Login failed for user 'sa'

Steps:

*

*I have enabled SA login and gave it a password but cannot connect via SSMS

*I have created another login and matched it to my project database, the project database now has the login under its users but again, I cannot log in.

*SSMS is installed on the actual db server so I doubt this is a remote login issue, but as the db server is isolated from the actual site I would like to update this if needed.
Any ideas would greatly be appreciated!

A: Did you enable the mixed mode authentication?
Did you restart SQL services after changing the mixed mode authentication?
Some of the server level properties takes only after a SQL restart , one such is authentication modes.

A: Usually a SQL Service problem.
Start - > View Local Services -> SQL Server(SQLEXPRESS) > restart it


text:
Q: Set Identity_insert on - Merge Replication I have merge replication set up between two databases and am using identity ranges on both.
I want to add a specific row to a merged table (setting the identity value to something outside of the identity range) on the publisher.  When I try this, I get the following error.

The insert failed. It conflicted with an identity range check
  constraint in database 'xxx', replicated table 'dbo.yyy', column
  'yyy_id'. If the identity column is automatically managed by
  replication, update the range as follows: for the Publisher, execute
  sp_adjustpublisheridentityrange; for the Subscriber, run the
  Distribution Agent or the Merge Agent.

Is there a way to force specific identity value into a merge replicated table that is using identity range management?

A: One way is to ensure that each node in the replication topology is using a different range of identity values, so that duplicates do not occur.

For example, the Publisher could be
  assigned the range 1-100, Subscriber A
  the range 101-200, and Subscriber B
  the range 201-300. If a row is
  inserted at the Publisher and the
  identity value is, for example, 65,
  that value is replicated to each
  Subscriber. When replication inserts
  data at each Subscriber, it does not
  increment the identity column value in
  the Subscriber table; instead, the
  literal value 65 is inserted. Only
  user inserts, but not replication
  agent inserts cause the identity
  column value to be incremented.

Ref. Replicating Identity Columns

A: I have resolved by increasing Automatic insert by increasing 20000 row .
Helpful blog added here


text:
Q: Finding the range of launch speeds for which water shot from a hose will enter a tank a distance away
A water hose is used to fill a large cylindrical storage tank of diameter $D$ and height $2D$. The hose shoots the water at $45^\circ$ above the horizontal from the same level as the base of the tank and is a distance $6D$ away. For what range of launch speeds $v_0$ will the water enter the tank. Ignore air resistance.

I've made a graphic representing the problem (with $D=1$) showing the trajectory of the water at the minimum launch speed $v_{0\text-m}$ (blue) and maximum launch speed $v_{0\text-M}$ (red) as well as the tank (light gray):

Clearly I've made a mistake in solving for the minimum launch speed - I expect the blue parabola to intersect the rectangle at its top left vertex. I'm not sure where the mistake lies, because as far as I can tell I've used the same approach to solve for $v_{0\text-m}$ as I had for $v_{0\text-M}$, which I'll show first.
The position vector for water particles escaping the hose has components
$$\begin{cases}
x=v_{0\text-M}\cos45^\circ t\\
y=v_{0\text-M}\sin45^\circ t-\frac g2t^2
\end{cases}$$
With $x=7D$, solve for $t$ in the first equation, substitute into the second with $y=2D$ to get
$$t=\frac{7D}{v_{0\text-M}\cos45^\circ}\implies2D=v_{0\text-M}\sin45^\circ\left(\frac{7D}{v_{0\text-M}\cos45^\circ}\right)-\frac g2\left(\frac{7D}{v_{0\text-M}\cos45^\circ}\right)^2$$
$$\implies5=\frac{49Dg}{v_{0\text-M}^2}\implies v_{0\text-M}=7\sqrt{\frac{Dg}5}$$
Now to find $v_{0\text-m}$, the only change in the work above - I would think - would be to set $x=6D$.
$$t=\frac{6D}{v_{0\text-m}\cos45^\circ}\implies2D=v_{0\text-m}\sin45^\circ\left(\frac{6D}{v_{0\text-m}\cos45^\circ}\right)-\frac g2\left(\frac{6D}{v_{0\text-m}\cos45^\circ}\right)^2$$
$$\implies2=\frac{12Dg}{v_{0\text-m}^2}\implies v_{0\text-m}=\sqrt{6Dg}$$
Manipulating the code for the plot of the blue parabola, it would appear the correct answer for $v_{0\text-m}$ is closer to $3\sqrt{Dg}$. How can I salvage my attempt to obtain the right solution?

A: Minor algebraic mistake...
$$2D=v_{0\text-m}\sin45^\circ\left(\frac{6D}{v_{0\text-m}\cos45^\circ}\right)-\frac g2\left(\frac{6D}{v_{0\text-m}\cos45^\circ}\right)^2$$
should reduce to
$$2D=6D-\frac g2\frac{36D^2}{v_{0\text-m}^2\cos^245^\circ}\implies4D=\frac{36D^2g}{v_{0\text-m}^2}\implies v_{0\text-m}=3\sqrt{Dg}$$
At some point I decided to divide through all terms by $2D$ except for one, which I had mistakenly divided by $3D$ instead.

A: The equation of trajectory of water jet is $y = x-\dfrac{g}{v^2} x^2$. Let $x$ and $y$ be coordinates of any point in water jet at a height of $2D$. So water to fall we must have $6D < x < 7D$.  By putting $y = 2D$ in above equation we get quadratic in $x$ as $\dfrac{g}{v^2} x^2 - x +2D = O$. Discard negative value of $x$ take only positive value then put value of $x$ in above inequality and solve you will get
$$\sqrt{9gD} < v < \sqrt{9.8gD}$$


text:
Q: Probability of Failure in System I was a given a question and its supposed solution, but I'm getting to a different result in the end. Please let me know if my reasoning is correct.

Consider the following system. The failure probability of each
  component is mentioned on the figure and we assume that the failures
  of the components are independent of each other.

Assume that the failure probability of component A is equal to $x$.
  What is then the failure probability of the system (as a function of
  $x$)?

I reasoned it's easier to think of the probability of failure as $1 - P\left( W \right)$, where $P(W)$ is the probability that it works flawlessly.
So, since in order for the system to work, each of the components must work,
$$\eqalign{
  & 1 - P\left( W \right)  \cr
  & P\left( F \right) = 1 - P\left( W \right) = 1 - \left( {1 - 0.25} \right)\left( {1 - 0.1} \right)\left( {1 - 0.3} \right)\left( {1 - x} \right)  \cr
  & P\left( F \right) = 1 - \left( {0.75} \right)\left( {0.9} \right)\left( {0.7} \right)\left( {1 - x} \right)  \cr
  & P\left( F \right) = 0.5275 + 0.4725x \cr} $$
While the solution shows

I experimented multiplying it to open the expression and it seems indeed a different one.

A: My assumption that all of them need to work was the problem; it turns out it's not a condition for the system to work.


text:
Q: Ada: gnat gprbuild How to link in libraries? In this multi-language GPRBuild project I'm working on, I have some c++ library files (*.a) I need to link into my executable. Is there an gpr attribute to tell it what to link in or anyway to pass -l -L switches to the linker?

A: Within the main project file,
package Linker is
   for Default_Switches ("Ada") use ("-L/where/ever", "-lbar");
end Linker;

A: Or even better:
Project my_library is
  For externally_built use "true";
  For library_dir use "/where/ever";
  For library_name use "mylibname";
  For source_dirs use (); -- no sources.
  For library_kind use "static";
  -- if it is a static lib .a

  -- for library_kind use "dynamic";
  -- if it is an so.
End my_library;

And in the application project.
   With "my_library.gpr";


text:
Q: When to use ClientAliveInterval versus ServerAliveInterval I'm connecting to a linux server (GoDaddy dedicated server) via SSH to compress incremental backups either via a tar cvfj or tar cvf to make .tar.bz2 or .tar files, respectively.
I've started to run into "Broken pipe" errors when compressing larger backup folders and found these three posts that address how to fix this issue:

*

*What options `ServerAliveInterval` and `ClientAliveInterval` in sshd_config exactly do?

*What does the Broken pipe message mean in an SSH session?

*https://askubuntu.com/questions/127369/how-to-prevent-write-failed-broken-pipe-on-ssh-connection/354245#354245
However, what I still can't quite see is whether I need to make an adjustment on my server using the ClientAliveInterval directive or on my computer using the ServerAliveInterval. Are those two used interchangeably and it's just up to what I prefer to do?
I added a config file to my .ssh folder on my computer with the following:
ServerAliveInterval 30
ServerAliveCountMax 1200

I also checked the /etc/ssh/sshd_config file on my server which had the following in it:
#ClientAliveInterval 0
#ClientAliveCountMax 3

Which I changed to this:
ClientAliveInterval 60
ClientAliveCountMax 3

I then ran another compression of a large backup folder and I didn't get the "Broken pipe" error. But I'm just wondering now if I need both adjustments—the one on my computer and the one on the server. Or if I can make do with just one of the two. And if so, which one.
Thanks so much!
Jutta

A: Either setting should do it.
You specify this on the server so that it affects all clients that connect via ssh or on the client so that it affects the client only.
If you do not use more than one computer to ssh into your server, setting it on the client would be enough.


text:
Q: Disable Delete for specific records of inline form Django Admin I have a stacked inline form in my admin.py:
class XYZInline(admin.TabularInline):

   model = XYZ
   readonly_fields = ['modify', 'approver_page']
   form = XYZForm
   extra = 0

And I have it initialized in another model on the admin.py:
class SomeOhterModelAdmin(admin.ModelAdmin):
    inlines = [XYZInline]

What I want to do is disable the Delete checkbox in the Inline form for specific form records after checking the value of some of the inputs on the records of the form. If a certain input value matches, we disable the checkbox, otherwise we don't. How can we do this? And how can we check for input values of some of the fields of the form?
Some stackoverflow examples suggest adding a self.can_delete=False to the form initializer method. However, that would disable delete for all the form records of the Inline model.


text:
Q: Count number of button clicks in given time JButton btnNewButton = new JButton("CLICK ME!");
btnNewButton.setBounds(134, 142, 274, 77);
btnNewButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {
    clicked++;
    String x=Integer.toString(clicked);
    textArea.setText(x);
    }
});

I'm stuck here I want to create a program in GUI that counts the number of button click in specific time for example the timer start then count the number of clicks when the loop stop the button click is not working or stop counting the clicks

A: There are two possible solution
1.Make the button clickable when timer starts and unclickable when timer stops
Or
2.also u can use flag to check whether timer is running Or not.If timer is running make flag true when gets over make it false. Somthing like below snipet
public void actionPerformed(ActionEvent e) {
if (flag) {
    clicked++;
    String x=Integer.toString(clicked);
    textArea.setText(x);
 }
else
{
 // doSomething
}
}

A: You can have some boolean variable which says if it's time for clicking (set on true when timer is started and on false when time's up). Then count clicks when this variable is true:
public void actionPerformed(ActionEvent e) {
    if (timeIsRunning) {
        clicked++;
        String x=Integer.toString(clicked);
        textArea.setText(x);
    }
}

A: https://stackoverflow.com/a/9413767/1306811
Have a click counter.
private int clickCounter = 0; // as an example

Create get/set methods for it.
Add a MouseListener to your JButton so you can effectively track click events (MouseEvent arg0, arg0.getClickCount(), etc). At the end of each call to mouseClicked increment the clickCounter (clickCounter += arg0.getClickCount(), as an example).
Modify the answer linked so that clickCounter is set to 0 at every "time step" (however long you want it to be).
Voila.


text:
Q: If $t=\tanh\frac{x}{2}$, prove that $\sinh x = \frac{2t}{1-t^2}$ and $\cosh x = \frac{1+t^2}{1-t^2}$.
If $t=\tanh\frac{x}{2}$, prove that $\sinh x = \frac{2t}{1-t^2}$ and $\cosh x = \frac{1+t^2}{1-t^2}$. Hence solve the equation $7\sinh x + 20 \cosh x = 24$.

I have tried starting by writing out $\tanh\frac{x}{2}$ in exponential form and then squaring it but I can't make any progress from this.

A: $$\sinh(x)=2\sinh(\frac x 2)\cosh(\frac x2)=\dfrac 2{\dfrac{\cosh^2(\frac x2)-\sinh^2(\frac x2)}{\sinh(\frac x 2)\cosh(\frac x2)}}=\frac 2{\dfrac1 {\tanh(x/2)}-\tanh(x/2)}=\frac{2t}{1-t^2}$$
$$\tanh(x)=\frac{2\tanh(x/2)}{1+\tanh^2(x/2)}=\frac{2t}{1+t^2}$$
$$\cosh(x)=\frac{\sinh(x)}{\tanh(x)}=\frac{1+t^2}{1-t^2}$$
Hence:
$$7\sinh(x)+20\cosh(x)=24$$
$$44t^2+14t-4=0$$

A: Note that
(i) tanh($x$) = sinh(x) / cosh($x$)
(ii) 1 - tanh$^2(x$) = 1/ cosh$^2(x$)
(iii) sinh($x + y$) = sinh($x$)cosh($y$) + sinh($y$)cosh($x$)
and apply these to the term
$\frac{2t}{1 - t^2}$ with $t =$ tan($x/2$) to directly obtain your result for sinh($x$). The formula for cosh$(x)$ follows then directly by applying (i) again.

A: Let $t$=$tanh$$\frac{x}{2}$.
Using Identity $sech^2$$\frac{x}{2}$=1-$t^2$
$cosh^2$$\frac{x}{2}$=$\frac{1}{1-t^2}$
$cosh$ $x$=2$cosh^2$$\frac{x}{2}$-1
$cosh$ $x$ =2 ($\frac{1}{1-t^2}$)-1
$cosh$ $x$=$\frac{1+t^2}{1-t^2}$ is obtained by simplifying the above.
Using another identity $cosh^2$$\frac{x}{2}$-$sinh^2$$\frac{x}{2}$=1
$sinh^2$$\frac{x}{2}$=$cosh^2$$\frac{x}{2}$-1
$sinh^2$$\frac{x}{2}$=($\frac{1}{1-t^2}$)-1
$sinh $$\frac{x}{2}$=$\frac{t}{\sqrt(1-t^2)}$
$sinh$ $x$=2$cosh$$\frac{x}{2}sinh$$\frac{x}{2}$
$sinh$ $x$=$\frac{2t}{1-t^2}$ is obtained by simplifying the above.
Moving to the 2nd part after replacing with $t$ in the equation, you will get
12$t^2$+17$t$-2=0.From here I guess you should solve for $t$. You will get something in terms of $\sqrt385$. What you can do is replace it in  $cosh$ $x$ and simplify by $x$ = $\underline+$$ln$($x+\sqrt{1+x^2}$). I have not tried it but still I hope it helps.


text:
Q: Show that the kernel of the adjoint representation of a connected Lie group is its center. Let $G$ be a connected Lie group with Lie algebra $\mathfrak g$. I'm trying to proof the following assertion:

the kernel of the adjoint representation of $G$ coincides with its center.

What I have done so far:
Let's recall that $Ad: G \to Aut(G)$ is given by $Ad(g) = d(Inn_g)$ where $Inn_g(h) = ghg^{-1}, \, h \in G,$ is the inner automorphism.
For the first one, if $g \in Z(G)$, then $gh = hg$ for all $h \in G$ what implies that $Inn_g (h) = ghg^{-1} = h = id_G(h)$. Hence
$$ Ad(g) = d(Inn_g) = d(id_G) = id_G $$
and so $g \in \ker Ad$. I'm stuck in the converse of this assertion. Well, if $g \in \ker Ad$ we have that $Ad(g) = id_G$ and, since $G$ is connected, $G$ is spanned by $\exp [\mathfrak g]$. However I can't proceed from this.
Help?

A: Assume that $Ad_{g}$ is trivial, and let $h$ be an arbitrary element of $G$ of the form $h=exp(v)$. We will first show that $g\cdot h=h\cdot g$.
1) Show that $t\mapsto g\cdot exp(tv)\cdot g^{-1}$ is a one-parameter subgroup of $G$. Its velocity at time zero is given by $Ad_{g}(v)=v$, using that $Ad_{g}=Id_{\mathfrak{g}}$.
2) But also $t\mapsto exp(tv)$ is a one-parameter subgroup of $G$ whose velocity at time zero is $v$. Since one-parameter subgroups are uniquely determined by their initial velocity, we have
$$
g\cdot exp(tv)\cdot g^{-1}=exp(tv).
$$
In particular, for $t=1$ we get $$g\cdot h \cdot g^{-1}=h,$$
so
$$
g\cdot h = h \cdot g
$$
Now, since $G$ is connected, any element $h$ of $G$ can be written as
$$
h=exp(v_{1}) \cdots exp(v_{k})
$$
for some $v_{1},\ldots,v_{k}\in\mathfrak{g}$. Using what we just proved, we have
\begin{align}
g\cdot h &= g\cdot exp(v_{1})\cdot exp(v_{2}) \cdots exp(v_{k})\\
&=exp(v_{1})\cdot g \cdot exp(v_{2})\cdots exp(v_{k})\\
&= \cdots\\
&=exp(v_{1})\cdots exp(v_{k})\cdot g\\
&=h\cdot g
\end{align}


text:
Q: Optimal Value & Uniform Distribution In a simple setting, $w$ is uniformly distributed on $[0,1]$, R is a function of $wd$.
I want to find optimal d in this expression,
$aR-(d^2-1)/2$.
When I try to find out optimal $d$ than it is $0$. But i think I am ignoring the fact that $R$ is a function of $wd$ but what form it is, is not known. Does this change the solution of this problem.
Guidelines will be appreciated.
Thanks

A: If $R$ is a function of $wd$ then presumably $\mathbb{E}[aR]$ is not a constant,
so its derivative of with respect to $d$ is not zero,
with the consequence that your second and third lines are not helpful.
To actually find optimal $d$, you will have to know what optimal means here, what the function $R$ is, and possibly some information about $a$.
Added: As an example, suppose $R=wd$, $a$ is positive and you want to maximise the expectation $\mathbb{E}\left[aR-\frac{d^2-1}{2}\right]$.
Then the first derivative with respect to $d$ of the expectation is $\frac{a}{2}-d$, and the second derivative is negative, so the maximum occurs when $d=\frac{a}{2}$ in which case the expectation would be $\frac{a^2}{8} + \frac{1}{2}$.


text:
Q: Different SUM values on Postgres vs RedShift So assume I have a list of values like so

+---------------+
| hours_worked  |
|---------------|
| 2.08333333333 |
| 2.08333333333 |
| 2.65          |
| 4.93333333333 |
| 5.08333333333 |
| 5.08333333333 |
| 5.7           |
| 6.3           |
| 7.05          |
| 7.23333333333 |
| 7.28333333333 |
| 7.31666666667 |
| 7.63333333333 |
| 8.33333333333 |
+---------------+

When I sum them up in Postgres, I get this

+-------------------+
| sum               |
|-------------------|
| 76.68333333333331 |
+-------------------+

However when I sum the exact same value in Redshift, I get this

+---------------+
| sum           |
|---------------|
| 78.7666666667 |
+---------------+

I manually added them and the Redshift summation is more accurate. Why does this discrepancy occurred?

A: At first I thought this was a case of floating point arithmetics. I would then have suggested to try other datatypes in PostgreSQL, e.g., numeric.
But I don't think this is the issue anymore. I'm pretty sure you have not given postgres the same data as redshift. In postgres, the following produces 78.76666666664:
select sum(q.hours) from (
    select 2.08333333333 as hours union all
    select 2.08333333333 union all
    select 2.65 union all
    select 4.93333333333 union all
    select 5.08333333333 union all
    select 5.08333333333 union all
    select 5.7 union all
    select 6.3 union all
    select 7.05 union all
    select 7.23333333333 union all
    select 7.28333333333 union all
    select 7.31666666667 union all
    select 7.63333333333 union all
    select 8.33333333333
) as q

Based on the numbers it looks like you were not adding one of the first two entries 2.08333333333. Removing on of them you get 76.68333333331, same as your first test.


text:
Q: Http Callout doesn't return the latest data Http callout is not returning the latest json response.
Below is the code used for calling Rest based web service. But it doesn't return the latest response. It takes time for the data to get updated. If we call the same service after 10 min the latest data is returned.
Prior to calling the get request we are calling Put request.
/*** Method to Get all Contracts from External system
public HttpResponse getHttpCall()
{
    System.debug(' ---------------- Inside getHttpCall --------------');
    Http httpProtocol=new Http();
    HttpRequest request=new HttpRequest();
    String endpoint='http://orbservice.com/customers';
    request.setEndPoint(endpoint);
    request.setMethod('GET');
    HttpResponse response=new HttpResponse();
    response=httpProtocol.send(request);
    return response;
}


text:
Q: Convert internal table to csv dump I use the function module SAP_CONVERT_TO_CSV_FORMAT but I have the following runtime error UC_OBJECTS_NOT_CHARLIKE.
The field that causes the error is a type I.
What should I do avoid the short dump?
CALL FUNCTION 'SAP_CONVERT_TO_CSV_FORMAT'
    EXPORTING
      i_field_seperator    = ';'
      i_line_header        = 'X'
    TABLES
      i_tab_sap_data       = p_csv1
    CHANGING
      i_tab_converted_data = gt_row
    EXCEPTIONS
      conversion_failed    = 1
      OTHERS               = 2.


text:
Q: Generating 5 random numbers with a given limit N, along with per random value constraint Program that gets a user input N and finds 5 random integers following the below 2 constraints:
(a) the minimum and maximum value for each random value:

(i)   25 ≤ random_val_1 ≤ 30
(ii)  25 ≤ random_val_2 ≤ 30
(iii) 17 ≤ random_val_3 ≤ 20
(iv)  5 ≤ random_val_4 ≤ 10
(v)   8 ≤ random_val_5 ≤ 10

(b) sum(random_val_1, random_val_2, random_val_3, random_val_4, random_val_5) should be equals N
The output should be in the following form:
[ <int> random_val_1, <int> random_val_2, <int> random_val_3, <int> random_val_4, <int> random_val_5 ]

I was able to generate random values and only pass the residue of the given input N to the remaining random values to satisfy constraint (b) but not (a)

A: We can see that for the given values, generating all possible solutions and randomly picking one won't take much time, as there are atmost (30 - 25 + 1) * (30 - 25 + 1) * (20 - 17 + 1) * (10 - 5 + 1) * (10 - 8 + 1) = 2592 possibilities.
For generating the numbers, we can observe that N cannot be less than the sum of all minimum constraint at each index. We can use this fact to recursively reduce the search space and generate the numbers.
Here's an implementation in C++.
Note that we can move the "random generation part" for picking the value at each index, instead of randomly picking one from all possible solutions, as in the former case, on average the runtime would be faster than the latter method (depending on the random generation method used).

A: So N is between 80 and 100. If N is 80 there is nothing to sample, same if N=100.
If N is set to something in the range [81...99], then find mean values M1, M2, M3, M4, and M5 still within the constrain (a) and summed to N.
Then find probabilities
p1 = M1/N, p2=M2/N, ...
Then use your favorite Multinomial distribution sampling routine with probabilities p1, p2, ...p5, and N as sum, and reject any sample that violates (a).
(b) would be satisfied automatically cause of distribution properties


text:
Q: Multidimensional array update I am trying to update each language as a multidimensional array to another multidimensional array but it seems to be only saving the last key e.g.(lang_3) but not lang_1 & lang_2. Cracking my head to figure this out. Hope someone can point out my faults. ($country_specs = list of language, $get_code = country code)
    $awards = array(
        'award_year'           => sanitize_array_text_field($_POST['award_year']),
        'award_title_user'      => sanitize_array_text_field($_POST['award_title_user']),
        'award_description_user'   => sanitize_array_text_field($_POST['award_description_user'])
        );

    foreach ($country_specs as $specs => $value) {
    if ($value[0] == $get_code ) {
        foreach ($value['lang'] as $lang_key => $lang) {

            $awards_title = 'award_title_'.$lang_key;
            $awards_description = 'award_description_'.$lang_key;

            $awards_lang = array(
                $awards_title       => sanitize_array_text_field($_POST[$awards_title]),
                $awards_description   => sanitize_array_text_field($_POST[$awards_description])
                );

            update_user_meta($user_id, 'awards', array_merge($awards,$awards_lang));
                }
            }
        }

Current code output example:

Array (
          [award_year] => Array (
                              [0] => 1999-01
                              [1] => 2010-02 )
          [award_title_user] => Array (
                              [0] => 2
                              [1] => tt )
          [award_description_user] => Array (
                              [0] => 2
                              [1] => ddd )
          [award_title_lang3] => Array (
                              [0] => 2CC
                              [1] => zz )
          [award_description_lang3] => Array (
                              [0] => 2CCCCCCC
                              [1] => dzz ) )

A: Working code as follows.

  $awards = array(
        'award_year'           => sanitize_array_text_field($_POST['award_year']),
        'award_title_user'      => sanitize_array_text_field($_POST['award_title_user']),
        'award_description_user'   => sanitize_array_text_field($_POST['award_description_user'])
        );
    $awards_new_lang = array();
    foreach ($country_specs as $specs => $value) {
    if ($value[0] == $get_code ) {
        foreach ($value['lang'] as $lang_key => $lang) {
            $awards_title = 'award_title_'.$lang_key;
            $awards_description = 'award_description_'.$lang_key;
            $awards_new_lang[$awards_title]         = sanitize_array_text_field($_POST[$awards_title]);
            $awards_new_lang[$awards_description]   = sanitize_array_text_field($_POST[$awards_description]);
                }
            }
        }
        $array_merge_new = array_merge($awards, $awards_new_lang);
    update_user_meta($user_id, 'awards', $array_merge_new);

I created a new array ($awards_new_lang) and did an array merge with the old array, thus combining both of the arrays together.

A: Try this code, it outputs as expected, I tried the mimic the variables structures
<?php
$awards = array(
    'award_year'           => '1999',
    'award_title_user'      => '2',
    'award_description_user'   => '2CCCCCCC'
);

$value = array();
$value['lang'] = array(1, 2, 3);

foreach ($value['lang'] as $lang_key) {

    $awards_title = 'award_title_'.$lang_key;
    $awards_description = 'award_description_'.$lang_key;

    $awards_lang = array(
        $awards_title       => "$lang_key title",
        $awards_description   => "$lang_key desc"
    );
    //array merge returns an array, we save the changes here to use them later when the loops are through
    $awards = array_merge($awards,$awards_lang);
}
echo '<pre>';
//Final updated version of the array
var_dump($awards);
echo '</pre>';
?>

Outputs:
array(9) {
  ["award_year"]=>
  string(4) "1999"
  ["award_title_user"]=>
  string(1) "2"
  ["award_description_user"]=>
  string(8) "2CCCCCCC"
  ["award_title_1"]=>
  string(7) "1 title"
  ["award_description_1"]=>
  string(6) "1 desc"
  ["award_title_2"]=>
  string(7) "2 title"
  ["award_description_2"]=>
  string(6) "2 desc"
  ["award_title_3"]=>
  string(7) "3 title"
  ["award_description_3"]=>
  string(6) "3 desc"
}


text:
Q: r convert data frame to list of lists Given the following data frame:
Date       Person   Article
---------------------------
01-01-2015 Bob      TV
01-01-2015 Bob      Video
01-01-2015 Pete     Book
02-01-2015 Rob      Skate
02-01-2015 Kate     TV

How could I convert this data frame to a list of list (or multidimensional array) so, that
my_ist[[01-01-2015]][[Bob]]

would give
TV, Video

?

A: What about this?
res <- lapply(split(df, df$V1), function(x) sapply(split(x, x$V2), function(y) y$V3))
res[["01-01-2015"]][["Bob"]]
[1] "TV"    "Video"


text:
Q: probability of repeated events I have a website and I want to calculate the probability of clicks on the ads.
Let the probability that each user clicks on a link be p (something like 1%)
if we have totally N users, What is the formula that computes the probability of exactly  n clicks?
of course we have

0< = n <= N

Each users can click only once

A: Consider each user as a trial. For every trial you have two outcomes, they are success (clicks on ad) and failure (does not click on ad). $P[success] = p $ and $P[failure] = 1-p$.
The total number of ways in which $n$ users can be selected from $N$ users is $\binom{N}{n}$. So, the probability of exactly $n$ clicks is $\binom{N}{n}*p^n*(1-p)^m$ where $m = N-n$, as the clicks are independent and exactly $n$ clicks mean exactly $N-n$ 'not clicks'.


text:
Q: Warning: preg_replace(): Unknown modifier '�' Another question that has been asked a million times, but I'm stuck here.
I'm getting the following error Warning: preg_replace(): Unknown modifier '�' for this line
$tweetText = preg_replace('@(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i','\0', $tweetText);

All I'm trying to do is retrieve a tweet from Twitter(successfully done) but replace the text urls with actual hyperlinks so the user can just click them instead of copy/paste.
The only reason I'm at a loss is because the error is listing � so I hadn't got a clue as to which character in that line is wrong.
Any help?

A: When I paste your code into hexed.it I see all kind of extraneous characters right after the ending @ delimiter:

Re-type @' and you should get rid of those non-printable chars.

A: Using the link that @Wiktor Stribiżew provided I was able to see 4 characters that were hidden. Removed them and the error is gone.


text:
Q: Bayesian updating of regression coeffieients I have two data sets, let's say A & B. I have an OLS regression model prepared by using dataset A, and now I want to update this model by using new dataset B.
Bayesian updating can be one way to update such model with the given formula:

here the defined parameters are :
 and  are the parameter vectors of the estimation context models and the locally estimated models respectively;  and  are corresponding vectors of variance in estimation and application contexts.
Here I am not able to understand what should be the terms,  and . Are they variances of the predicted valules by the models?


text:
Q: Intent filter for files only in our app, we want to appear in the "Share via" menu. So we added this intent-filter to our activity :
<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="application/*" />
    <data android:mimeType="audio/*" />
    <data android:mimeType="image/*" />
    <data android:mimeType="text/*" />
    <data android:mimeType="video/*" />
</intent-filter>

It works and our app appears in the Share menu.
Nevertheless, the intent filter doesn't do exactly what we want to achieve :

*

*we want to appear in the menu for all files, whatever there mime type is

*we want to appear only for files. And up to now, if the user wants to share a simple text, as its mime type will be text/plain, our app appears in the menu and we don't want it.

What would the correct intent-filter be for all files and only for files ?
Thanks in advance.

We tried to add scheme=file and host="" or "*" and it doesn't work as many app use a scheme=content to share file based content.

A:
we want to appear in the menu for all files, whatever there mime type is

Try a MIME type of */*.

we want to appear only for files. And up to now, if the user wants to share a simple text, as its mime type will be text/plain, our app appears in the menu and we don't want it. We tried to add scheme=file and host="" or "*" and it doesn't work as many app use a scheme=content to share file based content.

Then have two <data> elements, one for a scheme of content and one for a scheme of file.
<data android:mimeType="*/*" />
<data android:scheme="content" />
<data android:scheme="file" />

However, bear in mind that a content scheme does not mean that it is necessarily a file.

A: *

*If you want to be invoked for any mime type, don't place a single mine type in the filter

*scheme="file" is the answer to run only on files. Now if the 3rd party applicaiton pass the data as content, then it is (by defiinition) not a file any more


text:
Q: Understanding TypeScript Sequelize I am studying TypeScript for Bacend development and I came along this backend git project repo that uses Sequelize library. I have researched about this topic but there are varying examples with different code format. I am particularly confused with this code snippets
export class Sale extends Model<SaleAttributes, SaleCreationAttributes>
    implements SaleAttributes {
    .
    . *removed other codes*
    .
    // possible inclusions
    declare readonly products?: Product[];

    // associations
    declare static associations: {
        products:  Association<Sale, Product>;
    }

    static associate (models: Models) {
        this.belongsTo(models.Product, {
            as: "product",
            foreignKey: {
                name: "productId",
                allowNull: false
            }
        });
    }
}

Complete File Link
What is the use of the declare static associations and static associate in this context? Also, if I have OneToMany relationship, should I change Associate<Sale,Product> to HasMany<Sale,Product> or changing this.belongsTo to this.hasMany will suffice?


text:
Q: Excel data model - add records to existing table inside data model I have a table inside Excel data model, created by importing a csv file. The M code is this:
let
Parameters_Table = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
FilePath = Parameters_Table{5}[Value],
Source = Csv.Document(File.Contents(FilePath),[Delimiter=",", Columns=7, Encoding=1252, QuoteStyle=QuoteStyle.None]),
#"Renamed Columns" = Table.RenameColumns(Source,{{"Column1", "claim_id"}, {"Column2", "person_id"}, {"Column3", "date"}, {"Column4", "amount"},
{"Column5", "treatment_days"}, {"Column6", "text_short1"}, {"Column7", "text_short2"}}),
#"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns",{{"date", type date}, {"amount", type number}, {"treatment_days", Int64.Type}})
in
#"Changed Type"

The Excel file is given to a colleague, without the source csv file. Some pivots are inside and he can play with them without any issues. Now, I want to give him an update csv file, having a couple of rows only, which should be added to the existing table inside data model.
I created a new query with the update csv file and then I tried a Table.Combine (append query) with the original table and the update table, but this approach needs the source csv file. I also tried Table.InsertRows into original table, but I'm getting a circular reference.
Is there any way to accomplish this, adding rows to a table without having the source csv file?
Adrian

A: When refreshing Power Query, it needs to get all sources, I would import the source CSV into Excel as a new table (copying and pasting it in, not just letting  it be a loaded table) and reference that in a new Query (delete the source CSV query since  your colleague won't  have access to it) and append to it the new table or file that your colleague needs to add.


text:
Q: What is wrong with this NSMutableArray? @interface PINQuote : NSObject
@property (nonatomic, strong) NSMutableArray *lines;
@property (nonatomic, strong) NSString *quoteID;
@property (nonatomic, strong) NSString *customerName;
@end

When I try:
    PINQuote *quote = [[PINQuote alloc] init];
    [quote.lines addObject:@"TEST STRING"];
the array is still nil.
Any ideas?

A: add the following to the implementation:
- (NSMutableArray *)lines
{
    if (!_lines) // Lazy load the mutable array when asked for.
        _lines = [NSMutableArray array];
    return _lines;
}

or if you don't like lazy loading:
- (id)init
{
    self = [super init];
    if (self) {
        _lines = [NSMutableArray array]; // Eager load the mutable array.
    }
    return self;
}

A: You have only declared the property. You must now create it. Try lazy instantiation:
PINQuote.m
- (NSMutableArray*)lines {
    if (!_lines)
        _lines = [NSMutableArray array];
    return _lines;
}


text:
Q: SAS: Interesting Excel Import discrepancy I'm importing a file from excel which looks like this:
Row Col Bucket
1   2   01
2   2   00

%Macro ImportExcel(DF = , OF = , Type = , SheetName = );

proc import datafile = &DF
out = &OF dbms = &Type replace;
sheet = "&Sheetname";
run;

%Mend;
%ImportExcel(DF = "C:\Users\89974114\Documents\Book1.xlsx" , OF = Book1 ,     TYPE = xlsx , SheetName = Sheet1);

when I import the file the dataset looks like this
Row Col Bucket
1   2   1
2   2   0

Essentially, I lose my custom format from excel and it reverts to the no default, no leading zero's format - is there a way around this?

A: I don't know of a way to apply informats when using proc import - it's kind of a blunt instrument. You could simply add a short data step inside your macro like:
[proc import block]

data &OF ;
  set &OF ;
format Bucket z2.;
run;

%Mend;

Or, if you want to convert it to a character string, change the format line to BucketC = put(Bucket,z2.);
EDIT: Of course, the superior way is to use PROC DATASETS to modify the format, but that was too obvious for my dumb brain.


text:
Q: Polyline calls an Image in setTag My codes for polyline.
Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
            .clickable(true)
            .add(
                    new LatLng(-35.016, 143.321),
                    new LatLng(-34.747, 145.592),
                    new LatLng(-34.364, 147.891),
                    new LatLng(-33.501, 150.217),
                    new LatLng(-32.306, 149.248),
                    new LatLng(-32.491, 147.309))
.width(10)
.color(Color.Red)
);
polyline1.setTag(" ");

Can I put/call Images in this setTag?
polyline1.setTag(" ");


text:
Q: how to copy a dashboard in a different azure devops instance? I have a requirement to copy an existing dashboard dashboard in an org(source org) to a different org(target org) under a different ado instance by any means possible. Dashboard can have widgets and widgets can be linked to

*

*pipeline

*Query - A query can be referencing to a user, team, project, custom values of a standard field, custom fields

*some other things that i have not encountered so far

So far my steps are as follows

*

*get dashboard details using get dashboard rest api

*identify widgets in dashboard details api response

*get any pipeline if there is no pipeline create a dummy one and use its details for a widget that is using pipeline

*identify distinct queries present in all widgets

*create its equivalent query in target org and save its id

*replace  queryid  in widget settings to its equivalent created queryid in targetorg

*create dashboard in target org

I am facing issue in step 5
There are lot of moving variables in a query. Query might be referencing to things that does not exist in target org like a particular user, team, custom values of a standard field, custom fields. In order to create a query successfully i need to know possible values of a field in target org.  While creating a new query from ui it shows possible values for a field in dropdown so i am wondering is there any rest api that gives possible values of a field and if no such field exist in target org then it should throw error.
Looking forward to suggestions for a simpler or alternative approach to replicate a dashboard across different ado instance and/or better approach for step 5

A: If you are looking for a rest api the query the fields in your target process of the organization, you could refer to this doc. Field-list.
GET https://dev.azure.com/{organization}/_apis/work/processes/{processId}/workItemTypes/{witRefName}/fields?api-version=6.0-preview.2
After that, you could create the fields in your target process, you could refer to this rest api. Fields-Create
POST https://dev.azure.com/{organization}/_apis/work/processdefinitions/{processId}/fields?api-version=4.1-preview.1
Or could you share more details of your requirement, like screenshots and widget definition or dashboards configuration for update.


text:
Q: Python: Tell if the argument passed to a function is a constant or is a variable I want to create a function that would behave differently depending on how the input is passed to it.
For example:
def my_func(a):
   if is_constant_input(a): # Does something like this conditional exist?
      print(f"A constant input {a} was passed")
   else:
      print(f"A variable input {a} was passed")

then I call the function in two ways.
First way:
val = [1, 2, 3]
my_func(val) # A variable input [1, 2, 3] was passed.

Second way:
my_func([1, 2, 3]) # A constant input [1, 2, 3] was passed.

I want to know if there's a way to implement that is_constant_input() conditional?
EDIT: fixed the example by using an mutable argument (e.g., a list)


text:
Q: Manipulating textarea when using ajax to get data Hi all I'm using the following code to add data to my text area-
$('a#mod_description_onclick').click(function(){
    $('#MOD-DESCRIPTION').modal('show', {backdrop: 'static'});
    $.ajax({
        url: "tab.description.php",
        success: function(response){
            $('#MOD-DESCRIPTION .modal-body').html(response);
        }
    });
})

and the following code to count the characters when typing-
$(document).ready(function(){
    var left = 2000
    var txtrest = '<?php echo lang("SYSTEM_CHARECTERS_LEFT");?>';
    $('#text_counter').text(txtrest + ' ' + left);

        $('#field-ta').keyup(function () {

        left = 2000 - $(this).val().length;

        if(left < 0){
            $('#text_counter').addClass("overlimit");
             $('#submit_description').attr("disabled", true);
        }
        if(left > 1950){
            $('#text_counter').addClass("overlimit");
             $('#submit_description').attr("disabled", true);
        }
        else{
            $('#text_counter').removeClass("overlimit");
            $('#submit_description').attr("disabled", false);
        }

        $('#text_counter').text(txtrest + ' ' + left);
    });
});

To help here is the contents of my tab.description.php file that is called by the ajax to get data from my mysql and refresh the contents of the textarea.
<textarea  rows="5" maxlength="2000" class="form-control " id="field-ta" name="field-ta" >
   <?php echo get_profile_value('5001') ?>
</textarea>

So my problem is the following if I hard-code the textarea instead of using the ajax method  my character counter works. or in other words updating my modal form with ajax stops my character counter from working .
Where could the problem be?
Thanks

A: The problem is that the character counter is triggered by keyup event, but using ajax doesn't emit the keyup event

A: I don't believe that using AJAX triggers keyup events - only actually typing into the text field will trigger that. I'm not sure what the best solution is, though this should work:
function countChars = function () {
    left = 2000 - $(this).val().length;

    if(left < 0){
        $('#text_counter').addClass("overlimit");
        $('#submit_description').attr("disabled", true);
    }
    if(left > 1950){
        $('#text_counter').addClass("overlimit");
        $('#submit_description').attr("disabled", true);
    }
    else{
        $('#text_counter').removeClass("overlimit");
        $('#submit_description').attr("disabled", false);
    }

    $('#text_counter').text(txtrest + ' ' + left);
}

$(document).ready(function(){
    var left = 2000
    var txtrest = '<?php echo lang("SYSTEM_CHARECTERS_LEFT");?>';
    $('#text_counter').text(txtrest + ' ' + left);

        $('#field-ta').keyup(countChars);
});

Note that I have extracted the keyup event to another function, so that it can be called by the AJAX fucntion, below:
$('a#mod_description_onclick').click(function(){
    $('#MOD-DESCRIPTION').modal('show', {backdrop: 'static'});
    $.ajax({
        url: "tab.description.php",
        success: function(response) {
            $('#MOD-DESCRIPTION .modal-body').html(response);
            countChars();
        }
    });
})

Alternatively, you can trigger a manual keyup event, like so:
$('a#mod_description_onclick').click(function(){
    $('#MOD-DESCRIPTION').modal('show', {backdrop: 'static'});
    $.ajax({
        url: "tab.description.php",
        success: function(response) {
            $('#MOD-DESCRIPTION .modal-body').html(response);
            $('#MOD-DESCRIPTION .modal-body').trigger('keyup');
        }
    });
})

I hope this points you in the right direction.


text:
Q: Skip plotting NaN and inf values in python Is there a way to skip plotting NaN and Inf values in python?
Say I have something like:
m1  m2  m3
4   5   2
3   2   3
4   3   4
2   5   0
4   3   8
3   4   0
2   3   4

and I want to plot m1 vs m2/m3 so there are cases I am dividing by zero, so when I go to plot it throws a ValueError: Axis limits cannot be NaN or Inf
What's the solution? Thank you
(I am using dataframes in pandas where I go m4 = df['m2'] / df['m3'] and go to plot m1 vs m4)
Please not there are no inf or Nan Values in the dataframe itself, but they occur after manipulation.

A: According to what tools provides us Pandas, the easiest solution is to:

*

*replace Inf values (both positive and negative) with NaN,

*drop NaN values.

They your Series will contain neither Infs nor NaNs.
So, generating m4, expand your instruction to:
m4 = (df['m2'] / df['m3']).replace([np.inf, -np.inf], np.nan).dropna()

getting (in your case):
0    2.500000
1    0.666667
2    0.750000
4    0.375000
6    0.750000
dtype: float64

(no values for key 3 and 5), which can be plotted as you wish.
Edit
I noticed that (at least in Pandas v. 0.25) a DataFrame scatter plot
can be generated even with Inf or NaN values in y column.
I did the following experiment:

*

*Created m4 without removing Inf / Nan values, but setting its
name (will be needed in a moment in join):
m4 = df.m2.divide(df.m3).rename('m4')

*Replaced the second occurrence of Inf with NaN:
m4.iat[5] = np.nan

so now it contains both Inf and NaN.

*Generated the plot:
df.join(m4).plot.scatter(x='m1', y='m4');

In effect, I got the picture, without any errors.
Apparently, any Inf / NaN values are in this case silently dropped
and only after that the picture is generated.

A: What you can do is to yield the rows where all its elements are finite.
import pandas as pd, numpy as np
m1 = [4 ,3 ,4 ,2 ,4 ,3 ,2]
m2 = [5 ,2 ,3 ,5 ,3 ,4 ,3]
m3 = [2, 3, 4, 0, 8, 0, 4]
df = pd.DataFrame({'m1':m1,'m2':m2,'m3':m3})

Say m4 = m2/m3:  df['m4']= df.m2/df.m3
...and MAY CONTAIN infinite elements. To solve this problem, use NumPy's isfinite on your data frame df and then use .all(1), which returns TRUE if all cells in a row are finite:   df[np.isfinite(df).all(1)]

For visualization purposes, please see the attached screenshots.

After this, you can now plot m1 vs. m4 without worrying about the infinite values:

Hope this helps!


text:
Q: How do I periodically extend a function? I am given that $f(x) = -1-x$ on $[-1,1)$ and I'm asked to find the Fourier series for the $2$ period extension of $f(x)$. I get how to find a Fourier series for the given function on the given interval. From some googling I understand what an odd and even extension are, but what is an extension by a set amount of periods? Even and odd extensions are infinite extensions from my understanding.

A: "2 period extension" doesn't mean that there are two periods, it means that the period is $T=2$.

A: Every real number $x$ belongs to $[2n-1,2n+1)$ for a unique integer $n$. For such an $x$ define $F(x)=f(x-2n)$. This is a function defined on the whole line with period $2$ and it coincides with $f$ on $[-1,1)$.


text:
Q: Justify of equation to better explanation I am trying to create pure inequality like this

But I have:
\documentclass{article}

\usepackage{amsmath}

\begin{document}
\[
\int{\prod_{i=1}^{m+1}|f_{i}|d\mu} \leq
||f_{1}||_{p_{1}}
\left[
\prod_{i=2}^{m+1}
    \left(
        \int|f_{i}|^{p_{1}/(p_{1}-1) p_{i}(p_{1}-1)/p_{1}}d\mu
    \right)^{p_{1}/p_{i}(p_{1}-1)}
\right]^{(p_{1}-1)/p_{1}}
\]

\[
= ||f_{1}||_{p_{1}}
\prod_{i=2}^{m+1}
    \left(
        \int|f_{i}|^{p_{i}} d\mu
    \right)^{\frac{1}{p_{i}}}
\]

\end{document}

A: Some suggestions:

*

*use an align environment to contain both rows of the display-math material

*use a \notag instruction in the first row to suppress the typesetting of an equation number

*use \biggl and \biggr for all large parentheses and brackets

*load the mathtools package -- a superset of the amsmath package -- and define macros called \abs and \norm. This'll make reading the input code much easier

*optional: place brackets around the exponent of \abs{f_i} to help readers figure out what's going on

\documentclass{article}
\usepackage{mathtools} % for '\DeclarePairedDelimiter' macro
\DeclarePairedDelimiter\abs\lvert\rvert
\DeclarePairedDelimiter\norm\lVert\rVert

\begin{document}
\begin{align}
\int \prod_{i=1}^{m+1} \abs{f_{i}}\,d\mu
&\leq  \norm{f_{1}}_{p_{1}}
\biggl[\,
\prod_{i=2}^{m+1}
    \biggl(
    \int|f_{i}|^{[p_{1}/(p_{1}-1) p_{i}(p_{1}-1)/p_{1}]}\,d\mu
    \biggr)^{\!p_{1}/p_{i}(p_{1}-1)}
\,\biggr]^{(p_{1}-1)/p_{1}}\notag\\
&= \norm{f_{1}}_{p_{1}}
\prod_{i=2}^{m+1}
    \biggl(
    \int|f_{i}|^{p_{i}} \,d\mu
    \biggr)^{\!1/p_{i}}
\end{align}
\end{document}

A: With the help of split and a slightly smaller margin using the geometry package you can achieve the following output:

\documentclass{article}
\usepackage{geometry}
\usepackage{amsmath}

\begin{document}
\begin{equation}
\begin{split}
\int{\prod_{i=1}^{m+1}|f_{i}|d\mu} &\leq
\|f_{1}\|_{p_{1}}
\left[
\prod_{i=2}^{m+1}
    \left(
        \int|f_{i}|^{p_{1}/(p_{1}-1) p_{i}(p_{1}-1)/p_{1}}d\mu
    \right)^{p_{1}/p_{i}(p_{1}-1)}
\right]^{(p_{1}-1)/p_{1}}\\
&= \|f_{1}\|_{p_{1}}
\prod_{i=2}^{m+1}
    \left(
        \int|f_{i}|^{p_{i}} d\mu
    \right)^{\frac{1}{p_{i}}}
    \end{split}
\end{equation}

\end{document}


text:
Q: What's wrong here? Zend FW getDependentRowSet() Trying to use the getDependentRowset in a ZF application. I have the following relationship between two tables:

Where a user's organisation is a FK of the organisation table's PK, organisationId.
What I want to do is, retrieve a users' organisation name (organisation.name) by the user Id (user.userId).
Here's my User db-table model:
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{

        protected $_name = 'user';

        //define foreign keys here
        protected $_referenceMap = array (
            'Organisation'=> array (
            'columns'=>'organisation_organisationId',
            'refTableClass'=>'Organisation',
            'refColumns'=>'organisationId'
            )
        );

        public function getUser($emailAddress, $password) {

            $select = $this->select()
                            ->where("emailAddress = \"$emailAddress\" AND password=\"$password\"", 1);
            $row = $this->fetchRow($select);
            return $row;

        }

    }

And the offending code in my IndexController:
$user = new Application_Model_DbTable_User();
$res = $user->getUser($emailAddress, $password);
$organisationInfo = $res->findDependentRowset('organisation');

And ideas what could be causing this? I know this is relatively simple stuff!!!
Thanks

A: I belive an organization table is a parent table to the user table. So you should be using $res->findParentRow('Application_Model_DbTable_Organization');. However, when you want to find all users in a given organization, than you would use getDependentRowSet() method of an organisation row object.


text:
Q: Ckeditor 4.4.7 Can't Load In Master Page I tried Ckeditor 4.4.7 in normal pages without Master Page.
But when I tried using Master Page, Ckeditor 4.4.7 can't load into the Child Page.
I tried placing the Javascript into my Child Page but it still can't load.

                <script src="ckeditor_4.4.7_standard/ckeditor/ckeditor.js"></script>

Please help.
Thanks.


text:
Q: ELIMINAR REGISTRO DE UNA TABLA Y GUARDAR ESE MISMO REGISTRO EN OTRA TABLA Ahora vengo con este tema:
Tengo en una tabla guardados varios registros, tengo la necesidad de que cuando yo presione el botón de ELIMINAR el registro lo elimine de la primera tabla, pero que lo registre en una segunda tabla.
Aquí el código de eliminar que estoy utilizando:
<?php
include 'cn.php';

    $id = $_REQUEST['id'];

    $query = "DELETE FROM fallas WHERE id = '$id'";
    $resultado = $conexion->query($query);

    if($resultado){
      header("location: altafalla.php");
    }
?>

Quedo atento a su valioso apoyo.