Erase USB by means of Ubuntu 18.04

Question: I got a wrong Ubuntu OS downloaded to my USB.  I want to change its permissions so I can erase the USB and get the right OS, but it won't let me. How can I force it to change those permissions?
Gparted shows unallocated space. How to format the USB drive?
Answer: For just formatting a USB, there's no need to install any external packages.
Ubuntu 18.04 comes with Disks (gnome-disks) which can do basic management of drives.
You can launch it, then select the drive you want to format, click the vertical ellipsis icon (⋮) then Format Disk....
Comment: How do I launch gnome-disks?
Comment: It should just be one of the default applications if you check the app list, if in the terminal you can just do the `gnome-disks` command. (This assumes the OS installed is Ubuntu Desktop.)
Comment: No such command.  My output: mogens@mogens-ThinkPad-T60:~$ gnome-disk

Command 'gnome-disk' not found, did you mean:

  command 'gnome-disks' from deb gnome-disk-utility
Comment: That's because you typed the command wrong, it's `gnome-disks`, not `gnome-disk`. The output of the command also suggested the correct command.
Answer:
Open gparted (you can install it with the command sudo apt install gparted if it is not installed).
Select your USB drive in the right upper corner, it may be /dev/sdb.

Right click the partition in your USB drive, and format it to FAT32.
In case it shows unallocated, select new

Select FAT32, and leave the other option to default values.

Select the checkmark to apply the operation.

Close gparted, and you are done.
Comment: I got this output:
Comment: "Comment too long by 821 characters"....
Comment: How can I select the USB?
Comment: @MogensEliasen I have added a screenshot.
Comment: I do not get the screen you show...
Comment: @MogensEliasen Did you open gparted? What do you see?
Comment: The black terminal screen asking for input.
Comment: Is there a special way of OPENING the program?
Comment: @MogensEliasen *The black terminal screen asking for input.* Did you lose your graphical interface? Please edit your question and describe the exact issue you are facing. Possibly add a screenshot.
Comment: I don't understand what you want.
Comment: Nothing happens when I install gparted
Comment: Except that I can only type a line before the system freezes
Comment: You will have to go to the menu (or activities) and type gparted. Then you need to click on its icon to open it. But I am confused because you wrote there is a black terminal screen. Can you access the desktop interface? In that case you can even install gparted from the software center.

Possibly the system did not freeze. The terminal is waiting for you to type your password and press `Enter`
Comment: I do not know how to add a screenshot
Comment: I opened gparted as you said.  The terminal is gone.
Comment: My screen looks different from the one you showed.  I cannot rightclick on anything.
Comment: Rightclicking gives the option to resize or dismount, but none of is allowed by the system.
Comment: @MogensEliasen You can upload a screenshot to imgur or a similar website, and post the link here.
You will have to select the usb drive, right click to unmount, and right click to format it.
Comment: https://imgur.com/a/TiJuDOy
Comment: @MogensEliasen  1. Connect your USB drive (close gparted first). 2. Open gparted, and click here (see this https://imgur.com/a/V4IXjSj ). 3. Choose `/dev/sdb` (this is your usb drive. `/dev/sda` is your computer's HDD or SSD) . 4. Right click on the partition of the USB drive, unmount, and click format as FAT32. 5. Click on the checkmark to apply the format operation. Done
Comment: It does not work.  The device is "unallocated" and doing what you suggest gives the error "Not allowed".  Unmounting is impossible this way.,
Comment: @MogensEliasen Check the edited answer.
Comment: Please understand that I understand you. But things don;t happen as you suggest. Right-clicking on ANYTHING leads to an error message.  Unmounting this way is not possible.
Comment: @MogensEliasen What error message? Please post it. As I previously said, you don't need to unmount in case it is showing unallocated.
Comment: https://imgur.com/a/uwhIREY
Comment: https://imgur.com/a/4TgJwxe
Comment: So, I can freely use the USB-stick now?
Comment: Adding the USB-stick does not even show on the computer.
Comment: @MogensEliasen It is not showing up because it does not have a partition (because it says unallocated). You need to create a new FAT32 partition. I don't know why it shows that error. I suggest you ask a friend who can format it for you.
Comment: I played with the gparted program, and I think I got the USB-stick formatted to FAT32.
Comment: The rest went as you suggested.  Thanks for the help.
Comment: @MogensEliasen In case it worked, please consider accepting my answer (by clicking on the checkmark on my answer)
Comment: I don't know how to do that - I see no check marks.  But I flagged the central message, does that do it?
Comment: @MogensEliasen One has to click on this check mark to accept an answer (only do that if my answer fixed your issue). https://imgur.com/a/UyKueUe
Comment: I do not see that check mark.  But your answers helped me solve my problem.

Erase USB by means of Ubuntu 18.04


Error message "Incorrect values within SQLDA structure" with Firebird and Delphi 2009

Question: I'm strugling with error message "Incorrect values within SQLDA structure" when I'm trying to  update blob field within Firebird 2.1 database from Delphi 2009 DBX application.
However I get the error message when I'm trying to execute TSQLQuery with following SQL: "update MYTABLE set FIELD1= :data where id = :id"
The relevant delphi code is:
<code>MyQuery.ParamByName('id').AsInteger := id;
MyQuery.ParamByName('data').LoadFromFile(filename, ftBlob);
MyQuery.ExecSQL();
</code>
Where should I be looking? This has been working in earlier Delphi versions.
Answer: This is the kind of crypt error that Delphi's Interbase driver is used to show.
I've seen this problem when you have different numbers of parameters in your SQL statement and the ones defined in your query component.
Answer: Double check your driver - it is for Firebird or you just use the Interbase driver for this?. It is known that the Firebird team changed the SQLDA structure for Blobs in 2.1 and, hence, the Interbase driver cannot be used anymore.
You have some options here:

(recommended, imho) Upgrade to Delphi 2010 - besides of a DBX Firebird driver you will get much more things to play with (see here for more)
Buy a 3rd party driver for Firebird which works in Delphi 2009
'Downgrade' your Firebird (use it as a last resort, of course)
Change your connectivity library. Yes, it might imply code rewrite.
Answer: maybe you need to use the free dbx driver for firebird
http://sites.google.com/site/dbxfirebird/
Answer: The first thing that comes to mind is to make sure that the the client dll (gds32.dll or fb32.dll or fbclient.dll, the name depends on which version of Firebird you are using) exactly matches the server version you are using.
--jeroen
Answer: FWIW, I got this error in a perl program by executing a statement without bind variables, when it needed them.


How to solve: "error: cannot find symbol class ..." after converting Java class to Kotlin?

Question: I'm trying to start with Kotlin by converting some Java classes of my project to Kotlin and create a mixed Java/Kotlin project. In order to configure the environment I did the following:

Downloaded the latest version of Kotlin plugin (1.0.2);
On the top level gradle.plugin I've added: classpath "org.jetbrains.kotlin:kotlin-android-extensions:1.0.2" in the dependencies section;
In my module's gradle plugin I've added: compile "org.jetbrains.kotlin:kotlin-stdlib:1.0.2" in the dependencies section;
I've picked the POJO class I wanted to convert to kotlin, selected from menu Code -> Convert Java File to Kotlin File;
After that, all Java classes that were importing the converted class started to display: error: cannot find symbol class Chat. Below are the original class, the converted class and the log:

Original Java class:
package br.com.gogame.model;

import com.google.gson.Gson;
import com.orm.SugarRecord;
import com.orm.dsl.Ignore;

import java.io.Serializable;
import java.util.List;

import br.com.gogame.model.enums.ChatType;

/**
 * Created by edgar on 11-Apr-16.
 */
public class Chat extends SugarRecord implements Serializable {

    private String title;
    private String thumbnail;
    private ChatType chat_type;
    private long chat_id;
    private int num_of_members;
    private long user_id;
    @Ignore
    private List<Long> users;

    public Chat() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public ChatType getChat_type() {
        return chat_type;
    }

    public void setChat_type(ChatType chat_type) {
        this.chat_type = chat_type;
    }

    public long getChat_id() {
        return chat_id;
    }

    public void setChat_id(long chat_id) {
        this.chat_id = chat_id;
    }

    public int getNum_of_members() {
        return num_of_members;
    }

    public void setNum_of_members(int num_of_members) {
        this.num_of_members = num_of_members;
    }

    public long getUser_id() {
        return user_id;
    }

    public void setUser_id(long user_id) {
        this.user_id = user_id;
    }

    public List<Long> getUsers() {
        return users;
    }

    public void setUsers(List<Long> users) {
        this.users = users;
    }

    @Override
    public String toString() {
        Gson gson = new Gson();
        return gson.toJson(this, Chat.class);
    }
}

Converted Kotlin class
package br.com.gogame.model

import com.orm.SugarRecord
import com.orm.dsl.Ignore

import java.io.Serializable

import br.com.gogame.model.enums.ChatType

/**
 * Created by edgar on 11-Apr-16.
 */
class Chat : SugarRecord(), Serializable {
    var title: String? = null
    var thumbnail: String? = null
    var chat_type: ChatType? = null
    var chat_id: Long = 0
    var num_of_members: Int = 0
    var user_id: Long = 0
    @Ignore
    var users: List<Long>? = null
}

Error Log:
C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\commons\infra\App.java
    Error:(8, 42) error: cannot find symbol class DaggerMainComponent
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\view\fragments\FragmentChats.java
    Error:(23, 27) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\communication\post_office\GCMOffice.java
    Error:(25, 27) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\controller\util\JSONParser.java
    Error:(22, 27) error: cannot find symbol class Chat
    Error:(98, 17) error: cannot find symbol class Chat
    Error:(111, 60) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\controller\ChatController.java
    Error:(23, 27) error: cannot find symbol class Chat
    Error:(41, 12) error: cannot find symbol class Chat
    Error:(46, 12) error: cannot find symbol class Chat
    Error:(62, 32) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\commons\util\FakeDataProvider.java
    Error:(7, 27) error: cannot find symbol class Badge
    Error:(8, 27) error: cannot find symbol class Chat
    Error:(21, 24) error: cannot find symbol class Badge
    Error:(94, 24) error: cannot find symbol class Chat
    Error:(106, 20) error: cannot find symbol class Chat
    Error:(118, 20) error: cannot find symbol class Chat
    Error:(130, 20) error: cannot find symbol class Chat
    Error:(142, 20) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\controller\util\NotificationFactory.java
    Error:(19, 27) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\model\dao\ChatDAO.java
    Error:(13, 27) error: cannot find symbol class Chat
    Error:(24, 29) error: cannot find symbol class Chat
    Error:(46, 19) error: cannot find symbol class Chat
    Error:(60, 19) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\model\dao\ChatUserDAO.java
    Error:(7, 27) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\model\dao\Datamanager.java
    Error:(9, 27) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\model\dao\LocalUserDAO.java
    Error:(8, 27) error: cannot find symbol class Chat
    Error:(145, 24) error: cannot find symbol class Chat
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\view\adapters\BadgesAdapter.java
    Error:(15, 27) error: cannot find symbol class Badge
    Error:(21, 52) error: cannot find symbol class Badge
    Error:(25, 60) error: cannot find symbol class Badge
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\controller\FriendshipController.java
    Error:(21, 27) error: cannot find symbol class Chat
    Error:(195, 79) error: cannot find symbol class Chat
    Error:(33, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\controller\MessageController.java
    Error:(23, 27) error: cannot find symbol class Chat
    Error:(91, 50) error: cannot find symbol class Chat
    Error:(117, 61) error: cannot find symbol class Chat
    Error:(128, 65) error: cannot find symbol class Chat
    Error:(216, 46) error: cannot find symbol class Chat
    Error:(34, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\view\activities\ActivityCanvas.java
    Error:(38, 27) error: cannot find symbol class Chat
    Error:(64, 13) error: cannot find symbol class Chat
    Error:(53, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\view\activities\ActivityFriends.java
    Error:(22, 27) error: cannot find symbol class Chat
    Error:(196, 13) error: cannot find symbol class Chat
    Error:(39, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\view\adapters\ChatAdapter.java
    Error:(26, 27) error: cannot find symbol class Chat
    Error:(35, 50) error: cannot find symbol class Chat
    Error:(43, 58) error: cannot find symbol class Chat
    Error:(35, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
    C:\SIBEN\Edgar\workspace\GoGame\current\app\src\main\java\br\com\gogame\commons\infra\dagger\MainComponent.java
    Error:(42, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
    Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
    > Compilation failed; see the compiler error output for details.
    Information:BUILD FAILED
    Information:Total time: 7.406 secs
    Information:51 errors
    Information:4 warnings
    Information:See complete output in console

Comment: It looks like your kotlin code isn't compiled during build process.
Have you applied the required plugins, as the [tutorial](https://kotlinlang.org/docs/reference/using-gradle.html#targeting-android) suggests? Also take a look at this [example](https://github.com/JetBrains/kotlin-examples/tree/master/gradle/android-mixed-java-kotlin-project)
Comment: @EdgarDaSilvaFernandes You should add an answer to this question explaining what you did in order to fix it, and mark it as the accepted answer :)
Comment: That was it! I've added ```apply plugin: 'kotlin-android'``` and now .kt file is compiled and recognized. Thank very much.
Answer: As pointed out by user @Ilya, the problem was that the .kt files weren't being compiled and, therefore, couldn't be recognized when I tried to deploy the app in the device. To solve this problem, all I had to do was add apply plugin: 'kotlin-android' in my module's gradle.build as indicated in the links he has pointed in his comment, and that's all! It works now!
Answer: I had the same problem & fixed as follows (assuming that apply plugin: kotlin-android is added, but the problem still remains) :
Add sourceSets under android
android {
  ...
  sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
  }
}


Querying nested arrays in MongoDB

Question: I have a collection in MongoDB, where my data looks  like below. I am using NodeJS 12.X  platform along with Mongoose at backend for my application . Since i am new to development background, kindly help me in it.
Collection Data in DB :
<code>{
        "_id" : ObjectId("603faf38150786680421b51f"),
        "conversationMetricName" : [
                {
                        "metric" : "nConnected",
                        "stats" : {
                                "count" : 3
                        }
                },
                {
                        "metric" : "tAbandon",
                        "stats" : {
                                "max" : 2779,
                                "min" : 2779,
                                "count" : 1,
                                "sum" : 2779
                        }
                },
                {
                        "metric" : "tAcd",
                        "stats" : {
                                "max" : 2779,
                                "min" : 2779,
                                "count" : 1,
                                "sum" : 2779
                        }
                }
        ],
        "conversationInterval" : "2021-01-18T18:30:00.000Z/2021-01-19T18:30:00.000Z",
        "__v" : 0
}
{
        "_id" : ObjectId("603faf38150786680421b520"),
        "conversationMetricName" : [
                {
                        "metric" : "nConnected",
                        "stats" : {
                                "count" : 19
                        }
                },
                {
                        "metric" : "tAbandon",
                        "stats" : {
                                "max" : 293745,
                                "min" : 214878,
                                "count" : 2,
                                "sum" : 508623
                        }
                },

        ],
        "conversationInterval" : "2021-01-19T18:30:00.000Z/2021-01-20T18:30:00.000Z",
        "__v" : 0
}
}
</code>
Expected Response :
<code>{
chart:{

   date: [2021-01-18T18:30:00.000Z/2021-01-19T18:30:00.000Z, 2021-01-19T18:30:00.000Z/2021-01-20T18:30:00.000Z],
   nConnected: [3,19],
   tAbandon: [1,2],
   tAcd: [1,0],

   },

}
</code>
Could anyone advise me , how to filter the data as like above using their Counts value.
Thanks.
Answer: Use the sort method
collection.sort( { count: 1 } )
https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort
Comment: Hi @n7f , Actually i am trying to retrieve the desired response as posted above . Here i am not doing the sorting functionality. I can able to get the dates value, but remaining responses i am not sure how to retrieve count value  inside the array in respect with dates.

Querying nested arrays in MongoDB


Get the change of dimensions on resize using jQuery

Question: For my web site I am using the following code:
$(window).resize(function (event) {
    window.location.reload();
});

Unfortunately when using the site on a mobile device there are minute resize events that occur. I am wanting to put in a tolerance so that these minute changes do not fire this reload.For this I need to know the change in dimensions that occurred in the resize event. I have been looking at the event object however it is huge and ugly.
Thanks in advance :)
Comment: But what I mean is that you should just use a media query so that your function does not occur if you're on a mobile device. That's my first idea
Comment: @JBDouble05, certainly switching of page orientation would lead to window resize.
Comment: All you need to do is use a media query
Comment: That will not get to the root of this problem @JBDouble05 Please read the question
Comment: That is a fair point. However I want it to fire on decent sized resize events no matter the screen size
Comment: But how would you resize it on a mobile device?
Comment: Very good point @Arvind
Answer: You could achieve this by tracking the original window dimensions and then comparing those dimensions with current dimensions (acquired during each resize event) to determine the amount of change.
The following shows how you could trigger a reload if the width changes by a certain total THRESHOLD amount:
var THRESHOLD = 50; // the threshold that must be exceeded to trigger reload

$(window).resize(function(e) {

  var width = $(window).width();

  // Record the starting window width that the comparison will
  // be relative to
  if(window.startWidth == undefined) {
    window.startWidth = width;
  }

  // Calculate the total change since first resize event
  var widthChange = Math.abs(width - window.startWidth);

  // If change exceeds THRESHOLD, trigger reload
  if(widthChange > THRESHOLD) {
    window.location.reload();
  }

})

Comment: This won't work because the line `var width = $(window).width();` gets the new width so you are comparing the new width with the new width. I need to get the old width somehow
Comment: Hi @Worm , it only does so in the first resize event. Notice how `window.startWidth` is stored once, and then reused as a reference width to detect the threshold? Or perhaps I'm missing something here ?
Answer: Building on the helpful comments of JBDouble05 and the helpful answer by Dacre Denny I have made a final solution that fits my needs. Here it is to help others in the future hopefully.
var OGwidth = $(window).width();
var OGheight = $(window).height();
var threshold = 50;
$(window).resize(function (e) {
    if (OGwidth < 768) {
        var newWidth = $(window).width();
        var newHeight = $(window).height();

        var widthChange = Math.abs(OGwidth - newWidth);
        var heightChange = Math.abs(OGheight - newHeight);

        if (widthChange > threshold || widthChange > threshold) {
            window.location.reload();
        }

    } else {
        window.location.reload();
    }
    //reset for next resize
    OGwidth = newWidth;
    OGheight = newHeight;
})


Get the width and height of the camera space in Graphics Programming

Question: I have this AR project that I need to transform the screen coordinate to world coordinate. I follow this tutorial and I almost made it.
The only problem when I try to transform from homogeneous clip space to eye space, I use the wrong projection matrix. The reason why the projection matrix is wrong because I cannot get the right width and height of the camera space. I used this library called Kudan, when i move the camera phone forward and backward, I expect the camera width and height to change since the camera space size should be getting smaller when it moves forward and vice versa.
For the last resort, currently i try to find the camera space size by myself, How do I implement this?
This is my projection matrix
<code>Matrix4f projectionMatrix = new Matrix4f(-0.5f* currentCamWidth, 0.5f * currentCamWidth, -0.5f * currentCamHeight, 0.5f * currentCamHeight, -1f, node.getFullPosition().getZ());
</code>
Current cam width and current cam height are always constant. the coordinates are opengl coordinates
Comment: @RobertLimanto to construct perspective projection matrix you need: 1. aspect ratio or resolution , 2. znear, zfar  3. FOV angle or focal length. see [Perspective Projection matrix](https://stackoverflow.com/a/24009436/2521214)
Comment: Camera space does not have a width/height. The closest thing you get is the FOV and the aspect ratio.
Comment: how to get fov?
Comment: can we get projection matrix from aspect ratio?
Answer:
when i move the camera phone forward and backward, I expect the camera width and height to change since the camera space size

Why? Just because you move around the point of view that doesn't mean that the properties of the "virtual lens" change.

should be getting smaller when it moves forward and vice versa.

Why? That's not how cameras work.

It's really hard to give a helpful answer here, without seeing the code you've written so far. At the moment it's guesswork at best.
Comment: @RobertLimanto: No. For one `Matrix4f` reads like a constructor for a 4×4 matrix and thereby would either take 16 floats or 4 vectors of 4 floats. Not what you're passing there. I can see that you were thinking in parameters that construct a frustum, but even then it's not correct. Why? Because the parameters of a camera do no changes when it's position is altered, to that very last parameter that takes the result of a function call is surely not right. Here's a very thorough tutorial: http://www.songho.ca/opengl/gl_transform.html
Comment: i am just looking for theory, are you famiiliar with kudan?
Comment: for now, i know the position of the object in the camera space, when i adjust my camera space so that the object in the corner of my camera screen. the coordinate of the object is not the same with my screen size.
Comment: basically, i am trying to convert my screen coordinate to camera space coordinate. but without knowing the size of the camera coordinate, it is not possible.
Comment: when you move the camera closer to floor, the observable view will be smaller, therefore the camera space will be smaller too.
Comment: @RobertLimanto: When you move the camera closer nothing becomes "smaller" what's changes is the cross section of the projection volume with the object. This "getting smaller" is just caused by the movement of the camera in space. The camera itself doesn't change at all.
Comment: hi, i have updated my projection matrix, is that correct?
also, what should be the value for near plane?
Comment: this is the problem, the library does not use opengl fully, they only use the glsurfaceview. But for the camera, they use native camera of android. Therefore, i have to create my own projection matrix. You just said that "the parameters of the camera do not changes", Therefore, which parameter should I use? How to get the parameter in Android Camera?

Thanks so much for the help


Radial Gradient ellipse doesnt work properly

Question: I have a school project where i need to make a exact copy of a website.
The background is  a bit tricky because i need to  (what i think) add a radial ellipse but then with no sides or bottom, only the top.
when i try to make a ellipse i get a oval which covers all four sides (obviously) but i dont know hot to apply it to the top only.
can anyone help me out?
this is what is is supposed to look like
PLease pay attention to the background only

I already tried a ellipse and a normal radial gradient but i does not function how i want it to be.
this is the code i have
 background-image: radial-gradient(ellipse, white, lightgrey, lightgrey,
#1b1b2e
#1b1b2e);

Comment: Questions seeking code help must include the shortest code necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do).  See [**How to create a Minimal, Reproducible Example**](http://stackoverflow.com/help/reprex)
Answer: adjust your code like below:

html {
  min-height:100%;
  background-image: radial-gradient(150% 150% at bottom center, white, lightgrey,  #1b1b2e, #1b1b2e);
}


Fetch employee information by selecting employee_id from DropDownList

Question: My database has employee id, name, Email, address, and phoneno. I have used a dropdownlist for selection of employee id, for this I wrote this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Employeedetails : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=REVATI-PC;Initial Catalog=Test_Database;Integrated Security=True");
    SqlCommand cmd;
    SqlDataAdapter da;
    string query;

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        query = "select Employee_ID from Employee";
        cmd = new SqlCommand(query, con);

        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            DropDownList1.Items.Add(dr[0].ToString());
        }

        con.Close();

but by clicking on those particular id, I did not get other information. For this I used SelectIndexchanged event and write a select query
 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
 {
        string query = "select Employee_ID from Employee where Employee_ID='" + DropDownList1.SelectedValue.ToString() + "'";
        con.Open();
}

But it's not working
Comment: [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection
Comment: It doesn't look like you're ever executing your query in DropDownList1_SelectedIndexChanged()...
Answer: The problem you are seeing is two-fold. You are selecting only the employee ID during your query, not any additional information, and you do not appear to be running your query if the function you posted is complete. To select additional information, choose either select * (as below), or select specific column names and read them out from the reader by column name
Try updating your selectedIndexChanged function to this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string query = "select * from Employee where Employee_ID='" + DropDownList1.SelectedValue.ToString() + "'";

    conn.Open();

    cmd = new SqlCommand(query, con);

    SqlDataReader dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        DropDownList1.Items.Add(dr["<column_name>"].ToString());
    }

    con.Close();
}

Answer: try this
    string empname="";
    string query = "select * from Employee where Employee_ID=@value1";
    cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@value1",DropDownList1.SelectedValue.ToString());
    con.Open();
    SqlDataReader dr = cmd.ExecuteReader();
     while (dr.Read())
    {
        empname=dr["Employee_Name"].ToString();
    // and so on
    }
    con.Close();


How can I close the lid on my HP Pavilion g7 running Ubuntu 11.10 without crashing it?

Question: If I close the lid on my computer while it's running, it goes into sleep (hibernation?) mode. When I open back it up, the screen wakes up for a moment, then goes black. The computer is unresponsive and I must hard boot o avoid.
I've tried the following solutions. Neither worked:

Edit xorg.conf
Replace gnomescreensaver with xscreensaver

I'm not sure if this is related, but I had issues with the videocard on the laptop during install which I described here:
https://askubuntu.com/a/105792/46766
If you know of a reasonable solution, please share it with a short explanation indicating why you believe it will be effective.
Thanks in advance.
Comment: Why don't you just change the option for what happens when you close the lid to "Suspend" or "Do Nothing"? Is there any particular reason you need the laptop to hibernate?
Comment: @William That's what I ended up doing. I wasn't originally aware of the option.
Comment: OK. Are you okay with me making an answer as such so that the question isn't left unanswered?
Answer: First, start by going to the power cog in the upper-right hand corner of the screen and clicking 'System Settings".

You will see a screen like the following:

Click "Power", then change what happens when you close the lid to something other then "Hibernate".

Hope that helps!
Comment: The last interface is a little different on my machine (maybe I'm using a different desktop?). And "Blank Screen" was not an option. But setting it to "Do Nothing" solved the problem. Thanks for the screenshots.
Comment: Sorry, this is all I could find from Google Images as I'm not on Ubuntu right now. But it should looks similar.
Answer: Had problems finding the "power cog" so I entered in the search field, "power" and then selected "change what power options do," then selected "nothing" for "closing the lid."
Comment: Kindly rephrase your answer to include a step-by-step procedure, adding screenshots if possible. That would make this answer easier to follow for newbies and will attract upvotes for u.. ;)


Fine-tune CNN with different number of classes

Question: I'm trying to fine-tune a PASCAL-VOC trained faster-RCNN model on my own 30 classes dataset.
Reference model: link
Of course when I change cls_score and bbox_pred num_output to 30 and 120 instead of 21 and 84 respectively, these layers' weights aren't loaded and I need to change the layers' names.
I wonder if there is a way to preserve the data learned in the FC layers for different number of classes.
Thanks.
Answer: According to the Berkley repo, this should be simple.
You need to match your layer name with the reference model's layers you want. For example, if you want the weights from a reference model's ip1 layer, then your model should have the same name:
layer {
  name: "ip1"
  ...

Layers in your model with different names will be randomly initialized, or according to the scheme you've decided. When training, to borrow the weights from theirModel.caffemodel, you launch your model as so:
caffe train —solver ourSolver.prototxt —weights theirModel.caffemodel

EDIT
Sorry, I think I didn't answer your question at all. If a fully connected layer is a 100 x 10 matrix, you cannot use the weights for a 100 x 20 matrix for example. The weights don't mean anything in the new context. It's best to initialize the new layer randomly.
Comment: Thanks @vega. I indeed asked if the (in your example) 100 x 10 can have any meaning for new classes / another shape.
Comment: It won't have any meaning. So the original output layer 100x10 would be scrapped and you would initialize a new 100x20 layer. However, you can keep all the pretrained lower layers from the other model, those could be beneficial. Does that answer your question?


Patching together continuous maps from disjoint $G_\delta$ sets into a continuous map

Question: Let $(X,d)$ be a metric space, denote by $\tau_d$ the induced metric topology. Let $G_i$, $i\in I$, be a countable union of disjoint $G_\delta$-subsets. Mind that it could be that $G_i \notin \tau_d$ and $\cup_{i \in I}G_i$ could be a proper subset of $X$. Consider continuous maps $f_i:(G_i,d_{G_i}) \mapsto (Y,h)$, where $d_{G_i}$ is the restriction of $d$ to $G_i$ and $(G,h)$ is a metric space.
Question is it possible to patch together the maps $f_i$'s and extend the map so obtained, say $f$, to a continuous map $f:(X,d)\mapsto (Y,h)$?
Remark 1 Assume that in particular $G_i$'s are open and cover $X$, i.e. $X=\cup_{i \in I}G_i$. Then the disjoint union topological space $\coprod_{i\in I}(G_I,d_{G_i})$ and $(X,d)$ should coincide (since each ${\tau_{d_{G_i}}}$ would consists of intersections between $G_i$ and open sets, say $U$, of $\tau_d$; but then also $G_i\cap U \in \tau_d$). Then $f=f'$ would exists by the universal property of coproducts.
Remark 2 Let's now give up the assumption $X=\cup_{i \in I}G_i$, but retain $G_i \in \tau_d, \, \forall i \in I$. Endow $G=\cup_{i \in I}G_i$ with the restriction of $d$, say $d_G$. Then, we still have $G_i \in \tau_G$ and $f$ obtains as in the previous remark, but now as a continuous map from $(G,d_G)$ to $(Y,h)$. If $G$ is dense in $X$, then there exists also a continuous map $f'$ extending $f$ to $X$ (but it may not be unique, see e.g. the answer to this question Extending a function by continuity from a dense subset of a space ).
Remark 3 Let's finally give up also the assumption $G_i \in \tau_d, \, \forall i \in I$. If there existed $\tau_d$-open, disjoint sets $G_i'$ such that $G_i=G \cap G_i'$, then the $G_i \in \tau_{d_G}$, then it should be possible to obtain $f:(G,d_G)\mapsto (Y,h)$ as above and, if $G$ is again dense, then we can extend $f$ to some continuous $f'$.
Does the third remark make sense? Is it always possible to construct the aforementioned open sets $G_i'$? (If yes, this is not immediately clear to me). Can we obtain a positive answer to the above main question also beyond the restrictions in Remark 3? (That was the more general setting I managed to handle so far). Any help or refs are appreciated.
Answer: Every singleton set in $\mathbb R$ is a $G_{\delta}$ set. Consider the collection of sets $\{\{r\}: r \in \mathbb Q\}$. This is a disjoint countable collection of $G_{\delta}$ sets. Let $f$ be any map from $\mathbb Q$ to $\mathbb R$. This gives a family of continuous functions on these singletons.  Your question asks if we can find a continuous map extending these functions. The answer is obviously NO.
Comment: Ok. But do you think that, at least in some cases, the sets $G_i'$ might exist and Remark 3 work well, or do you think it's incorrect?
Answer: The minimal requirement is of course that $f_i\mid_{G_i \cap G_j} = f_j\mid_{G_i \cap G_j}$ for all $i, j$. So let us assume this in the sequel.
Remark 2: It is false. Extending a function by continuity from a dense subset of a space deals only with extending uniformly continuous maps. Take for example $X = [0,1], G = (0,1]$ and $f : G \to \mathbb [0,1], f(x) = \sin(1/x)$. This has no continuous extension to $[0,1]$ since $\lim_{x \to 0}f(x)$ does not exist.
Remark 3: In that case the $G_i$ are open in $G$, thus you get $f : G \to H$ as desired. But there is no reason why an extension to $X$ should be possible.
Comment: Actually the answer to the linked question starts with ``If you only need continuity of $g$, then continuity (not uniform) of $f$ is enough", where in my case $g$ would be $f'$. Is the cited statement false? According to that answer, it would seem that uniformity is only needed for unicity. Or, more informally, if the extension is not univocally defined (for which uniform continuity is needed), is the extension substantially useless, since it is not well defined?
Comment: In addition, in Remark 2, estension of $f$ to some $f'$ should be allowed by adding assumptions on $(Y,h)$, e.g. Theorem 1 A. in blair (1976) https://www.jstor.org/stable/2040816?seq=1#metadata_info_tab_contents
Comment: It is definitely wrong that any continuous $f : D \to Y$ defined on a dense subset of a metric space $X$ has a continuous extension $F : X \to Y$. See my example for Remark 2. If $X$ is compact and $Y$ is complete, then $F$ exists **iff** $f$ is  uniformly continuous. The acknowledged answer to the linked question does not define an extension $g$ of $f$, but only proves that the definition $g(x) = \lim_{x_n \to x, x_n \in D} f(x_n)$, **if** this limit always exists, yields a continuous $g$.See Srivatsan's answer to the question.
Comment: Uniform continuity is irrelevant for the uniqueness of continuous extensions. In fact, any two contiuous maps $F : F' : X \to Y$ into a  Hausdorff space $Y$ which agree on a dense subset $D$ agree on $\bar D = X$. See https://math.stackexchange.com/q/305472
Comment: Blair's paper gives conditions on $Y$ **and** on $f$ which guarantee the existence of an extension. It does not say that any $f$ has an extension.
Comment: Sure. Anyway in Remark 2 at least a *continuous* map $f:(G,d_G)\mapsto (Y,h)$ obtains, right? So, if $G$ is dense **and** $(Y,h)$ is compact, the continuous extension to $X$ exists, correct?
Comment: Yes, $f : G \to Y$ exists. But see my example where we have a single $G_1 = (0,1]$ (i.e. $G = G_1$). $X = Y = [0,1]$ are compact, but $f$ does not have a continuous extension to $X$.
Comment: Ok, many thanks, I misinterpreted the reference by Blair.


How to send powershell script output to printer with formatting?

Question: I need to send a script output (basically, agenda from my Outlook calendar filtered by category) that is made within the script to a printer. For the purpose of readability I'd like it to be formatted.  At least print some words bold, some italics, maybe change font.
The text is assembled from a custom object and might looks something like this:
text =
@"
Monday

Meeting with Joe : 07:00 - 08:00
Meeting with Ann : 8:30 - 09:00

Tuesday

No meetings
"@

I would ideally like it to print something like this:

Monday
Meeting with Joe : 07:00 - 08:00
Meeting with Ann : 8:30 - 09:00
Tuesday
No meetings

What I have so far (leaving the code pulling calendar events out):
text =
@"
Monday

Meeting with Joe : 07:00 - 08:00
Meeting with Ann : 8:30 - 09:00

Tuesday

No meetings
"@

Add-Type -AssemblyName System.Drawing
$PrintDocument = New-Object System.Drawing.Printing.PrintDocument
$PrintDocument.PrinterSettings.PrinterName = 'Microsoft Print to PDF'
$PrintDocument.DocumentName = "PipeHow Print Job"
$PrintDocument.DefaultPageSettings.PaperSize = $PrintDocument.PrinterSettings.PaperSizes | Where-Object { $_.PaperName -eq 'Letter' }
$PrintDocument.DefaultPageSettings.Landscape = $true

$PrintPageHandler =
{
    param([object]$sender, [System.Drawing.Printing.PrintPageEventArgs]$ev)

    $linesPerPage = 0
    $yPos = 0
    $count = 0
    $leftMargin = $ev.MarginBounds.Left
    $topMargin = $ev.MarginBounds.Top
    $line = $null

    $printFont = New-Object System.Drawing.Font "Arial", 10

    # Calculate the number of lines per page.
    $linesPerPage = $ev.MarginBounds.Height / $printFont.GetHeight($ev.Graphics)

    # Print each line of the file.
    while ($count -lt $linesPerPage -and (($line = ($text -split "`r`n")[$count]) -ne $null))
    {
        $yPos = $topMargin + ($count * $printFont.GetHeight($ev.Graphics))
        $ev.Graphics.DrawString($line, $printFont, [System.Drawing.Brushes]::Black, $leftMargin, $yPos, (New-Object System.Drawing.StringFormat))
        $count++
    }

    # If more lines exist, print another page.
    if ($line -ne $null)
    {
        $ev.HasMorePages = $true
    }
    else
    {
        $ev.HasMorePages = $false
    }
}

$PrintDocument.add_PrintPage($PrintPageHandler)
$PrintDocument.Print()

which I took from the corresponding articles on the internet, replacing StremReader from the file by line-by-line reading the multiline string.
How would I format text like that? Put some markers in the text, just like I do here or in HTML? and then parse them within $PrintPageHandler? Would I use $printFont for that or StringFormat in DrawString?
Please give me some direction to keep digging...
Answer: Hm, because you have outlook, I'm going to assume you have Word as well. Using the Word COM object is the only really easy way I can think of doing what you're trying to do.
#didn't know how you generated the calender info, so I took liberties here,  using nested hashtables
$calendarStuff = @{

    week1 = @{
        Monday =  @(
            "Meeting with Joe : 07:00 - 08:00",
            "Meeting with Ann : 8:30 - 09:00"
        );
        Tuesday = @("No meetings")
    }

}

#path where to save the doc
$docPath = "C:\temp\printTestThing.docx"
# instantiation of the com-object. It's by default not visible
$wordCom = New-Object -ComObject Word.Application
# uncomment this to see what's going on
#$wordCom.visible = $true

# creates and selects the word document we'll be working with
$doc = $wordCom.Documents.Add()
$selection = $wordcom.Selection

# go through and grab each week
foreach($week in $calendarStuff.Keys)
{
    # go through each week and grab the days
    foreach($day in $calendarStuff[$week].keys)
    {
        # Apply the style 'Heading 1' to what we're about to type
        $selection.Style = "Heading 1"
        # type out what the day is
        $selection.TypeText($day)
        # make a paragraph
        $selection.TypeParagraph()
        # switch the style back to normal
        $selection.Style = "Normal"
        foreach($thing in $calendarStuff[$week][$day])
        {
            # type out what the event is, prepending it with a 'tab' character
            $selection.TypeText("`t" + $thing)
            # make a paragraph
            $selection.TypeParagraph()
        }
    }

}
# print the doc
Start-Process -FilePath $docPath -Verb print

You can add way more customization if you want, but hopefully this is the catalyst you needed.
Example of what this looks like if printed to pdf
Comment: Thanks, that's an approach I will most definitely try. I'm more comfortable constructing html file. I guess it's going to be essentially the same to print html file, right?
Comment: One more question though - is everything going to change much off I want to print that not on ordinary office printer, but a thermal printer for receipts?
Comment: I don't think it would be similar to building and printing an HTML file.
As for the thermal printing question, I'm not sure, but I would hope at least the formatting would stay the same.


Why do we have two ways to add an event listener on a view in android?

Question: In android, we have two ways to add an onClick listener on a view, one is through the XML and the other is through the java code.
Why do both of them exist and why does android provide us two ways for that?
What good does it do to the overall code or is it due to the way the android framework works or is it due to the time taken to write a code or is there anything more to it?
Answer: For explanation about defining onClick attribute in android in the XML layout vs Java/Kotlin code, since I wouldn't like to take any credits from this video, so I am linking the resource for you, it has almost every aspect for your question covered by this channel. Feel free to comment and ask me again if anything sounds confusing to you.

https://www.youtube.com/watch?v=cMVlhTT9fL4


Wood Cladding Construction Technique

Question: I am working on a tiny house idea that includes a construction technique that I've modified somewhat from something else I saw. I wanted to run it by folks, to see about the wisdom of it.
The desire here is to build more simply, but the welcome byproducts include it being cheaper and quicker.
I think I'm talking about wood cladding, where I would simply stack 2 x 6 tongue and groove lumber on top of each other to form a big box. At the corners, in the design I'm borrowing from the planks are notched and fit together much like a log cabin. In my design, I'd rather not have the crossed wood for aesthetic reasons, so I simply butt the pieces but alternate the butt at each flight. I have to add a little lateral notch to the end of each board so that it grabs on to the tongue of the lower flight.
I've constructed a small box using this technique and it holds together somewhat without any fasteners, but the next step is to figure out how to fasten it well. As long as it maintains it's box shape, it will be strong.
My idea is to run a piece of angle iron, or perhaps aluminum up each corner to attach the boards to. Lag boots could go into every other board on each wall skipping the ones that present their end grain, since that wouldn't be a strong connection anyway.
I'm wondering if a) this is a known construction technique, and I just don't know the right name. b) If you have any other ideas on how to fasten it. c) Ff the design seems structurally sufficient to you.
My idea originated from this EZ Cabin system that I found.
My only modification is to change the way the corners join. Instead of the extra effort to notch the wood, I would do it like this...

The tongue and groove boards would each be glued to one another and then I would lag bolt a piece of angle iron vertically to each corner attached to every plank. Obviously I am not under the impression that what works at this size will work at any size.
Thanks for the opinions and intuition so far, but I wonder if seeing the existing cabins and pictures of my design convinces anyone that it will work.
Comment: Two concerns, structural integrity doesn't scale.  What works small, will not always work big.  If you are already having some issues, once you scale it those issues will become bigger.  Another concern, this structure will have to support a roof.  Roofs are heavy and put a lot of stress on the walls, I don't think stacked lumber will up for the challenge.  Also typically the most expansive part of building a structure is the lumber costs.  Standard 2x4 framing and siding will be easier to construct and most likely cheaper.
Comment: In general it's not a great idea to make up construction methods as you go unless your a really good architect.
Comment: You can see pictures of the structures that inspired my idea here : http://www.i5rvs.com/custompage2.asp?pg=in-stock. I've talked with these guys and walked in the buildings. They make and sell them by the thousands. My design, like theirs would not include insulation. I live in a moderate climate. They say the buildings are very easy to heat with a small space heater.
Comment: @iLikeDirt, I don't know the terms, but the boards would be the structure as well as the finished exterior (painted to protect the wood) and the finished interior.
Comment: Yah, can't do that, then. You need a 2x4 structure to support the cladding and roof, for that matter. Furthermore, your plan will result in a wall with no insulation. I'd reconsider.
Answer: I don't think this is a great idea. The cabin kits you've found have the following major drawbacks that I can see:

No insulation. You'll have unnecessarily high heating and cooling bills unless you plan to build where it's 75 and cloudy year-round.
No real protection from water. When those boards get wet, so will the interior side, eventually. As soon as that happens, everything will immediately suck.
No racking resistance. I don't see anything but a hope and a prayer protecting a house built out of those from blowing down in high wind.
No bowing resistance. The heavier your roof, the more those walls look likely to bow out.
Not airtight. You can see the gaps in the corners in your picture. Hot or cold air is going to whistle through those joints. During a windstorm, it'll be very uncomfortable.
Nowhere to hide wiring and plumbing.
Awkward integration with windows and doors. Most of them have jambs or frames that are 3.5" thick; they'll protrude awkwardly from one of the two sides. You could trim wood frame door jambs, but you can't do the same for windows.

Those things really look more like storage sheds than anything I'd want to live in. In order to make it work, you'd be swimming upstream every step of the way. Why bother? Go with the flow. Conventional wood frame construction is super cheap and easy to do--that's why it's the dominant construction method in price-sensitive America. It's easy to learn, too. Almost all tiny house builders had no conventional construction expertise beforehand, but they picked up what they needed in a week or two of hands-on work. It's really not that hard.
Additionally, one of the advantages of building a tiny house is that you can utilize high-quality components due to the fact that you don't need a lot of them. I'm talking about things like mineral wool insulation batts and boards, standing seam roofing, wood shingle siding or stone veneer, deluxe high-performance windows, etc. Really nice stuff. All of these things will be barely more expensive than their crappier equivalents for a <200 sf house due to how little you'll need. But if you try to turn a glorified storage shed into a house, you'll lose the ability to easily do that, and spend all your time cutting door frames to fit your super thin wall and devising ways to make the roof not collapse once you realize you need more insulation. What's the point?
Comment: Marking as answer. Completely appreciate the time and thought. Would love to continue the conversation if you're willing.
1. not a big concern for me
2. Wouldn't a good paint layer protect?
4. How could they if the roof is holding them in? And as long as they're where they should be isn't it all compression strength?
5. Agreed. Those would be covered. All joints and seams would be glued/sealed.
6. Not a concern for me
7. I don't know much about this. Isn't a thin wall with trim on either side bringing it to 3.5" the same as a stud?
Thanks again!
Comment: Sure, though this isn't the best place. Maybe a mod could move the conversation to the community section or something. But my TL;DR answer is that you're fighting the tide. None of your proposals are impossible, but they're like trying to turn a bicycle into a motorcycle instead of simply buying a motorcycle in the first place... especially if a motorcycle would be barely any more expensive than a bicycle!
Answer: This is a bad idea.
If you span more than 6 feet the T&G boards will flex alot.
It will not hold weight of roof.
You would need to use 4x4's to be strong enough to hold roof and to have shear strength
Wood will expand and contract and you will get gaps for water and cold air to get in.
T&G boards are expense and will cost more or very similar to conventional framing,siding and drywall.
What will you do for insulation? Foam sheets are very expensive. Then you still need to cover the foam.
Running wires and plumbing will be very difficult.
How will you frame in your doors and windows?
If you want the look of T&G boards you will need to frame a wall out of 2x4's or 2x3's first. You can build it 2'oc You could probably build it 4'oc safely if it was an interior wall.
Comment: Thank you for the info. I wonder if you can help me substantiate that point of view at all. I've gotten feedback that it won't work - won't be strong our warm enough, but the link I included above is a company that's actually doing this and they're apparently strong and warm. My only modification to their design is to interweave the corners to avoid the crossover look.
Comment: No insulation, no running utilities (surface mount electric, water/sewer run under and come straight up through the floor to point of use), doors and windows could be trimmed to be the same size as a conventionally framed configuration.
Comment: Think of a tiny house as, well, a tiny house. That means you build it like a house, The guys in your links are RV guys who appear to also sell cabin kits. Those things would not pass building codes. And they wouldn't be much fun to live in due the absence of any insulation.
Comment: I only seen one shed on that website with 3/4 inch walls and it was only 6'x'6 the rest of the structures where built using thicker pieces of wood 1 3/8" and 2 1/4" logs

Wood Cladding Construction Technique


Unable to create cloudkit Container

Question: I am creating an app with core data that is hosted in a cloud kit. I have added a developer account to my Xcode. This account is added as a developer in a paid developer account (organization's account). But when I tried to create a cloudkit container it showed an error. How can I create the cloud kit container? I am following this article to create the app. Article link. What I am missing now. If it is not possible to create automatically how to create the cloudkit container manually add the capabilities and download the profile. Usually, these things(manual generation) are done by the CI/CD team. Is it possible to create it manually?
Answer: You can create manually, follow these steps:

Login to developer.
Select Identifiers on Certificates, IDs & Profiles section.
Register a new identifier, and tick on iCloud Containers. Then paste on Project -> Capability -> iCloud.
Login to CloudKit Console.
Select CloudKit Database.

Now you're ready to create some mock records.
Comment: by using that provisioning profile I can run the project, right?
Comment: By adding iCloud capability to bundle ID then, yes, you can.

Unable to create cloudkit Container


How to detect changes in local files in bitbake?

Question: Let's say I have a simple recipe that only adds one script file:
LICENSE = "CLOSED"
SRC_URI += "file://test.sh"
S = "${WORKDIR}"

do_install () {
    mkdir -p ${D}/usr/bin
    cp -r test.sh ${D}/usr/bin
}

If I modify test.sh and re-run bitbake, it does nothing because it doesn't realize anything has changed. Is there any way to get the recipe to check if there are changes in SRC_URI files? And recompile if changes are found. SRC_URI[md5sum] is not supported for local files.

EDIT: My original question was a bit flawed, due to my somewhat unrealistic test setup. But it did show an interesting feature in bitbake.
I switched between two versions of test.sh, where I just added or removed one character. What happened was this:

Run bitbake -> test-recipe is compiled
Edit test.sh by adding one char
Run bitbake -> test-recipe is compiled
Edit test.sh by removing the char
Run bitbake -> test-recipe is not compiled
Edit test.sh by adding the same char as before
Run bitbake -> test-recipe is not compiled

So if test.sh changes to a previous version, bitbake does not notice the change. There must be some sort of weird caching going on somewhere. What this means is that the recipe I used originally worked, but only if the changes to test.sh are new, actual changes and not the artificial ones I used to test the recipe.
Comment: Can you store test.sh in a git repository? If so, then it is done for you as the git checkout hash will cause rebuilds when changed.

Also, you could build by doing the following...
bitbake test-package
bitbake image-name
Comment: I am aware of that option, but unfortunately in this case using a git repository is not an option.

Also, just running "bitbake test-package" will not trigger a rebuild. I have to run "bitbake -c cleansstate test-package" first. But I would prefer just to run "bitbake image-name" and have all recipes with updated files be recompiled automatically. That's what I was looking for with the original question.
Answer: As already stated, it is better suited to have the recipe under version control so that new commits will cause a state change and the SRCREV would hence be altered and trigger a new fetch/compile/install
I just tried your recipe and added it to my core-image-minimal image and I did not see any problems with detecting changes in the test.sh script. This is my slightly modified recipe I am using.
LICENSE = "CLOSED"
SRC_URI += "file://test.sh"
S = "${WORKDIR}"

PR = "0"

do_install () {
    install -d ${D}/usr/bin
    install -m 0644 test.sh ${D}/usr/bin
}

Save it as test.bb inside an existing layer. Add this recipe to your image recipe:
IMAGE_INSTALL += "test"
Then bitbake your image. I used the minimal base image.
bitbake core-image-minimal.
Edit test.sh and re-run the previous bitbake. You should see bitbake install your new script into your image located at tmp/deploy/images/<your_target>/core-iamge-minimal.tar.xz
If that fails, then you can always manually bump the PR value in your recipe.

After seeing your edit:

So if test.sh changes to a previous version, bitbake does not notice the change. There must be some sort of weird caching going on somewhere.

bitbake caches all inputs so that different iterations of your script can be quickly pulled from the shared-state cache. You should see a folder inside your tmp folder labeled sstate-cache. This is where your previously compiled script resides. In short - this is expected behavior and everything is fine.
Comment: I commented the original question, my initial observation was wrong. I'll accept this as the answer because you are essentially correct.
Comment: @Sampo I re-edited my answer for your recent edit. In short - yes, this is normal operation since bitbake is pulling your previously compiled script from cache which is why you don't see the `do_compile` task occur.


Prove that $\overline{AM}$ is perpendicular to $\overline{BM}$

Question: All points are in the middle of this separating it into $3 $ equal parts prove that it is $\frac{1}{9}$ of the whole thing.
Answer: So given the triangle draw AM and from that you get that ABD and AMC are similar then you get that BD is the middle point to AD is equal to GF and form that you get that am is pretty to bc


CoreOS access from other instance

Question: I have a coreOS cluster with 3 instances. I need to init a service in the 3 instances, but I don't want to use the IP to connect. Is there a dynamic way to scan the instances and get the IP's and then use it?
Answer: You can use the following command to get a list of the cluster instances for further processing:
fleetctl list-machines | awk '{print $2}' | tail -n +2

Answer: If you want to use the IP in one of your containers/services, and you're running CoreOS on a cloud providers, you can source in an environment file with the allocated IPs:

[Service]
EnvironmentFile=/etc/environment

and then use those values as environment variables.
Answer: CoreOS has a built in scheduler called fleet that runs on all hosts. You can just create the service and execute the command to run the service:
fleetctl start myunit.service.
To tail the output of the service you can run: fleetctl journal -f myunit.service which will automatically ssh into the host running the container, and see the output.
"I need to init a service in the 3 instances"
It seems like you're trying to run a service that should be active on all hosts in the CoreOS cluster. Take a look at the X-Fleet variable Global. You can set up a service to run on all hosts by adding this to the bottom of your service/unit file:
[X-Fleet]
Global=true

This way you will only have to start the service once, to initiate it on all hosts in the CoreOS cluster.

CoreOS access from other instance


Using simple approximation theorem to show set where measurable function differ from bounded simple function has tiny measure

Question:
Let $f$ be a measurable function on $[a,b]$ that takes $\pm \infty $ only on a set of measure zero. Show that for any $\epsilon >0$, there is a bounded simple function $\phi$ on $[a,b]$ such that the measure of the set where $f$ and $\phi$ differs is small.  $$m (\{ x : |f(x) -\phi (x)| \geq \epsilon\}) < \epsilon \tag{*} $$

I know the Simple Approximation Theorem (SAT) states that a measurable function can be approximated by a sequence of simple functions. In this case, how do I show $(*)$ is true? I am using the Royden Fitzpatrick book but the proof for SAT is not very useful here.
Answer: For each $n\in\mathbb N$, let $E_n=\{|f|\geq n\}$. Then $E_{n+1}\subset E_n$ for all $n$. And by continuity of measure $$0=m(\{f=\pm\infty\})=m\biggl(\bigcap_nE_n\biggr)=\lim_nm(E_n)$$ So there exists $n_0$ such that $m(E_n)<\varepsilon$ for all $n\geq n_0$. Choose $n\geq n_0$ with $n>1/\varepsilon$. Now let
$$
\phi(x)=\sum_{j=-n^2}^{n^2-1}\frac{j}{n}\,1_{\{\frac jn\leq f<\frac{j+1}n\}}.
$$
Outside of $E_n$, we have $|f-\phi|<\tfrac1n<\varepsilon$. Thus
$$
\{|f-\phi\|\geq\varepsilon\}\subset E_n.
$$
Comment: The set is the complement of $E_n$.
Comment: I can understand the proof but I am wondering how to construct the simple function function $\phi$ as above (this was not obvious to me) in order to show that the set where $f$ and $\phi$ differs is less than $\epsilon$. Thanks.
Comment: Ok I understand the reasoning for the set where the difference between the two functions is greater than $\epsilon$ is tiny and goes to zero as $n$ goes to infinity.
Comment: The point is that simple functions are bounded; so you cannot approximate an unbounded function uniformly. So one gets the $E_n$ with small measure, and outside of $E_n$ the function $f$ is bounded and can be approximated by a simple function.


can't make ssh connection via python

Question: I followed this question
I have this function in PostgreSQL:
CREATE OR REPLACE FUNCTION a()
  RETURNS void AS
$BODY$
import subprocess
cmd1 = "usr/bin/ssh firstname.lastname@example.com time"
out1, err1 = subprocess.Popen(cmd1,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE).communicate()
plpy.notice(out1)
$BODY$
  LANGUAGE plpythonu VOLATILE

This should login to the server specified and display its time.
No matter what I do I always get :

ERROR:  OSError: [Errno 2] No such file or directory

The only time I don't get the error is if
    cmd1 = "usr/bin/ssh"
but then it does nothing.
How can I make it work?
Comment: `cmd1` should look more like: `cmd1 = ['/usr/bin/ssh', 'email@example.com', 'time']`. This is (if i'm not mistaken) because `Popen()` assumes the command parameter is a list unless dangerously supplying `shell=True`. You can also use `cmd1 = shlex.split("/usr/bin/ssh firstname.lastname@example.com time")`.
Comment: I think that the path to the `ssh` command should start with the root folder - `/usr/bin/ssh`. Without the leading slash it would be a relative path - perhaps this is why the "No such file or directory" error is being raised.
Comment: @Torxed this prevent the error however nothing is printed to the screen
Comment: @avi most likely because the host running the script, isn't allowed to SSH without a password - or `plpy.notice()` wan't a string? If SSH is hanging waiting for a password, `.communicate()` will hang and wait as per described in the doc as well: `Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. >>>Wait for process to terminate.<<<`. Have you tried running this command from the server manually once to see what happens?
Answer: The problem you're facing is that Popen() assumes the command to be a list of command+arguments.
There for, cmd1 should look more like:
cmd1 = ['/usr/bin/ssh', 'email@example.com', 'time']

(unless dangerously supplying shell=True, then you can keep your command string as is).
You can also use:
import shlex
cmd1 = shlex.split("/usr/bin/ssh email@example.com time")

This is also covered under the docs for Popen().
Last notes: I've never used plpythonu or this SQL version of code execution, but I'd assume that you would want to specify the full path for SSH as Lix pointed out, that being /usr/bin/ssh and not usr/bin/ssh. But your main problem is how you pass the arguments to Popen().
Don't forget to allow SSH to login with a key, otherwise the command might hang asking for a password in the background.
Seeing as many people have issues running system commands that hangs without the programmer understanding why, try the following modification to get output as the command is executed instead of at the end (.communicate() will wait for EOL, meaning hang forever if the process never quits):
CREATE OR REPLACE FUNCTION a()
  RETURNS void AS
$BODY$
import subprocess
cmd1 = ["usr/bin/ssh", "firstname.lastname@example.com", "time"]
process = subprocess.Popen(cmd1,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT).communicate()
while process.poll() is None:
    plpy.notice(process.stdout.readline())
$BODY$
  LANGUAGE plpythonu VOLATILE

It's still highly inefficient since i fused STDERR and STDOUT together and using readline() instead of read(). Also import select might be useful here.
But this will give you output "live" from the command instead of bunkered up at the end. It should also print any errors that the command is throwing (but still hanging because the error didn't close the application properly).
This is a common mistake and people aught to read the examples/docs more on this.
Comment: I have no actual need for the command to be string. I'll use the list method. How can I know if the option was successful are there any error codes?
Comment: @avi I suggest you try the code and see if there's any errors. The last edit I gave should print any errors. If there are any, correct them. But I can't in advance know if there'll be any errors ^^ If it didn't work, I suggest you create a new question that is in regards to that specific problem, seeing as this was a `Popen()` usage problem thread :)

can't make ssh connection via python


Regex format with numbers and one letter

Question: I would like to know how to create a regex pattern in format:
111.222-3M
and
1112223M
What are numbers are only numbers allowed, and last one is a letter only.
Thx in advance.
Comment: The question is quite trivial. What specific part did you have trouble with?
Answer: A strict, case-sensitive version:
<code>\d{3}\.?\d{3}-?\d[A-Z]
</code>
Will match 1112223M, 111.222-3M, 111.2223M and 111222-3M. If the last two are undesirable:
<code>(\d{3}\d{3}\d[A-Z])|(\d{3}\.\d{3}-\d[A-Z])
</code>
Will match only the first two.
Comment: Great. Thank you for your solution too. Its great one. Can I ask you, if its possible to match ONLY to 1st and 2nd type?
Comment: Crazy. How did you learn to make patterns? I would like to learn too. Any suggestions? Please...
Comment: I use RegexBuddy; QuickREx is an open source alternative.
Answer: If those really are the only two patterns to match, this will work:
<code>^\d+\.?\d+\-?\d+[a-zA-Z]$
</code>
As @ThomSmith stated, this regex will match numbers with the decimal and hyphen in different locations as well, such as 11.12-2223M. If that is undesirable, let me know.
EDIT:
If those patterns are exactly the same as the ones you want to match, this is a better one:
<code>^\d{3}\.?\d{3}\-?\d[a-zA-Z]$
</code>
Comment: Note: this will match strings like 111.2223M or 111222.3M, which may or may not be a problem. Also, I'm not sure if the number of digits may be significant.
Comment: @ThomSmith Good point - I should have specified. I assumed the number of digits before and after the, uh, punctuation? would be fluid. I may or may not have been correct in that assumption
Comment: The only 2 allowed formats are those 2 I showed in my 1st post! So it will work? Else formats must not be passed forward.
Comment: If it's EXACTLY that format (7 numbers and a letter or {3}.{3}-{1}Letter), then a more specific regex should be used. Hang on.
Comment: I did thx. Ok, I will try it out. One more q: will this work for format without any - and . in between?, So in format {7}{1} - 7 numbers and a letter.
Comment: @MitjaBonca Is this part of a larger string? If so, take out the `^` and `$` and try again.


django retrieveing user objects

Question: I have a simple model like this:
class Auction(models.Model):
    name = models.CharField()

class Item(models.Model):
    auction = models.ForeignKey(Auction)
    name = models.CharField()
    price = models.FloatField()

class Bid(models.Model):
    item = models.ForeignKey(Item)
    user = models.ForeignKey(User)
    price = models.FloatField()

users place bids for an item. Knowing that a user is allowed to place just one bid for each item. If I have the auction id, can I get all user objects (not simple usernames, like in a values_list()) that placed a bid in that auction?
EDIT: I would also like to avoid using 'in'
Answer: users = User.objects.filter(bid__item__auction_id=auction_id)

Comment: but `bid` field is not part of the `User` model.
Answer: It's probably possible to do it much easier, but this is the way I would try.
Add related names:
from django.db import models
from django.contrib.auth.models import User

class Auction(models.Model):
    name = models.CharField(max_length=20)

class Item(models.Model):
    auction = models.ForeignKey(Auction,related_name="items")
    name = models.CharField(max_length=20)
    price = models.FloatField()

class Bid(models.Model):
    item = models.ForeignKey(Item,related_name="bids")
    user = models.ForeignKey(User,related_name="bids")
    price = models.FloatField()

Now, if you have these:
a = Auction.objects.get(pk=auction_id)
users = set([]) #because there's no reason to have dupe users
for item in a.items.all():
    for bid in item.bids.all():
        users.add(bid.user)

Now, all the users with one or more bids in that auction is in the list
Comment: xpanta: Daniel's answer works if you add related names the way I did, and change his sentence to:

    users = User.objects.filter(bids__item__auction=auction_id)

django retrieveing user objects


Different behaviour of sockets in Java program running in Ubuntu or Windows

Question: I am working in the communication between two programs, one in C++ and the other in Java, connected using standard sockets. Both programs run under UNIX (Ubuntu) within the same machine and share information for a period of time in regular basis. At some point of the execution and always at the same point it gets stuck since the program in C++ sends the information and the one in Java does not get all the info so they block since the first expect to receive that and the second is not sending anything because did not receive the information in the firs place.
The odd thing is one you execute the program in Java under Windows. Then it works fine, the program ends correctly without any blocing.
I think is an issue with the Java application but why the difference between running the under Ubuntu or Windows? Do the socket behave differently? Is some parameter different from the JVM in Ubuntu and Windows?
Thank you very much in advance!
Julen.
EDIT:
This the code in the Java side that reads the buffer:
   if (task.equals("receiving")){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = socket.getOutputStream();

            // receive messages
            char[] length = new char[5];
            while (!socket.isClosed()&&(!socket.isInputShutdown())){
                in.read(length,0,5);
                // this way of reading the length implies that only one command
                // at a time can be received and interpreted, so far the iCS does not
                // concatenate more commands in one transmission
                int commandLength = length[4];
                System.err.println("Speed Advice --> command received with length "+ commandLength);
                char[] command = new char[commandLength - 1];
                in.read(command,0,commandLength - 1);
                /*if (cow){
                    System.err.println("Speed Advice --> Last byte received for X-pos is "+(int)command[commandLength-1]);
                }*/
                readCommand(command);
            }
            System.err.println("Speed Advice --> Socket was externally closed.");
            in.close();
            closeConnection();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

And this C++ sending information:
void
    Socket::
    send( std::vector<unsigned char> b)
    throw( SocketException )
{
    if( socket_ < 0 ) return;

    size_t numbytes = b.size();
    unsigned char *const buf = new unsigned char[numbytes];

    for(size_t i = 0; i < numbytes; ++i)
    {
        buf[i] = b[i];
    }

    if (verbose_)
    {
        cerr << "Send " << numbytes << " bytes via tcpip::Socket: [";
        for(size_t i = 0; i < numbytes; ++i)
        {
            buf[i] = b[i];
            cerr << " " << (int)b[i] << " ";
        }
        cerr << "]" << endl;
    }

    unsigned char const *buf_ptr = buf;
    while( numbytes > 0 )
    {
#ifdef WIN32
        int n = ::send( socket_, (const char*)buf_ptr, static_cast<int>(numbytes), 0 );
#else
        int n = ::send( socket_, buf_ptr, numbytes, 0 );
#endif
        if( n<0 )
        {
            // BailOnSocketError definitely throws an exception so clear up heap
            delete[] buf;
            BailOnSocketError( "send failed" );
        }

        numbytes -= n;
        buf_ptr += n;
    }

    delete[] buf;
}

Comment: Actually, sorry for being blunt, but the highest probability is that there's something wrong with your code. This may be as simple as an assumption you have made which isn't true on all platforms. It could be that Windows is working despite this problem :-)
Comment: IIRC java `char`'s are 2 bytes big. c++'s `char`'s are 1 byte big. Could this be your issue?
Comment: Also 2 tips: #1: pass your vector like this: `const std::vector &b`. The way you are doing at the moment is a full **copy** of the one you pass. #2. no need to allocate a new buffer and copy into it, just use `&b[0]` which will give you a pointer to the vector's internal array. This is fine since you don't try to modify the passed data.
Comment: yup, you have a bug. Let's see some code
Answer: The BufferedReader is not the problem specifically, and neither is 'the TCP stack [being] full'. And select() isn't required to solve it.
You are making several common mistakes here.

You are ignoring the return value of read(). It could be -1, indicating that the peer has closed the connection, which you must test for and act on first. Or it could be any value between 1 and the size you requested. You are just blindly assuming you will get 5 bytes when you call in.read(buffer,0,5). There's no guarantee of that. You need to use DataInputStream.readFully().
You are sending 8-bit chars from C++, and using a Reader in Java. This doesn't make any sense whatsoever. Use an InputStream. Specifically, a DataInputStream so you can call readFully() as suggested above.
Socket.isClosed() tells you whether you have closed the socket. It doesn't tell you whether the peer has closed the connection. That's what the -1 above is for.
Similarly Socket.isInputShutdown() tells you whether you have shutdown input on this socket. It doesn't tell you whether the peer has shutdown output at his end. Again, that's what the -1 above is for.

So both those tests are pointless, and the message you are printing when either of them is true is incorrect.
Answer: Inspect the communication with a sniffer. Wireshark is a good one.
Answer: While BufferedReader is great for file operations, it strikes me as a really bad idea to use one while reading from a Socket.
Otherwise, it might be that the BufferedReader thinks that data is still coming into the buffer when it really isn't.
I recommend removing it and dealing with the InputStreamReader directly to see if the problem still occurs.
Comment: Why exactly would using a BufferedReader over a Socket be a really bad idea? And how exactly might it be that 'the BufferedReader thinks that data is still coming into the buffer when it really isn't'? This is all nonsense, sorry.
Comment: This is just more nonsense. The 'cost' of reading a socket consists of the context switch into the kernel, and reducing them via buffering has a marked effect on performance. Clearly you haven't tried it. And the Socket library *doesn't* do its own buffering. And you haven't answered my second question.
Comment: Because the *kernel* has socket send and receive buffers. And you still haven't answered my 2nd question.
Comment: @EJP: I haven't looked at the internal workings of `BufferedReader`, but buffering is for reading data that has a high retrieval cost, such as reading a large section from disk rather than one byte at a time.  Sockets are coming in over the wire at a rate the receiver doesn't control.  The `Socket` library already does its own buffering.
Comment: @EJP: The `Socket` library doesn't buffer?  Then why does the documentation for `Socket` mention "bytes buffered on the socket" in several spots, in particular in the documentation for `getInputStream` (which Julen is using)?
Answer: Note that big chunks of data can be divided into several packages when sending over sockets. I wrote an answer here regarding sockets in C++, that addresses it shortly.
I see three possibilities:

Your tcp stack could be full. Thats a real bugger. You can read more about that in this article, but in short: the socket is full in some end of your socket, making the sender block more writes. You will have to read that data from the receiving side before send will unblock. You can check for "TCP ZeroWindow" with wireshark to find this. (default settings will be black with red text, you can't miss it)
It could be your sending side that is waiting for you to push more data to send
I don't think this is valid, but I guess that the receiving side could as well wait for more data to receive. As I understand it it is really up to the underlying network to decide if the data should be sent or not.

You can use select (sorry, don't know of the unix equivalent arguments, or java's) when sending data to check if you are ok to actually send (also described in my answer here).
Comment: `select` is part of C, so I'm assuming it's in C++ as well.
Comment: @R. Bemrose, is it the same arguments? Microsoft likes to change everything :) Because that link goes to msdn - winsock library.
Comment: Actually, select is not part of C, it's part of POSIX, coming from BSD. It was added to BSD together with sockets in 4.2, it appears on Winsock because of that.
Comment: As for compatibility between POSIX and Winsock select(), the only important difference I can see is that Winsock apparently sets errorfd s on failure to connect on a non-blocking socket, while it should set writefds
Comment: 'socket is full in some end of your socket, making both ends block'. This is not correct. A socket send buffer being full doesn't make both ends block. It makes the sending end block. The other end can read, and it can write until it fills up its own socket send buffer.
Comment: @EJP: hm.. I just took it from my personal experience that both ends blocked. Although, I wrote alot from both ends so it might just be that both my ends filled their respective buffers themselves, thus both blocking. I'll add your comment, thanks


How do I get two pistons (one of them on an inverted signal) to go at the same time?

Question: Here's the problem - I need two pistons to go at the exact same time, so that one of them is contracted and the other is expanded, on a switch mechanism. To achieve this, one of the pistons has to have an inverted redstone signal, like so.

This would be all fine and dandy except that when the signal is inverted it's slower by the tiniest fraction of a second. So, I add a repeater onto the other piston to slow the signal, but then that one is slower than the other. This problem has stumped me on many of my redstone projects, and any solution would be much appreciated.
Comment: The repeater should make the two occur at the same time. Did you set the repeater down to only 1 tick? It defaults to 4.
Comment: @LyonesGamer a repeater is if you place it on 1 tick... not on 4?
Comment: Does it default to 1? Sorry, I must have had it backwards.
Answer: The NOT gate also called inverter delays the time exact one tick.

circuit delay: 1 tick

from the minecraft gamepedia
That means the signal on the otherside is one tick to fast. To solve that simply put a repeater in the connection to the other piston.
A repeater also delays the signal with one tick.

When initially placed, a redstone repeater has a delay of 1 redstone
tick.

from the minecraft gamepedia
That means your circuit should look like this:

I only have the ability to check that with my eyes and ears and it seems pretty at the same time. Anyway you said you tried that...
Here is your secound answer:
There is a thing called instant inverter. It looks like this:

To get the whole thing working remove your inverter and place this instant inverter at this place. Keep in mind that the piston with the inverter acts strange. But this does not influence the block movememt. Neiter from a normal or sticky piston.

circuit delay: 0 ticks

from the minecraft gamepedia
You find other instant inverter possibilitys in the source link above.
Comment: It's not the not gate itself causing the delay, it is the redstone torch taking one tick to toggle state that is causing the delay. So anywhere you have a redstone torch being toggled, add a tick to your delay.


How To Add Remote Control Box In Ceiling Fan

Question: I recently purchased a new ceiling fan that has a box that the remote control will connect to and control lights/fan speed.  In the instructions for the fan it says to place the box above the mounting bracket and inside of the mounting box.  However, there isn't enough space to add the remote box.  So I'm not sure what options I have to hide the remote box under the fan housing.
Anyone here experienced something similar and have ideas?
Below are images of the box as well as the ceiling mount.
Comment: And, are you sure you have the mounting bracket installed correctly?  If it's upside down, it would protrude into the space the box is supposed to go.
Comment: What all is in the ceiling box?  Should just be a couple of wires/wire nuts.  The couple of fans like that that I've fooled with, you could usually make room for the control box by moving the wires around.
Comment: can we have  picture
Comment: This is not uncommon. Try again, but with all the wire connections pushed up into the junction box. This is usually tough to do.
Answer: The box is supposed to slide into the slot that is in the middle of the fan bracket. The slot is visible in your second photo. You'll need to move the wiring as far into the upper part of the box as possible, then slide the control box in and arrange the remainder of the wiring so it won't interfere with the cover. Then install the cover.
It's often quite tricky to do this, keep trying.
Comment: Yes, hardware store should have it, and your local big home improvement store would have it for sure also.
Comment: ahhh, this is one where there is an opening in the mounting bracket and you have to slide the "ball" from the fan into it to mount.  I might take it down and try to see if that makes a diffference or easy for me
Comment: ohhh, so if I push all the wiring into the electrical box in the cieling there will be space for the "control"?  Any tips on how to do it?  If it's tricky to do, i can keep on trying, just wanted to make sure it is/was possible before i had something FUBAR
Comment: I usually try to connect the box to the ceiling wires before installing the bracket, then carefully put the wiring into the box and route it so it won't get pinched when installing the bracket. Then install the bracket, slide the box in, and make the fan connections. Some fans have a little hook you can use to hold it up temporarily while you're doing this - make sure you make use of this, or have a helper to hold it up.
Comment: I think part of my problem is that the electrical box is not properly secured to a stud in the cieling....the box wiggles way to much and the sheet rock on the cieling is starting to flake away....i'll take it all down and attempt to connect the remote box before the mounting bracket this time.
Comment: @user2676140 -- that's a *bad* sign -- I suspect the original box was never fan rated and is starting to fail, so you need to replace it with a fan rated box
Comment: @ThreePhaseEel - wow, I didn't know there was a "fan rated box" - is this something my local hardware store would have?  (pretty standard thing)
Answer: I had this exact same problem and what we found was that the ball hanger was supposed to be sitting in a groove in the bracket (once it's in place it won't spin freely anymore, and it drops a fraction of an inch lower giving enough clearance for the receiver to sit without interfering). I was about to take an angle grinder to mine to make a channel for the excess wire. Glad I didn't go to that length.


Sequence space norm on $\mathbb{R}^2$

Question: I am working on an assignment so I won't be stating the actual question, but it's about showing extensions of a linear functional in $\mathbb{R}^2$ and it says, I quote

Determine all it's linear extensions to $\mathbb{R}^2$ with the same norm if $\mathbb{R}^2$ is given

the $\ell^1 norm$

The $\ell^p$ norm

and I am primarely stuck on the wording here s I don't quite grasp what this norm on $\mathbb{R}^2$ would be.
I know that the norm on $\ell^p$ is for $x=(x_1,x_2,\ldots)\in \ell^p$
$$||x||=(\sum_i x_i^p)^(1/p)$$
But this on $\mathbb{R}^2$ baffles me, would it be like viewing elements $(a,b)\in\mathbb{R}^2$ as $(a,b,0,0,0,0,\ldots)\in\ell^p$? Then it makes some sense to me, or am I completely out there?
Answer: The $l_p$ norm for $(x,y)\in\mathbb{R}^2$ is this:
$$||(x,y)||_p=(|x|^p+|y|^p)^{1/p}$$
So basically your intuition of putting zeros after the second place in an infinite dimensional vector is correct, but in fact there is no need to carry them around.
Comment: So it is as I said viewing it as $(x,y,0,0,0,\ldots)$ then?
Comment: Yes, it is, but then it is easier to think of them as two dimensional.
Comment: I agree on that which is what it reduces to, but it made no sense without that middle step of translation. Thank you.

Sequence space norm on $\mathbb{R}^2$


C# enum to string auto-conversion?

Question: Is it possible to have the compiler automatically convert my Enum values to strings so I can avoid explicitly calling the ToString method every time.  Here's an example of what I'd like to do:
enum Rank { A, B, C }

Rank myRank = Rank.A;
string myString = Rank.A; // Error: Cannot implicitly convert type 'Rank' to 'string'
string myString2 = Rank.A.ToString(); // OK: but is extra work

Comment: Unfortunately, programming involves a lot of typing, so you're just going to have to get used to it.
Comment: @codeka: Your response is funny. Dunno about you but I started coding for the sole fact that I am lazy and wanted to make using the computer easier (ie: shell script automation, simple batch files, etc.). It's a perfectly valid question to ask how to make something easier.
Comment: @Cory: there's being lazy and then there's being *lazy*. It's good to write shell scripts to make your life easier, but it's bad to circumvent the type system to save typing 11 characters.
Comment: Hmm not sure about on an enum but on a class you could use an implicit operator. http://msdn.microsoft.com/en-us/library/85w54y0a.aspx
Answer: No.  An enum is its own type, so if you want to convert it to something else, you have to do some work.
However, depending on what you're doing with it, some methods will call ToString() on it automatically for you.  For example, you can do:
Console.Writeline(Rank.A);

Comment: Also, just to be clear, there's nothing special about `Console.WriteLine`, it just has an overload that takes an Object and the enum is getting boxed, passed as an object and then `WriteLine` calls `ToString` on it.
Comment: @dcompiled - if you're curious, it is possible to write your own implicit conversion operator for your enum to a string! http://www.csharphelp.com/2006/10/type-conversion-and-conversion-operators-in-c/
Comment: Ok, just wishful thinking on my part.
Comment: Perhaps I'm missing something but I actually don't think it is possible to write your own implicit conversion, enum is not a class so you cant add methods to it.
Answer: You are not probably looking for enums itself, but a list of string constant. It can fit your needs better in some scenarios.
Use this instead:
public static class Rank
{
   public const string A = "A";
   public const string B = "B";
   public const string C = "C";
}

Comment: The issue with this solution is that the type that is getting passed around is a string. The caller can still pass in any string that they want.
Answer: No, but at least you can do things with enums that will call their ToString() methods when you might need to use their string value, e.g.:
Console.WriteLine(Rank.A); //prints "A".

Answer: The correct syntax should be
myRank.ToString("F");

Answer: [Caution, hack] Unsure as to whether this is nasty, to me it seems a reasonable compromise.
var myEnumAsString = MyEnum+"";
Console.WriteLine(myEnumAsString); //MyEnum

This will force implicit ToString()
Answer: This question was asked many years ago, but nevertheless...
Here's a very easy way to get a string[] from an enum:
public static string[] EnumToStr<T>() where T : Enum
{
    return Enum.GetNames(typeof(T));
}

Simply use it like this:
public enum Test
{
    alpha,
    beta,
    gamma
}

var test_str = EnumToStr<Test>();

foreach (var name in test_str)
     Console.WriteLine(name);

C# enum to string auto-conversion?


how to pass path of folder image directory in argument parser to test all images on my folder instead of only one?

Question: My program is testing only one picture example_01.png, I want to test all images that I put in my folder examples
so how can I do that ?
thanks
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
    help="path to input image")
ap.add_argument("-f", "--face", type=str,
    default="face_detector",
    help="path to face detector model directory")
ap.add_argument("-m", "--model", type=str,
    default="mask_detector.model",
    help="path to trained face mask detector model")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
    help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

# load our serialized face detector model from disk
print("[INFO] loading face detector model...")
prototxtPath = os.path.sep.join([args["face"], "deploy.prototxt"])
weightsPath = os.path.sep.join([args["face"],
    "res10_300x300_ssd_iter_140000.caffemodel"])
net = cv2.dnn.readNet(prototxtPath, weightsPath)

# load the face mask detector model from disk
print("[INFO] loading face mask detector model...")
model = load_model(args["model"])

# load the input image from disk, clone it, and grab the image spatial
# dimensions
image = cv2.imread(args["image"])
orig = image.copy()
(h, w) = image.shape[:2]

Call:
python detect_mask_image.py --image examples/example_01.png

Answer: def main(args):
 # Prepare an image
    directory = 'example'
    img_path_list =[]
    for filename in os.listdir(directory):
        f = os.path.join(directory, filename)
        # checking if it is a file
        if os.path.isfile(f):
            print(f)
            # print(type)
            img_path_list.append(f)
    print(img_path_list)
    args.image = img_path_list
    print(args.image, "**") #list of Frames path
    print(args.image[0])
    print(type(args.image[0]))

    for i,j in enumerate(args.image):
        image = load_image(args.image[i], transform)
        image_tensor = image.to(device)

        # Generate an caption from the image
        feature = encoder(image_tensor)
        sampled_ids = decoder.sample(feature)
        sampled_ids = sampled_ids[0].cpu().numpy()          # (1, max_seq_length) -> (max_seq_length)

        # Convert word_ids to words
        captions = []
        sampled_caption = []
        for word_id in sampled_ids:
            word = vocab.idx2word[word_id]
            sampled_caption.append(word)
            if word == '<end>':
                break
        sentence = ' '.join(sampled_caption)

        # Print out the image and the generated caption
        print("*****************************************")
        print (sentence)
        captions.append(sentence)
        print("*****************************************")
        image = Image.open(args.image[i], "rb")
        plt.imshow(np.asarray(image))

Comment: Please provide some explanation to your code.
Comment: I think you forgot to remove the "solution:" at the begining of the code.
Answer: Did you try os.list_dir(pathName)?
By this function you can list all the photos which are present in a directory "path"
You can convert the result from this to list and loop through all the images!
#!/usr/bin/python

import os, sys

# Open a file
path = "/var/www/html/"
dirs = os.listdir( path )

# This would print all the files and directories
for file in dirs:
   print file

Code from - https://www.tutorialspoint.com/python/os_listdir.htm
Comment: path = 'Image Path'
# Using cv2.imread() method
img = cv2.imread(path)
Comment: But i find problems with ap = argparse.ArgumentParser()