Why make cheese if milk is already food?

Question: In Dwarf Fortress, milk is already a food item, and if I am not mistaken, you get one cheese for every one milk.  So would the only benefit of cheese be that it is just one more ingredient for making meals?  Do dwarves, even without a preference for cheese, generally like cheese better or get more out of it?
Are there any other advantages? (besides cheese loving dwarfs making engravings of cheese)
Answer: Milk rots. I'm fairly sure cheese doesn't - or at least does so at a much slower rate.
ETA: Apparently, it does rot, but cheese is ten times as valuable as the milk it was made from - and turning milk into cheese frees up the jug you were using.
... And, of course, is an extra task, meaning extra job experience.
Comment: There is nothing in dwarf fortress to support rotting at different speeds. It either `[ROTS]` or it doesn't. Cheese is, however, 10 times more valuable than the raw milk.
Comment: Cheese **does** rot. There is no real difference, aside from individual dwarf preferences.
Answer: I think cheese is worth more, as it can have quality.
Comment: @Wipqozn cheese is worth more, but it can't have quality. It does have 10x the value of the milk, however.
Comment: Are you able to confirm this? If you're not sure, you should post this as a comment, not an answer, until you can confirm it.
Answer: And the most important reason: dwarves don't consider milk drinkable. Only booze (and water if injured) is drinkable. Cheese, on the other hand is not only eatable for your dwarves, it is also a solid food which means you can increase its value even more by cooking it into meals with much less trouble than liquid foods.


Angular using Apollo: Unit testing: Error: Client has not been defined yet

Question: I'm using apollo client for graphql. I set up the client in GraphQLModule which I'm importing in AppModule. I'm making a query in a service which is also imported right in the AppModule.
But i get this error: Error: Client has not been defined yet
Tried already: Angular - Apollo: Client has not been defined yet.
grapgql.module.ts
import { NgModule } from '@angular/core';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { environment } from 'src/environments/environment';
import { GraphqlService } from './graphql.service';

const uri = 'https://api.example.com/graphql';
export function createApollo(httpLink: HttpLink) {
    return {
        link: httpLink.create({ uri }),
        cache: new InMemoryCache(),
    };
}

@NgModule({
    exports: [
        ApolloModule,
        HttpLinkModule
    ],
    providers: [
        {
            provide: APOLLO_OPTIONS,
            useFactory: createApollo,
            deps: [HttpLink],
        },
        GraphqlService,
    ],
})
export class GraphQLModule { }

graphsl.service.spec.ts - this test passes.
import { TestBed } from '@angular/core/testing';

import { GraphqlService } from './graphql.service';
import { Apollo } from 'apollo-angular';

describe('GraphqlService', () => {
    let service: GraphqlService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                GraphqlService,
                Apollo
            ]
        });
        service = TestBed.inject(GraphqlService);
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });
});

app.module.ts - this test fails and throws error: Client has not been defined yet
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { GraphQLModule } from './graphql/graphql.module';
import { HttpClientModule } from '@angular/common/http';
import { CmTableModule } from './shared/cm-table/cm-table.module';
import { CmComponentsModule } from './shared/cm-components/cm-components.module';
import { CmDirectivesModule } from './shared/cm-directives/cm-directives.module';
import { CmPipesModule } from './shared/cm-pipes/cm-pipes.module';
import { CmDragDropModule } from './shared/cm-drag-drop/cm-drag-drop.module';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { GraphqlService } from './graphql/graphql.service';

const uri = 'https://api.example.com/graphql';
export function createApollo(httpLink: HttpLink) {
    return {
        link: httpLink.create({ uri }),
        cache: new InMemoryCache(),
    };
}
@NgModule({
    declarations: [
        AppComponent,
    ],
    exports: [
        ApolloModule,
        HttpLinkModule
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        NoopAnimationsModule,
        GraphQLModule,
        HttpClientModule,
        CmTableModule,
        CmComponentsModule,
        CmPipesModule,
        CmDirectivesModule,
        CmDragDropModule,
        ApolloModule,
        HttpLinkModule
    ],
    providers: [{
        provide: APOLLO_OPTIONS,
        useFactory: createApollo,
        deps: [HttpLink],
    },
        GraphqlService],
    bootstrap: [AppComponent]
})
export class AppModule { }

app.component.spec.test
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { GraphqlService } from './graphql/graphql.service';
import { Apollo, ApolloModule } from 'apollo-angular';

describe('AppComponent', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule,
                ApolloModule
            ],
            declarations: [
                AppComponent
            ],
            providers: [
                GraphqlService,
                Apollo
            ]
        }).compileComponents();
    }));

    it('should create the app', () => {
        const fixture = TestBed.createComponent(AppComponent);
        const app = fixture.componentInstance;
        expect(app).toBeTruthy();
    });

});

Answer: Add imports: [GraphQLModule] to your TestBed.configureTestingModule:
TestBed.configureTestingModule({
        imports: [
            RouterTestingModule,
            **GraphQLModule**,
            ApolloModule
        ],
        declarations: [
            AppComponent
        ],
        providers: [
            GraphqlService,
            Apollo
        ]
    }).compileComponents();


How to make a ball hang from a rope?

Question: I'm trying to make a simple game using P5.js library where a ball is attached to a pin with a rope and it must not exceed the rope lenght when it falls down.
The ball must fall until it reaches the distance from the pin equal to the rope length. How can I do it? I just need it working with the y axis.
here is some code:

var compound;

function Compound(){
    this.pinDiameter = 25;
    this.pinx = width/2;
    this.piny = height/2;

    this.ballDiameter = 50;
    this.ballx = width/2;
    this.bally = height/2 + 200;

    this.ropeWidth = 4;
    this.ropeHeight = 200;
    this.ropex = this.pinx - this.ropeWidth/2;
    this.ropey = this.piny;

    this.updatePin = function(){
    }

    this.updateBall = function(){
        this.ballSpeed  = this.ballSpeed + 1;
        this.bally = this.bally + this.ballSpeed;
    }

    this.updateRope = function(){
    }

    this.show = function(){
        ellipse(this.pinx, this.piny, this.pinDiameter);
        fill(255);
        noStroke();

        ellipse(this.ballx, this.bally, this.ballDiameter);
        fill(255);
        noStroke();

        rect(this.ropex, this.ropey, this.ropeWidth, this.ropeHeight);
        fill(255);
        noStroke();
    }
}

function setup() {
    createCanvas(600, 600);
    compound = new Compound();
}

function draw() {
    background(0);
    compound.updatePin()
    compound.updateBall()
    compound.updateRope()
    compound.show()
}

Answer: hope it helps

var compound;

    function Compound(){
        this.pinDiameter = 25;
        this.pinx = width/2;
        this.piny = height/2;

        this.ballDiameter = 50;
        this.ballx = this.pinx;
        this.bally = this.piny + 100;
        this.ballSpeed = 0;
        this.ballGravity = 0.5;

        this.ropeWidth = 4;
        this.ropeHeight = 200;
        this.ropex = this.pinx - this.ropeWidth/2;
        this.ropey = this.piny;

        this.onPin = function(x, y) {
            let dx = x - this.pinx;
            let dy = y - this.piny;
            let dist = Math.sqrt(dx*dx, dy*dy)
            return dist <= this.pinDiameter/2;
        }

        this.ropeheightcalc = function(){
            let dx = this.bally - this.piny;
            return dx;
        }

        this.drag = false;
        this.catch = function() {
              this.drag = true;
              this.mousex = mouseX;
              this.mousey = mouseY;
        }

        this.drop = function() {
              this.drag = false;
        }

        this.updatePin = function(){
            if (this.drag) {
                this.piny = mouseY;
                this.mousey = mouseY;
            }
        }

        this.updateBall = function(){
            this.ballSpeed  = this.ballSpeed + this.ballGravity;
            this.bally = this.bally + this.ballSpeed;

            if(this.bally > this.piny + 200){
                this.bally = this.piny + 200;
                this.ballSpeed = 0;
            }
        }

        this.updateRope = function(){
            if (this.drag) {
                this.ropey = this.piny;
                this.ropeHeight = this.ropeheightcalc();
            }
        }

        this.show = function(){
            ellipse(this.pinx, this.piny, this.pinDiameter);
            fill(255);
            noStroke();

            ellipse(this.ballx, this.bally, this.ballDiameter);
            fill(255);
            noStroke();

            rect(this.ropex, this.ropey, this.ropeWidth, this.ropeHeight);
            fill(255);
            noStroke();
        }
    }

    function mousePressed() {
        if ( compound.onPin(mouseX, mouseY))
            compound.catch();
    }

    function mouseReleased() {
        compound.drop();
    }

    function setup() {
        createCanvas(600, 600);
        compound = new Compound();
    }

    function draw() {
        background(0);
        compound.updatePin()
        compound.updateBall()
        compound.updateRope()
        compound.show()
    }

Comment: I am proposing a code change to the logic in the distance function as it looks like a typo has it broken. I am going to leave my answer as well because it shows the behavior the question is asking for with less extras. Moving the pin is a nice touch but maybe not directly related to the question.
Answer: Starting with the OP code here is an example that allows the ball to slide down the rope as if the rope is threaded through the ball and has a knot at the end.

var compound;

function Compound(){
    this.pinDiameter = 25;
    this.pinx = width/2;
    this.piny = this.pinDiameter;

    this.ballDiameter = 50;
    this.ballx = width/2;
    this.bally = this.ballDiameter + this.pinDiameter * 2;
    this.ballSpeed = 1;

    this.ropeWidth = 4;
    this.ropeHeight = 200;
    this.ropex = this.pinx - this.ropeWidth/2;
    this.ropey = this.piny;

    this.updatePin = function(){
    }

    this.updateBall = function(){

    if (this.bally < this.piny + 200){
        this.ballSpeed  = this.ballSpeed + 1;
        this.bally = this.bally + this.ballSpeed;
    }
    }

    this.updateRope = function(){
    }

    this.show = function(){
        ellipse(this.pinx, this.piny, this.pinDiameter);
        fill(255);
        noStroke();

        ellipse(this.ballx, this.bally, this.ballDiameter);
        fill(255);
        noStroke();

        rect(this.ropex, this.ropey, this.ropeWidth, this.ropeHeight);
        fill(255);
        noStroke();
    }
}

function setup() {
    createCanvas(600, 600);
    compound = new Compound();
 setFrameRate(1);
}

function draw() {
    background(0);
    compound.updatePin()
    compound.updateBall()
    compound.updateRope()
    compound.show()
  }

The main change is here within update where we need to check that the ball is not off the rope. We also initialize the ball position to near the top of the rope so we can watch it slide down.
this.updateBall = function(){
    if (this.bally < this.piny + 200){
        this.ballSpeed  = this.ballSpeed + 1;
        this.bally = this.bally + this.ballSpeed;
    }
}

How to make a ball hang from a rope?


How to deconstruct arrays of arrays in Javascript

Question: I'm working with an API and after I try to clean up the data, I got an array of arrays of arrays:
arr = [[[{name: "john"}],[{name: "jack"}]],[[{name: "joe"}],[{name: "bob"}]]]

How can I clean this up to something like this:
arr = [{name: "john"},{name: "jack"},{name: "joe"},{name: "bob"}]

Comment: Look into `Array.flat` and `Array.flatMap`
Answer: You can use Array.prototype.flat(), providing Infinity as the depth argument to flatten all sub-arrays recursively:

const arr = [[[{name: "john"}],[{name: "jack"}]],[[{name: "joe"}],[{name: "bob"}]]];

const flattened = arr.flat(Infinity);

console.log(flattened);
Answer: In this case calling arr.flat().flat() would do the trick.
Comment: @jsejcksn's answer is _flat-out_ better ;) (see what I did there?)
Comment: Using `.flat(2)` would be more suitable imo


Node setMouseTransparent Exceptions

Question: If I have a VBox with 3 buttons and make the VBox mouse transparent, how can I ensure that its children won't be made transparent? I need the buttons to be clickable.
I'm trying to make a clock, and my solution so far is to have a StackPane. Add 12 VBoxes in the StackPane, make it as large as the StackPane, and rotate it around the center axis 30 degrees * n. Unfortunately, the VBoxes block the layers beneath it all the way up to the top of the StackPane.
Comment: Mouse transparent will affect also its children. Maybe [`setPickOnBounds`](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#setPickOnBounds-boolean-) can help you.
Comment: Why do you want to make it mouse transparent? Mouse events should propagate through to the `StackPane` anyway.
Comment: Because I have 12 Vboxes that are rotated about the center, 30 degrees each. They overlap each other on opposite ends, and block input on half of the VBoxes.
Answer: The answer was to set each VBox's pickOnBounds property to false. Since a VBox is really a blank container with no geometric shape, disabling the pick on bounds renders the VBox invisible while leaving its children intact.

Node setMouseTransparent Exceptions


Separating Ground and Neutrals in Mainpanel before installing sub panel

Question: I'm planning to get a 100 amp sub panel installed in my garage but got conflicting opinions on a point from different master electricians. The point is one electrician is saying it's a must to separate ground and neutrals in the main panel before the sub panel is installed while the other says that's not needed. I know that ground and neutrals have to be separated in the sub panel per NEC code (which both electricians agreed to). The distance between the main and subpanel is going to be around 40ft.
Any suggestions or thoughts on this?
Comment: Main panel is the only place that grounds and neutrals can be connected/bonded.  Sub panels they must be separated.  Distance does not matter.  Is the sub panel inside the same building or a detached building?
Comment: If for a detached building, the ground for the sub panel might need to be separated from the main panel neutral bus.  Not sure but might what the electrician was referring to.
Comment: The 1st electrician may have misunderstood and thought you were make your main panel **into** a sub panel. That would explain the answer.
Comment: @crip659 it's not a detached building, the subpanel is going to be in the garage.
Comment: i could give benefit of doubt on the misunderstanding but i was pretty clear on my terms for the panels @DoxyLover
Answer: The grounds and neutrals do not have to be separated in the main panel if it is, in fact, the main panel. Sometimes there's confusion if you have a main disconnect/breaker outside by the meter. In that case, that's the main panel and your breaker panel in the house would actually be a sub panel and neutrals and grounds would have to be separated. If your panel is fed directly from the meter and the only main disconnect is in the panel, then it's your main panel and neutrals and grounds don't need to be separated.
Comment: yes the panel is fed directly from the meter and its the only panel in the house currently where i can disconnect.


How to edit the display settings for Micropolis OUTSIDE of the game?

Question: I recently installed Micropolis on my laptop running Ubuntu 14.04. Unfortunately, the default resolution and aspect ratio of the game puts the settings button off my screen. I have tried finding a config file, but I can't seem to locate it. I've also tried Googling the problem, but I can't find any solutions that let me fix the problem out of the game.
So, basically, I want to know if there is some kind of command line argument I can pass Micropolis so that it will run in a lower resolution, or a file I can edit to achieve the same effect. I have to assume that I'm not the only person with this problem.
Answer: Upon much more extensive research (I did a Google image search for the main menu), it turns out there is no "Settings" option on the main menu. I have also found out that the  game window is resizable once the game actually starts. Unfortunately, this leaves a lot to be desired, especially considering the first report that I could find of this bug was in 2010.
So, for anyone who is having the same problem as I did, just start a game and it should work just fine once the game is running.
As a side note, I guess I just found my first open source video game project.
Comment: Thanks for posting this, I had the same issue and question and it worked great to just get into a game.


Create application based on Website

Question: I searched and tried a lot to develop an application which uses the content of a Website. I just saw the StackExchange app, which looks like I want to develop my application. The difference between web and application is here:
Browser:

App:

As you can see, there are some differences between the Browser and the App.
I hope somebody knows how to create an app like that, because after hours of searching I just found the solution of using a simple WebView (which is just a 1:1 like the browser) or to use Javascript in the app to remove some content (which is actually a bit buggy...).
To repeat: the point is, I want to get the content of a website (on start of the app) and to put it inside my application.
Cheers.
Answer: What you want to do is to scrape the websites in question by getting their html code and sorting it using some form of logic - I recomend xPath for this. then you can implement this data into some nice native interface.
You need however to be very aware that the data you get is not allways formated the way you want so all of your algorithems have to be very flexible.
the proccess can be cut into steps like this

retrive data from website (DefaultHttpClient and AsyncTask)
analyse and retrive relevant data (your relevant algorithm)
show data to user (Your interface implementation)

UPDATE
Bellow is some example code to fetch some data of a website it implements html-cleaner libary and you will need to implement this in your project.
class GetStationsClass extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "iso-8859-1");
        HttpPost httppost = new HttpPost("http://ntlive.dk/rt/route?id=786");
        httppost.setHeader("Accept-Charset", "iso-8859-1, unicode-1-1;q=0.8");
        try {

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            int status = response.getStatusLine().getStatusCode();
            String data = "";
            if (status != HttpStatus.SC_OK) {
                ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                response.getEntity().writeTo(ostream);
                data = ostream.toString();
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
                        "iso-8859-1"));

                String line = null;
                while ((line = reader.readLine()) != null) {
                    data += line;
                }
                XPath xpath = XPathFactory.newInstance().newXPath();
                try {
                    Document document = readDocument(data);
                    NodeList nodes = (NodeList) xpath.evaluate("//*[@id=\"container\"]/ul/li", document,
                            XPathConstants.NODESET);
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Node thisNode = nodes.item(i);
                        Log.v("",thisNode.getTextContent().trim);
                    }
                } catch (XPathExpressionException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
         //update user interface here
    }

}

private Document readDocument(String content) {
    Long timeStart = new Date().getTime();
    TagNode tagNode = new HtmlCleaner().clean(content);

    Document doc = null;
    try {
        doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
        return doc;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return doc;
}

to run the code above use
new getStationsClass.execute();

Comment: that of cause depends on your algorithem, but generally speaking it dosn't. usually the data is analysed (with your alorithem) in <1 second. in the implementations I have made usually (using wifi) take ~0.5 seconds to run
Comment: I have updated my answer with an example - this one recives the buslines of a local Danish bus company
Comment: Sounds like the solution I'm searching for, but doesn't it take long for devices to do this?
Comment: Thanks for the help. One last question: do you have any example code for getting a website and picking something out?

Create application based on Website


nhibernate set custom generator class in mapping file

Question: i try to implement a custom generator class like this:
Creating a custom id generator for nHibernate
This example is in fluent Nhibernate and not what I want exactly. I want it for nhibernate with mapping.
I have the following lines of Code:
namespace webportale_ger_webservice.Routinen
{
    public class NextKey : TableGenerator
    {

    private const Int32 SeedValue = 1048576;

    public override object Generate(ISessionImplementor sessionimpl, object obj)
    {

        var session = NHibernateHelper.GetSession();

        int counter = Convert.ToInt32(base.Generate(sessionimpl, obj));
        return counter + SeedValue + 1;

    }
}

}
Now I want to give this generator class the ID-property of the mapping document, like this:
<hibernate-mapping assembly="webportale ger webservice" namespace="webportale_ger_webservice.Model" xmlns="urn:nhibernate-mapping-2.2">

 <class name="SPTPL" table="SPTPL" lazy="false" >
    <id name="AR" column="AR" generator="webportale_ger_webservice.Routinen.NextKey"/>

But it doesn't work with generator="webportale_ger_webservice.Routinen.NextKey", the error message is the following:

NHibernate.Id.IdentifierGenerationException: Could not interpret id generator strategy: webportale_ger_webservice.Routinen.NextKey
     bei NHibernate.Id.IdentifierGeneratorFactory.GetIdentifierGeneratorClass(String strategy, Dialect dialect)
     bei NHibernate.Id.IdentifierGeneratorFactory.Create(String strategy, IType type, IDictionary`2 parms, Dialect dialect)
     bei NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
     bei NHibernate.Cfg.Configuration.BuildSessionFactory()
     bei webportale_ger_webservice.DatabaseInterface.NHibernateHelper..cctor() in C:\Quellen\VSWebNeoBackEnd\VSWebNeoBackEnd\VSWebNeoBackEnd\project india webservice\DatabaseInterface\NHibernateHelper.cs:Zeile 34.
     --- Ende der internen Ausnahmestapelüberwachung ---
     bei webportale_ger_webservice.DatabaseInterface.NHibernateHelper.GetSession()
     bei webportale_ger_webservice.india_webservice.InsertSP_Leistungsort(String vornameStr, String nachnameStr, String strasseStr, String hnrzusatzStr, Int32 hausnrStr, String plzStr, String ortStr, String mailStr, String dateStr, String telStr, String argef, String bemerkungStr, String arstrasse, String arplz) in C:\Quellen\VSWebNeoBackEnd\VSWebNeoBackEnd\VSWebNeoBackEnd\project india webservice\webportale_ger_webservice.asmx.cs:Zeile 382.

Does anyone know how to define the class correctly in mapping documents?
thank you.
Answer: In case, we provide a type, it is better to use full type name - mostly including the assembly name. So this should work:
<class name="SPTPL" table="SPTPL" lazy="false" >
  //<id name="AR" column="AR" generator="webportale_ger_webservice.Routinen.NextKey"/>
    <id name="AR" column="AR" generator="webportale_ger_webservice.Routinen.NextKey,webportale_ger_webservice"/>

Expecting that the assembly name is webportale_ger_webservice
Comment: Great to see that, sir ;) Enjoy NHibernate


Storing 3D animations for ray tracing

Question: I've just finished writing a path tracer that takes OBJ files and renders it. This is convenient for still images, but my end goal was to export a sequence from a 3D application (Blender was what I had in mind), and then render an image sequence from that. Originally I figured an OBJ sequence would do, but that would take a massive amount of space for complex scenes.
I began looking into parsing .fbx, .3ds and other popular file formats, but there's so little out there that I could find. I still don't really understand how those files store animations. I can imagine the mesh is stored and then keyframes indicate which vertices translate...? Maybe? Or whole objects? What happens when you have complex deformation like an ocean wave, fluid, or character where many, many vertices are translating? At that point would it be easier to do some sort of OBJ like sequence? I want to stay away from that if I can since it takes lots of memory/time to export.
Hopefully someone can point me in the right direction or explain how other standalone renderers keep their animation data. Thank you!
Answer: I think that it is important to classify between different types of animations here. One rough classification could be

Rigid body animations
Vertex skinning animations
Others...

Rigid body animations
This refers to animations where the actual geometry data does not change. For example, you could have a geometric object, like a unit cube, and apply (usually affine) transformations to it: You can rotate, translate or scale this object. This is usually accomplished by some sort of scene graph: Each node of this scene graph can have information about the rotation, translation and scaling that should be applied to the objects. In general, this is something that can be expressed with a 4x4 transformation matrix.
The key point is that you don't have to store "animated geometry data". You only have to store the geometry data once, in its original state. In addition to that, you store the key frames of the transformation.
In your case, if you wanted to do a rigid body animation, you could store the geometry in an OBJ file, and additionally store the key frame information in an arbitrary form, for example
<code>TIME  TRANSLATION
0.0   ( 0, 0, 0)
0.1   (10, 0, 0)
0.2   (10,10, 0)
0.3   ( 0,10, 0)
0.4   ( 0, 0, 0)
</code>
This could describe a movement of the object along a rectangular path, taking 0.4 seconds. Fortunately, you don't have to create your own file format for that. There already are solutions for storing this sort of animation data. For example, the COLLADA format already supports animations like this. A more compact representation of such an animation can be stored in a glTF asset. For example, it can represent animations like this one, from the glTF sample models repository:

Vertex skinning animations
This technique refers, roughly speaking, to cases where you have an "initial" geometry, and you can define "rules" of how this geometry should be deformed based on the pose of a skeleton. As the name suggests, this is mainly intended for character animations, where you define a skeleton consisting of the "bones" of the character, and the geometry defines the "skin" of the character. Vertex skinning is also supported by different file formats like COLLADA or glTF. The effect is shown in this image, again, from the glTF sample models:

As already mentioned by joojaa in his answer, implementing vertex skinning according to the specifications of these file formats may be a bit tricky. Additionally, a considerable amount of the skinning computations is usually done by the vertex shader. So for a ray-tracer, you would have to move these computations into your application code.
Others...
This refers to what you already alluded to in the question: There may be cases where the animation is not a simple transformation of rigid objects, and where you cannot define any "rules" of how the vertices should be transformed. For example, when the vertex positions are computed by a simulator, like a fluid simulator or a soft body simulator.
In doubt, it may simply be necessary to actually store the positions of all vertices, frame for frame. You could achieve this as a sequence of OBJ files. But note that OBJ files contain ASCII data, and thus, are usually large and the geometry data has to be parsed before it can be used. Storing the data in a binary form that can be used by the application directly may be beneficial here.
There are some possible approaches for reducing the amount of data that has to be stored. For example, one could extend the concept of "key frames" here. For example, one could store the initial configuration of al vertices, and then only store the movement of vertices that acutally have changed between two frames. But of course, if (nearly) all vertices changed, the savings may be diminishing.
I'm not aware of any universally applicable, "standardized" solutions for this. Maybe some of the solutions that joojaa referred to in his answer could be helpful here.
Answer: Pixar spent quite much time, money and other capital to archive all their renders. What they did was just to store the raw render description files their render engine used. The reason for this is that it's the only way to ensure that the features stay intact. Of course they had a very well documented standardized format to work with.
The benefit of this method is that it stores things relevantly. In other words static objects can be stored static and only animation objects need to be stored frame by frame which is the only way to ensure compatibility for animation without relying on host apps to do this for you.
Alembic works on a similar principle. The downside is big formats. But note that formats such as FBX and Collada (*.dae) are not much better. While it's true that they can contain some of the animation data they cannot always do everything that you want them to do. Which means that in the end it might not do what you want.
The animation exchange formats (FBX, Collada etc...) do not usually store vertex positions, if they did then they would just have same problem as your obj storage. Instead they store the modification history so that they can redo the animation. So for example the bones are stored as transforms and the vertex weights are used to compute their position. The downside is that your reader needs to implement substantial amounts of the animation core. And anything the format does not know how to do is stored either as point caches, or not at all. Realistically speaking for FBX you would use the API to do this. Implementing it yourself is a quite big undertaking, it may be cheaper to just buy more storage space.
Personally I would implement something like the RI spec for my own renderer. If not RI spec itself which would allow you to swap renderer if need be (also the other way around a user could swap to your renderer without many changes).

Storing 3D animations for ray tracing


httpd virtual hosts are not working

Question: So I recently am working on my new bootstrap website where I am using a VPS. Since I am only assigned one IP and I cannot get additional IP's, I was thinking of using Apache VirtualHosts combined with SRV records. While setting up the virtual hosts, I noticed that only virtual hosts on port 80 and 443 work. I am using ports 80, 8080, 8081, 8082 and 443. While connecting to 8080, I get a "This web page is not available" from google chrome. While connecting to 8081 and 8082, I get a "Oops! Google Chrome could not connect to ...". For now, I am using the domain "entel.us" because I am still transferring starfire1337.com. Here is my httpd.conf file: http://pastebin.com/awvR55aE
Any suggestions?
I am running CentOS 6
Answer: All your VirtualHost servernames are set to: *.starfire1337.com  but you say your using entel.us...?
Perhaps try adding:
ServerAlias *.entel.us  where * is your subdomain, i.e. js.
Another issue is that you have only set a Directory for the /var/www/html directory, where all your virtualhosts goto other directories in /var/www/ so either add a <Directory> for each of your virtual hosts like:
<Directory "/var/www/js">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

or add change this:
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

to this:
<Directory "/var/www">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

httpd virtual hosts are not working


Centering the gnome terminal or console window on start-up

Question: Using Ubuntu 22.04, I want either my gnome terminal or console to start centered on the screen. Bard AI told me to use this command:
gsettings  set  org.gnome.desktop.wm.preferences  center-new-windows true
I got an error message that the key doesn't exist which I confirmed by using the gsettings list commands.
So how do I accomplish my goal?
Comment: Who is this? Bard AI told me to use this command:
Comment: Bard AI is google's AI program. It explained subsequently that the "center-new-windows" key only works in the latest release of Ubuntu - not in 22.04.
Comment: xdotool run as a startup script. might delay it, or loop , to wait for your startup apps to start. thwen along these lines, but with a position center (if that is an xdotool option, or get your screen res.  xdotool  getdisplaygeometry
 and do maths on that to centre)..  Annot, replace with terminal name.

name=$(ps -A | grep Annot)
id=$(echo $name | cut -c1-6)
echo "$id"

i=$(xdotool search --pid "$id")
xdotool getwindowname "$i"
xdotool windowactivate --sync "$i"
xdotool windowsize "$i" 1000 1050
Answer: The answer is to not use gnome-terminal in the first place. I installed Sakura terminal emulator and it works great. You've also got to use a desktop entry file that calls Sakura instead of gnome-terminal. Apparently Ubuntu's next release will improve on gnome but there is no way to simply upgrade 22.04 LTS.
Answer: With a little bit of googling I was able to find what's the issue with the command and an alternative solution as well, there are mainly two ways :

Correct your above command to the following :
gsettings set org.gnome.mutter center-new-windows true

Through Gnome Tweaks.

Install the package using command :
sudo apt install gnome-tweaks

Once installed, inside of it navigate to the "Windows" tab change the

Toggle for "Center windows" to true

This is how it will look like within the Gnome Tweaks tool:

Explanation for 1.:
I believe the property has been moved to a different schema (from org.gnome.desktop.wm.preferences to org.gnome.mutter) due to which the error which you have mentioned above is thrown and so using the right schema fixes the error. (ref: https://www.omgubuntu.co.uk/2023/04/center-new-windows-ubuntu-gnome)


UX for selecting complex set of nodes from 2-level, dynamic, moderate-size tree?

Question: What is a good UX design for letting a user select a complex set of nodes from a 2-level, dynamic, moderate-size tree? (I say a 2-level tree, but to be more accurate, the implied root could be considered a third, hidden level; the root is not to be represented to the user.) All leaves of a branch may be selected distinctly from the branch itself (because branch selection implies future inclusion of added leaves, whereas selecting all current leaves does not).
Is there a good existing design to this problem?
Detail
The tree will have at least one branch node, and all branch nodes will have at least one leaf node. Both the original tree and the selection are dynamic. That is, the membership of the tree can change in the future (branches and leaves can be added and removed), and so can the user's selection (if the user revisits the app).
The resulting selection will be composed of a set of branch and leaf nodes. If a branch is selected, then implicitly all its leaves (now and in the future) are effectively selected as well (and that should somehow be made clear to the user). Therefore if a branch is selected, it is redundant to select any of its leaves (indeed this could be prevented in the UX design). However, it is valid to select all leaves in a branch rather than the branch (and leave the branch unselected), because in the future the membership of the branch's leaves could change -- if additional leaves are later added to the branch but the selection has not changed, such leaves will not be implied selected unless and until the user explicitly does so in a future selection.
The scale is moderate. Roughly 10 branches max, 50 leaves per branch max. Small enough to load everything at once (no lazy loading or infinite scroll). Large enough that scrolling may be required, and searching is helpful but not critical. The resulting selection is likely relatively small, because generally leaves won't be individually selected if more than 5 or so leaves (in those cases the branch would generally be selected instead). Most likely the selection could be represented with 25 or fewer nodes.
Examples of Original Tree
The structure being selected from could be represented like this:
branch1
 ∟ leaf1-1
branch2
 ∟ leaf2-1
 ∟ leaf2-2
branch3
 ∟ leaf3-1
...

And the minimal structure is:
branch1
 ∟ leaf1-1

Design Possibilities
I am thinking of a 2-column view showing the unselected (first/source column) and selected (second/destination column), but that's not set in stone.
Also thinking a drag-and-drop or add/remove interaction (or both) to move members from one set to the other. Pre-move multi-select of the nodes (e.g. Ctrl+click several nodes then add or remove them) can be considered as well but is not strictly required.
Searching/filtering the nodes can be considered, but that feature is of secondary importance for this design.
Challenges
One challenge of the design is whether and how to depict a branch that has some but not all of its leaves selected. If a 2-column design (see Design Possibilities above) is used, should the branch be depicted in both columns, and if so should there be any visual indication that it is partly selected?
Another challenge of the design is now to depict the leaves of a branch where the branch itself is selected but its leaves aren't explicitly selected. Should the leaves appear as if they have been explicitly selected or not, or should they appear in some third state that indicates their selection is implicit?
Another challenge is, if a branch is added to the selection, (how) can one of its leaves be removed from the selection? Must the user remove the branch first, or is there a way to remove a leaf from a selected branch? If the latter, is the branch removed from the selection but its remaining leaves added to the selection?
A final challenge is, whether to represent the final selection in the same way as the original tree. It might be easier to visualize the final selection in a more compact representation.
An excellent UX design solution to this problem would address the above challenges in a way that is clear and intuitive.
Different Questions
This question addresses selecting a single path (one node per branch):
Designing a control to select elements from a tree?
This question is very similar but does not address the critical distinction between selecting all leaves of a branch vs. selecting the branch (which are distinct selections in my question):
For large hierarchies - checkbox tree or 'guided tree construction'
This question is similar but not as detailed and is more tied to large scale rather than basic usability:
Alternative UI patterns for a large, shallow tree
Answer: I'm not shure if a tree is the right pattern here. For the user it is only groups with Elements. My answer is not about the visual presentation it is more about the behaviour.
You will need a design which states clear if a item or group (leave or branch) is selected or not. A checkbox seems OK to me. A checkbox is even able to show the partly selected state of a group.
See the example:
Branch 1 = partly selected (some leaves, could also be all)
Branch 2 = nothing selected
Branch 3 = branch is selected (note the inactiv checkboxes of the leave)

Now to the behaviour:
If the user selects a branch, all leaves should be selected, by showing the checkboxes in inactive state it should be clear, that this means "all leaves ar selected an it is not possible to deselect one"

If the user klicks on the branch to unselect it, the branch should go to state "partly selected" and select all the leaves. So the User can unselect any leave as desired.:

A klick on the "partly selected" branche will unselect the branche and all leaves. Now the user is able to either select the whole branch again or the desired leaves.

What should happen if the user changes the group of a leave. This depends on the current state of the moved leave and the state of the group of the target:

Source: leave is checked / target: group is either unchecked or partly checked -> leave should be checked at targetgroup.
Source: leave is checked / target: group is checked -> leave is checkt but displayed with inactive checkbox
Source: leave is unchecked / target: group is either unchecked or partly checked -> leave should be unchecked
Source: leave is unchecked / target: group is checked -> leave should be checked with inactive checkbox
Comment: The indication and behavior around partially selected branch indicator with all leaves selected is what sold me in particular. Agreed that multiple visualizations could work and that getting the behavior right is the crux of this problem. My question was perhaps overly lengthy, and I agree that details about visually how selections are transitioned from unselected to selected is less important, although your basic visuals are already quite satisfactory. Your state representations and overall behaviors address all the "challenges" I listed.


Java Swing: JTable with subitems

Question: In my Project i want to have a Table with items that may have subitems, like in the Eclipse 'Problems' View. (Indexes 2-17 should be Subitems of 1)
My Project so far:
Overview of my Project
What i want to have:

Content of Main.java:
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;

public class MainFrame extends JFrame {

    private JPanel contentPane;
    private JTable table;

    public static void main(String[] args) {
        MainFrame frame = new MainFrame();
        frame.setVisible(true);
    }

    public MainFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        table = new JTable(new CostumTableModel());
        table.setFillsViewportHeight(true);
        contentPane.add(table);
    }

}

Content of CostumTableModel.java:
import javax.swing.table.AbstractTableModel;

public class CostumTableModel extends AbstractTableModel {

    public CostumTableModel() {
    }

    @Override
    public int getColumnCount() {
        return 5;
    }

    @Override
    public int getRowCount() {
        return 5;
    }

    @Override
    public Object getValueAt(int row, int col) {
        if (col == 0) {
            return row + 1;
        }
        return row * col;
    }

}

Full Version of my Code, except this feature can be found at my Github.
Does anybody of you know how to do this? I'm searching the whole day for a solution, but didn't find one.
Answer: I would suggest you to use SwingX
See printscreen:

Java Swing: JTable with subitems


Mean Value Theorem does not (seem to) prove my result

Question: Using the Mean Value Theorem, prove the following:

Let $f : [a,b] \rightarrow [a,b]$ be differentiable. Then, $f$ is a contraction mapping if and only if there exists $r \in (0,1)$ such that $\lvert f'(x)\rvert \leq r$ for all $x \in [a,b]$.

I've seen other threads asking about this question, but none of them answer my question: How is the Mean Value Theorem enough to prove this statement?
Here's a proof in one direction:
Suppose $f$ is a contraction mapping.
Thus there exists an $r \in (0,1)$ such that $\lvert f(x)-f(y) \rvert \leq r \lvert x-y \rvert$ for all $x,y \in \mathbb{R}$.
By the Mean Value Theorem, there exists a point $c\in [a,b]$ such that$f(x)-f(y)=f'(c)(x-y)$ so $\lvert f(x)-f(y) \rvert = \lvert f'(c) \rvert \lvert x-y \rvert$
and thus $\lvert f'(c) \rvert \lvert x-y \rvert \leq r \lvert x-y \rvert \implies \lvert f'(c) \rvert \leq r$.
But what I am supposed to obtain is:
$\lvert f'(c)\rvert \leq r$ for all $c \in [a,b]$
How do I prove that this is true for all points, instead of just one point with the Mean Value Theorem? Am I misunderstanding the theorem?
Comment: The mean value theorem is only needed for the opposite direction. For the direction you are trying to prove, the answer to the thread you linked shows how to prove it directly using the definition of the derivative.
Comment: Seems hopeless. Yet it didn't asked you to use MVT for **both directions**.
Comment: Actually, in your case, $c$ can be found strictly between $x$ and $y$. So, fix $x$ and vary $y$, say, let $y\to x$.
Answer: My suggestion and the suggestion of many other commenters is that the mean value theorem is most cleanly applied in the direction where you assume $|f'(x)| \leq r$ for $r\in (0,1)$. For any two $x,y\in [a,b]$ there is $c\in (a,b)$ with $|f(y) - f(x)| = |f'(c)||x-y|$. Now you can use the bound on $f'$ to your advantage.
If $f$ is a contraction mapping, then you've already shown that there is $r\in (0,1)$ such that $$\left|\frac{f(x) - f(y)}{x-y}\right|\leq r$$ for all $x,y\in [a,b]$ with $x\neq y$. What does this mean for the derivative of $f$ in $[a,b]$?


Permutation does not change if we multiply by left by another group element?

Question: Let $(G=(a_1,...,a_n),*)$ be a finite Group. Define for a element $a_i \in G$ a permutation $\phi = \phi(a_i)$ by left multiplication:
$$
 \begin{bmatrix}
a_1 & a_2 & ... & a_n \\
a_i*a_1 & a_i*a_2 & ... & a_i*a_n \\
\end{bmatrix}
$$
I am struggling to understand why this is the permutation as
$$
 \begin{bmatrix}
a_k*a_1 & a_k*a_2 & ... & a_k*a_n \\
a_i*a_k*a_1 & a_i*a_k*a_2 & ... & a_i*a_k*a_n \\
\end{bmatrix}
$$
where $a_k \in G$. Can somebody give me a reason for why these permutations are the same? Thanks for any help.
Comment: Because both of then are the map $a_j\mapsto a_i*aj$.
Comment: I'm struggling to understand how you're struggling to understand (not meant in a mean way)
Answer: We check that the map $\phi: G \times G   \rightarrow G,
\quad \phi(g_1, g_2) \rightarrow g_1*g_2 $ satisfies the following property:
$$\forall a \in G, \quad h_a(x) = \phi(a, x) = a*x$$ is a bijection on G.  We can see the maps are onto as for any fixed $a \in G$ $$\forall y \in G, \quad \exists a^{-1}y \in G  \text{ such that } h_a(a^{-1}y) = a*(a^{-1}y)=y
$$
and we can see the maps are injective as for any fixed $a \in G$
$$\begin{align*}
h_a(x) = h_a(y) &\iff \\
a * x = a * y &\iff \\
a^{-1} * (a * x) = a^{-1} * (a * y) &\iff \\
(a^{-1} * a) * x = (a^{-1}*a)  * y  &\iff  \\x = y
\end{align*}
$$
Thus each map $h_a$ is a bijection on $G$.  Now notice that in your final example the question can be phrased as does the equality $\phi(a_i, x) = \phi(a_i a_k, a_k^{-1} x)$ hold.  Well notice that $$\phi(a_i a_k, a_k^{-1}x) = (a_i a_k)(a_k^{-1} x) = a_i(a_ka_k^{-1})x=a_ix = \phi(a_i, x).$$  Demonstrating that the two permutations are equal.
Answer: As José has said, both homorphisms have the same effect. Perhaps what you're confused about is that the second homomorphism sends $a_k * a_x \mapsto a_i * a_k * a_x$, seeming like it only applies to elements of the form $a_k * a_x$. While that is true, every element of $G$ may be expressed in the form $a_k * a_x$.
Let $a_x \in G$. Then $a_x = a_k * (a_k^{-1} * a_x)$. The second homomorphism sends
$$a_x = a_k * (a_k^{-1} * a_x)  \mapsto a_i * a_k * (a_k^{-1} * a_x) = a_i * a_x$$
and so is identical to the first homorphism.


Exception with sqoop, com.mysql.jdbc.exceptions.jdbc4.CommunicationsException

Question: I am trying to import data from MySQL to HDFS by using sqoop. To do this I am using following command.
<code>sqoop import --connect jdbc:mysql://192.168.0.121:3306/snachitdb --username root --password root --table webdemo_vendorinfo --m 1 --target-dir /user/hduser/test/
</code>

my IP address or hostname in JDBC URL is correct.
Port number is correct in JDBC URL.
DB server is up.
DB server is accepting TCP/IP connections.

Still I am getting following error: I searched a lot but couldn't resolve, please help me to resolve it. Thanks in advance.
<code>`15/03/05 14:44:48 ERROR manager.SqlManager: Error executing statement: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 0 ms ago.
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 0 ms ago.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2104)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
    at java.sql.DriverManager.getConnection(DriverManager.java:571)
    at java.sql.DriverManager.getConnection(DriverManager.java:215)
    at org.apache.sqoop.manager.SqlManager.makeConnection(SqlManager.java:877)
    at org.apache.sqoop.manager.GenericJdbcManager.getConnection(GenericJdbcManager.java:52)
    at org.apache.sqoop.manager.SqlManager.execute(SqlManager.java:736)
    at org.apache.sqoop.manager.SqlManager.execute(SqlManager.java:759)
    at org.apache.sqoop.manager.SqlManager.getColumnInfoForRawQuery(SqlManager.java:269)
    at org.apache.sqoop.manager.SqlManager.getColumnTypesForRawQuery(SqlManager.java:240)
    at org.apache.sqoop.manager.SqlManager.getColumnTypes(SqlManager.java:226)
    at org.apache.sqoop.manager.ConnManager.getColumnTypes(ConnManager.java:295)
    at org.apache.sqoop.orm.ClassWriter.getColumnTypes(ClassWriter.java:1829)
    at org.apache.sqoop.orm.ClassWriter.generate(ClassWriter.java:1641)
    at org.apache.sqoop.tool.CodeGenTool.generateORM(CodeGenTool.java:96)
    at org.apache.sqoop.tool.ImportTool.importTable(ImportTool.java:478)
    at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:605)
    at org.apache.sqoop.Sqoop.run(Sqoop.java:143)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:179)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:218)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:227)
    at org.apache.sqoop.Sqoop.main(Sqoop.java:236)
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at java.net.Socket.<init>(Socket.java:425)
    at java.net.Socket.<init>(Socket.java:241)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2027)
    ... 30 more
15/03/05 14:44:48 ERROR tool.ImportTool: Encountered IOException running import job: java.io.IOException: No columns to generate for ClassWriter
    at org.apache.sqoop.orm.ClassWriter.generate(ClassWriter.java:1647)
    at org.apache.sqoop.tool.CodeGenTool.generateORM(CodeGenTool.java:96)
    at org.apache.sqoop.tool.ImportTool.importTable(ImportTool.java:478)
    at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:605)
    at org.apache.sqoop.Sqoop.run(Sqoop.java:143)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:179)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:218)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:227)
    at org.apache.sqoop.Sqoop.main(Sqoop.java:236)
</code>
Answer: Please copy the mysql-connector.jar into your sqoop/lib folder and try.
Comment: Thanks for your time, but I have already copied mysql-connector.jar into sqoop/lib folder.
Comment: @VikramSinghChandel did you solve this issue? I am also facing the same but can't resolve


Differential equation substitution $z=\frac y x\implies z'=xz'+z$

Question: So I'm reading book about differential equations and there is said that you can substitute $z=\dfrac yx$ and that means $z'=xz'+z$.
How this is possible?
Comment: I cant write those upper "code marks".
Answer: if $z = \frac{y}{x}$ then $y(x) = x\cdot z(x)$ - the important part here is that $x$ is your independent variable and both $y$ and $z$ depend on it. Hence when we take $\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{\mathrm{d}}{\mathrm{d}x} (x\cdot z(x))$ we have to use the product rule on the right hand side)
\begin{equation}
\frac{\mathrm{d}}{\mathrm{d}x} (x\cdot z(x)) = x\cdot \frac{\mathrm{d}z}{\mathrm{d}x} + \frac{\mathrm{d}x}{\mathrm{d}x}\cdot z(x) = x\cdot \frac{\mathrm{d}z}{\mathrm{d}x} + z(x).
\end{equation}


Build Docker and deploy to ECR using CDK

Question: I am very new to CDK and use dockers. For my application, for any code change I want the CDK pipeline to build the Docker and store it in ECR. I am seeing some examples but mostly found the one which have ECS task linked in it.
Is it possible to build docker and update ECR with most recent image through CDK pipeline ? If yes can you provide some example which does not involve ECS, just ECR and docker.
Thanks
Answer: (https://github.com/cdklabs/cdk-ecr-deployment) this construct from the CDK labs should do just that, but its not super hard following the conventional approach: (https://docs.aws.amazon.com/cdk/api/v1/docs/aws-ecr-readme.html)


How to display that the product has different sizes?

Question: How can I display that the product has different sizes available in stock in the homescreen/catalog without redirecting the user to a product details screen or by opening a pop up on the desktop. Keep in mind the product may have 10 or more sizes
Is there a suitable design pattern for this which is easy to use ?
Here is  three samples I did
https://goo.gl/CUSkWX
Comment: Need more information.. going by what you have in the question at this time, you can quickly accomplish by having a drop down of different sizes.. check amazon , pick a shoe or shirt and there is a drop down with sizes.. similar to that.. but I am sensing thats not what you want.. please clarify with more information. Mobile ? or Desktop ?
Comment: Why the requirement that sizes have to appear on the homepage? Look at how everyone else handles this issue. The product list shows products and the detail page shows the sizing options and other info.
Comment: Because not everyone clicks on the details , I need him to show the size options and the price of each
Answer: When hovering over the product, you could display it like this

or something like this, if you have too many sizes to fit in
Answer: How about this ? Display the sizes in a ladder design to the left or right or top , bottom whatever pleases the eye.
Comment: This photo when I click on the product to preview it, I want to enable the user to change the size from the tumbnail
Comment: Is it enough if you change the size in the backend ? or does the shape, picture have to change (not knowing what product it is you have) on the display ?
Answer: You can have a simple approach using a select:

That way, the product can have a lot of different sizes and prices, and the user will know that he can change the size with the select list.


Triple Integral $\iiint x^{2n}+y^{2n}+z^{2n}dV$

Question: Evaluate:
$$\iiint_{x^2+y^2+z^2 \leqslant 1} x^{2n}+y^{2n}+z^{2n} dV $$
I have tried to convert to spherical polars and then compute the integral, but it gets really messy because of the 2n power. Any tips?
Comment: Spherical coordinates definitely seems like the way to go. Your integration occurs within a sphere of radius $1$, which simply integrating $r$ from $0$ to $1$ and letting your angles map out the whole of a sphere
Answer: First observation: it is symmetric in $x,y,z$, so by linearity we have
$$\iiint_{x^2+y^2+z^2 \leqslant 1} x^{2n}+y^{2n}+z^{2n} dV =3\iiint_{x^2+y^2+z^2 \leqslant 1} z^{2n} dV.$$
Choosing spherical coordinates it becomes
$$3\iiint_{x^2+y^2+z^2 \leqslant 1} (r\cos \theta)^{2n} dV$$
where $dV= r^2 \sin \theta \ \text{d}r \ \text{d}\theta \ \text{d}\phi$.
Thus the integral simplifies to
$$3 \int_0^{2\pi}\int_0^{\pi}\int_0^1 r^{2(n+1)} (\cos \theta)^{2n} \sin \theta \ \text{d}r \ \text{d}\theta \ \text{d}\phi = \frac{3}{2n+3}2 \pi  \int_0^{\pi}(\cos \theta)^{2n} \sin \theta \ \text{d}\theta. $$
Using that
$$\int_0^{\pi}(\cos \theta)^{2n} \sin \theta \ \text{d}\theta = \frac{2}{2n+1} $$
we have
$$\iiint_{x^2+y^2+z^2 \leqslant 1} x^{2n}+y^{2n}+z^{2n} dV= \frac{3}{2n+3}2 \pi  \frac{2}{2n+1}.$$
Comment: The trigonometric integral simplifies to $$2\int_0^1 x^{2n} \text{d}x $$ by using the axis symmetry at $\frac{\pi}{2}$ and substitution by $\cos \theta = x$.
Comment: My tips are: first use symmetry, then spherical coordinates, then with some Fubini and elementary integrals you can solve it.
Comment: beat me to it (+1)


unable to deploy a basic react app on elastic beanstalk

Question: I created a simple react-app and I was able to run it locally. However I am unable to deploy the app on elastic beanstalk using eb cli or manually.
There seems to be no node server running, hence the health checks were failing.
How can I resolve this error?

Environment health has transitioned from Pending to Degraded. Initialization completed 6 seconds ago and took 2 minutes. Impaired services on all instances.

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I have also noticed the following message

Instance deployment: You didn't specify a Node.js version in the 'package.json' file in your source bundle. The deployment didn't install a specific Node.js version.

So I have updated the package.json with the following, however it didn't help.
 "engines" : {
    "npm" : ">=8.0.0 <9.0.0",
    "node" : ">=16.0.0 <17.0.0"
  }

Answer: The problem was I was using node.js when I deploy. Instead I should use docker with nginx.
FROM node:17.1-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx:1.22.1-alpine as prod-stage
COPY --from=build-stage /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

After building the docker image, we should use eb cli to deploy by executing the following commands eb init and eb create.


Python cron job vs Kapacitor UDF

Question: I need to perform some background advanced calculations on my data after it is collected in InfluxDb which is stored on the edge server, which means I have limited resources for the calculations.
Also I cannot block the data collection while I do calculations.
I am weighing using Kapacitor UDF streams vs custom Python scripts.
Please note I need to make the scripts configurable so that I can easily deply them to different environments with different sensors
Answer: It probably makes little difference, in general, especially for 'simple' usecases, though I lean towards standalone python scripts. (It may be better to use Kapacitor if you can cover your usecase using the kapacitor language for this instead of python based UDFs, but I found it insufficient since I needed to retrieve additional data from other databases)

Standalone python scripts could be a bit lighter, since you don't need to run the Kapacitor service.
Standalone python scripts could be a bit more configurable. Kapacitor is also pretty configurable but you'd have to spend a bit of time learning how to use it.
Standalone python scripts could be a bit more stable. I've experimented with python UDF's a couple of years ago and found them unstable and buggy. While this may have improved by now, you'd still be relying on this being supported and if go is not your language you might have trouble debugging and fixing issues yourself.

Python cron job vs Kapacitor UDF


How do I fight Alghouls effectively?

Question: I'm doing a contract at the moment, but I ran into trouble defeating two level 5 Alghouls that roam the area I have to examine. I'm at the same level myself, but the Alghouls are quite a bit harder than any other enemy of that level that I previously encountered. I'm playing on the second-hardest difficulty level.
I know that Axii is supposed to help, but when I tried it I still got staggered when attacking them after axiing them. They're also pretty fast, I had some trouble dodging them, which is quickly fatal as I can only survive 2-3 hits from them. The bestiary also doesn't contain a lot of useful information about them.
How do the spikes on Alghouls and Axii work exactly? How do you evade their attacks, dodging or rolling, and in which direction? Any other tips on defeating them?
Answer: My technique for this monster. I rely on dodging and the fast attack skills, other tactics might vary by build.
Dodge
You'll want to dodge instead of rolling or parrying. If you roll, you'll be too far away to strike them, and parrying you'll still take damage. Also, you will not be able to counter so holding down the Parry button is a waste.
Watch the monster carefully and continually circle around them. When they flash red, that is the visual signal that they are about to attack. Then you'll want to dodge to the side and get three fast strikes in. Then immediately back off. Don't get greedy, they can hit you through your own attacks.
If you have the Fleet Footed perk and Fast Attack perks, all the better.
Oils
If you have the Necrophage oil, and you've spotted the Alghoul far enough away that you're not in combat, apply your oil. A good technique for this is to use your Witcher senses to look for movement circles (the white wobbly circles) then listen, you'll hear gutteral gurgling and growling, which to me says Necrophage. Bear in mind you cannot apply oils when in combat, ie, Geralt has drawn a sword automatically and you can parry rather than Witcher sense.
Signs
You mentioned the Axii sign, indeed the Bestiary covers this. The sign is used when the Alghoul, after taking some damage, will produce large spikes from it's back. If you try and attack it in this state you'll take damage and will be staggered. It's in this scenario that you want to hit them with Axii, and wait a few seconds for the spikes to retract. Now you can continue to cicle, dodge and fast attack.
I also find some use of Igni to be helpful, but that's personal choice. Keep an eye on your stamina if using Axii and Igni.
Crossbow
If you are at a stage where you have acquired the crossbow, which it sounds like you have, you can apply some additional pressure with that if you're circling far enough away, or you do dodge roll. Just be sure to equip bolts with some silver damage otherwise it's a waste. Also be mindful of the often lengthy reload of the crossbow if the Alghoul closes on you quickly.
Comment: The part about waiting a few seconds after Axii is important, that was my mistake, I attacked directly afterwards. That's why I was confused about how this is supposed to work.
Answer: I used Quen to protect myself. It only absorbs 1 hit from them, but when you attack them it only takes away like 10% of your shield, so you can hit them multiple times without losing your shield or getting staggered.
Anytime you get hit by them though, you should dodge and wait until you can cast your shield again. I also was able to fight them only one at a time, after I drew one away from the other.
Answer: I was having this exact problem and what I found to be very helpful was to circle around behind them and fire a crossbow at the closest one from a good distance away. He will then go after you but the other will not, that way you must only fight one at a time and it is much easier.
Answer: For me, Igni was the winner. It stuns, burns and can even set the Alghoul on fire. A blast of Igni, a couple dodges back, giving time for stamina to regen before the Alghoul advances again. Rinse-repeat 4 times, dead Alghoul. The first time I tried Quen/necrophage oil/fast attacks - took me ages, and I died. Igni was the way to go!

How do I fight Alghouls effectively?


Dynamic selector answers

Question: Background
On a step, we have two selectors. "Travellers outside Wingly" depends on "Offered to Wingly". It works that you have N number of seats and you can share them or select that some seats will be taken. And you do not need to use all the seats even.
The problem that I run into is that most of the users will select all seats to share with Wingly. As it is convenient for the user I want to even preselect this option. But the dropdown is that then the second selector emphasized text(Travellers outside Wingly) will have no options to select which makes it counter-intuitive...
Question
Is there a better way to display the connection between fields "Offered to Wingly" and "Travellers outside Wingly"?
Answer: Since the user need not assign all seats, I think the clearest way would be to:

keep the inputs separate
don't restrict user inputs
provide immediate validation for their selection

download bmml source – Wireframes created with Balsamiq Mockups
This kind of loose structure seems necessary due to your requirements: a user can assign 0-n seats, and any combination whose total is <= n is valid. I think the key here is clear feedback.
Answer: I'm not sure if I've understood this correctly but I don't understand why you need to change the available options in the select boxes.
If I have 10 seats the both dropdowns should allow me to select 10 seats for either option.
When I land on the page the 10 seats are allocated to "Offered for Wingly" which means that the selected option for the "Travellers outside Wingly" list should be 0.

download bmml source – Wireframes created with Balsamiq Mockups
If I then decide that I want to put three seats onto the "Travellers outside Wingly" list, then I should be able to select '3' from that dropdown and the "Offered for Wingly selector should automatically change to '7'.

download bmml source

download bmml source
If I want to remove seats altogether then I could set both dropdowns to '3' giving me 4 unallocated seats.
You don't have to remove options from either list - the lists should both give the full possible range of selection - you only select the correct option from the each list based on what is selected in it's counterpart.
Does that make sense?

Dynamic selector answers


one side border of a paragraph

Question: I am trying show a left border for a paragraph using :before class.
But the output seems bit different from what I want to achieve.
Code:

p.left-border::before {
    border-left: 3px solid #9e9464;
    content:"";
    padding: 0 20px 0 0;
    vertical-align: middle;
}
p {
    line-height:30px;
}

Our Unique Approach

Aspire to Acheive is unlike anything you've ever experienced. The Fellowship brings together some of the world's most creative and motivated young people, and helps them bring their most ambitious projects to life. Thiel Fellows are given a grant of $100,000 to focus on their work, their research, and their self-education while outside of university.

Here is the link to a demo of what I have done so far.
Here is the screenshot of what I want to achieve:
Answer: maybe so?

p {
    line-height:30px;
    padding-left: 20px;
    position: relative;
}
p.left-border::before {
    content:"";
    position: absolute; top: 10px; left: 0;
    vertical-align: middle;
    height: 60%;
    width: 5px;
    background: #9e9464;
}

Our Unique Approach

Aspire to Acheive is unlike anything you've ever experienced. The Fellowship brings together some of the world's most creative and motivated young people, and helps them bring their most ambitious projects to life. Thiel Fellows are given a grant of $100,000 to focus on their work, their research, and their self-education while outside of university.

Comment: Brilliant just awesome. That's what I was looking for. I will go through the code to understand. Thank you so much.
Answer: This is possible by positioning the before element absolute, like so:
http://jsfiddle.net/e12pk3bp/2/
Comment: Thanls Jm for your help.

one side border of a paragraph


Any concerns with moving a plumbing vent?

Question: We are currently in the process of evaluating placing solar panels on our roof. The south facing roof with best sunlight currently has a plumbing vent that would be nice to move if possible.
My plan is to reroute the plumbing vent using two 45 degree elbows, and routing the new vent higher up on the roof, as well as patching the old hole and re-shingling.
Does this renovation makes sense and am I overlooking anything or possibly breaking any codes/best practices?
Answer: Your plan looks fine to me assuming this isn't an absurdly long run that exceeds code requirements at that size. You'll need to support the pipe, so it may actually make more sense to use 90° elbows and keep the horizontal run down low.
Comment: Though if you use a horizontal component, make sure it has a slight slope such that rainwater will drain down into your plumbing system and won't pool up in your vent stack and possible fill up your vent pipe and prevent airflow through the vent to the roof.
Answer: You only need 1/4" per foot slope once 6" above the flood rim of the highest fixture served by the vent. Presumably that's true anywhere in the attic.
Assuming you are in an area where attic may be cold, it's arguably better to run at 1/4" per foot (or "plumbing horizontal") down in the insulation, and then have a short vertical run out the roof, rather than having a long 45 degree frost-collector to get the same movement. It's not uncommon to collect all the vents in the attic so there's only one roof penetration (though it's also not uncommon to have a roof penetration for every branch vent, but it's a tradeoff that I'm not fond of.)


Concrete first timer, needing a block

Question: I have a fifth wheel parked on dirt (only option I have), I cannot pave the entire section due to cost mostly.
I'm planning on making a few 1' x 1' slabs 4" thick to set the jacks on, and probably 1' x 2' 4" thick for the wheels.
Is there any issue with this? Also, should I be adding mesh/rebar or just do straight concrete? Any extra input is always welcome as well.
Comment: I would rather use brick, or solid block, for ease of replacement, as frost heave and rain/ponding can soften the ground and dislocate the pads. BTW, for 10,000 weight spread over 5 points, each will support 2000 pounds. Given your soil can support 1500 lb/sf without excessive settlement, and with a safety factor of 1.5, you will need 2 square feet of pad under each wheel/jack.
Comment: Why bother to make a concrete block? You can simply build a brick pavement to handle light load.
Comment: It's a 10,000-pound trailer, wouldn't the 2" bricks break? Being a fifth wheel weight would be supported from the 4 tires and the front jacks. I see 4" as the minimal on other forums so thought that was pretty much what I had to get but can't buy 4" slabs ready made around here.
Comment: Thanks for the comments, ended up going with the solid block pilers for the jacks as you suggested, still gotta find/make a slab for the wheels. Will be adding the gravel underneath the slabs as suggested in the answer which from what I found is 5000 lb/sf.
Comment: I like that answer too, but suggest at least 6" coarse gravel to reduce the chance for ice forming, and maintain free drainage. Good luck.
Answer: If you can make them slightly bigger by 4" each way the off the shelf 3/8" rebar will fit into the pour properly, with 2" away from the forms. 2 pieces each way on the 1'X1' and 3 across the 2' way
Immediately after pouring tap the edges of the forms with a hammer or heavy block to vibrate the air out of the edges. Do round over the edges so when the forms are removed the concrete will be less prone to chip off at the corners.
Answer: Since we're in december, do not pour concrete when it freezes. If the weather is too cold it will take longer to set, and if it freezes, it will crumble.
Dig hole. Try not to loosen the dirt too much below the bottom of the hole, otherwise it will compact later when you park the vehicle on it and the slab will sink in.
Pour a layer about 2-3" thick large gravel on the bottom. This is mostly for drainage, to keep your concrete dry so it doesn't freeze and crack in winter.  It'll also give more even support.
If you want it to look nice, make a rectangular form with some planks. You can oil them with rapeseed oil.
Put in some mesh rebar. You'll need a bolt cutter, or a hacksaw and lots of sweat. It should be in the middle of the concrete, because if it is too close to the edges, it will rust, expand, and crack your concrete from the inside. So you can mix a bit of concrete to make a few heaps and rest the rebar on them.
Mix concrete. If you use a cement mixer, you can throw some reinforcing fiber into the concrete for extra strength. If you mix it by hand, only use fiber if you have big arms and enjoy a good workout.
Pour concrete, work it with trowel, etc. Make sure there are no holes, "vibrate" it with the trowel to help it set, hit the planks with a hammer, etc. Basically vibrations help it set and fill voids.
Next, do the surface so it looks nice. There must be a slope so water drains, so you can make it a bit higher in the middle. If you expect it to sink into the ground a bit, you can make it higher by about 1/2", but then if it doesn't sink, watch your toes when you walk around.
Next wait long enough for it to set, and remove planks.

Concrete first timer, needing a block


How to label "H₂O" in gwt label text

Question: My problem is that I haven't any idea how to label "H₂O" in GWT label text.
I want to set "2" at the base of "H" within GWT label text. My code is
<g:Label text="H2O"></g:Label>

It shows "H2O".
Answer: Try ₂ Instead of the 2. It should produce a subscript 2, which is what you want. It is a unicode XML entity. Not sure if gwt decodes them though.
Comment: GWT uses an XML parser (Xerces) so yes it'll work. Or you could just type in the character in the file, as it has to be in UTF-8 anyway.
Comment: Added the x, forgot that it is the hex version of the code.

How to label "H₂O" in gwt label text


Get value from JSON and put it in String

Question: it's my first question here, i've try to be the more explicit :)
I want get value from a JSON page : https://api.dailymotion.com/video/x3p6d9r?fields=onair.
I have follow a tutorial about json object.
But i want get the value "onair" and put this in a String for use a IF STRING == "XX".
This is my code :
public class notification extends AppCompatActivity {

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

        detectonline();

    }

    public void detectonline(){
        /*
        if (xx == "false") {
             Do something is live is off
        }
        else{
           Do something is live is on
        }

         */

    }

    public static boolean checkIfOnline(String channel) throws IOException {
        String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";

        String jsonText = readFromUrl(channerUrl);// reads text from URL

        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(jsonText).getAsJsonObject();

        return !json.get("onair").isJsonNull();
    }

    private static String readFromUrl(String url) throws IOException {
        URL page = new URL(url);
        StringBuilder sb = new StringBuilder();
        Scanner scanner = null;
        try{
            //scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
            scanner = new Scanner(page.openStream());
            while (scanner.hasNextLine()){
                sb.append(scanner.nextLine());
            }
        }finally{
            if (scanner!=null)
                scanner.close();
        }
        return sb.toString();
    }
}

Answer: I remake your method according what you are looking for it's one of several way to parse json data :
 public static boolean checkIfOnline(String channel) throws JSONException, IOException {
    String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";

    String jsonText = readFromUrl(channerUrl);// reads text from URL

    JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
    if(json.has("onair")) { // just a simple test to check the node that you need existe
        boolean value = json.getBoolean("onair"); // In the url that you gave onair value is boolean type
        return value;
    }
    return false;
}

Comment: Thank you for you help, but i have an error on `String jsonText = readFromUrl(channerUrl);// reads text from URL`. I have a error : `Unhandled exception: java.io.IOexception`
Comment: then just wrap the statement with a try catch block
Comment: Change the method like this : public static boolean checkIfOnline(String channel) throws JSONException , IOException
Answer: I will create methode using your way  !
public static boolean checkIfOnline(String channel) throws IOException {
        String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";

        String jsonText = readFromUrl(channerUrl);// reads text from URL

        JsonParser parser = new JsonParser();

      String myString =json.get("onair");
 return mystring;}


.NET Core MVC fallback-href for resources to multiple files?

Question: Is there any way to do this? For production I am concatting and minifying all my css and js into one file each while in dev I just have the normal separate files. But in the classic fallback href example in the documentation they only allow you to provide one href:
<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css"
  asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css"
  asp-fallback-test-class="hidden"
  asp-fallback-test-property="visibility"
  asp-fallback-test-value="hidden" />

Which doesn't work if you are concatting files for production. I know you can also do some globbing like this:

But doesn't seem like you can combine the two. Is there anyway to do this?
Answer: I would only bundle custom js files, and keep all the js libraries as they are.
Almost always they will be loaded/cached from the CDN anyway. This is what you want since it saves the most loading time on average.
The question is - when will there be problems loading a file from the cdn?
Usually only when a firewall blocks those requests, may it be during development or using the software locally in intranet.
If you know your software will only be working in situations without internet, then removing the cdn version and bundling them all the together will be your best option.


CKeditor in Jquery Simplemodal box

Question: I am trying to use the SimpleModal plugin for jquery to load a popup div with a CKEditor in it, but when the modal box opens up, the CKeditor is all disabled and won't let me type text into it. I am using all default settings.
Any suggestions would be great.
Answer: Are you initializing the CKEditor at the right time? From the simplemodal docs:

onShow: Useful for binding events or any other actions you might want to perform after the modal dialog elements have been displayed. If you are including another plugin (TinyMCE, DatePicker, etc.) in a modal dialog, this is where you want to initialize that plugin.

And a second possibility, I'm not sure whether this will help you, but the JQuery UI modal dialog has a  similar problem showing CKEditor for which a patch exists.
Comment: Thanks Pekka! That did the trick nicely.

Also, I didn't know about the UI modal dialog. Maybe that one would be better to use. You are a rock star!

CKeditor in Jquery Simplemodal box


C# Null Conditional in Ternary condition

Question: Am refactoring some old code and see something in the following format:
Type = rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"

which should not work if rec["IsFlagged"] is null, in which case I need to return null. How would one refactor to keep code in one line, if possible?
I can do something like but am wondering if the following can be achieved in one line to have minimal changes to code
    if (rec["IsFlagged"] != null)
    {
       return rec["IsFlagged"].ToString() == "True" ? "Yes" : "No"
    }
    else
    {
        return null
    }

Thanks,
Comment: `null == "True"` would be false, since null is not equal to a string "True", so should result in "No"
Comment: rec["IsFlagged"]? means return null if rec["IsFlagged"]? is null, otherwise return .ToString()
Comment: There likely is no way to achieve what you've show in a single statement (assuming that "one line" means a single statement, not just removing new lines from the code) because only half of the choices have return (when `rec["IsFlagged"]`  is null code continues)... Make sure what question is asking is what you want (probably the case because second code is not equivalent the first one)
Comment: It looks like `rec["IsFlagged"]` is a `bool` value when it's not `null`. Can you confirm that?
Comment: Thanks... you guys were too quick for me.. :)... I edited the question and added some more information.
Answer: The original code works fine.
rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"

The ? operator before .ToString() prevents the method from being called if null. The result of rec["IsFlagged"]?.ToString() would be null
Then, it compares null to "True" which is false (they are not equal).
The ternary operator then evaluates "No" and assigns it to the lvalue.
EDIT
So, now you want 3 possible results: "Yes", "No" or null. A single ternary only gives you two choices. There are many possibilities and yours is fine, unless you have multiple places doing something similar.
In that case, you could use an extension method:
public String CheckTrue(this object input) {
    return input?.ToString() == "True" ? "Yes" : "No"
}

and then in your specific case:
return rec["IsFlagged"]?.CheckTrue()

Another alternative is to use multiple ternary operators?
return rec["IsFlagged"]==null ? null : (rec["IsFlagged"].ToString() == "True" ? "Yes" : "No");

Comment: Oof, nested ternaries are a slippery slope!
Comment: Using multiple ternary works (I know its difficult to read and debug) but opted for it since it has minimal changes to existing code.

Thanks to everyone who proposed a solution
Answer: This will do want you want..
rec["IsFlagged"]?.ToString().Replace("True","Yes").Replace("False","No")

.. but you perhaps shouldn't want to do it!
I prefer Garr's suggestions, though if it's a bool inside rec (is rec a DataRow?) I'd skip the ToString/compare with string and just use it as a bool once we know it's not null
return rec["IsFlagged"]==null ? null : ((bool)rec["IsFlagged"] ? "Yes" : "No");

But all in I like the extension method approach more, and we can tweak it some, leveraging conversion between a bool-or-null-stored-in-object and bool?:
public static string ToNullaboolString(this bool? x, string t = "Yes", string f = "No", string n = null){
  if(x.HasValue)
    return x.Value ? t: f;
  return n;
}

Calling it like:
((bool?)rec["IsXxx"]).ToNullaboolString()

or supplying parameters if you want to change the strings returned (localization?)


Has anybody seen this after starting a new Imperial Level construction?

Question: Earlier today I started construction of a second Imperial Level (I had another under construction already). I just noticed that the title is different than normal.
Specifically, I'm looking at why the second Imperial Level is called "Food", when it's clearly an Imperial Level (and specifically, that one is either Blast Doors or Droid Works).
Answer: Answer derived from previous comments (now deleted):

This is generally just a display bug, the level is actually an Imperial Level despite the name.
You should try closing the game and reopening it. This often fixes similar display issues.


update old processes with the new process definition -Activiti

Question: I have some processes that ran with old process definitions. But due to requirement change the user task data has been updated with new attributes and this process definition has been deployed. I'm aware that "SetProcessDefinitionVersionCmd" can be set to "yes" to point the processes to the new definition/version.
I would like to know how to migrate the old process data to have the newly added attributes of the user task updated in them?
Answer: There is no easy way to migrate process instance data, however, when you set the version to the new process definition the instance data will go with the migrated instance.
What you have to be careful of is to make sure you include null checks for any of the data that may not be present in the migrated process instances.
Hope this helps,
Greg
Answer: Indeed there is no easy way for migration, however depending on the differences between the two definitions and to what extend you may not prefer to use SetProcessDefinitionVersionCmd, you may find DynamicBpmnService useful when combined with detecting definitions' versions inside your logic.
And yes another way would be to use SetProcessDefinitionVersionCmd but  be extra cautions for tasks that were actually active prior to migration, as Activiti's database model have some redundant data (some for performance reasons), you are better studying the DB tables first for these tasks and then inspecting the before and after migration state. For example, keeping up with a simple changed attribute is much easier than an added boundary event on an active User Task, which affects the "execution tree".
I would also advice to compare SetProcessDefinitionVersionCmd's implementations between Activiti and Camunda, it is sad to have such enhancements efforts separated, but that is another story.


Django running wrong view method

Question: I have to view files stored in mysite folder. one is named as views.py and other is named as request_view.py. In urls.py, I have used 'answer' method for views.py and 'display_meta' method for request_view.py.
(django version: 1.5 and python version: 2.7.3)
this is the url pattern:
url(r'^twitter/$', answer), url(r'request/$', display_meta)

when  I call http:/127.0.0.1:8000/request/, then also first view(i.e. /twitter/) is called!
any help?
one more thing. In my view.py, I have some unbounded code (i.e. the code which is neither present in a method or class). can this be the cause of the problem?
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
keyword = input('enter the keyword you want to search for?')
stream.filter(track = [keyword])

apart from this code, evry code is either in the class or method.
One thing that I noticed is that first the code of the view.py runs, then display_meta runs.
Thanks in advance.
SOLVED
The problem was with the import function that I was using. since my code was unbounded in one of the views, the import function always import that regardless of the url that I choose.
Suggestion
Always use the nomenclature mentioned in the this example. In many books it has been suggested that we should import the views, but it might cause an error if you have unbounded code like I had.
Answer: I don't know exactly why /twitter/ view is called, but I can see two things to change:

You should use a string as the second parameter for url(), as you can see in this example [1]. You can use 'myapp.views.my_method' nomenclature.
You forgot to start the request URL with ^ that indicates the start of the URL.

About the unbounded code, I don't know if that could be causing the problem. But I can't see why are you putting that code unbounded. I am not sure when that code would be executed, I guess the first time you call a view in that file and Django loads the file (I'm guessing, I don't know exactly), but I don't think that would be a good way to do that. Think when do you want to execute that code, put it in a method, and call it.
[1] https://docs.djangoproject.com/en/1.5/topics/http/urls/#example
Comment: Thank you so much! :) problem solved!
although the exact problem was of the use of 'import' function.
Comment: I'm glad :) Maybe when you wrote url(r'^twitter/$', answer), the answer method were being called and django didn't continue searching the right url. In any case, problem solved :)
Answer: HI hemant i am wondering why you have written request_view.py.
Please see the django docs.
what you can do is .
Create two function in your views.py like
def answer(request):

   do some stuffs.

   render_to_response(template.html)

and on the same page write another
def display_meta(request):

   # do your studd
   render_to_response(some.html)

YOU NEED NOT TO CREATE TWO SEPERATE VIEWS.PY
I dont know what this code does
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
keyword = input('enter the keyword you want to search for?')
stream.filter(track = [keyword])

But if you want to use StdOutListener  inside your function you can call in your view
like
def display_meta(request):
   stobject  = StdOutListener()  # use parameters if you have here
   # do your studd
   render_to_response(some.html)

Comment: alternatively you can put this code in some other file and import and start using that class or function in your views   Please check how Django MVT works first
Comment: It's simply not true that urls.py will only look in views.py. It doesn't care where the view functions are, only that they are properly referenced in the urls.
Comment: hi, I use 'from mysite.request_view import display_meta'. I thought using this command will help me importing this function (display_meta) from the file request_view.py
The reason why I used this another file is that in views.py I have a different code and jst don't want to mix my practice codes with it.
so, wat u suggest?
Comment: actually these two functions have nothing in common! display_meta is just a practice example given on "djangobook.com". the answer method is for my project work.
I know I should create a different project for practicing but this error made me think how to resolve such errors.
Comment: @Daniel: that's wat I was saying/doing! ne idea wat's happening here?
Comment: @Hemant not with the information you've provided. You'll need to show the full urls.py at least. And I agree with masterofdestiny in that I've no idea what you're doing with that "loose" code.
Answer: Organizing views into a python package could solve this problem. So if you have a structure like this...
# views.py
def SomeView(request):
    return HttpResponse('SomeView')

# another_view.py
def AnotherView(request):
    return HttpResponse('AnotherView')

Your can reorganize these separate view files into a views package. That is...
# views
    # __init__.py
    from views import SomeView
    from another_view import AnotherView

    # views.py
    def SomeView(request):
        return HttpResponse('SomeView')

    # another_view.py
    def AnotherView(request):
        return HttpResponse('AnotherView')

And now, everything can be called in a django-standard way:
url(r'^url-to-some-view/$', 'views.SomeView'),
url(r'^url-to-another-view/$', 'views.AnotherView'),

UPDATED:
To make a 'python package'...

Create a views directory at the same level as the view.py file [mkdir views]
Create a __init.py__ file inside the views directory # this is what makes a directory a 'python package'
Move views.py into the views directory.
Move your request_view.py into the views directory.
Edit the __init__.py file with the necessary import statements. In this case:
from views import answer
from request_view import display_meta

What this does is replace a file with a directory. By importing everything into the __init__.py file, this directory looks like a large file to your code, rather than another module.
Comment: hey. Thanks for the help.. can u pls tell me how to create this package?

Django running wrong view method


SQL exception: No suitable driver while using MS JDBC in Android Studio

Question: I'm trying using MS JDBC to connect to my SQL Server database but encountering this error.
java.sql.SQLException: No suitable driver
Here is my code
@SuppressLint("NewAPI")
public void Connect() throws Exception {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    connection = null;
    String S_url = null;
    String driver = null;
    try {
        DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
        driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        Class.forName(driver);
        S_url = "jdbc:jtds:sqlserver://" + ip + ";"
                + "databaseName=" + db + ";user=" + un + ";password="
                + pass + ";";
        connection = DriverManager.getConnection(S_url);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

I already added a .jar file into my project
Jar file
And set a dependency
Dependencies setting
Really appreciate your help and sorry if my English bother you, it's not my native language
Answer: Remove the jtds: from your JDBC URL that you assign to S_url. You register a Microsoft driver, but use the URL format of a jTDS driver.