text:
Q: Can we pass event name as props in react? Hi I am new to react and I am trying to create a component where we can pass event name(onclick, onChange etc.) as props. So the component can be customize in an event way as well. Is it possible?
<Input  {this.props.eventName} = {this.props.name} />

This I want to do. Is it possible?

A: Do you want to achieve something similar to this -
One problem is that you must pass only supported events to the element type.
e.g in case of button onClick and other events supported by button.

class Parent extends React.Component {

  render() {
    return(
       <ChildComponent
        evtName = 'onClick'
        evtHandler={ () => { console.log("event called!");}}
       />
    )
  }
}

class ChildComponent extends React.Component {
  render() {
     return React.createElement(
        'button',
        { [this.props.evtName] : this.props.evtHandler },
        'Click me'
      );  }
}

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);

A: Here is example how to pass an event from parent Component to Child - by having result in Parent Component.
class Parent extends Component {
  //constructor, other methods, etc...

  // We call our event update
  update(stuff) {
    console.log(stuff);
  }
}

We pass in ParentComponent's render method a ChildComponent with props onClick(you can name it whatever you want).
<ChildComponent
  onClick={this.update.bind(this)}
/>

Now, ChildComponent. To access our props onClick, we just use this.props.onClick. Our argument is just hello, you can pass as many arguments you want.
<button onClick={ (e) => this.props.onClick('hello') }>
  Action
</button>

Here is working example:

class Parent extends React.Component {

  update(stuff) {
    console.log(e, stuff);
  }

  render() {
    return(
       <ChildComponent
        onClick={this.update.bind(this)} />
    )
  }
}

class ChildComponent extends React.Component {

  render() {
    return(

      <button onClick={ (e) => this.props.onClick('hello') }> Action</button>

    )
  }
}

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);

A: If I understand you correctly, just pass the event and it's handler as props. I didn't see the use case just considering the event name.
See the below example of reusing the same element with different events.

class Input extends React.Component {
  render(){
    const {} = this.props;
    return (
      <input {...this.props} />
    );
  }
}

class Test extends React.Component {
  render(){
    return (

        <Input name="onClick" onClick={(e) => console.log(e.target.name)}/>
        <Input name="onChange" onChange={(e) => console.log(e.target.name)}/>

    );
  }
}

ReactDOM.render(<Test />, document.getElementById("root"));


text:
Q: Расширить иерархию классов C# Я жестко туплю.. Не могу собрать с мыслями.. Как расширить иерархию классов с использованием виртуального класса в качестве основы иерархии? На основе этого кода:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StructApp
{
    class Student : Person
    {
        public void Delaet()
        {
            Console.WriteLine("Студент идет на учебу ");
        }
    }
    class Prepod
    {
        public string rabotaet;
        public string gde;
        public void Delaet()
        {
            Console.WriteLine("Преподователь работает в " + gde);
        }
    }
    class Person
    {
        public string chelovek;
        public string name;
        public void Delaet()
        {
            Console.WriteLine("Персона - " + name);
        }
    }
    class Zavkaf : Prepod
    {
        public void Delaet()
        {
            Console.WriteLine("Заведующий кафедрой сейчас в " + gde);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student persona = new Student();
            persona.Delaet();
            Prepod prepod = new Prepod();
            prepod.gde = "Университете ";
            prepod.Delaet();
            Person person = new Person();
            person.name = "Владимир ";
            person.Delaet();
            Zavkaf zavkaf = new Zavkaf();
            zavkaf.gde = "Университете ";
            zavkaf.Delaet();

            Console.ReadKey();
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: route model binding with query strings If I have a url like this:
localhost:8000?campaign=1

Is it possible to fetch the campaign from db like what we do in route model binding

A: Instead of localhost:8000?campaign=1 you should pass query string as: localhost:8000/campaign/1
and in Route:
Route::get('campaign/{id}', ['as' => 'campaigns.index', 'uses' => 'CampaignController@index']);

and in Controller:
public function index($id)
{
    //Your Code Goes Here
}

That's it! :)


text:
Q: How do I link libraries in Xcode 4? I'm a complete beginner to Apple's Xcode, but I have followed the Xcode documentation and the advice of a few related questions without success.
I installed GMP to /usr/local/bin, wrote a short program using the library, and compiled with gcc main.c -lgmp. It compiled with no warnings or errors, and the executable worked flawlessly.
I started a new Xcode project (Command Line Tool; Type: C), copied the code to the newly created main.c, and opened the project build settings. From there I set Linking > Other Linker Flags to -lgmp and Search Paths > Library Search Paths to /usr/local/bin. However, the build fails with the preprocessor error "Gmp.h: No such file or directory".
I have tried almost every header imaginable:
#include "gmp.h"
#include <gmp.h>
#include "gmp"
#include "libgmp.a" . . .
This has been my main obstacle over the last three months which has prevented me from learning C. Any help leading me to an eventual solution would be greatly appreciated.

A: There's a few things you have to set up in your Xcode project. For example, I have gmp installed in /opt/gmp/5.0.2 and I will use that as an example. The actual library is installed into /opt/gmp/5.0.2/lib and the header files into /opt/gmp/5.0.2/include. When installing the library setting the --PREFIX flag to /opt/gmp/5.0.2 would handle this automatically. If you don't set this flag the prefix is usually set to /usr/local by default.

*

*The Other Linker Flags looks right, it should be the name of the library.

*Set the Header Search Path to the include directory, in my case /opt/gmp/5.0.2/include.

*Set the Library Search Path to the lib directory, in my case /opt/gmp/5.0.2/lib.

Since the header search path has been set, you should now be able to include the header file like this:
#include <gmp.h>

Of course, replace /opt/gmp/5.0.2 with the PREFIX path you used when you installed gmp.
Lastly, you typically don't install libraries to /usr/local/bin, you would install to /usr/localand let any binaries be installed into bin while libraries like these would be installed into lib. Of course any path scheme would work, I usually recommend /opt/<project-name>/<version-number> since it allows me to keep better track of what I have installed and have multiple versions of the same libraries and tools without having to deal with collisions.

A: I have updated my system from snow leopard to mountain lion and had to install gmp.
First of all I have installed Xcode CommandLineTools set.
Secondly, installed Homebrew. Then with it I have done steps in this topic: https://apple.stackexchange.com/questions/38222/how-do-i-install-gcc-via-homebrew
In my last step, made changes to an xcode project as colleague Marcus Karlsson told.
It's finally working! Very big Thank You :)


text:
Q: ExpressJS Redirect Method If I use the res.redirect( url ) will the redirection method also append the previous parameters to where it will be redirected?
It means if I passed/send request with a json parameters using POST method then I redirect the request to another server, will that other server (where it is redirected) receives the json parameters?

A: No, it's a plain and simple HTTP Redirect header, most browsers will just "jump" to the destination URL when receiving such a header.
If you're posting programmatically, then how to react to the HTTP Redirect header is all up to you. You can send the original data to the redirect destination if you want.
See also:
http://en.wikipedia.org/wiki/URL_redirection


text:
Q: Control sound line-in How Can I control (tune up or down) the level of the line-in or microphone channel? and how can I visualize the spec (as a graph or something)?

A: Also see Alvas.Audio RecordPlay example http://alvas.net/alvas.audio.aspx

A: you can try using the mixer APIs to find the line in volume control. I've found it is very tricky to pick out the right one (especially if you want it to work in both XP and Vista/Win7). Have a look at .NET Voice Recorder for an example of how to use NAudio to do this.


text:
Q: Not "window" and not "window.innerHeight" but I have a site where I have a HEADER element, then a MAIN element, and then a FOOTER element. I want the HEADER and MAIN elements to take up whatever height they naturally take up, and then for the FOOTER to take up the remaining browser height (without creating a scroll) assuming there is any remaining browser height. But when I check browser height with either "window" or "window.innerHeight" and then subtract the HEADER height and MAIN height to get the FOOTER's height the FOOTER's height ends up being higher than it seems it should be and creates a scroll. Here's the scripting I have in place now:
if (window.innerHeight > $('HEADER').height() + $('MAIN').height() + $('FOOTER').height()) {
    $('FOOTER').height(
        window.innerHeight - ($('HEADER').height() + $('MAIN').height())
    );
}

The staging site is proprietary, so hopefully someone will see the flaw in my code without needing to see the site.

A: Looks like the problem is the box model...
so try
footer {
    background-color: lightgreen;
    padding-bottom: 4em;
    padding-top: 1.4em;
    box-sizing: border-box;
}

then
var windowHeight = window.innerHeight,
    header = $('HEADER').outerHeight(),
    main = $('MAIN').outerHeight(),
    footer = $('FOOTER').height();
if (windowHeight > header + main + footer) {
    $('FOOTER').css('height', windowHeight - (header + main));
}


text:
Q: How do I increase the score value of my game? I am making a game in which the player catches falling objects. When an object is caught, the score should increase by one, but it doesn't. I have a collision function already in which the objects disappear when the player catches them. The score is already displayed on the screen. Here is my code:

(() => {
    // In general, don't touch anything except for sections explicitly marked as such.
    // Look for the exclamations points (!!!!!) for such markers.
    let canvas = document.getElementById("game");
    let game = canvas.getContext("2d");
    let lastTimestamp = 0;
    let playerScore = 0;
    const FRAME_RATE = 60;
    const FRAME_DURATION = 1000 / FRAME_RATE;

    // !!!!! Change/add to this as needed. What other objects or variables will you need for your game idea?
    //       A score? Different kinds of fallers? Player statistics? It's all up to you!
    let fallers = [];

    // Check out that cool ES6 feature: default parameter values!
    const DEFAULT_DESCENT = 0.0002; // This is per millisecond.
    let Faller = function (x, y, width, height, dx = 0, dy = 0, ax = 0, ay = DEFAULT_DESCENT) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;

        // Velocity.
        this.dx = dx;
        this.dy = dy;

        // Acceleration.
        this.ax = ax;
        this.ay = ay;
    };

    Faller.prototype.draw = function () {
        game.fillStyle = "blue";
        game.fillRect(this.x, this.y, this.width, this.height);
    };

    Faller.prototype.move = function (millisecondsElapsed) {
        //Good old Newtonian physics.
        this.x += this.dx * millisecondsElapsed;
        this.y += this.dy * millisecondsElapsed;

        this.dx += this.ax * millisecondsElapsed;
        this.dy += this.ay * millisecondsElapsed;
    };

    const DEFAULT_PLAYER_WIDTH = 45;
    const DEFAULT_PLAYER_HEIGHT = 20;
    const DEFAULT_PLAYER_Y = canvas.height - DEFAULT_PLAYER_HEIGHT;
    let Player = function (x, y = DEFAULT_PLAYER_Y, width = DEFAULT_PLAYER_WIDTH, height = DEFAULT_PLAYER_HEIGHT) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    };

    Player.prototype.draw = function () {
        game.fillStyle = "aqua";
        game.beginPath();
        game.moveTo(this.x - this.width / 2, this.y + this.height);
        game.lineTo(this.x - 2, this.y);
        game.lineTo(this.x, this.y - 20);
        game.lineTo(this.x + 2, this.y);
        game.lineTo(this.x + this.width / 2, this.y + this.height);
        game.closePath();
        game.fill();
    };

    let player = new Player(canvas.width / 2);

    // !!!!! You can treat this function like Khan Academy's `draw`---just precede all
    //       drawing instructions with `game.`
    let draw = (millisecondsElapsed) => {
        game.clearRect(0, 0, canvas.width, canvas.height);

        fallers.forEach((faller) => {
            faller.draw();
            //COLLISION FUNCTION!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            let playerScore = document.getElementById("playerScore");
              if (player.x < faller.x + faller.width && player.x + player.width > faller.x &&
                player.y < faller.y + faller.height && player.y + player.height > faller.y) {
                  game.clearRect(0, 0, canvas.width, canvas.height);

                };
                playerScore += 1;

            faller.move(millisecondsElapsed);

        });

        player.draw();

        // Remove fallers that have hit the ground. You might have other reasons to remove fallers.
        fallers = fallers.filter((faller) => {
            return faller.y < canvas.height;
        });
    };

    // !!!!! This section is modifiable to a degree. It is responsible for generating falling objects at random.
    //       You don't want to completely eliminate this code, but you may want to revise it to modify the rate/range
    //       of objects that get generated.
    const MIN_WIDTH = 10;
    const WIDTH_RANGE = 20;
    const MIN_HEIGHT = 10;
    const HEIGHT_RANGE = 20;
    const MILLISECONDS_BETWEEN_FALLERS = 800;

    let fallerGenerator;
    let startFallerGenerator = () => {
        fallerGenerator = setInterval(() => {
            // !!!!! This code looks really repetitive! Hmmmm, what to do...
            let fallerWidth = Math.floor(Math.random() * WIDTH_RANGE) + MIN_WIDTH;
            fallers.push(new Faller(
                Math.floor(Math.random() * (canvas.width - fallerWidth)), 0,
                fallerWidth, Math.floor(Math.random() * HEIGHT_RANGE) + MIN_HEIGHT
            ));
        }, MILLISECONDS_BETWEEN_FALLERS);
    };

    let stopFallerGenerator = () => clearInterval(fallerGenerator);

    // !!!!! This section is also modifiable to a degree: it is responsible for moving the "player" around based on
    //       mouse movement.
    let setPlayerPositionBasedOnMouse = (event) => {
        player.x = event.clientX / document.body.clientWidth * canvas.width;
    };

    document.body.addEventListener("mouseenter", setPlayerPositionBasedOnMouse);
    document.body.addEventListener("mousemove", setPlayerPositionBasedOnMouse);

    // OK, back to the no-touch zone (unless you _really_ know what you're doing).
    let running = false;
    let nextFrame = (timestamp) => {
        if (!lastTimestamp) {
            lastTimestamp = timestamp;
        }

        if (timestamp - lastTimestamp < FRAME_DURATION) {
            if (running) {
                window.requestAnimationFrame(nextFrame);
            }

            return;
        }

        draw(timestamp - lastTimestamp);

        lastTimestamp = timestamp;
        if (running) {
            window.requestAnimationFrame(nextFrame);
        }
    };

    document.getElementById("start-button").addEventListener("click", () => {
        running = true;
        lastTimestamp = 0;
        startFallerGenerator();
        window.requestAnimationFrame(nextFrame);
    });

    document.getElementById("stop-button").addEventListener("click", () => {
        stopFallerGenerator();
        running = false;
    });
})();
canvas {
    border: solid 1px gray;
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 1024px;
}

p {
    text-align: center;
}
<!doctype html>

    <meta charset="utf-8" />
    <title>Undefined</title>

    <link rel="stylesheet" href="falling.css">

Not finished

      Score: 0

    <canvas id="game" width="1024" height="536">
      Sorry, but you need a web browser that supports the
      canvas element.
    </canvas>

      <button id="start-button">Start</button>
      <button id="stop-button">Stop</button>

A: You start the game with:
let playerScore = 0;

But in your collision code you have:
let playerScore = document.getElementById("playerScore");

and
playerScore += 1;

Aside from having two variables with the same name (albeit in different scopes), you end up calling += 1 on the HTML element, and never actually write the value of the score to the document for display.


text:
Q: Is there a way to buffer current for high usage periods? I am using a USB port as a power source(500-1000ma) for my latest design(Wireless Comms and lots of LED's) and most of the time things work perfectly. However at times I do get spikes where the current draw can go higher than the supply and restart the MCU.
Is there a solution to store extra current?
I know a battery might solve this but I prefer to not go that way... Any other options?

A: Providing the circuit with a larger capacitors is a good start. To determine the required capacity you need the energy used during the spike. To do this one can measure voltage and current as a function of time with an oscilloscope.
The energy the capacitor has to provide during the spike is roughly \$W_S \approx  \int_{t_{s0}}^{t_{s1}}u(t)(i(t)-I_{USB,max}) dt\$
where \$I_{USB,max}\$ is the current the USB Port can provide. The energy in a capacitor is
\$W= \frac{1}{2}C\cdot V_{USB}^2 \$ and the capacitor needs to keep at least the voltage \$V_\mu\$ required to supply the microcontroller. Thus the minimal energy in the capacitor is \$W_\mu=\frac{1}{2}\cdot V_{\mu}^2\cdot C\$. Consequently we have \$ W = W_s + W_\mu \$ which solves to a minimal capacity of \$C=2\frac{\int_{t_{s0}}^{t_{s1}}u(t)(i(t)-I_{USB,max}) dt}{V_{USB}^2-V_{\mu}^2}\$
Alternatively set a very large capacitor in parallel to the supply. Measure the current over time during the spike. The minimal capacity would then be \$C= \frac{(\overline{I}-I_{USB,max})\cdot T}{V_{USB}}\$ where \$\overline{I}\$ is the arithmetic average of the current flown during the spike.

If those current spikes result from switching the LEDs and the switching timing is not critical (e.g. no optical data transmission) you can add an inductance in series to the LEDs. Sized large enough compared to the needed energy and duration of the spikes this will even the spike over a larger time interval reducing the required capacitor size by using the current supplied via USB. This is not recommended for the time critical wireless communication.
Edit: After a spike there also has to be enough time to the next spike in which the capacitor can be recharged, which depends on \$I_{USB,max}\$.

A: There are 3 solutions to your problem as far as I can see:

*

*Turn off the low voltage drop detection function in your MCU.

*Limit the current draw, i.e. remove some of the LEDs, or add higher value resistors.

*Use super-capacitor such as 1F rated at 5V.


text:
Q: Stateless with cookie vs stateful I found sth like this:
"stateful – keep track of the previously stored information which is used for current transaction.
stateless – every transaction is performed as if it were being done for the very first time. There is no previously stored information used for the current transaction.
In a purely stateless environment you wouldn't need this session id. Each request would contain all the information the server would need to process. But many applications need to maintain state to keep track of whether or not a session is authenticated to view certain content or to keep track of what a user is doing. You wouldn't want to send user credentials over the wire for each request."
I'm quite confuse. So if stateless session with cookie maintain the state so it's mean that:
stateless session with cookie= session stateful?
Another think. I found information that session stateless is client side session and stateful is server side session. How we can discuss about client side session if stateless session does not maintain session?

A: In a purely stateless environment you really don't need sessions or cookies.
Both sessions and cookies are used to maintain state. The only question is where. Cookies maintain the state on the client while sessions maintain state on the server.
From Wikipedia: Representational state transfer

The session state can be transferred by the server to another service such as a database to maintain a persistent state for a period and allow authentication.

So typically in a stateless design, yes there is no state between client requests.
Every client request will have sufficient info to perform the requested action.
However, you still need authentication and/or authorization so who the client is identified from request headers (typically).


text:
Q: How and where to send status code for response in strapi? I have developed simple posts endpoint and I do not know what to override and where to add status code. For example when some error happens I want to send 500 or when object created I want to send 201 instead of 200.
How and where to set status code in response of strapi?

A: Check out the strapi docs on responses, it uses a koa response object.
So you can do something like:
//controller
ctx.send({
    message: 'The content was created!'
}, 201);

You can apply your own logic and response by using custom endpoints or modifying the existing ones. These are some closely related examples of how to do that - answer1 , answer2.
Comment if you need more info


text:
Q: Sequelize, find where sum of two fields (one is date and another is number of hours) is bigger then Now I have a table:
createdOn: DateTime,
alarmDeadline: SmallInt

I need to find all records where (createdOn + alarmDeadline > new Date())
in other words: find all records where date created from adding date and hours are bigger then Now).
I need to do it using Sequelize for MySQL.
Any help please? :-)

A: Use Sequelize.literal:
const foudnRecrods = await Model.findAll({
  where: Sequelize.where(Sequelize.literal('DATE_ADD(createdOn,INTERVAL alarmDeadline HOUR'), '>', new Date())
});


text:
Q: No "Tests" Tab in TeamCity Build Log after Selenium GUI Tests Execution with Nunit 3.0 We are executing our Selenium WebDriver GUI tests as a Nunit 3.0 build step in TeamCity 10 and after going through the documentation, we were expecting to see the test execution log in a separate "Tests" tab in the build log. However, there is no "Tests" tab at all in our log and the nunit.xml file with the results is saved only as an artifact in the tmp folder.
Have you come into the same issue? Could you please assist us?
Thank you in advance.

A: The tests results should be somehow reported into TeamCity. Test can reported by build runner (see the list of the supported frameworks), using XML Report processing build feature or via service messages. In your case you can use XML report processing feature to parse nunit.xml and report test in TeamCity.


text:
Q: how to dynamically add value to object in an array of objects in TypeScript? How do I add value to object in an array of objects in Typescript?
Say I have an array of object like this:
[{name:'John',age:20}, {name:'Sam',age:26}, {name:'Will',age:2}]

What I want is dynamically generated property in each object of array as this:
[{name:'John',age:20, value:'John 20'}, {name:'Sam',age:26, value:'Sam 26' }, {name:'Will',age:2, value:'Will 2'}]

This is what I tried: I have a created a model for type checking and created a method in it which will return the value.
export class Names {
    name: string;
    age: number;
    constructor() {
    }
    getConcat() {
        return this.name + ' ' + this.age;
    }
}

Although when I get data from server of type Names[], I am not able to fetch the dynamically generated value. I am trying to get values like this:
this.somevariable:Names[]=[];  //declarartion
this.somevariable[0].getConcat() // inside a method after api call

How do I do that? Any help would be much appreciated. Thanks!

A: as you made the class for the purpose of typechecking - I'm guessing you mixed up javascript's class and typescript's interface:
an interface is only present during development, and gone in your actual production app.
a class is a living js object that is compiled into a functioning object in your app.
an interface for typechecking may look like this:
interface Name {
  name: string;
  age: number;
  getConcat: () => string; // hints about the presence of a function that returns a string, within the typed object - but is not a function by itself!
}

while a class requires a bit modification
export class Names {
    name: string;
    age: number;

    constructor(name: string, age: number) { // pass arguments to initialize the class object
      this.name = name;
      this.age = age;
    }

    getConcat() {
        return this.name + ' ' + this.age;
    }
}

using interfaces, you could say that the array of names you have is of type Name[], meaning:
function getConcat () {
   return this.name + ' ' + this.age
}

const names: Name[] = [{name: 'a', age: 1, getConcat: getConcat }, {name: 'b', age: 2, getConcat: getConcat },...];

and throughout your code development, you will be hinted about the already preset getConcat method, and be warned if it is not there now, or in future.
But in order to use the class for both typechecking AND the getConcat function, you will have to map each object into a class:
const objects = [{name: 'a', age: 1}, {name: 'b', age: 2}];
const names: Name[] = objects.map(obj => new Name(obj.name, obj.age));

And now you can access any method you declared within Name class, for each item in names array.
You can actually mix the two up, initializing the js classes as shown above, while typechecking the class itself:
export class Name implements NameInterface {
    name: string;
    age: number;

    constructor(name: string, age: number) {
      this.name = name;
      this.age = age;
    }

    getConcat() {
        return this.name + ' ' + this.age;
    }
}

And now you will be warned if your class object has not implemented any member of the NameInterface declared members (say you forgot to add the getConcat function within the class).

A: You want to insert new attribute then you should write like this: arr[i].value = arr[i].name + ' '+ arr[i].age;. Once you get data from API store it in an array and then do as shown below to update your array.
Following is working example:

arr = [{name:'John',age:20}, {name:'Sam',age:26}, {name:'Will',age:2}];

for(let i=0;i<3;i++){
    arr[i].value = arr[i].name + ' '+ arr[i].age;
}

console.log(arr);

A:

arr = [{name:'John',age:20}, {name:'Sam',age:26}, {name:'Will',age:2}];

const generateValue = (items) => {
  return items.map(x=> {
    return {...x, value: `${x.name} ${x.age}`};
  });
};

arr = generateValue(arr);
console.log(arr);

You can create function like this


text:
Q: Realm clear DB when the class changes Why is Realm completely cleared when changing the database class? That is, I had a class
Weapon.class
public class Weapon extends RealmObject {

    @PrimaryKey
    private int ID;
    private String NameWeapon;

    //Constructor, getters, setters...

}

And everything is fine, the data is saved and read without problems, when adding new entries nothing flies. But, for example, I need to change the class
public class Weapon extends RealmObject {

    @PrimaryKey
    private int ID;
    private String NameWeapon;
    private float Cost = 0f;

    //Constructor, getters, setters...

}

I added a new variable to the class, and if I start the application, it will crash, because there will not be anything in the database, Realm will not let the old records be read. And if you rebuild the database (insert the records by default), then the data that was entered by the user will be lost.

A: The reason why my database was deleted:
MyApp.class
mRealmConfiguration = new RealmConfiguration.Builder()
            .name(Constants.DATABASE_NAME_REALM)
            .schemaVersion(0)
            .deleteRealmIfMigrationNeeded()
            .build();

I completely forgot about this moment. It turns out I myself instructed everyone to delete (.deleteRealmIfMigrationNeeded()) when the database is migrating
mRealmConfiguration = new RealmConfiguration.Builder()
            .name(Constants.DATABASE_NAME_REALM)
            .schemaVersion(0)
            .migration(new Migration())
            .build();

Migration.class
public class Migration implements RealmMigration {

    @Override
    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

    RealmSchema mSchema = realm.getSchema();

    /****************************************************************
     * Version 0
     *
        class Weapon
           @PrimaryKey
           private int ID;
           private String NameWeapon;

     *
     * Version 1
     *
         class Weapon
            @PrimaryKey
            private int ID;
            private String NameWeapon;
            private float Cost = 0f;
     ****************************************************************/

    if (oldVersion == 0) {
        RealmObjectSchema mPrimaryCaseSchema = mSchema.get("Weapon");

        mPrimaryCaseSchema
                .addField("Cost");
        oldVersion++;
    }
}

More Info: https://github.com/realm/realm-java/tree/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample
https://realm.io/docs/java/latest/#migrations


text:
Q: How to update the data source of a dashboard in Kibana I have a dashboard with some visualizations on it. Recently, we have a new data source that is a saved search, and we need to change the index pattern of the dashboard to the saved search.
This is my first time working with kibana. I'm considering changing the index pattern of each panel on the dashboards. But when I edit the reference of the visualization to the id of the saved search, the visualization could not open. Is there anyway to change the data source of a visualization?

A: I don't believe that is possible. Read this post.


text:
Q: simple error on datetime column I am getting an error in simple entry into a datetime column. How to enter this data?
We are using SQL Server 2005 here
Error:

Msg 241, Level 16, State 1, Line 1
  Conversion failed when converting datetime from character string.

Code:
 insert into OGEN.EMR_MONITOR_TRANSACTIONS (PATIENT_ID, MONITOR_CODE, RESULTS, RESULTS_VALUES, NOTE, ADD_OBSERVATIONS, DATE_ENTERED, ENTERED_BY)
  Values('103545281', 'P100', '1', '1', ' ', '111', '2014-11-11 05:05:05', 'Nurse1')

Defined:
DATE_ENTERED datetime

I tried this way as well 20141118 10:34:09 AM and also this '12-mar-2013'same error

A: There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:

*

*YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!

or:

*

*YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.

This is valid for SQL Server 2000 and newer.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
So in your concrete case - try this:
INSERT INTO OGEN.EMR_MONITOR_TRANSACTIONS (PATIENT_ID, MONITOR_CODE, RESULTS, RESULTS_VALUES, NOTE, ADD_OBSERVATIONS, DATE_ENTERED, ENTERED_BY)
VALUES('103545281', 'P100', '1', '1', ' ', '111', '20141111T05:05:05', 'Nurse1')

A: '20141111 05:05:05' (no 'AM' or 'PM') should convert correctly regardless of language settings.


text:
Q: Ansible hostvars and template I have haproxy role , variables defined under vars/main.yml
and template defined under template/haproxy.cfg.j2
in main.yml var file I defined this variable :
iface: ansible_default_ipv4.interface
in the template file:
backend app
balance     roundrobin
{% for host in groups['web'] %}
    server {{ host }} {{ hostvars[host]['ansible_'+ iface ]['ipv4']['address'] }}:80 check
{% endfor %}

The problem is when I execute the playbook I get the following error :
changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute u'ansible_ansible_default_ipv4.interface'
So as I know I have problem in the concatenation ['ansible_'+iface].
Please your help.

A: You have ansible_ on both the variable definition
iface: ansible_default_ipv4.interface`

and the template
server {{ host }} {{ hostvars[host]['ansible_'+ iface ]['ipv4']['address'] }}:80 check

As such, the concatenation creates the name ansible_ansible_default_ipv4.interface that you see in the error message.
Remove it from one of these places and try again.


text:
Q: Google translate header bar appearing in IE9 when not translating - also drop down doesn't work Unfortunately, I don't have this on a live server anywhere at the moment but I'm having issues in IE9 with google translate inserting a div at the top of the page and the dropdown not opening on click. There are no JS errors so I'm not sure what's going on.
Has anyone seen this or knows what I might take a look at to fix it?

The div that is showing at the top of the page normally pops up in a popover when you hover a translated word. Currently in IE9 it's showing before even translating the page.


text:
Q: Filtering Data from a Query with SQL I'm really running into issues with this SQL code I'm using. I've been posying about this, but not really getting answers. I tried to adapt this code to what I am trying to do, but I keep getting the screen shot of the error message screen grabbed below.
SELECT LoginID, ShiftNumber, PalletQTY, Group, ShiftDate
FROM Database
COUNT(PalletQTY) AS TotalCount
SUM(IF(Group='PUT',1,0)) AS ActiveCount,
ROUND((SUM(IF(TALLY_TRAN_MSTR.PRI_GRP_CD='PUT',1,0))*100/COUNT(TALLY_TRAN_MSTR.FULL_PLLT_QTY)),2) AS PctActive
FROM WBR_RW.TALLY_TRAN_MSTR TALLY_TRAN_MSTR

Now, there are many dates and many names with each date, so I want the code recognize that. I'm not sure if the code I'm trying to adapt is able to do that.
I'm really struggling at this point for how to make this code work, or find code that may work. Any help would be appreciated. Let me know if additional information is needed.
EDIT

I am trying view data of a person who is spent more than 75% of his time doing "PUT" for a specific date.
An example of what I'm trying to do is (Calculated manually)
McMillan has 3 items associated with his name 6/15/2017. 1 of those is "PUT". The total of the "PUT" items for that date for him are 132. The sum of everything associated with his name for that date is 167. 132/167 = 0.79. 0.79>0.75 so I want his data to show in my query results.
Malone has 4 items associated with his name on 6/15/2017. 1 of those is "PUT". The "PUT" summed is 4. The sum of all 4 items is 36. 4/36=0.11 0.11 < 0.75, so I want to get rid of that data.

A: Oracle does not support if().  Use proper Oracle syntax.  I think the query should look more like this:
SELECT LoginID, ShiftNumber, PalletQTY, "Group", ShiftDate,
       COUNT(PalletQTY) AS TotalCount,
       SUM(CASE WHEN "Group" = 'PUT' THEN 1 ELSE 0 END) AS ActiveCount,
       ROUND(SUM(CASE WHEN TALLY_TRAN_MSTR.PRI_GRP_CD = 'PUT' THEN 1 ELSE 0 END)*100 /
             COUNT(TALLY_TRAN_MSTR.FULL_PLLT_QTY), 2) AS PctActive
FROM WBR_RW.TALLY_TRAN_MSTR TALLY_TRAN_MSTR
GROUP BY LoginID, ShiftNumber, PalletQTY, "Group", ShiftDate;

A: Aside from the basic syntax issues Gordon pointed out, you seem to be confusing the count() and sum() aggregate functions. You can do both, but from your description you're interest in the total quantity of pallets, not the number of entries for the group type.
You seem to want something more like this, Using dummy data based on your original description:
-- CTE for dummy data
with tally_tran_mstr (loginid, shiftdate, shiftnumber, pri_grp_cd, palletqty) as
(
  select 'Steve', date '2017-06-15', 1, 'PUT', 40 from dual
  union all select 'Steve', date '2017-06-15', 1, 'PUT', 80 from dual
  union all select 'Steve', date '2017-06-15', 1, 'PUT', 45 from dual
  union all select 'Steve', date '2017-06-15', 1, '???', 7 from dual
  union all select 'Steve', date '2017-06-15', 1, '???', 5 from dual
  union all select 'Steve', date '2017-06-15', 1, '???', 3 from dual
  union all select 'Steve', date '2017-06-15', 1, '???', 1 from dual
)
-- end of CTE for dummy data
select loginid, shiftnumber, shiftdate,
  count(*) as totalcount,
  count(case when pri_grp_cd = 'PUT' then 1 end) as activecount,
  round(100 * count(case when pri_grp_cd = 'PUT' then 1 end) / count(*), 2)
    as pctactivecount,
  sum(palletqty) as totalqty,
  sum(case when pri_grp_cd = 'PUT' then palletqty else 0 end) as activeqty,
  round(100 * sum(case when pri_grp_cd = 'PUT' then palletqty else 0 end) /
    sum(palletqty), 2) as pctactiveqty
from tally_tran_mstr
group by loginid, shiftnumber, shiftdate;

LOGIN SHIFTNUMBER SHIFTDATE  TOTALCOUNT ACTIVECOUNT PCTACTIVECOUNT   TOTALQTY  ACTIVEQTY PCTACTIVEQTY
----- ----------- ---------- ---------- ----------- -------------- ---------- ---------- ------------
Steve           1 2017-06-15          7           3          42.86        181        165        91.16

I've taken palletqty and group out of the select-list because if they are in there they have to be included in the group-by clause, which won't do the counting and summing at the right level.
That should give you one row of output for each person on each day/shift they have records for.
If you want to exclude the results rows where the percentage doesn't meet some threshold then you can add a having clause:
...
group by loginid, shiftnumber, shiftdate
having sum(case when pri_grp_cd = 'PUT' then palletqty else 0 end) /
  sum(palletqty) > 0.8;

You may prefer to avoid repeating some of the terms; you can move the count/sum/group into a subquery (inline view), and then filter that with a where clause instead of a having clause:
select loginid, shiftnumber, shiftdate, totalcount, activecount,
  round(100 * activecount / totalcount, 2) as pctactivecount,
  totalqty, activeqty, round(100 * activeqty / totalqty, 2) as pctactiveqty
from (
  select loginid, shiftnumber, shiftdate,
    count(*) as totalcount,
    count(case when pri_grp_cd = 'PUT' then 1 end) as activecount,
    sum(palletqty) as totalqty,
    sum(case when pri_grp_cd = 'PUT' then palletqty else 0 end) as activeqty
  from tally_tran_mstr
  group by loginid, shiftnumber, shiftdate
)
where activeqty / totalqty > 0.8;


text:
Q: Find composite location on screen I am implementing a on screen keyboard in Java for SWT and AWT.
One important thing is to move the keyboard to a position where the selected text field can show and is not lying behind the on screen keyboard.
For AWT i can detect the position of the current selected component with
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner == null) {
    return;
}
Point ownerLocation = owner.getLocationOnScreen();
Dimension ownerSize = owner.getSize();

How can i implement the same logic in SWT?
I get the current selected widget by adding a focuslistener to the SWT event queue. But when i call
Point location = new Point(mTextWidget.getLocation().x, mTextWidget.getLocation().y);
Dimension dimension = new Dimension(mTextWidget.getSize().x, mTextWidget.getSize().y);

I will get the position relativ to the parent composite.
How can i get the location of a special widget relativ to the complete screen?

A: I believe the method Control.toDisplay() should be able to translate your coordinates into ones relative to the screen.
This snippet may illustrate what you are after:
package org.eclipse.jface.snippets;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Bla {
    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);

        final Text t = new Text(shell,SWT.BORDER);
        t.setBounds(new Rectangle(10,10,200,30));
        System.err.println(t.toDisplay(1, 1));

        Button b = new Button(shell,SWT.PUSH);
        b.setText("Show size");
        b.setBounds(new Rectangle(220,10,100,20));
        b.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
                System.err.println(t.toDisplay(1, 1));
            }

        });

        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }

        display.dispose();
    }
}


text:
Q: What does native aspect ratio mean in Unity?
What does the word native means here? What aspect ratio will be set if I choose native aspect ratio?

A: Native aspect ratio means that your game will always be rendered on the native (natural) resolution of the device. For example, an iPhone 6S Plus has a native resolution of 1920 x 1080, meanwhile an iPad Pro has a resolution of 2224 x 1668. If you choose native resolution and build for iOS, the resolution will be different between devices with different resolutions.

A: I am not sure but i think it means that you can either set your custom resolution for every device or native resolution i.e. the resolution that is available on the device.


text:
Q: Convert IBM437 data into readable English text (UFT-8 or ASCII) Here is sample code:
input = 'C:\\GOOD_AOA21_420031042_2016-02-09_02.38.11.txt'
file = File.open(input)
original_file_data = file.read
original_file_data_encoding = original_file_data.encoding
puts "String Encoding #{original_file_data_encoding}"
puts "#{original_file_data}"
#===============================================
ec = Encoding::Converter.new("IBM437", "UTF-8")
converted_to_utf_8 = ec.convert(s).dump
puts "Encoding after IBN 437 to UFT-8 conversion: #{converted_to_utf_8.encoding}"
puts "#{converted_to_utf_8}"

The output is:
String Encoding IBM437
 ���������@@�@@����������@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@      @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  Encoding after IBN 437 to UFT-8 conversion: UTF-8
"\u{2248}\u{b0}\u{2500}\u{2264}\u{b0}\u{2248}\u{2248}\u{2219}\u{2261}@@\u{251c}@@\u{2261}\u{2320}\u{2265}\u{2261}\u{2261}\u{2264}\u{b1}\u{2261}\u{2320}\u{2265}@ @@@@@@@@@@@@@@@

I am not sure why I am getting
"\u{2248}\u{b0}\u{2500}\u{2264}\...

and how to convert it to readable English.


text:
Q: Adding gmail to your created app I am creating a task organizer for my android device.  I am trying to allow the organizer to schedule its tasks on the gmail calendar directly from my created app.  Every time I search for this I get results on how to use google apps, not the ability to integrate them within my own app.  I know this information must exist somewhere.  Is it possible someone can point me in the right direction or shed some light on this situation in general.  Thank you.

A: You will want to use the google calendar API: https://developers.google.com/google-apps/calendar/


text:
Q: How to change screen in react native with react-navigation on click of a button? I have defined all my routes/navigations in my root component (App.js) and am trying to access one of those screens (UserScreen) from a child component(LoginScreen) on click of a button.
Here is my App.js
import React from 'react';
import { StyleSheet, Text, View, TextInput, TouchableHighlight, Button } from 'react-native';
import LoginComponent from './components/LoginComponent';
import { StackNavigator } from 'react-navigation';

class MainWelcome extends React.Component {
 render() {
   return (
    <View>
     <Text>Welcome Page</Text>
    <Button
      title="Login"
      onPress={() => this.props.navigation.navigate('Login')}
    />
  </View>
  );
 }
}

class LoginScreen extends React.Component {
 render() {
  return (
   <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
     <LoginComponent />
   </View>
  );
 }
}

class UserScreen extends React.Component {
 render() {
  return (
  <View>
    <Text>Details Screen</Text>
  </View>
  );
 }
}

 const RootStack = StackNavigator(
  {
  Register: {
   screen: RegisterScreen,
  },
  Login: {
   screen: LoginScreen,
  },
  UserPage: {
   screen: UserScreen,
  },
  Welcome: {
   screen: MainWelcome,
  },
 },
{
  initialRouteName: 'Welcome',
 }
);

export default class App extends React.Component {
  render() {
    return (
     <RootStack />
   );
  }
 }

This is my LoginComponent.js
  import React from 'react';
  import { StyleSheet, Text, View, TouchableHighlight, TextInput, StackNavigator } from 'react-native';

  class LoginComponent extends React.Component {
   constructor(){
    super();
        this.state = {
                loginusername: '',
                loginpassword: '',
                isloggedin: false,
                loggedinuser: null,
        }
      }

  render() {
   return (
    <View>
      <Text>Please Log In</Text>
    <View>
       <TextInput
           placeholder="USERNAME"
           placeholderTextColor = 'black'
           onChangeText={(loginusername) => this.setState({loginusername})}
            />
      <TextInput
                placeholder="Password"
                placeholderTextColor = 'black'
                onChangeText={(loginpassword) => this.setState({loginpassword})}
            />
      <TouchableHighlight onPress={() => {
        {this.props.navigation.navigate('UserPage')}
        }
      }>
      <View>
      <Text>Login</Text>
      </View>
    </TouchableHighlight>
    </View>
  </View>
  );
 }
}

export default LoginComponent;

Here in LoginComponent.js, I am doing {this.props.navigation.navigate('UserPage')} to redirect to the userscreen on click of a button but it says TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate'). I am not sure what I am doing wrong and if I should be passing something from the App.js to LoginComponent.js.

A: If you tried to print your LoginComponent's props you would end up with nothing!,
But what if you pass the navigation as prop to your component like this! :
// App.js
class LoginScreen extends React.Component {
...
<LoginComponent navigation={this.props.navigation}/>
...
}

You will end up with functional navigation prop.
Happy user details navigation :)


text:
Q: Solr Tokeniser/Filter not scoring catenated/tokenised words I'm having trouble with solr field types, basically I can't seem to get it to return a decent score for stupidly similar terms.

Heres an example:
A store called "Bagelkingdom"
I have two records for this - "Bagelkingdom" and "Bagel Kingdom"
When i search on "Bagelkingdom" I get a score of 14, it returns "Bagel Kingdom" too, but only with a score of 4!
When i do the reverse search on "Bagel Kingdom" I get a score of 13 and it again returns "Bagelkingdom", but this time with a score of 0.16.

I won't paste all my schema file here - I've tried so many different filters the current one doesn't do much.
At the moment my filter is;
     <fieldType name="text_catenate" class="solr.TextField"  positionIncrementGap="2"  autoGeneratePhraseQueries="true">
  <analyzer>
            <filter class="solr.LowerCaseFilterFactory"/>
            <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1"
                    generateNumberParts="1"
                    catenateWords="1"
                    catenateNumbers="1"
                    catenateAll="1"
                    splitOnCaseChange="0"
                    splitOnNumerics="0"
                    preserveOriginal="1"/>
                    <tokenizer class="solr.KeywordTokenizerFactory"/>
  </analyzer>
</fieldType>

A: Maybe you can try to analyze your score to fix it. You can use for example this tool to observe how score is build.


text:
Q: how to do controller initialization in emberjs I have a State in my router which connects an outlet using my view class UserApp.RegistrationView.  Creation of the right controller class for that view, RegistrationController, seems to work magically based on convention:
registration: Em.State.extend({
    route: '/reg',
    registrationModel: null,
    connectOutlets: function (router) {
        router.get('applicationController').connectOutlet(UserApp.RegistrationView, UserApp.RegistrationModel.create());
    }
})

So I do not control creation of the controller, BUT I would like to run some initialization code when a controller is created.  What is the best way to do that?

A: What kind of initialization ? The controller is looked up, and then injected by the framework.
Anyway, with the latest version of emberjs, you can pass an instance of a controller to connectOutlet.
@see https://github.com/emberjs/ember.js/commit/be69395f5eec4187b1df052d7386bcda45f79475

A: You'd better go directly to the source code of built ember.js from master branch. The code annotations are more informative.


text:
Q: How to divide a float number with integer in linux? I have a requirement. I am just trying to find out how can I divide a float with integer in linux and store it in a variable
I tried this, but it didn't work
percent1=`echo "$used*100/$sl"|bc`

Also this
percent1=`echo ($used*100)/$sl | bc


text:
Q: Assign polygon duplicate area (overlap) to only one polygon I have a shapefile (which can be downloaded here http://www.car.gov.br/publico/municipios/downloads?sigla=MA (any would do)) where each polygon represent a rural private property, as the owner submited it. However, the polygons overlap. For the analysis I need to run, an area cannot be accounted twice (ie. be in two properties ). So, on the areas that do overlap, I wanted to assign this duplicate area to the polygon with the smallest area and erase it from the other one.
I've looked at other questions such as this one. But none do really adress this.

A: You can do this by subtracting the smaller polygon from the larger using rgeos::gDifference.
An example:
First we make some dummy polygons to demonstrate on
library(sp)
library(rgeos)
p1 <- Polygon(matrix(c(
  100, 100,
  100, 500,
  900, 500,
  900, 100,
  100, 100), ncol=2, byrow = T))
p2 <- Polygon(matrix(c(
  50, 400,
  50, 600,
  800, 600,
  800, 400,
  50, 400), ncol=2, byrow = T))
p1 <- SpatialPolygons(list(Polygons(list(p1), "p1")))
p2 <- SpatialPolygons(list(Polygons(list(p2), "p2")))
plot(p1)
plot(p2, add=T)

We can use gArea to find which is smaller
a1 = gArea(p1)
## [1] 320000
a2 = gArea(p2)
## [1] 150000

Now we can remove the intersection from the larger polygon with like this:
if (a1>a2){
  p3 = gDifference(p1,p2)
  p4 = p2
} else {
  p3 = gDifference(p2,p1)
  p4 = p1
}
plot(p3)

The two polygons together look like this
plot(p4, add=T)


text:
Q: Output two viewbag values in one embedded code block I have the following code for my HomeController.cs
ViewBag.Test = "hi there";
ViewBag.Message = "sausages";

and then I return View();
In my aspx page, I reference ViewBag.Message like this:

<%:ViewBag.Message %>

How do I go about doing something like ( I know it makes no sense to but... )
<% ViewBag.Message; ViewBag.Test %>

?
In order to output: sausages hi there

A: You're asking how to concatenate strings:
<%: ViewBag.Message + ViewBag.Test %>

You may also want a space.


text:
Q: Jquery appendTo and append is not working in IE11 This is pastehandler.js
$(function () {
    $('div.popp_dialog').each(function (i, el) {

        var paste = (new $.paste()).appendTo(el).on('pasteImage', function (ev, data) {
            var dataUrl = getBase64Image(data.dataURL);
            var imageType = "image/jpeg";
            if (data.dataURL.indexOf("image/png") > 0)
                imageType = "image/png";
            opener.uploadFileOnPaste(dataUrl, imageType);
            // closeWindow();
            window.close();
        })
            .on('pasteText', function (ev, data) {
                alert("Pasted content is not valid. Please paste image content.");
            });
        $(el).click(function () {
            $(paste).focus();
        });
        if (i == 0) {
            paste.focus();
        }
    });

});//]]>

Here my paste.js file
(function() {
  var $, getImageData, readImagesFromEditable;

  $ = jQuery;

  readImagesFromEditable = function(element, cb) {
    return setTimeout((function() {
      return $(element).find('img').each(function(i, img) {
        return getImageData(img.src, cb);
      });
    }), 1);
  };

  getImageData = function(src, cb) {
    var loader;
    loader = new Image();
    loader.onload = function() {
      var canvas, ctx, dataURL;
      canvas = document.createElement('canvas');
      canvas.width = loader.width;
      canvas.height = loader.height;
      ctx = canvas.getContext('2d');
      ctx.drawImage(loader, 0, 0, canvas.width, canvas.height);
      dataURL = null;
      try {
        dataURL = canvas.toDataURL('image/png');
      } catch (_error) {

      }
      if (dataURL) {
        return cb({
          dataURL: dataURL,
          width: loader.width,
          height: loader.height
        });
      }
    };
    return loader.src = src;
  };

  $.paste = function() {
    var div;
    div = document.createElement('div');
    div.contentEditable = true;
    $(div).css({
      width: 1,
      height: 1,
      position: 'fixed',
      left: -100,
      overflow: 'hidden'
    }).on('paste', function(ev) {
      var clipboardData, item, reader, text, _i, _len, _ref, _ref1, _ref2, _ref3,
        _this = this;
      if (((_ref = ev.originalEvent) != null ? _ref.clipboardData : void 0) != null) {
        clipboardData = ev.originalEvent.clipboardData;
        if (clipboardData.items) {
          _ref1 = clipboardData.items;
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            item = _ref1[_i];
            if (item.type.match(/^image\//)) {
              reader = new FileReader();
              reader.onload = function(event) {
                return getImageData(event.target.result, function(data) {
                  return $(div).trigger('pasteImage', data);
                });
              };
              reader.readAsDataURL(item.getAsFile());
            }
            if (item.type === 'text/plain') {
              item.getAsString(function(string) {
                return $(div).trigger('pasteText', {
                  text: string
                });
              });
            }
          }
        } else {
          if (clipboardData.types.length) {
            if ((_ref2 = (text = clipboardData.getData('Text'))) != null ? _ref2.length : void 0) {
              $(div).trigger('pasteText', {
                text: text
              });
            }
          } else {
            readImagesFromEditable(div, function(data) {
              return $(div).trigger('pasteImage', data);
            });
          }
        }
      }
      if (clipboardData = window.clipboardData) {
        if ((_ref3 = (text = clipboardData.getData('Text'))) != null ? _ref3.length : void 0) {
          $(div).trigger('pasteText', {
            text: text
          });
        } else {
          readImagesFromEditable(div, function(data) {
            return $(div).trigger('pasteImage', data);
          });
        }
      }
      return setTimeout((function() {
        return $(div).html('');
      }), 2);
    });
    return $(div);
  };

}).call(this);

Basically this Paste.js and pastehandler.js are child window scripts.
My Code is working fine on all the browsers except IE11. I think appendTo is causing issues.
I tried different way like (new $.paste()).empty().append(el) $(el).append(new $.paste())
neither worked. I think It required some ugly code to get listeners right.
Could Someone please help me. Thanks in Advance.


text:
Q: Is there an Excel formula to provide nth occurrence within a group I'm trying to find a formula to give me the values in 'value' column. I have 2 groupings of items in column A and B. These are overlapping. Given the Product Group in column 1, I want the rank of the Vendor.
I've tried various array formula with if's but am having difficulty figuring it out.
EDIT1:
updating column names so its a bit clearer. my final result wants to be the Product Group_vendor rank column which concatenates the Vendor [B] and the value [D].
See below for example:

A: Product Group
B: Vendor
C: Product
D: value
E: Product Group_vendor rank

1
a
01
bikes
1
a-1

2
a
01
sandals
1
a-1

3
a
01
jeans
1
a-1

4
a
02
barbies
2
a-2

4
b
01
rats
1
b-1

5
b
02
pants
2
b-2

6
b
03
legos
3
b-3

7
c
04
widgets
1
c-1

8
c
05
patches
2
c-2

9
c
05
jewels
2
c-2

10
c
06
bottles
3
c-3

A: You want to use a combo of index match with an array.  You'll need to enter the equation as an array, so hit ctrl + shift + enter instead of just enter after building it.  The {} tells excel it's an array function
First you need a cell with your target group and value for n. For example I'll use G1 for target group and H1 as n.
{=INDEX(D1:D10,SMALL(IF(B1:B10=G1,ROW(B1:B10)-ROW(INDEX(B1:B10,1,1))+1),H1))}

A: This formula will work only if your data is sorted like the one you've posted (it looks like everything is sorted first by column A and then by column B):

=IF(AND(A2=A1;B2=B1);D1;IF(A2=A1;D1+1;1))

In column E, formula is just =A2&"-"&D2

A: This will do it, pasted into D2
=COUNTIFS(A2:A12,A2:A12,B2:B12,">="&B2:B12)


text:
Q: NP-Completeness in Task Scheduling So this is a bit of a thought provoking question to get across the idea of NP-Completeness by my professor. I get WHY there should be a solution, due to the rules of NP-Completeness, but I don't know how to find it. So here is the problem:
The problem is a simple task scheduling problem with two processors. Each processor can handle one of the n tasks, and any two tasks can be done simultaneously. Each task has an end time e, it must be completed by this time. Each task also has a duration d. All time values, such as end time, duration, and the current time in the system (the time will start at 0), are all integers. So we are given a list of n tasks and we need to use these two processors to schedule them ALL. If any one can not be scheduled, the algorithm has to return no solution. Keep in mind that the order does not matter and it doesn't matter which processor gets which task, as long as there is no overlap and each task finishes before its deadline.
So here is where the problem gets conceptual/abstract, say we have access to a special little function, we have no idea how it works, all we know is this: given a list of n tasks and the current schedule, it will return true or false based on whether or not the algorithm is solvable from this point. This function assumes that the already scheduled tasks are set in stone, and it will only change the times of the unscheduled tasks. However, all this function does is return true or false, it will not give you the proper schedule if it does find a solution. The point is that you can use the special function in the implementation of the scheduling problem. The goal is to solve the scheduling problem, and return a working schedule with every job scheduled properly, using a polynomial number of calls to the special function.
EDIT: To clarify, the question is this: Create a solution to schedule all n tasks without any going over deadline, using a polynomial number of calls to the "special function."
I think this problem is to show that verifying a solution is polynomial, but finding it is nonpolynomial. But my professor is insistent that there is a way to solve this using a polynomial number of calls to the special function. Since the problem as a whole is NP-Complete, this would prove that the nonpolynomial aspect of the runtime comes in during the "decision portion of the algorithm.
If you would like me to clear up anything just leave a comment, I know this wasn't a perfect explanation of the problem.

A: Given an oracle M that returns true or false only:
input:
tasks - list of tasks
output:
schedule: a triplet(task,processor,start) for each task
algorithm:
While there is some unscheduled task:
   let p be the processor that currently finished up his scheduled tasks first
   let x be the first available time on x
   for each unscheduled task t:
      assign t with the triplet: (t,p,x)
      run M on current tasks
      if M answers true:
            break the for loop, continue to next iteration of while loop
      else:
            unassign t, and continue to next iteration of for loop
    if no triplet was assigned, return NO_SOLUTION
return all assigned triplets

*

*The above runs in polynomial time - it needs O(N^2) calls to M.

*Correctness of the above algorithm can be proved by induction, where the induction hypothesis is After round k of the while loop, if there was a solution before it, there is still a solution after it (and after the assignment of some task). After proving this claim, correctness of the algorithm is achieved trivially for k=#tasks
Formally proving the above claim:

*

*Base of induction is trivial for k=0.

*Hypothesis: for any k < i, the claim "if there was a solution before round k, there is still one after round k", is correct

*Proof:

Assume there is some solution { (tj,pj,xj)  | j=1,...,n}, ordered by j<u <-> xj<xu, and also assume that t1,t2,...,ti-1 is assigned same as the algorithm yielded (induction hypothesis).
Now, we are going to assign ti, and we'll be able to do it, since we are going to find the smallest available time stamp (xi), and place some task on it. We are going to find some task, and since ti is a possibility - it will not "fail" and yield "NO_SOLUTION".
Also, since the algorithm does not yields "NO_SOLUTION" in iteration i, from correctness of M, it will yield some task t, that by assigning (t,p,x) - there will still be a solution, and the claim for step i is proven.


text:
Q: Why must a module's exports be declared at the bottom of a file? I have the following redacted code:
module.exports = {
  read: read,
  write: write,
};

var read = function(parameters, config, next) {
  /* <snip> */
};

var write = function(parameters, config, next) {
  /* <snip> */
};

If I go to require() this file elsewhere, it will crash node and say that the required object has no method read or write.  Wouldn't variable hoisting pull the functions above the modules.export = { ... };?

A: It's the syntax you use to declare functions that matters due to function hoisting. If you declare those functions like this, they will get "hoisted" up in the scope and all is well.
module.exports = {
  read: read,
  write: write,
};

function read(parameters, config, next) {
  /* <snip> */
};

function write(parameters, config, next) {
  /* <snip> */
};

Side note: Named functions like in my snippet, as opposed to anonymous functions assigned to variables like in your snippet, are easier to debug and profile because their name gets included in stack traces.


text:
Q: How to get find if the input is empty? In my script everything works well except for the output for an empty input.
    <input id="id1" type="number" max="100" min="40">

    <button onclick="count()">OK</button>

I have no idea why is this not working.
Thanks.

A: Try this :
function count() {
        if(inpObj.checkValidity() == false ) {
            document.getElementById('test').innerHTML = inpObj.validationMessage;
        } else if(inpObj.value.length === 0) {
            document.getElementById('test').innerHTML = "Empty"
        } else {
            document.getElementById('test').innerHTML = "Input OK";
        }
    }

See : https://jsfiddle.net/Ldj170Lc/

A: Try this:
length is applied on string not on input object.
inpObj is HTML object(Input)
if(inpObj.checkValidity() == false || inpObj.value.length === 0) {
}

A: You should use inpObj.value.length instead of inpObj.length https://jsfiddle.net/IA7medd/g7e0bLjc/
var inpObj = document.getElementById('id1');

  function count() {
    if(inpObj.checkValidity() == false || inpObj.value.length === 0) {
      document.getElementById('test').innerHTML = inpObj.validationMessage;
    } else {
      document.getElementById('test').innerHTML = "Input OK";
    }
  }


text:
Q: How to improve SEO while using MVC with AJAX I am developing a site using asp.net MVC. I have used AJAX for paging,sorting dropdown fillup,showing different content on link click etc. I came to know that AJAX call is always against SEO and SEO is most important for my site.
Please suggest me ways to improve SEO of my site without removing AJAX.

A: You should have been using progressive enhancement from the start. Your site should work without JavaScript/Ajax being enabled. This way all users, including search engines, can get to your content. Then you should enhance your users' experience by adding JavaScript and Ajax to provide a better experience.
At this point you don't have a lot of options. You'll need to go back and make that content available without JavaScript. You can also use Google's crawlable Ajax standard, too, but that only works for Google and for a slightly more amount of work you can make every search engine, and every user, able to reach your content by not making JavaScript required to use your website.


text:
Q: Changing file extensions
Possible Duplicate:
Renaming multiple files (changing extension)

Suppose I have a bunch of files with the extension .x and I want to change them so that they have the extension .y. I know $ mv *.x *.y wouldn't work because I havn't expressed each file to change their respective extensions (that and the command expects *.y to be a directory).
What command should I issue?

A: You can use rename to rename files based on a pattern, and one of the examples from the man page is changing the extension of a group of files. It takes the source pattern, modified pattern, and the files to operate on, so in your case:
$ rename .x .y *.x

It changes the first occurrence of .x to .y, so if you happen to have .x anywhere other than the end of the filename it's going to change that first


text:
Q: Nativescript + Vue: sync only works the first time on both device and emulator Project Nativescript + Vue
NativeScript CLI version: 5.4.2
package.json
  "dependencies": {
    "axios": "0.19.0",
    "jwt-decode": "2.2.0",
    "moment": "^2.24.0",
    "nativescript-iqkeyboardmanager": "^1.5.1",
    "nativescript-pulltorefresh": "2.3.0",
    "nativescript-theme-core": "~1.0.6",
    "nativescript-ui-listview": "6.4.2",
    "nativescript-vue": "~2.2.2",
    "nativescript-vue-navigator": "0.0.3",
    "tns-core-modules": "~5.4.3",
    "vuex": "3.1.1"
  },
  "devDependencies": {
    "@babel/core": "~7.4.5",
    "@babel/preset-env": "~7.4.5",
    "babel-loader": "~8.0.6",
    "nativescript-dev-webpack": "^0.24.1",
    "nativescript-vue-template-compiler": "~2.2.2",
    "node-sass": "^4.12.0",
    "vue-loader": "^15.7.1"
  },

When I build and run "tns run" or "tns debug" or use "Run on device" on Sidekick, the syncronization on both device and emulator only works the first time.
From the second time I get blank screen or get the error:

Calling js method onCreateView failed
Error: View already has a parent. View: Page(23) Parent:
  TabViewItem(22)

I've already tried to disable Hot Module Replacement but the problem continue.
The only solution is to uninstall the app and rerun the local build.
The problem occours on both local and cloud build.
Any idea?
Thanks

A: Actually I refactored my application ising NS6 and now it works well!


text:
Q: Passing outside variable to a class c++ I have put a simplified version of my code here. What I'm trying to do is to read every line from an input file and store it in class "fifo". Before every store however, I try printing my previous fifo value (this was for debugging). What I see is that the previous value is being overwritten even before I call the fifo.add function. The getline function itself is overwriting the fifo on its own. Can somebody please tell me what is going on here?
//fifo.h

#ifndef FIFO_H_
#define FIFO_H_

class fifo {
        private:
                char* instr_arr;
                int head;
                int tail;
        public:
                fifo();
                fifo(int,int);
                void add(char*);
                void print_instruction(void);
};

#endif

//fifo.cpp

#include "fifo.h"
#include <iostream>
//using namespace std;

fifo::fifo() {
        head = 0;
        tail = 0;
        instr_arr = "NULL";
}

fifo::fifo(int h, int t) {
        head = h;
        tail = t;
}

void fifo::add (char *instr) {
        instr_arr = instr;
}

void fifo::print_instruction (void) {
        std::cout << instr_arr << std::endl;
}

//code.cpp

#include <iostream>
using namespace std;
#include <fstream>
using namespace std;
#include "fifo.h"

#define MAX_CHARS_INLINE 250

int main (int argc, char *argv[]) {
        char buf[MAX_CHARS_INLINE];     //Character buffer for storing line
        fifo instruction_fifo;          //FIFO which stores 5 most recent instructions

        const char *filename = argv[1];
        ifstream fin;
        fin.open(filename);

        while(!fin.eof()) {
                std::cout << buf << std::endl;
                fin.getline(buf, MAX_CHARS_INLINE);
                instruction_fifo.print_instruction();  //This instruction prints the line which was read from getline above!! Why??
                instruction_fifo.add(buf);
                }
        return 0;
}

A: You are not actually storing the data in the FIFO (or in a memory block managed by the FIFO), only the pointer (which points to buf).
When you print instr_arr, you are basically printing buf, because instr_arr points to buf.


text:
Q: How do you use the Chinese Remainder Theorem? I know that the theorem is

$$x \equiv b_1\pmod {m_1}$$
  $$x \equiv b_2\pmod {m_2}$$
  $$x \equiv b_3\pmod {m_3}$$
  $$\cdot\quad\cdot\quad\cdot$$
  $$x \equiv b_k\pmod {m_k}$$
  has a unque solution modulo $m_1m_2...m_k$

but I don't know how to use it. I can multiply the $m$'s together, but what do I do after that? How do I know what to multiply the whole expression by?

A: We also need to suppose that $\gcd (m_1,\ldots, m_k) = 1$, otherwise the theorem does not hold.
For each  $i = 1,\ldots,k$, let us define $n_i = \frac {m_1\cdots m_k}{m_i}$. Note that $\gcd (n_i, m_i) = 1$, because $\gcd (m_j,m_i) = 1, \forall j \neq i$. Let $\alpha_i$ be the inverse of $n_i$ modulo $m_i$, i. e., $\alpha_i$ is such that $\alpha_i n_i + \beta_i m_i = 1$, for some $\beta_i$.
Fact: $x_0 = b_1\alpha_1 n_1 + \cdots + b_k\alpha_k n_k$ is solution to the system.
Indeed, notice that if $j \neq i$, $n_j \equiv 0 \pmod{m_i}$ and, therefore, $$x_0 \equiv b_i\alpha_i n_i + \sum_{\substack{j = 1\\j \neq i}}^k b_j\alpha_j n_j \equiv b_i (\alpha_i n_i) + 0\equiv b_i1 \equiv b_i\pmod{m_i}.$$
Since the solution is unique modulo $m_1\cdots m_k$, we have that all solutions are of the form $$x = x_0 + k(m_1\cdots m_k), \quad k \in \mathbb{Z}.$$

A: You may also use it in its other form: Znm~Zn×Zm if and only if (m,n)=1. (also working for more than two numbers)


text:
Q: How to mask svg image with a rectangle using d3? I'm trying to mask an svg image with a gray background rectangle so that I can show a different color partially using d3.js v5.
SVG
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 18.1.1, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 53.545 53.545" style="enable-background:new 0 0 53.545 53.545;" xml:space="preserve">
<g>
    <g>
        <circle cx="26.686" cy="4.507" r="4.507"/>
        <path d="M28.256,11.163c-1.123-0.228-2.344-0.218-3.447,0.042c-7.493,0.878-9.926,9.551-9.239,16.164
            c0.298,2.859,4.805,2.889,4.504,0c-0.25-2.41-0.143-6.047,1.138-8.632c0,3.142,0,6.284,0,9.425c0,0.111,0.011,0.215,0.016,0.322
            c-0.003,0.051-0.015,0.094-0.015,0.146c0,7.479-0.013,14.955-0.322,22.428c-0.137,3.322,5.014,3.309,5.15,0
            c0.242-5.857,0.303-11.717,0.317-17.578c0.244,0.016,0.488,0.016,0.732,0.002c0.015,5.861,0.074,11.721,0.314,17.576
            c0.137,3.309,5.288,3.322,5.15,0c-0.309-7.473-0.32-14.949-0.32-22.428c0-0.232-0.031-0.443-0.078-0.646
            c-0.007-3.247-0.131-6.497-0.093-9.742c1.534,2.597,1.674,6.558,1.408,9.125c-0.302,2.887,4.206,2.858,4.504,0
            C38.678,20.617,36.128,11.719,28.256,11.163z"/>
    </g>
</g>
</svg>

d3.js
private createSVG(rect): void {

    this.svg = d3.select(rect)
      .append('svg')
      .attr('class', 'psych-chart')
      .attr('width', this.width/2)
      .attr('height', this.height / 2)
      .attr("viewBox", '0 0 65 60')

  }

  private createChart() {

    let that = this;

    const rect = this.svgContainer.nativeElement;
    this.createSVG(rect);

    mask();

    d3.xml("../assets/images/person.svg")
      .then(xml => {

        var personFigure = xml.getElementsByTagName('g')[1];

        that.svg.node().append(personFigure);

        that.person = that.svg.select('g')
          .attr('transform', `translate(${that.margin.left}, ${that.margin.top})`)
          .attr('class', 'person-svg')

        that.person.select('path')
          .style('fill-opacity', 1)
          .style('fill', '#e7e7e7')
          .style('stroke-width', 0.3)
          .style('stroke', '#e7e7e7')
          .attr('mask', 'url(#person-mask)')

        that.person.select('circle')
          .style('fill', '#e7e7e7')
          .style('stroke-width', 0.3)
          .style('stroke', '#e7e7e7')
          .attr('mask', 'url(#person-mask)');

        styleImportedSVG();

      });

    function mask() {
      const mask = that.svg
        .append('defs')
        .append('mask')
        .attr('id', 'person-mask')
        // add image in the clip-path

      // add background which is clipped
      mask.append('rect')
        .style('fill', '#01579b')
        .attr('width', 65)
        .transition()
        .duration(5000)
        .attr('height', 60)

    }

    function styleImportedSVG() {

      console.log('count', that.psychSafeMembersPercent);

      //that.svg.on('mouseover', function () {
      //  d3.selectAll('path')
      //    .attr('fill-opacity', 0.1)
      //    .attr('stroke-opacity', 0.3)
      //})

    }

  }

I don't know why the masking is not working in my case. What I want is to fill the SVG image with masking rect such that it's only filled partially depending on the value I provide - like 10%, 20% etc. How can I achieve this?
jsfiddle

A: I figured it out. This is the way that I did it but I'm sure there's a better way to do it. Any help and modification would be greatly appreciated.
this.maskHeight = (parseFloat(percentage) / 100 * parseFloat(this.mask.attr('height')));

    // add background which is clipped
    this.mask.append('rect')
      .attr('fill', '#fff')
      .attr('width', 65)
      .transition()
      .ease(d3.easeBounce)
      .duration(2000)
      .attr('height', this.maskHeight)

    d3.xml("../assets/images/person.svg")
      .then(xml => {

        var personFigure = xml.getElementsByTagName('g')[1];

        // adds person image to svg
        that.svg.node().append(personFigure);

        // styling
        // person svg for the background
        that.svg.select('g')
          .attr('transform', `translate(${that.margin.left}, ${that.margin.top})`)
          .attr('class', 'person-svg-bg')

        var clone = that.svg
          .select('g').node()
          .cloneNode(true);

        that.svg.node().append(clone)

        var circle = that.svg.selectAll('circle')
          .attr('id', function (d, i) { return 'person-head-' + i })
          .style('fill', function (d, i) { if (i === 0) { return '#FFCC00' } else { return 'none' } })
          .style('stroke', function (d, i) { if (i === 0) { return null } else { return '#E7E7E7' } })
          .style('stroke-width', function (d, i) { if (i === 0) { return null } else { return 0.6 } })
          .attr('mask', function (d, i) { if (i === 0) { return 'url(#person-mask)' } else { return null } })

        var path = that.svg.selectAll('path')
          .attr('id', function (d, i) { return 'person-path-' + i })
          .style('fill', function (d, i) { if (i === 0) { return '#FFCC00' } else { return 'none' } })
          .style('stroke', function (d, i) { if (i === 0) { return null } else { return '#E7E7E7' } })
          .style('stroke-width', function (d, i) { if (i === 0) { return null } else { return 0.6 } })
          .attr('mask', function (d, i) { if (i === 0) { return 'url(#person-mask)' } else { return null } })

      });


text:
Q: chrome.mediaGalleries / cannot read property 'getMediaFileSystems' I have some problem with chrome app:
I need to get a local img, but chrome.mediaGalleries.getMediaFileSystems does not work.
But its already added to permission :
"mediaGalleries":["read","allAutoDetected"]
Where can be a problem?
  chrome.mediaGalleries.getMediaFileSystems(
  {interactive: 'no'},
  function(mediaFileSystems){
    mediaFileSystems.forEach(
      function(item, indx, arr){
        var mData = chrome.mediaGalleries.getMediaFileSystemMetadata(item);
        console.log(mData);
      });
  });

A: Check the chrome.mediaGalleries docs again. It's getMediaFileSystems not getMediaFileSystem. There's an 's'.
Also, check the full chrome app sample in chrome-app-samples/samples/media-gallery.


text:
Q: Data not showing in JTable I am using a DAO Factory to get my Data from the database. When i am running my program the data is showing in the printline so he is getting it out of the database. But i want it to show in my JTable but this one is empty and i dont know how to fill it.
Code JFrame:
package View;

import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.WindowConstants;
import javax.swing.table.TableModel;

import Controller.VerwijderController;
import Model.OefeningenListModel;
import Model.OefeningenTableModel;

public class VerwijderenHome extends JFrame {

    private JList LijstOefening;
    private JScrollPane jScrollPane1;
    private Container window = getContentPane();
    private JButton delete;
    private VerwijderController Controller;
    private JTable tabel;

    public VerwijderenHome()
    {
        initGUI();
    }

    public void addDeleteListener(ActionListener a){
        delete.addActionListener(a);
    }

    private void initGUI() {
        setPreferredSize(new Dimension(800, 600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(null);
        setVisible(true);

        JTable table = new JTable(new OefeningenTableModel());
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(50, 50, 300, 60);
        window.add(scrollPane);

        delete = new JButton("Delete");
        delete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        delete.setBounds(50, 265, 100, 30);
        window.add(delete);

        pack();

        Controller = new VerwijderController();
        addDeleteListener(Controller);

    }

    public JButton getDelete(){
        return delete;
    }

    public JList getLijst()
    {
        return LijstOefening;

}
    }

Code DefaultTableModel?? (Dont know if i must use this one)
package Model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

import datapackage.DAOFactory;

public class OefeningenTableModel extends DefaultTableModel {

      ArrayList<Oefening> oefeningen;

      public OefeningenTableModel(){

          oefeningen = DAOFactory.getFactory(0).getIDAOOefening().load();

      }

    }

A: The DefaultTableModel is backed by a Vector representing the columns and rows of the table model.
You've provided your own ArrayList of objects, but you've not overridden the methods you will require to supply that data back to the table.  The DefaultTableModel has no idea of your ArrayList
Try overridding some of the following;
public class OefeningenTableModel extends AbstractTableModel {

    ArrayList<Oefening> oefeningen;

    public OefeningenTableModel(){
        oefeningen = DAOFactory.getFactory(0).getIDAOOefening().load();
    }

    @Override
    public int getRowCount() {
        return oefeningen.getSize();
    }

    @Override
    public int getColumnCount() {
        // You'll need to fill this out to meet your requirements
    }

    @Override
    public String getColumnName(ing column) {
        // You'll need to fill this out to meet your requirements
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        // You'll need to fill this out to meet your requirements
    }

}

Take the time to have read through How to use Tables.


text:
Q: Render multiple files in POV-Ray (Windows) I know this has been asked before, but none of the answers really helped me. So my problem is this: I have a bunch of .pov files named, XXXXX000001...., and I want to render them, but the queue thing inside of POV-Ray only lets you render 500 at a time. So, is there a way to render them all automatically? I know the answer is to write a script of some kind, but I don't know a lot about it so if you could give me a step by step instructions I would be grateful.

A: Create a POV-Ray .ini file SimpleAnimation.ini using notepad, and in that file specify the number of .pov files as Initial_Frame/Final_Frame. This .ini file is the file you Open and Run to render all the frames. You can also use Subset_Start_Frame/Subset_End_Frame with duplicate .ini files when rendering subsets over multiple machines:
Input_File_Name="SimpleAnimation.pov"
Width=800
Height=600
Antialias=On
Antialias_Threshold=0.05
Output_File_Type=N

Initial_Frame=1
Final_Frame=124

# Change these values to render a subset of the frames #
Subset_Start_Frame=1
Subset_End_Frame=124

Your SimpleAnimation.pov file will then be loaded once per frame and in that .pov file you just load the relevant frame file you want using the POV-Ray variable frame_number:
#if(frame_number=1)
#include "SimpleAnimation000001.pov"
#end
#if(frame_number=2)
#include "SimpleAnimation000002.pov"
#end
#if(frame_number=3)
#include "SimpleAnimation000003.pov"
#end

The rendered images will be generated with names according to the Input_File_Name in the SimpleAnimation.ini file with leading zeros according to the number of digits in Final_Frame, e.g. for 124 frames you get:
SimpleAnimation001.png
SimpleAnimation002.png
...
SimpleAnimation124.png

A: An addition to the previous answer, SimpleAnimation.pov file can be just a one line:

#include concat("FolderPath/SimpleAnimation.", str(frame_number, -6, 0), ".pov")


text:
Q: Undefined at the end of console output from a for in iteration over an associative array, JavaScript? I have the following code( function named group) which groups people objects from persons array into arrays by a certain property(belonging to person object) inside an associative array. So groups(arrays) of people are placed into the resulting associative array by a key that is the property value. For example we have an array that is created and stored into the final array by lastname='Bunny': all the four people from persons with last name Bunny. The problem is that when I do a for in loop trying to display the objects I have at the end of every group an undefined object. This does not happen if I go through the array/object with a for loop. But I can not do it with the associative array since it does not have indexes. I wanted to know why does console.log display an undefined value, can it do something with the prototype? Thanks.
                persons=[
                    { firstname: 'Funny', lastname: 'Bunny', age: 32 },
                    { firstname: 'Little', lastname: 'Bunny', age: 12 },
                    { firstname: 'Buggs', lastname: 'Bunny', age: 42 },
                    { firstname: 'Ivan', lastname: 'Petrov', age: 52 },
                    { firstname: 'Honey', lastname: 'Bunny', age: 22 },
                    { firstname: 'John', lastname: 'Doe', age: 32 },
                    { firstname: 'Mike', lastname: 'Doe', age: 22 }
                ];

                function group(personsArray, groupType) {
                    var associativeArray = {};
                    for (var i in personsArray) {
                        if (!associativeArray[personsArray[i][groupType]]) {
                            associativeArray[personsArray[i][groupType]] = [];
                        }
                        associativeArray[personsArray[i][groupType]].push(personsArray[i]);
                    }
                    return associativeArray;
                }
                var res = group(persons, 'lastname');
                for (var item in res) {
                    console.log('GROUP: ' + item);
                    for (var i = 0; i < res[item].length; i++) {
                        console.log((res[item])[i].firstname);
                    }
                }

                Output:
                        GROUP: Bunny
                        Funny
                        Little
                        Buggs
                        Honey
                        GROUP: Petrov
                        Ivan
                        GROUP: Doe
                        John
                        Mike
                        GROUP: undefined
                        undefined

A: Read Why is using "for...in" with array iteration a bad idea?. If you have any other enumerable properties on your persons array - e.g. inherited from the Array.prototype, then it will also group their lastNames, which are undefined.


text:
Q: Cross compiling issues with mkbundle in Mono I facing some issues while trying to use the new cross-compile/linking feature on Mono Linux, with the mkbundle tool.
I'm using Linux Mint 14.04 32 bit in a Intel x86 environment and I would like to create a static binary using mkbundle for 64bit platforms.
As a reference I'm using Mono, version 4.6.2
mc@Carles-nix ~ $ mono --version
Mono JIT compiler version 4.6.2 (Stable 4.6.2.16/ac9e222 Tue Jan  3 11:57:29 UTC 2017)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           __thread
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  x86
    Disabled:      none
    Misc:          softdebug
    LLVM:          supported, not enabled.
    GC:            sgen

According to the documentation I need to have the destination target file first, so I try to fetch it from the server:
mc@Carles-nix ~ $ mkbundle --fetch-target 4.6.1-linux-libc2.12-amd64 --target-server https://download.mono-project.com/runtimes/raw/
Downloading runtime https://download.mono-project.com/runtimes/raw/4.6.1-linux-libc2.12-amd64 to /home/mc/.mono/targets/4.6.1-linux-libc2.12-amd64/mono
Failure to download the specified runtime from https://download.mono-project.com/runtimes/raw/4.6.1-linux-libc2.12-amd64
mc@Carles-nix ~ $

But as you can notice, I always get the same error, no matter what is the file that I try to download.
I've noticed that there is no file for my version (4.6.2), so I'm not sure if this could be the root of the issue.
Could anybody please give me any clue on what is going on?
Thank you very much in advance.

A: Just in case anybody would need an answer to this:
I've contacted the guys at the Mono Project and it seems that there is a problem in their servers, so they proposed me to use an alternate server:
$ mkbundle --fetch-target 4.6.1-linux-libc2.12-amd64 --target-server https://mono-project.azureedge.net/runtimes/raw/

A: For me, I need to add .zip to download targets:
mkbundle --fetch-target mono-4.8.0-ubuntu-16.04-x86.zip

As well as adding .zip on --cross option.


text:
Q: trouble requiring unique input in c#? I need to request 10 numbers from the user as individual inputs. Each number must be between 10 and 100, inclusive.
Compare each number to the last one entered to determine if it is a duplicate. If it is, ask the user for a different number.
Output each number to the screen once you have determined that all conditions are met.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
          String userNumber;
          int userNumberInt;
          // declare a variable to save the previous
          for (int i = 0; i < 10; i++)
          {
              Console.WriteLine("Enter your Number:");
              userNumber = Console.ReadLine();
              userNumberInt = Convert.ToInt32(userNumber);
              if ((userNumberInt <= 100) && (userNumberInt >= 100))
              {
                  Console.WriteLine("Your Valid number is" + userNumber);
                  // set previous to the usernumber
              }
              // else if(previous == userNumber)
              // another invalid situatuion just like below
              else
              {
                  Console.WriteLine("Invalid Number"};
                  i--; // giving another chance
              }
          }
          Console.ReadLine();
        }
    }
}

A: Just do that the comments state...
// declare a variable to save the previous

Should be:
int previous = 0;

Then:
// set previous to the usernumber

Should be:
previous = userNumberInt;

Ajust and fix you condition:
if ((userNumberInt <= 100) && (userNumberInt >= 100))

Should be:
if ((userNumberInt <= 100) && (userNumberInt >= 10) && (userNumberInt != previous))

Outputting the numbers is left as an exercise... ;)


text:
Q: Referencing to python array slices and memory usage I would like to create multiple references to the same sequence of numbers. Can't use indexes, the data should be explicitly available as a sequence. The results is used later for read-only operations.
What i tried:
m = np.array([[199, 299,   3],[  4,   5,   6],[  7,   8,   9]])
a=m[1,]

I know that this supposed to copy:
a[:]

now if I try:
b=[]
for x in range(100000): b.append(a[:])

I get an about 16MB increase in memory usage (task manager)
Where:
for x in range(100000): b.append(a)

adds less than 1MB to used mem.
Anyway changing a or changing a[:] changes m. And b appears to be equal in both examples.
What is going on here, and what is the best way to reference the same row with minimum memory usage.


text:
Q: jpanel overeride the other compoent zorder in java swing application I am making a network managemant system with arcgis map using arcobject java and swing application but the problem is that one panel zindex override the others. the result is that Jpopup menu and tab menu list not showing in the main frame.
I think its Zcompent order problem. I have hanlde these problems in javascipt with increasing the zindex of corresponding div and span but in java swing application its very difficult to find the problem.
Kindly suggest the possible solution. please see the image to understand the problem in deatils.

*

*


text:
Q: Creating object from subset of properties inline in ES6 Let's say I have an object obj:
let a = b = c = d = 1;
let obj = { a, b, c, d };

I would like to create new object inline, with the same properties but one property changed. So far I have this:
let other = Object.assign({a: obj.a, b: obj.b, c: obj.c}, {d: 3});

and this:
let other = Object.assign((({a, b, c}) => ({a, b, c}))(obj), {d: 3});

Is there a better way how to do this in ES6? Does functional libraries (like lodash) have any utility to do this?

A: You can unpack the old object with the Object Spread operator into a new object and just supply the key you want overwritten with the new value.
let obj2 = {
  ...obj,
  d: 4
}

[object Object] {
    a: 1,
    b: 1,
    c: 1,
    d: 4
}

As @azium pointed out this is a stage-2 proposal meaning you need to install it into Babel if you have Babel 6.x if 5.x it'll be enabled by default.
npm install babel-preset-stage-2

A: For sure, Object.assign can do it for you. It accepts multiple objects as arguments:
 let other = Object.assign({}, obj, {d: 3})

Here we created a new "object-receiver" and put it as the first argument. Then goes our source object and, at last, we added new properties. In a case of overlapping keys, the value from latest argument will be used.
Object Spread operator from Henrik's answer does exactly the same thing, but it hasn't standardized yet. Object.assign is a part of ES6 and already implemented in the most recent browsers.


text:
Q: Laravel 5: The server responded with a status of 405 (Method Not Allowed) I am trying to upload a file via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" The route is defined like this: Route::post('/file/upload', 'Upload@importFile');  And the Ajax code I'm using is this:
var upload_file=function(input_file,format){
            var formData = new FormData();
            formData.append("upload_file",input_file);
           // formData.append("format",format);
            return $.ajax({
                type: 'POST',
                dataType: 'json',
                processData: false,
                contentType:  false,
                data: formData,
                cache:false,
                url: '/file/upload/'
            });
        }

Somehow it works locally, but it throws this error when I try it on the server, however I've used this same code before and it's worked fine

A: You can try to remove last "/" in the url.Like that: url: '/file/upload'
var upload_file=function(input_file,format){
        var formData = new FormData();
        formData.append("upload_file",input_file);
       // formData.append("format",format);
        return $.ajax({
            type: 'POST',
            dataType: 'json',
            processData: false,
            contentType:  false,
            data: formData,
            cache:false,
            url: '/file/upload'
        });
    }


text:
Q: create and save cookies on onclick Can anyone help me set up a cookie function that can take user input by checking which link the user clicked on and then redirect them to that link and create a cookie for it so the next time the user comes they automatically get redirected.
Can anyone please tell me what am I doing wrong. I want multiple links and clicking on each link should create a cookie and redirect the user.
Can anyone provide a working jsFiddle please.
The code is below please help:
  //Html
  something site
  something2 site
  // Javascript
  function redirectOne(state)
  {
    createCookie('state', state, 90);
    window.location.href = "www.something1.com" + state;
  }

  function redirectTwo(state)
  {
    createCookie('state', state, 90);
    window.location.href = "www.something2.com" + state;
  }

  var cookie = readCookie('state');
  if (cookie != null)
  {
    window.location.href = "www.something.com" + cookie;
  }

 function createCookie(name,value,days) {
 if (days)
   {
     var date = new Date();
     date.setTime(date.getTime()+(days*24*60*60*1000));
     var expires = "; expires="+date.toGMTString();
   }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
 }

 function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
   }
     return null;
}

function eraseCookie(name) {
   createCookie(name,"",-1);
 }

A: Your problem is that when you call this line in each function
 createCookie('state', state, 90);

It's taking the value of '/home' from the onClick event and passing it to the cookie creation routine.  You should be passing in something other than '/home' for both functions.
  something site
  something2 site
  // Javascript
  function redirectOne(state)
  {
    createCookie('state', state, 90);
    window.location.href = state+'/home';
  }

You do not need the redirectTwo function at all.


text:
Q: bash script to stop certain idVendor from mounting I wanted to write a bash script to stop certain idVendors from mounting, my thought was to use tail -f /var/log/messages and greping it to idVendor and blocking that certain vendor upon detection, can someone help me on this please?

A: A udev rule would come in handy here. On my arch system I would simply add a rule like this (didn't try it out though). create a file in
/etc/udev/rules.d/40-do-not-mount.rules

and add a line like this (replacing [VENDOR ID] and [PRODUCT ID] with the ones from your device, wildcards are allowed)
SUBSYSTEM=="usb",ATTR{idVendor}=="[VENDOR ID]", ATTR{idProduct}=="[PRODUCT ID]",ENV{UDISKS_IGNORE}="1"

then reload
udevadm control --reload-rules

test your rule:
udevadm test /sys/dev/block/[device]

it should output something like
...
UDISKS_IGNORE=1
USEC_INITIALIZED=760036464
unload module index
Unloaded link configuration context

Some references:

*

*Arch linux docs

*Writing udev rules