How can I get a list of tables in an Access (Jet) database?

Question: I need to see if a table exists in an Access database used by my c# program. Is know there are SQL commands for other databases that will return a list of tables. Is there such a command for Access/Jet databases?
Answer: Try the GetSchema()
    connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\access.mdb";

    connection.Open();

    DataTable userTables = connection.GetSchema("Tables");

Comment: So many big fancy answers when this was all I wanted!  Thanks!!
Answer: Full code : Get List of Tables in an Access Database - ADO.NET Tutorials
// Microsoft Access provider factory
DbProviderFactory factory =
    DbProviderFactories.GetFactory("System.Data.OleDb");

DataTable userTables = null;

using (DbConnection connection =
            factory.CreateConnection())
{
    // c:\test\test.mdb
    connection.ConnectionString = "Provider=Microsoft
        .Jet.OLEDB.4.0;Data Source=c:\\test\\test.mdb";

    // We only want user tables, not system tables
    string[] restrictions = new string[4];
    restrictions[3] = "Table";

    connection.Open();

    // Get list of user tables
    userTables =
        connection.GetSchema("Tables", restrictions);
}

// Add list of table names to listBox
for (int i=0; i < userTables.Rows.Count; i++)
    listBox1.Items.Add(userTables.Rows[i][2].ToString())

here is answer for you : http://social.msdn.microsoft.com/Forums/en/adodotnetdataproviders/thread/d2eaf851-fc06-49a1-b7bd-bca76669783e
Answer: Something like this should do the trick. The clause Type = 1 specifies tables. Note that this will also include the system tables in the result set (they start with the prefix "MSys".
SELECT Name FROM MSysObjects WHERE Type = 1

Comment: just trying it and I get: `Record(s) cannot be read; no read permission on 'MSysObjects'`.
Comment: @David-W-Fenton my understanding is that the "MSys" objects in an Access database default to not having permissions granted to even the Admin user, especially for a remote connection. I agree that if this project used the built in Access security features AND this was going to be a long standing query \ process that using a dedicated account with the appropriate permission would be best. I got the sense, however, that this might be a down and dirty type of query request in which case adding another user account w permissions would be overkill.
Comment: @hawbsl It sounds like you might need to modify permissions within the Access Database. Tools Menu -> Security -> User and Group Permissions. Assign 'Read Data' permission to the Admin user on the MSysObjects table.
Comment: Changing permissions like that would perhaps violate user-level security that has been set up on purpose. The solution is not to change the permissions on the underlying object (which would make it wide open to anybody), but to use a username/password that has the permissions you need.
Comment: If you don't have the permissions to read the system tables with the default admin account, you're not going to have the permission to do anything else. Likely the wrong workgroup file is being used and that's the cause of the read failure on the system tables.
Answer: that one worked for me
using (OleDbConnection con = new OleDbConnection(connectionString))
            {
                con.Open();
                DataTable dt = con.GetSchema("Tables");
                var selectNames = dt.Rows.Cast<DataRow>().Where(c => !c["TABLE_NAME"].ToString().Contains("MSys")).ToArray();
                foreach (var item in selectNames)
                {
                     // add names to comboBox
                    comboBox1.Items.Add(item["TABLE_NAME"]);
                }
            }


Set slider drawer height

Question: I have a slider drawer in my application. If I set wrap_content as a value for the layout_height field, the slider drawer will stretch on the whole screen. Using a constant as a height is not a good alternative either.
Is it possible to have a slider drawer with the height of it's content?
  <LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/frameLayout"
  android:layout_gravity="bottom"
  android:orientation="vertical">
    <View
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:background="@color/blue"/>
    <SlidingDrawer
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:handle="@+id/handle"
        android:content="@+id/content"
        android:id="@+id/slide"
        android:orientation="vertical">
    <RelativeLayout android:id="@+id/handle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/list_header">
         <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="@dimen/padding"
            android:textColor="@color/black"
            android:textStyle="bold"
            android:text="@string/ingredients_list_title"/>
         <ImageView
            android:id="@+id/handle_indicator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/padding"
            android:src="@drawable/arrow_up"
         />
    </RelativeLayout>
    <RelativeLayout android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/list_row_background">
        <LinearLayout android:id="@+id/list_ant_title"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_above="@+id/gallery"
             android:orientation="vertical">
              <ListView
                android:id="@+id/listview"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:divider="@drawable/divider"
                android:cacheColorHint="@color/transparent"
                android:fadingEdge="none"/>
        </LinearLayout>
        <Gallery
            android:id="@+id/gallery"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_alignParentBottom="true"
            android:background="@drawable/list_row_background"/>
    </RelativeLayout>
</SlidingDrawer>

Answer: What's the container? A LinearLayout? Add another empty element, and give them both a weight of 1.
Comment: It was a FrameLayout. I've changed it to LinearLayout and set the weights. But is the same thing.
Comment: I've posted it in the initial question. I did some fixing and the last conclusion is that if i set the weights to 1 for the dummy view and the drawer, both of them will have the height equal to 1/2 of the screen. I would like to have a sliding drawer with the height equal to it's content height.
Answer: Use topOffset attribute for SlidingDrawer.
like this.
<SlidingDrawer
    ...
    android:topOffset="800px">

Set slider drawer height


Convert a SortedList to a List

Question: Is there a way to convert android.support.v7.util.SortedList to java.util.List? (Or any other subclass) The only way I see is to go through the SortedList and add the elements one by one to a List, however this seems ugly and inefficient.
Answer: First things first: SortedList is a class and List is an interface, so you are maybe talking about ArrayList, but not List.
Have you tried with arraylist.addAll(sortedList)? But I don't think it will work, I am checking that SortedList doesn't implement Collection...
You can easily go from an ArrayList to a SortedList, though. Maybe you can refactor your code and handle an ArrayList from the very beginning, convert it to a SortedList for your needs, and then keep using the original ArrayList. Does it need to be a SortedList right from the beginning?

Convert a SortedList to a List


protractor instance does not do anything

Question: from one to anothet day i cannot interact with the angular page i am testing.
The only result i get:
Started
A Jasmine spec timed out. Resetting the WebDriver Control Flow.
F

the page has this:

So it should work, or not?
I tried checking on iFrames and also enhanced the allScriptTimeout: 360000, but nothing helped.
here is my config:
var TIMEOUT = 360000;
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporter = new HtmlScreenshotReporter({
    dest: 'report/screenshots',
    filename: 'my-report.html'
});
exports.config = {
    seleniumAddress: 'http://dmc-l01-ap08.dmc.de:4448/wd/hub',
    baseUrl: 'https://int.system.com/',

    specs: [
        './UseCases/protractorTestcaseNightly.js',
    ],

    Capabilities: [
        {
            'browserName': 'chrome',
            shardTestFiles: false,
            maxInstances: 1,
            maxSessions: -1,
            restartBrowserBetweenTests: true,
        },
    ],

    getPageTimeout: TIMEOUT,
    allScriptsTimeout: TIMEOUT,
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: TIMEOUT,
        includeStackTrace : true,
        isVerbose : true,
    },
    framework: "jasmine2",
    onPrepare: function () {
        browser.driver.manage().window().maximize();
        browser.driver.manage().deleteAllCookies();

        jasmine.getEnv().addReporter(reporter);

        var reporters = require('jasmine-reporters');
        var junitReporter = new reporters.JUnitXmlReporter({
            savePath: 'report/xml',
            consolidateAll: false,
            filePrefix: 'xmloutput'
        });
        jasmine.getEnv().addReporter(junitReporter);
    }
};

UPDATE:
I added
rootElement: 'html',

to my config. But nothing changed. I also took a screenshot from the page before clicking the first element. In the screenshot i can see the element i want to click at.
this is my Testspec:
describe('Start testspec | ', function () {

    it('opens the start', function () {
        browser.get("/de-de/connect/").then(function () {
            console.log("1"); //works
            browser.executeScript('localStorage.clear();sessionStorage.clear();'); //works (?)
            console.log("2"); //works
            expect(element(by.xpath('//*[@class="btn-link"]'))).toBeTruthy(); //works
            console.log("3"); //works

            browser.sleep(3000);  //works
            element(by.css('.ms-linklist-typ-1 a')).click(); //DOES NOT WORK :(
            browser.sleep(3000); //works
        });
    });
});

I do have to click on the "btn-link" / css element, because this is the cookie layer, which has to be clicked first before i can reach any other element...
any ideas?
Comment: Can you update your question with the test spec also .. a code snippet of the `it` block where you are seeing this issue .. may that will help to debug
Answer: Looks like you are using the timeout configuration incorrectly. allScriptTimeout is only for the backend application scripts is not for the overall Jasmine spec
Please take a look at the three timeouts explained below

allScriptsTimeout - This timeout config indicates the time
application needs to finish running back-end scripts
getPageTimeout - This indicates the time to wait for Page
Load
jasmineNodeOpts.defaultTimeoutInterval - This indicates the
time    that Jasmine waits for overall spec

So in your case you increase the jasmineNodeOpts.defaultTimeoutInterval to increase the timeout for overall spec
Try making the below change and see if this resolves the issue
   jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 120000,
        includeStackTrace : true,
        isVerbose : true,
    },

Also, Protractor assumes your angular-app root element to be body. Please see the below extract from the documentation below. Since your ng-app resides on a different element , may be update the config.js accordingly

/**    * CSS Selector for the element housing the angular app - this
  defaults to    * 'body', but is necessary if ng-app is on a descendant
  of .    */

 rootElement?: string;

Answer: it looks like i found the fix. My tests are running again by changing the versions of my installation. I looks like there is incompatibility between some version. It now works with:
Node LTS (6.10.0)
Selenium Server Standalone 3.0.1
firstname.lastname@example.com
email@example.com


Creating Ubuntu image to flash onto USB drive

Question: I'm working for a school, and we're replacing our bloated LTSP system, which has proven to be unreliable and difficult to maintain. Rather than creating another LTSP server, we want to run Ubuntu off USB drives.
For practicality and maintenence, I'd like it to be a "full" install of ubuntu so I can clusterssh into the workstations to run updates.
Sitting there and installing Ubuntu on each of the computers would be wildly inefficent, so I want to create a prefab image to dd to the drives, much like an embedded OS.
Unfortunately, all the information I can find is about either a single install, or creating a live image.
The installation process will probably be a script that formats the drive, runs dd to copy the image, then runs grub-install to put a bootloader on it.
I've tried creating a chroot in a mounted raw ext3 image, but I can't seem to make it boot. I'm assuming I'm going to have to do some hacky solutions with the kernel and initrd, but I'm not sure where to look.
These are the resources I've been pulling from:
Live CD Customization
Debian QEMU Image
The Ubuntu OEM Install seems close to what I'm looking for, but I'm looking for a preconfigured image with a guest account to be used by the end user.
Comment: Possible duplicate of [How to customize the Ubuntu Live CD?](http://askubuntu.com/questions/48535/how-to-customize-the-ubuntu-live-cd)
Comment: See https://askubuntu.com/questions/228687/difference-between-oem-install-and-custom-ubuntu-image
Answer: The Ubuntu OEM Install is the way to go, at least if the target computers are rather similar (so that the system is portable between them). Do the preconfiguring in a prototype system. Ubuntu has a guest account.
When you are happy with it, create an image either with dd|xz or maybe better with clonezilla. Then you can clone from that image to the target computers. There is a server version of Clonezilla, that might fit your purpose.
clonezilla.org
Answer: Why not build your USB just how you like it and then use dd or clonezilla to clone it to multiple drives?
dd will clone the bootloader along with everything else.
Installing to a USB drive is just like installing to internal drive, a flash drive is just another hard drive to Ubuntu.
It is best to remove the internal drive before proceeding, this protects it and results in a clean grub menu.
When you get to partitioning, select "Something else" and confirm the disk for the bootloader,
Perhaps make the first partition NTFS if the drives will ever be used for data on a Windows machine.
If ability to hibernate is required, provide at least as much swap as there is RAM on the computers they will be used on, .
For cloning I usually just use:
sudo -i
dd if=/dev/sda of=/dev/sdb

with no modifiers.
Cloning can be a slow process.
The cloned drives will all have the same UUID, but this can be changed if required.
Edit:
Alternately an image can be taken of the prototype drive using dd:
sudo -i
dd if=/dev/sdb of=/home/clone.img

The image can be written to the new USB drives using Win32DiskImager in Windows or mkusb in Ubuntu.


Using html5 localstorage to retrieve data from server, to allow editing of and appending to data source, then saving back to server

Question: I'm creating a standard user-data collection form that will be used by standard web browsers, as well as the iPhone and iPad. The app will allow users to create new records, as well as edit and delete existing records.
I've gotten the gist of using html5's 'localstorage' to create a client-side data source and am looking for direction for getting existing data from a server into a client-side data source, and then being able to edit or delete that data, or to append a new record to the existing data. Finally, being able to save the updated data back to the server.
It sounds like a lot, I know. But I've been pouring through html5 tutorials and can't seem to find exactly what I'm looking for.
Answer: As you've already decided to use HTML 5's localStorage, you'll be using JavaScript anyway. In that case, I think you should use XMLHttpRequests to retrieve from and send data back to the server. There exist several nice introductions to this on the net, like the W3C Working Draft and on Apple's site, on MDC and on MSDN. Please search for questions containing the AJAX tag.
BTW, if you merely want to store data during page sessions (so, you don't have to store data locally in between several page visits), you can also store your data in JavaScript arrays/objects. They are very easy to access and manipulate. This approach also has the benefit of better browser support (contrary to HTML 5's localStorage and proprietary solutions).


How to ignore invalid value and set null value when use jackson paring json string from webfront?

Question: Is there a good way to change the parsing strategy,even comes out a value cant convert to specific type just set null and continue parsing.
Here is the error info.
15:39:29 WARN  (DefaultHandlerExceptionResolver.java:424) Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.math.BigDecimal` from String "-": not a valid representation; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.math.BigDecimal` from String "-": not a valid representation
 at [Source: (PushbackInputStream); line: 1, column: 1483] (through reference chain: com.vicson.SGHDGD.base.model.DailyOutputUpdatePojo["sheet0"]->com.vicson.SGHDGD.base.model.UpdateSheet["insertRows"]->java.util.ArrayList[1]->com.vicson.SGHDGD.base.model.DailyOutput["weekOutputDRatio"])

Comment: You are trying to fit a String into a BigDecimal... obviously it won't work
Comment: It is nothing to do with JSON but how did you represent `desh(-)` as numeric?
Comment: set null value and continue parsing,if string is invalid.
Comment: You don't. Handle the exception by registering an exception handler and sending a bad request response to the client with a suitably descriptive message.
Answer: The most simple way is to have String field that will be successfully deserialized from JSON. And then parse BigDecimal in setter/constructor that receives field value. Like this:
public void setWeekOutputDRatio(String value){
  try{
    this.weekOutputDRatio = new BigDecimal(value.toCharArray())
  } catch (Exception ignored) {
    this.weekOutputDRatio = DEFAULT_VALUE;
  }
}

Comment: invalid value can be any properties,so it cant solve my problem
Comment: this should be an accepted answer. the best solution is using validator for form parameters to not to pass invalid values to server-side, but this way is the simplest solution.


How to display image which is stored in local drive?

Question: I have a asp page in which i have to display the image which is stored in my local disk C:
i.e..
C:\Program Files\Adrenalin\Adrenalin\UploadedFiles\TemplateFile\abc.jpg
how can i do that...i am not able to do so.
the image is not displayed instead it shows a empty image holder with the name of the image as specified and URL as not available.
Please help....
Comment: Show us some code. Difficult to guess at what issues you are having if you do not post the code you have and what errors and issues you are experiencing.
Comment: actually i'm having a database in which the path mention above is stored for different employees...when i click on the name of that employeee,it should retreive the path of the image corresponding to that employee and display its image.Now i am able to retreive the path from the database but it does not display the image which is stored in C: drive.

what problem might have been occured?
Answer: You will have problems with permissions if the image is outside of the web site folder. Traditionally, web sites run under the NETWORK SERVICE user account, which will limit access to files outside of the folder. You will need to extract the file from a folder with similar access and it is extremely unwise to do so, particularly from Program Files.
You should possibly proxy the file via a web page or web service, which doesn't expose the fact that the image is served external to the web site. You'll need to make sure the target folder C:\Program Files\Adrenalin\Adrenalin\UploadedFiles\TemplateFile has NETWORK SERVICE Read-access.
eg. create a blank ASP.NET page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageServer.aspx.cs" Inherits="ImageServer" %>

with the code behind:
class ImageServer
{
  void Page_Load(object sender, EVentArgs e)
  {
    Response.ContentType="image/jpeg"; // for JPEG file
    string physicalFileName=@"C:\Program Files\Adrenalin\Adrenalin\UploadedFiles\TemplateFile\abc.jpg";
    Response.WriteFile(physicalFileName);
  }
}

And test in your browser by going to the URL
http://<localhost>/<website>/ImageServer.aspx

You should get the image.
Then, within the  tag, use the URL of the page as your image placeholder:

UPDATE:
Looking at your latest comments, I suggest you send a QueryString parameter with some sort of employee code and use that to query the database and get the appropriate filename within the Page_Load() method. Don't send the filename as part of the QueryString.
Comment: This works great. I don't understand why the web page proxy can access the image but the other cannot, though. I feel like I'm missing something - do you know where I might read more about this?
Answer: What you're trying to do can work, but it's highly discouraged in Web development. Putting the permissions problems aside (which are very serious), you can never assume that your images will be available in the absolute path you provided on drive C:.
What you should do, is create a folder inside your website directory and use it to store the images, and use relative links instead of absolute links.
Even if you manage to make absolute links work now, prepare yourself for sever headaches in the future when running your application in different configurations.
Answer: copy the image in your project root folder and provide the image source as only the name of the image instead of the complete path.
e.g., img src = "battlefield.jpg"


Render to multisample buffer and resolved frame buffer independently

Question: So im doing some graph drawing using GL_LINE_STRIP's and i am using a multisampled buffer so the lines dont look so jagged. the problem is i have some lines in the background of the graph that act as a legend. The multisampling kind of screws the lines up cause they are meant to be exactly 1 pixel thick, but because of the multisampling, it will sometimes put the line spread over 2 pixels that are slightly dimmer than the original colour, making the lines look different to each other.
Is it possible to render those legend lines directly to the resolved frame buffer, then have the multisampled stuff drawn on top? this will effectively not multisample the background legend lines, but multisample the graph lines.
Is this possible? I just want to know before i dive into this and later find out you cant do this. If you have some demo code to show me that would be great as well
Comment: or maybe you can think of a better way of doing this..
Answer: It would be much easier if the legend came last: You could just resolve the MSAA buffers into the view framebuffer and then normally render the legend into the resolved buffer afterwards. But the other way won't be possible, since multisample resolution will just overwrite any previous contents of the target framebuffer, it won't do any blending or depth testing.
The only way to actually render the MSAA stuff on top yould be to first resolve them into another FBO and draw that FBO's texture on top of the legend. But for the legend to not get completely overwritten, you will have to use alpha blending. So you basically clear the MSAA buffers to an alpha of 0 before rendering, then render the graph into it. Then you resolve those buffers and draw the resulting texture on top of the legend, using alpha blending to only overwrite the parts where the graph was actually drawn.
Comment: ah i see, writing the MSAA to a diff FBO will probably work, ill give it a bash


Can you override interface methods with different, but "compatible", signatures?

Question: Consider the following PHP interfaces:
interface Item {
    // some methods here
}

interface SuperItem extends Item {
    // some extra methods here, not defined in Item
}

interface Collection {
    public function add(Item $item);
    // more methods here
}

interface SuperCollection extends Collection {
    public function add(SuperItem $item);
    // more methods here that "override" the Collection methods like "add()" does
}

I'm using PHPStorm, and when I do this, I get an error in the IDE that basically states the definition for add() in SuperCollection is not compatible with the definition in the interface it extends, Collection.
In one way, I can see this being a problem, as the signature of the method does not match the one it "overrides" exactly.  However, I do feel that this would be compatible, as SuperItem extends Item, so I would view add(SuperItem) the same as add(Item).
I'm curious as to if this is supported by PHP (version 5.4 or above), and maybe the IDE has a bug that doesn't properly catch this.
Comment: In 5.3, I get "Fatal error: Declaration of SuperCollection::add() must be compatible with that of Collection::add()". So it looks like PhpStorm is correct. Why do you think that 5.4 might behave differently?
Answer: No, I'm pretty sure PHP doesn't support this, in any version, and it would rather defeat the point of an interface.
The point of an interface is that it gives you a fixed contract with other code that references the same interface.
For example, consider a function like this:
function doSomething(Collection $loopMe) { ..... }

This function expects to receive an object that implements the Collection interface.
Within the function, the programmer would be able to write calls to methods that are defined in Collection, knowing that the object would implement those methods.
If you have an overridden interface like this, then you have a problem with this, because a SuperCollection object could be passed into the function. It would work because it also is a Collection object due to the inheritance. But then the code in the function could no longer be sure that it knows what the definition of the add() method is.
An interface is, by definition, a fixed contract. It is immutable.
As an alternative, you could consider using abstract classes instead of interfaces. This would allow you to override in non-Strict mode, although you'll still get errors if you use Strict Mode, for the same reasons.
Comment: I have to disagree with this answer.  Interfaces aren't concerned with method definitions or the relationships therein (e.g. `add()`ing an item means you can also `delete()` it).  Their only responsibility is enforcing compatible method signatures (inputs/outputs).  You're correct about them being fixed contracts, but incorrect about the purpose of that contract.  Two classes could very easily implement the same interface and have *totally different* semantics (e.g. `add()` could actually *delete* items in one class and it wouldn't matter as long as the inputs/outputs remain the same type).
Comment: @FtDRbwLXw6 It's a matter of interpretation, but I consider the responsibility of an interface to extend to the semantics of the functions, not just the signatures. Many prominent PHP interfaces come with docblocks, e.g. https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php or https://github.com/php-fig/http-message/blob/master/src/RequestInterface.php . Implementers need to read the docs to ensure that they don't violate the Liskov Substitution Principle. That's an advantage of PHP having nominal, rather than structural, typing.
Comment: @drrcknlsn altough i don't think it invalidates the explanation, it is very much something to keep in mind.
Comment: Thanks for the explanation! I was thinking that this should work in my head, but you helped me see the error in that.
Answer: PHP 7.4, released November 2019 has improved type variance.
The code from the question remains invalid:
interface Item {
    // some methods here
}

interface SuperItem extends Item {
    // some extra methods here, not defined in Item
}

interface Collection {
    public function add(Item $item);
    // more methods here
}

interface SuperCollection extends Collection {
    public function add(SuperItem $item); // This will still be a compile error
    // more methods here that "override" the Collection methods like "add()" does
}

Because the Collection interface guarantees that anything that implements it can accept any object of type Item as the parameter of add.
However, the following code is valid in PHP 7.4:
interface Item {
    // some methods here
}

interface SuperItem extends Item {
    // some extra methods here, not defined in Item
}

interface Collection {
    public function add(SuperItem $item);
    // more methods here
}

interface SuperCollection extends Collection {
    public function add(Item $item); // no problem
    // more methods here that "override" the Collection methods like "add()" does
}

In this case Collection guarantees that that it can accept any SuperItem. Since all SuperItems are Items, SuperCollection also makes this guarantee, while also guaranteeing that it can accept any other type of Item. This is known as a Contravariant method parameter type.
There is a limited form of type variance in earlier versions of PHP. Assuming other interfaces are as in the question, the SuperCollection may be defined as:
interface SuperCollection extends Collection {
    public function add($item); // no problem
    // more methods here that "override" the Collection methods like "add()" does
}

This can be interpreted as meaning any value whatsoever may be passed to the add method. That of course includes all Items, so this is still type safe, or it can be interpreted as meaning that an unspecified class of values, generally documented as mixed may be passed and the programmer needs to use other knowledge of exactly what can work with the function.
Answer: As a workaround I'm using PHPDoc blocks in interfaces.
interface Collection {
   /**
    * @param Item $item
    */
    public function add($item);
    // more methods here
}

interface SuperCollection extends Collection {
    /**
    * @param SuperItem $item
    */
    public function add($item);
    // more methods here that "override" the Collection methods like "add()" does
}

This way, in case you are properly using interfaces, IDE should help you catch some errors. You can use similar technique to override return value types as well.
Answer: You cannot change the methods arguments.
http://php.net/manual/en/language.oop5.interfaces.php
Comment: Except for the cases when you assign default values to the new arguments.
Answer: Extending interface is not allowed to change method definitions. If your SuperItem is extending Item, it should be passing through classes implementing Collection interface without problems.
But based on what you really want to do, you can try:

Create interface with slightly different methods for SuperItem and implement that:
interface SuperCollection extends Collection {
    public function addSuper(SuperItem $superItem);
}

Use decorator pattern to create almost same interface without extending:
interface Collection {
    public function add(Item $item);
    // more methods here
}

interface SuperCollection {
    public function add(SuperItem $item);
    // more methods here that "override" the Collection methods like "add()" does
}

Then decorator (abstract) class, which will use this interface:
class BasicCollection implements Collection {
    public function add(Item $item)
    {
    }
}

class DecoratingBasicCollection implements SuperCollection {
    protected $collection;

    public function __construct(Collection $collection)
    {
        $this->collection = $collection;
    }

    public function add(SuperItem $item)
    {
        $this->collection->add($item);
    }
}

Answer: The problem is not in the IDE. In PHP you cannot override a method. And the compatibility is only in the opposite direction - you can safely expect an instance of the parent class and receive a subclass. But when you expect a subclass, you cannot be safe if you receive the parent class - the subclass may define methods that do not exist in the parent. But still, you can't override the method
Comment: Please, please try to use the right words. You CAN override a method in PHP, just not overload it.
Answer: When I have a method that I may need to overload (which PHP does not support), I make sure that one of the method arguments (usually the last) is an array.  In this way I can pass whatever I need to. I can then test within the function for various array elements to tell me what routine in the method I need to perform, usually in a select/case.


When green oak dries, will a screw in it loosen or get tighter?

Question: I plan to make a three-legged stool from three branch pieces and a slice of trunk from a forty-year-old oak we just took out of our yard.  I'm wondering whether I should put the screws in now so it will grab them tighter when it dries, or whether to wait so it doesn't loosen as it dries.
In response to questions, here are the loose pieces in position.  The idea was to drill the legs and bottom the shaft size of the four-inch double-pointed screws.
Comment: tighter, but it could also split it. you could do tendons, but it's probably best to wait if you don't have a lot of woodworking experience.
Comment: No first hand experience, but friends that have rebuilt an early 1800's cabin used new oak, not seasoned, as nails could be driven into the new wood but would have been much more difficult once the oak seasons.
Comment: Wood shrinks as it dries....so it would grab screws tighter...at least in theory!
Comment: Is the seat of the stool going to be a cross section of the tree trunk , or a section split in half to make the sitting portion? This will affect greatly how the wood reacts to shrinkage. I can already foresee the limbs being full round limbs for the legs... Will it be a tall stool or short?
Comment: Looser and tighter.  Depends on which direction you're going and whether you're looking inside-out or outside-in.
Answer: Sounds like a fun project!  I hate to say it, but you'd be better off and have a better result if you gave that oak a chance to dry.  Rule of thumb is about 1 year per inch of thickness air drying in an area with relatively low humidity.  You don't have to go that long, but I'd at least give it a few months before trying to work it. You'll want to sticker it (putting small slats between the parts to aid for air flow). If you have a covered area, like a woodshed or covered patio, that would be best, you don't want to cover it tightly with a tarp, it needs airflow.    I know this doesn't directly answer your question, but just wanted to give you my advice.   If you put it together green and wet, I really think you're gonna have some issues.  Sorry to rain on your parade, but for best results, give that oak at least a few months to dry out in a covered (not tarped) area.
Comment: Additionally, expect the round to crack and check. There are some questions on [woodworking.se] about drying pieces like this including some advice on how to get them to dry while minimizing the size/amount of checks that happen. But it _will_ have some sort of checking at a minimum, potentially splitting in two, worst case, if it's not dried properly.
Comment: @FreeMan  YES, YES and YES! Now having seen the picture, that large round is almost surely to check if dried too quickly.   It's not likely to split in two, bc once the first major check happens, it relieves  the tension on the rest of the round.  But it will probably check right to the center of the round unless dried very very slowly.  You should probably post your comment as an answer, I'll UV it if you do.  I already UV your comment.
Answer: The screws are the least of your worry.
Expect the round to check and crack.
There are some questions on the Woodworking sister site about drying pieces like this including some advice on how to get them to dry while minimizing the size/amount of checks that happen. But it will have some sort of checking at a minimum, potentially splitting in two, worst case, if it's not dried properly.
You can turn green wood into a bowl and use the warpage as it dries as a decorative/creative effect, but in a thick slab like this, you're going to be sorely disappointed if you don't care for it extremely carefully.
Comment: We're in the Willamette valley, so plenty of rain is likely.  But it is under a roof at the moment.  If we end up discarding it, no biggie.  But I'll look at some of the references.


Why is the spigot on my oil heater dripping?

Question: We have fuel oil and a Beckett oil burner that heats our house. I just noticed water is dripping out of this hosebib/spigot at the bottom of it:

What could be causing this and how can I troubleshoot? Also, in case you're wondering, we had a basement flood a few months ago and I put down cat litter around the base of my Beckett to wick water away; thats the gravely/grainy stuff you're seeing in the photo.
Answer: Is it the spigot, or is there leakage from a corroded boiler?
If you determined it's the valve that's leaking, you'll need to:

Shut the electricity to the heating system to prevent it running while dry.
Shut the cold-water feed to the boiler.
Drain the whole heating system through that valve... you could run a garden hose to the fitting once it's cooled.
Replace the washer in the valve, just like you would a faucet valve.
Close the repaired valve.
Open the valve to the cold-water feed slowly.
Check for leaks.
Once the system is filled at bottom, purge air from baseboard convectors or radiators. This is a bit of a nuisance, since each valve at each heater must be opened until air stops hissing, and water starts to drip. Failure to do so will restrict heat to some areas of the house. Purging may need to be repeated after the system runs for a while!
Turn the electricity on again.
Turn up the temperature at the room thermostat and check that heat is coming out of all the convectors/radiators.

Yep, what a pain it is to replace one washer.
Comment: Thanks for the **awesome** answer @DrMoishe Pippik (+1) -- real quick here, this morning I noticed the water/wetness was gone and all dried up. So this is clearly an intermittent issue that comes and goes. Does that tell you anything else?
Answer: As a temporary fix you can get a brass hose cap and screw it on the spigot:
Comment: A draincock is not a pressure relief device.  This boiler should have a overpressure relief value that is separate from the drain.
Comment: Thanks @jwh20 (+1) -- is there any risk or danger that doing this will block off "pressure" that's correctly trying to be released? You hear stories (possibly urban legends) about water heaters exploding because they were unable to let off pressure. I know this isn't a water heater, but still, the same concerns might be warranted?
Answer: Another cause would be a loose stem package sealing right at the spindle of the dark valve handle - if there is a stem package sealing at all. Just close to that handle is a big nut which needs some tightening (only very few, e.g. 1/8 turn every 5 years) from time to time. Often,  it can be sensed if it is too loose.
If the valve or washer need to be replaced, another simple method to avoid all the work for draining and purging air would be to freeze the line(s) to the valve with CO2 or ice spray. But choosing that method, there is a small possibility that it does not work like intended or the work is not finished when the cooling medium is running out.
Since it is intermittent, another cause could be a defect/de-adjusted pressure compensation tank. Every time the boiler is heating up the water, the pressure raises and needs to be compensated. If that fails, the water takes the weakest point to leave the closed circuit - and may even destroy some components of the heating system.
This is why there should be another item: a safety valve that opens if a certain pressure is reached, e.g. 300kPascal (3 bar). Normally that valve is installed somewhere above the heater. If there is some dirt in that safety valve, it could open too early.


iOS 13 UIPrinter quickly goes out of existence

Question: User selects a printer (UIPrinter) using the UIPrinterPickerController.  Once selected, that UIPrinter is used for output (print(to:) throughout the app and persists for subsequent launches of the app.  From iOS 9 through iOS 12, this method has worked well.
However, under iOS 13, the following happens:
The UIPrinter is always available when used for the first time.  But once used, after a short period of time (less than a minute) the UIPrinter seems to go out to existence.  This happens when using the Xcode Printer Simulator or an actual physical printer via AirPrint.
Here's the Xcode Console message on the first print - it works:
Simulated\032Color\032Laser\032@\032myMac._ipps._tcp.local.: Print-Job successful with warning: Job attributes did not match print document.

Simulated\032Color\032Laser\032@\032myMac._ipps._tcp.local.: Release-Job successful with warning: successful-ok (successful-ok)

Here's what happens 1 minute later:
Simulated\032Color\032Laser\032@\032myMac._ipps._tcp.local.: Print-Job failed: Printer "Simulated_Color_Laser_myMac" does not exist.

When this happens, the only way to continue is to re-select the UIPrinter in the PrinterPicker.
Any ideas as to what might be happening here?
Thanks,
Answer: Fixed in iOS version 13.4 released 3/24/2020.


RestController design struggle - Spring Boot REST API

Question: I'm quite new into REST API development. I have decided to create a Blog application using Spring Boot and I'm really struggling with the design and structure of my app.
Right now my app consists of Post and Comment models and repositories. For both models, I have created service classes (PostService and CommentService). In these classes, I have all the business logic (just simple CRUD right now).
Now I am scratching my head about the design of my @RestControler for Posts. In PostController I have exposed these actions:
@PostMapping("/api/posts/create")
public Post create(@RequestBody Post post) { ... }

@GetMapping("/api/posts")
public List<Post> findAll() { ... }

@GetMapping("/api/posts/{id}")
public Post findById(@PathVariable("id") Long id) { ... }

@PutMapping("/api/posts/{id}")
public Post update(@RequestBody Post post) { ... }

@DeleteMapping("/api/posts/{id}")
public void delete(@PathVariable Long id) { ... }

Now I'm getting to my question. I am wondering what is correct design of adding a Comment to the Post.

Should I expose all CRUD method for Comment using CommentController class and use create method?
Is it ok to add a new method addComment to PostController which will create a new Comment?

In my head adding a Comment to the Post belongs to the Post, but I really don't know.
Could some of give me some advice regarding this matter?
Thanks a lot!
Bye,
Tom
Comment: Your api doesn't look to bad! You can remove create from /api/posts/create because the POST Request still implies that you create a Post. For adding a Comment you can add a CommentController which has a dependency to your two services (PostService and CommentService). The URL could look like this /api/posts/{id}/comment . Have a look at this https://spring.io/guides/tutorials/rest/
Comment: Thank you guys.... just one question. Since it does not make sense to have comments without post, is it correct to use URL like this in CommentController: @PostMapping("/api/post/{id}/commets") for create method?
Comment: Create a new Controller to handle the comment functionalities. Keeping them in the same controller will make that controller cumbersome as you will have to add other functionalities to the comment section at some point.
Answer: To be honest I don't think that someone can give you the perfect answer here. It is often a personal decision. In common you can say the following about a REST API.

the path should only represent your data structure in the database. So for example /api/posts

No verbs in your path. What you want to do should be handled by the RequestType (GET, POST, PUT, PATCH, DELETE, etc.)

Now to your case. I can really good understand why you are struggling. I think here are two options:

PostsController
You say a Comment is always a part of a Post and because of this
you design your API like this.
@PostMapping("/api/posts/{id}/comment")
public Comment create(@PathVariable Long id), @RequestBody Comment comment) { ... }

CommentsController
You handle Comment as an own object and the Post is just a relation you add to it by attribute.
@PostMapping("/api/comments")
public Comment create(@RequestBody Comment comment) { ... }

So it is always is it a Subset vs make own Object structure. I think in this case here I would prefer option 2 because I think you want do more operations on this object.
Also you can than design your API in the way that every Controller starts with the object that will be handled /api/OBJECT/xxx/yyy
UPDATE
After reading the comment from @gulliva I think also a good way is to use this URL @PostMapping("/api/posts/{id}/comment") but put it in the CommentsController. I think this is a good way.
Answer: If I were you, I'd consider REST Design Principles from the OpenAPI Specification and would follow resource -> sub-resource -> method||identifier pattern. This would probably be the most KISS and clean design for the readability and understanding purposes.
@PostMapping("/api/posts/") //you don't need /create as a separate URI
public Post create(@RequestBody Post post) { ... }

@GetMapping("/api/posts") //This is OK.
public List<Post> findAll() { ... }

@GetMapping("/api/posts/{id}") //OK, however {id} should be optional, hence you can combine this and upper methods in one method.
public Post findById(@PathVariable("id") Long id) { ... }

@PutMapping("/api/posts/{id}") //OK.
public Post update(@RequestBody Post post) { ... }

@DeleteMapping("/api/posts/{id}") //OK.
public void delete(@PathVariable Long id) { ... }

and now, for the comments API design, I would have contain them under posts resource, and would have added these corresponding URIs:
@GetMapping("/api/posts/{id}/comments/{commendId}") //commentId is optional
@PostMapping("/api/posts/{id}/comments/") //you don't need any {commendId} here, just post the payload

and etc. I hope you can come up with method signatures and other method mappings.
You can also see the RESTful naming conventions here
Comment: @TomášNa'viKoválik not methods, per se, but resource path URIs under the posts URIs. Think from the Representation Perspective. Comment doesn't exist on its own without its parent resource `Post`, right? so handling comments separately wouldn't be the intuitive and understandable design when you expose your API to the 3rd party world. Besides, if you'll create two discrete URIs, (as accepted answer suggest) for GET and POST, this will violate DRY principle as well.. and you'll just have duplication, which is not good.
Comment: First you should hold on before coding and think well your design. :) What your comments will be? what for? where you would use them?.. you first have to come up with the abstract design of *What you are trying to achieve* and then.. it depends on what you consider your comments will be. In your current example, it's crystal clear, that you have a *posts*, and you have their respective *comments*. So, as PID doesn't exist without person, similarly, comment won't exist if you don't have its parent post (if you, for example, delete the post).
Comment: Thanks a lot for the great answer. Could just explain to me why would you keep Comment methods inside the PostController?
Comment: OK, now it makes more sense to me. One more question: if I decide in the future to use comments not only for Posts, then I should expose separate API for Comments, right?


NHibernate and SQL Server Temporal Tables

Question: I am using Fluent NHibernate to query data stored in a SQL Server temporal table. All I really want to do is to run a query such as
SELECT * FROM [MyDB].[dbo].[MyTable] for system_time as of '2022-12-28T21:00:00.0000000' where ...

Via NHibernate. It doesn't seem like there's any way built in to NHibernate that can run that query. I can run queries such as below but that only hits the current table, and not the history table.
session.QueryOver<MyDTO>().Where(x => x.TemporalPeriodStart > ...)

Answer: You can execute native SQL queries (and return non managed entities).
The query needs to specify:

Query String
A Result transformer

Example:
session.CreateSQLQuery("SELECT * FROM [MyDB].[dbo].[MyTable] for system_time as of '2022-12-28T21:00:00.0000000' where...")
    .SetResultTransformer(Transformers.AliasToBean(typeof(CustomObject)))

Worth noting that the custom IResultTransformer should override "Equals" and "GetHashCode", otherwise a memory leak is possible since query translation won't be cached.
You can also use Named SQL query, which can be defined in the mapping document and called in the same way as a named HQL query...


polymer app with phonegap showing blank screen

Question: I am testing polymer with phonegap.When I try this with the phonegap app,it is working but when i build it with adobe build and try it with my device it is showing a blank screen.
This is the code:
    <!DOCTYPE html>

    <meta name="viewport"
    content="width=device-width, minimum-scale=1.0, initial-scale=1.0,user-scalable=yes">
    <link rel="import"
  href="bower_components/paper/font-roboto/roboto.html">
<link rel="import"
  href="bower_components/paper/core-header-panel/core-header-panel.html">
<link rel="import"
  href="bower_components/paper/core-toolbar/core-toolbar.html">
<link rel="import"
  href="bower_components/paper/paper-tabs/paper-tabs.html">
    <link rel="import"
  href="bower_components/paper/paper-elements/paper-elements.html">
        <link rel="import"
  href="bower_components/paper/core-drawer-panel/core-drawer-panel.html">

<core-toolbar>

    <paper-icon-button icon = "menu">

    </paper-icon-button>

    Hello world
   <paper-menu-button>
    <paper-icon-button icon = "create"></paper-icon-button>
       <paper-dropdown class = "dropdown" halign = "right">
           <paper-menu>
               <paper-item>
hi
</paper-item>
           </paper-menu>
       </paper-dropdown>
    </paper-menu-button>

    </core-toolbar>
   <paper-button>Test</paper-button>

I have made other apps but not with polymer that work with phonegap.
I am running android 5.0.2.
Thanks.
Comment: I dont see `cordova.js`
Comment: I forgot to add it! I added that but it didn't help.
Answer: Disabling hardware acceleration is an (ugly) workaround.


Spring Integration SFTP (xml) Outbound Gateway - copy folderstructure from remote directory to local directory using SPEL Expression and java

Question: I am totally new to Spring Integration and a beginner in Spring. It is a miracle that I got so far but I already can copy my files recursively into a local folder. I based my app on this sample application from Spring:
https://github.com/spring-projects/spring-integration-samples/blob/main/basic/sftp/src/test/resources/META-INF/spring/integration/SftpOutboundGatewaySample-context.xml
Now I want to keep the same subdirectories as in the remote folder.
I am using Spring 4.1.9 Release, because of legacy code. These are my dependencies.
<dependencies>
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-core</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-sftp</artifactId>
        <version>4.1.9.RELEASE</version>
    </dependency>
</dependencies>

This is a simple App class with main method which loads the applicationcontext.
@Component
public class App {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:SftpOutboundGateway-context-test.xml");
        ToSftpFlowGateway toFtpFlow = ctx.getBean(ToSftpFlowGateway.class);

        toFtpFlow.lsGetAndRmFiles("/remote_directory/");

    }
}

This is the interface, and the bean is made in the xml config underneath
public interface ToSftpFlowGateway
{
    List<Boolean> lsGetAndRmFiles(String dir);
}

This is the xml spring config. It has a reference to web.xml where the sessionfactory is made. Here I use the outbound-gateway
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
       xsi:schemaLocation="http://www.springframework.org/schema/integration
                           http://www.springframework.org/schema/integration/spring-integration-4.1.xsd
                           http://www.springframework.org/schema/beans
                           https://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/integration/sftp
                           https://www.springframework.org/schema/integration/sftp/spring-integration-sftp-4.1.xsd">

    <import resource="web.xml"/>

    <int:gateway id="gw"
                 service-interface="ToSftpFlowGateway"
                 default-request-channel="receiveChannel"
    />

    <int-sftp:outbound-gateway id="gateway1"
                              auto-startup="true"
                              session-factory="sftpSessionFactory"
                              request-channel="receiveChannel"
                              command="mget"
                              local-directory-expression="'C:/temp/' + headers['file_remoteDirectory']"
                              auto-create-local-directory="true"
                              rename-expression=""
                              command-options="-R"
                              mode="IGNORE"
                              expression="payload"
                              reply-channel="loggingChannel"
    >
        <int:poller fixed-rate="1"/>
    </int-sftp:outbound-gateway>

    <int:channel id="receiveChannel">
        <int:queue/>
    </int:channel>

    <int:logging-channel-adapter id="loggingChannel" log-full-message="true" logger-name="tapInbound"
                                 level="INFO" />

</beans>

I want to know why my subdirectories are null. I want my subdirectories to be C:/temp/in and C:/temp/out as the following picture.

Now i get the following output as logging:
INFO: GenericMessage [payload=[C:\temp\null\file.txt, C:\temp\null\file2.txt, C:\temp\null\file3.txt], headers={replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@534a53da, errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@534a53da, id=f012840c-184e-203e-1a90-754beb8796d1, file_remoteDirectory=/remote_directory/, file_remoteFile=, timestamp=1684943419215}]

This is probably wrong
local-directory-expression="'C:/temp/' + headers['file_remoteDirectory']"

Spring documentation says the following, but I don't understand:

Typically, you would use the #remoteDirectory variable in the
local-directory-expression so that the remote directory structure is
retained locally.
Answer: The headers['file_remoteDirectory'] expression references to the request message which is definitely doesn't have that info because it is a plain message:
toFtpFlow.lsGetAndRmFiles("/remote_directory/");

Try to modify your local-directory-expression to this:
local-directory-expression="'C:/temp/' + #remoteDirectory"

Where that remoteDirectory SpEL variable is populated for the path of the remote sub-dir against every file retrieved:
private File generateLocalDirectory(Message<?> message, String remoteDirectory) {
    EvaluationContext evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
    if (remoteDirectory != null) {
        evaluationContext.setVariable("remoteDirectory", remoteDirectory);
    }
    File localDir = ExpressionUtils.expressionToFile(this.localDirectoryExpression, evaluationContext, message,
            "Local Directory");
    if (!localDir.exists()) {
        Assert.isTrue(localDir.mkdirs(), () -> "Failed to make local directory: " + localDir);
    }
    return localDir;
}

Comment: Thanks a lot Artem! I adjusted my code to your answer and finally have something working.

You can find my new code here and I have another question: https://stackoverflow.com/questions/76339926/sftp-integration-how-do-i-make-my-poller-work-to-get-the-files-periodacally


$\mathbb{R}$ as a $\mathbb{Q}$ vector space has a lebesgue measurable basis

Question: After studying some measure theory i found this sentence without proof.
$$\mathbb R \quad \text{as a} \quad \mathbb Q \quad \text{vector space has a lebesgue measurable basis}$$
A hint is given: Analyse the family of all $\mathbb Q$-linear independent subsets of the Cantor set for maximal elements.
I have zero clues on how to progress with this so if anyone is interested in checking this I would gladly appreciate it. Thanks!
Comment: I think this might help - any real number on $[0,2]$ is a sum of two Cantor numbers.
Comment: What have you found out about $\mathbb Q$-linearly independent subsets of the Cantor set? Is there a maximal one? If so, what do you know about its $\mathbb Q$-linear span?
Comment: @bof to be honest I am completely lost here
Answer: Maybe you could prove first that the Cantor set is $C=\{\sum\limits_{n=0}^\infty \frac{x_n}{3^n}:\ x_n\in \{0,2\} \}$. With this in mind you can prove what TZakrevskiy said in the comments. This means that
$Span(C)=\mathbb{R}$, because $\mathbb{R}=Span[0,2]=Span(C)$. By Zorn's lemma you can find a maximal linearly independent subset $\beta$ inside of $C$. You can see that $Span(\beta)\supseteq C$ so $Span(\beta)=\mathbb{R}$.
This concludes the result because every subset of a null set is Lebesgue measurable.
Comment: Dont worry, i edited the proof, i hope is more useful now.
Comment: I have proven both before but i dont really see on how to continue from this. Sorry for bothering so much but this messes with me alot
Comment: I need to read about zorns lemma again etc. this was the part I am still missing to fully understand this. Thank you alot for the effort


How to put the every start time as 0 in every day for specific column input data using panda python

Question: This question is related to this question
How to get time difference in specifc rows include in one column data using python
Here I have three inputsX1,X2,X3. So here I want to find time difference only X3 inputs.
Code:
df=pd.read_csv('data6.csv')
df['date'] = pd.to_datetime(df['date'] + " " + df['time'], format='%d/%m/%Y %H:%M:%S', dayfirst=True)

df.time = pd.to_datetime(df.time, format="%H:%M:%S")
df = df[df['X3'] != 0]
values_others_rows = np.NaN

sub_df = df[df.X3 != 0]
out_values = (sub_df.time.dt.hour - sub_df.shift().time.dt.hour) \
        .to_frame() \
        .fillna(sub_df.time.dt.hour.iloc[0]) \
        .rename(columns={'time': 'out'})  # Rename column
print(out_values)

df = df.join(out_values)                # Add out values
print(df)

When I use this code came time difference but with minus value. Because I have different days values.
I got the value with minus :

As a example:

date      time          x3
10/3/2018 6:00:00     0
10/3/2018 7:00:00     2      start time =0
10/3/2018 8:00:00     0                 time difference=2
10/3/2018 9:00:00     50     first time =9:00:00
10/3/2018 10:00:00    0            :
10/3/2018 11:00:00    0            :
10/3/2018 12:00:00    0            :
10/3/2018 13:45:00    0
10/3/2018 15:00:00    0
10/3/2018 16:00:00    0
10/3/2018 17:00:00    0
10/3/2018 18:00:00    0
10/3/2018 19:00:00    20
10/3/2018 20:00:00    0
10/4/2018 6:00:00     50     new day : start time=0
10/4/2018 7:00:00     50     first time: 7:00:00   time difference=1
10/4/2018 8:00:00     0
10/4/2018 9:00:00     0
10/4/2018 11:00:00    10     second time: 11:00:00  time difference=4
10/4/2018 12:00:00    20
10/4/2018 13:00:00    50

So I want to write this in my code. But I don't know how to write this. Can anyone help me to solve this problem?
My csv file :
CSV file
After using new code nothing display of time difference

After print(df)
When I used the jezrael  code again the minus value is showing:
df=pd.read_csv('data6.csv')
df['time'] = pd.to_datetime(df['date'] + " " + df['time'], format='%d/%m/%Y %H:%M:%S', dayfirst=True)

df.time = pd.to_datetime(df.time, format="%d/%m/%Y %H:%M:%S")

df1 = df[df.X3!= 0]

df['new'] = df1['time'].dt.minute.groupby(df1['date']).diff()
df['new'] = df['new'].fillna(0).astype(int)

print(df)

Image of data['new']

But my expected time difference is:

date      time          x3    time_difference
10/3/2018 6:00:00     0           -
10/3/2018 7:00:00     2          start_time=0
10/3/2018 8:00:00     0
10/3/2018 9:00:00     50          2hr
10/3/2018 10:00:00    0
10/3/2018 11:00:00    0
10/3/2018 12:00:00    0
10/3/2018 13:45:00    0
10/3/2018 15:00:00    0
10/3/2018 16:00:00    0
10/3/2018 17:00:00    0
10/3/2018 18:00:00    0
10/3/2018 19:00:00    20          12hr from starting time
10/3/2018 20:00:00    0
10/4/2018 6:00:00     50          start_time=0
10/4/2018 7:00:00     50            1hr
10/4/2018 8:00:00     0
10/4/2018 9:00:00     0
10/4/2018 11:00:00    10          5hr
10/4/2018 12:00:00    20          6hr
10/4/2018 13:00:00    0
Comment: Not 100% sure what is expected output, can you add new column to your sample data for check my solution?
Comment: @ jezrael  yes checked it.
Answer: Filter rows by condition and use DataFrameGroupBy.diff for difference, last replace missing values by 0:
df = pd.read_csv('data6 - data6.csv')
#print (df)
df.time = pd.to_datetime(df.time, format="%H:%M:%S")

df1 = df[df.x3 != 0]

df['new'] = df1['time'].dt.hour.groupby(df1['date']).diff()
df['new'] = df['new'].fillna(0).astype(int)

print(df.head(20))
         date                time   x1  x2  x3  new
0   10/3/2018 1900-01-01 06:00:00   63   0   0    0
1   10/3/2018 1900-01-01 07:00:00   63   0   2    0
2   10/3/2018 1900-01-01 08:00:00  104  11   0    0
3   10/3/2018 1900-01-01 09:00:00   93   0  50    2
4   10/3/2018 1900-01-01 10:00:00  177   0   0    0
5   10/3/2018 1900-01-01 11:00:00  133   0   0    0
6   10/3/2018 1900-01-01 12:00:00   70   0   0    0
7   10/3/2018 1900-01-01 13:45:00   83   0   0    0
8   10/3/2018 1900-01-01 15:00:00  127   0   0    0
9   10/3/2018 1900-01-01 16:00:00  205   0   0    0
10  10/3/2018 1900-01-01 17:00:00  298   0   0    0
11  10/3/2018 1900-01-01 18:00:00  234   0   0    0
12  10/3/2018 1900-01-01 19:00:00  148   0  20   10
13  10/3/2018 1900-01-01 20:00:00  135   0   0    0
14  10/3/2018 1900-01-01 21:30:00  100   0  50    2
15  10/4/2018 1900-01-01 06:00:00  166   0   0    0
16  10/4/2018 1900-01-01 07:00:00   60   0   0    0
17  10/4/2018 1900-01-01 08:00:00  120  10  10    0
18  10/4/2018 1900-01-01 09:00:00   80  40  20    1
19  10/4/2018 1900-01-01 11:00:00   60  70  50    2

Comment: @team - hmm, so you need `df['new'] = df1.groupby('date')['time'].diff().dt.total_seconds() // 3600` instead `df['new'] = df1['time'].dt.minute.groupby(df1['date']).diff()` ?
Comment: Absolutely. It worked. Your code is now absolutely works for me. and I apologies from you , because I guess some of my question didn't clear for you. So once again Thank you for helping me.
Comment: Thank you for the fast reply. When I used your code one problem is coming that length is reducing. But I want is keeping the same length of X1,X2 and X3 and finding the time difference of X3 input value.
Comment: @team - reducing? Hmmm, do you correct assign `df1` and `df`? Because in my solution is no reducion, because assign filtered values `df1` to column in `df` - in code `df['new'] = df1['time'].dt.hour.groupby(df1['date']).diff()`
Comment: @ jezrael  After changing the code length is okay, but no time difference values are showing. I pasted the image of data['new']
Comment: @ jezrael  Can we put this as minute not in hour, I guess it will be easy , isn't it?
Comment: @team - `Can we put this as minute not in hour` - do you think change `.hour` to `.minute` ? Not understand. Btw, tested your smple data and seems working nice
Comment: @ jezrael  yes converting .hour to .minute, But why mine is coming no values. here why did you put like this "data6 - data6.csv'" it should be like "data6.csv" isn't it
Comment: hay I found the error, why is it coming like that, here first I combine date and time together and tried to display the difference of time , then again coming minus  value, Because of date. In your code you just use time only and came with "1900-01-01" instead of that I want to find the time difference with combination of date and time , I rewrite the code and paste the image of data['new']
Comment: @team - I dont understand, is possible add excepted output to values with seen also another columns? my solution not working? Or yes?
Comment: Here I upload the what I expected for time_diffrence. Your code helpful to me change some part of my code. But still minus values are displaying .


Icons - Differentiating between viewing the current 'item' vs selecting an 'item'

Question: On a mobile app what would be the best way to differentiate between viewing a current 'item' vs selecting an 'item' using icons.
In my specific case, its for a religious app where the person counts each day towards a holiday and a religious text is said each day. They can either view the current days text or select a day from a number picker dialog box (so I don't want to have a single icon which contains both the number picker with an option for today as I don't want to add unnecessary complexity or the extra step of choosing a day as people will almost always want the current day).
As of now I just have it as a drop down menu which has 2 options saying 'Today's Text' and 'Select Day', but I would like to have icon only options for greater visibility/quicker access.
Answer: Take a look at how Microsoft Outlook mobile app displays the calendar and today's events.
The default view shows Today's events:

You can easily navigate back over the past week or over the next week:
Note how 'Today' is still highlighted.

For a more detailed history, you can swipe down the calendar area to open it up and see an overview of which dates have/had events, and then select a date to go to.
Answer: I think you may be hinting at my answer in your own question. Why not show today's text by default, and let them pick other days using your dialog?
Okay, I whipped up a Windows form for you after my comment about adding a gesture to go to today's date. Your comment about polluting the screen with a button to achieve this made me think about how "polluted" the screen might be just by adding a button. Personally, I don't really think using the entire screen for text is very appealing--you need some margins, etc. or it looks like smashed ants.

You probably don't have a title bar, but if you did you could put your app name or the date the user is on. I did add the date the user is on above the "Lorem" where your text would go. The buttons on the bottom don't seem too obtrusive to me, but I guess it's a matter of personal preference.
Comment: Welcome to UX.SE! Be sure to take a stop by the [Help Center](https://ux.stackexchange.com/help) to get a feel for how we answer questions here. After that, you can [edit](https://ux.stackexchange.com/posts/117481/edit) your answer to expand on your suggestions a bit. Your answer could afford to include some examples, sources, a wireframe/sketch, or some other forms of support. Thanks, and welcome!
Comment: Thank you for this answer I do show the current days text by default. However, if they switch to another days text I need an easy and obvious way for them to get back to the current days text (I'd rather not pollute the screen with a "Go to todays text" button on the screen that shows another days text).
Comment: @maxathousand--thanks, I will try to do that. My answer was so simple that I really didn't think it needed much expansion.
Comment: @yitzih--if you track just the last day they were on, the Back button could be set to go to that day's text. For situations where they've looked at many days and want to go back to today, the only thing I can think of (besides having a button) is to set up some sort of gesture to go to today. (It could be as simple as swiping left or right.)
Answer: I would suggest using a calendar like icon with a check in the center to signify today. Then a normal calendar icon to signify other dates. If you search Icon for today, you will see several examples of that icon. Another suggestion would a calendar with an arrow to signify today.
This is an example from FontAwesome.
As for your initial question, I would suggest using an "active" styling similar to common practice in HTML. User would be acclimated to this. For instance changing the color of the the current 'item'.
Answer: Why not use fragments/ viewPager with a tab layout that will do that for you.
Have your two fragments : today and pick date, the tab layour automatically uses your colorAccent to underline the active fragment, the Today fragment is loaded as default.
Upon swiping or tapping on pick date, the second fragment comes into play and you can select a date, after date is selected a new activity with that date as the title is created and all info are given.
Answer: 1 question I have on this.
Q. How many days in the past would the users usually go back to?
Ans 1: Usually 2-3 days back
I would use the following as a potential solution
Display today's date and today's text as the default. Enable swipe on this card to show the previous date and previous date's text. You can have up to 5 cards like these. This takes care of the users needs to look at up to 4-5 days worth of texts.
Ans 2: Any day in the past
Use a date-picker where the users can pick any date and then the text for that date can be displayed in a dialog. That way the default for today always stays and they can always get back to it.
Another approach:
Alternatively you can combine the two approaches together and have 5 cards along with a date picker to pick a particular date.
Let me know your thoughts! Happy to chat further.


My dwarves are sleeping in each other's beds!

Question: At least for the first few waves of migration, I try to make sure every dwarf has his or her own bedroom. So each one gets a small room with a bed in it assigned to him or her. But the dwarves don't seem to take any notice of this: they all just sleep in whichever room they feel like!
Now, if this doesn't bother the owner of the room (I don't know whether it does) then I might as well just leave all the rooms unassigned and let the dwarves sleep wherever (this would save me a lot of room-assigning whenever a big wave arrives) and I probably wouldn't need as many rooms, since not everybody wants to sleep at the same time.
Is there a way I can force the dwarves to sleep only in their designated room or in the overspill/new migrant dormitory?
Comment: I'd be very interested to see this whole question answered. Say you have every dwarf assigned to a bed. Why do they still sleep in beds assigned to other dwarves? How can you stop this? It annoys my OCD incredibly. :)
Comment: 1 dorf, 2 dorfs. All DF players will know what you're talking about :-)
Comment: @Grace, both versions of the word are actually accepted (I checked the other day)
Comment: @Juan - Apparently it depends on the dictionary, the one I checked before had only dwarves as a plural. (I made the initial correction)
Comment: @Juan It's not a matter of which version is accepted. [It's a matter that if you're going to edit the post for a replacement, then it should hit all instances and not just most](http://gaming.stackexchange.com/questions/2252/what-changes-are-required-to-create-my-own-dwarf-fortress-graphics "Guess who started the whole not-catching-all-instances?"). And curse your counter-counter-counter-counter, Arda!
Comment: ah, I didn't understand the previous edits were the reason you changed it, sorry.
Comment: Is it standard practice to edit out phrases that add character like "wherever they damn well feel like"? That seems a shame.
Comment: @Seamus - I've seen a question flagged as offensive for less. I was trying to be pre-emptive. Seeing as it's still your question you can always revert it, I have a 1RR. :-)
Comment: Yeah, "dorves" just looks wrong...
Answer: There's also a bug causing dwarves to not respect assigned beds when choosing where to sleep. Generally it doesn't make a huge difference, but when you get nobles showing up (who have preferences about how fancy their bedrooms need to be), they can become unhappy about sleeping in an inferior room, even though they chose to sleep there.
Edit: per the changelog, this bug has now been fixed for the next release. You may have to remove old beds and make new ones though, as there were some issues that weren't fixable by just having the new version update the save.
Answer: Dwarves will generally sleep wherever they see fit unless they have an assigned bed, in which case they will prefer this one. Sleeping in an assigned bed does give happy thoughts, being unable to makes a dwarf unhappy.
However, you don't generally have to bother with assigning beds since dwarves will claim unassigned bedrooms for themselves automatically.
Just a side-note: married dwarves and children share beds.
Comment: @Mana. Of course they're inHUMANe. They're DWARVES.
Comment: @WillfulWizard: Some irony was intended in my comment. :P
Comment: "Just a side-note: married dwarves and children share beds." What sort of inhumane creatures are these, to **share beds**?! How deplorable.
Comment: @Doltknuckle - it's actually mostly to stop the bad thoughts dwarves get from sleeping without their own bed.
Comment: The main reason you give dwarfs beds is so the they can have some possessions. I use the bedroom as an anchor for their cabinets and coffers so they can store items that they claim.


Android Text to Speech voice to indian accent

Question: I have developed an android application which provides text to speech functionality. I have used below code syntax to set indian accent :
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        int result;
        Locale locale = new Locale("en","IN");
        if (textToSpeech.isLanguageAvailable(locale) == TextToSpeech.LANG_AVAILABLE) {
            result = textToSpeech.setLanguage(locale);
        } else {
            result = textToSpeech.setLanguage(Locale.ENGLISH);
        }
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        }

    } else {

        Log.e("TTS", "Initilization Failed!");
    }
}

But when i access this functionality, it still speak in US accent.
Any help would be much appreciated.
Comment: You need to use the new `setVoice()` function
Comment: Can you write details of function with parameter to set?
Comment: Take a look at the `Voice` documentation https://developer.android.com/reference/android/speech/tts/Voice.html
Answer: I Tried doing this , which worked for me
tts.setLanguage(new Locale("hin", "IND"));

Otherwise, you can also select Google's Text To Speech Engine while initialising the TextToSpeech Object and after that, you can just select Hindi as the language.
 tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
    //code for TTS
  tts.setLanguage(new Locale("hin"));
      }, "com.google.android.tts");//specifying which engine to use; if this is not available, it uses default

In this the string "com.google.android.tts" is the package name of the Google's Text To Speech Engine.
I hope this works for you too!
Cheers!
Answer: mLanguage = new Locale(language_codes);
tts = new TextToSpeech(mContext, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                int result = tts.setLanguage(mLanguage);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Log.e("Text2SpeechWidget", result + " is not supported");
                }
            }
        }
    });

And I use language from https://www.w3schools.com/tags/ref_language_codes.asp
Hope to help you.
Comment: `setLanguage()` is deprecated.
Answer: you should use
textToSpeech.setLanguage(new Locale("en", "IN"));

Answer: The code below gives you the list of available languages for the TextToSpeech
TextToSpeech textToSpeech;
Log.e(TAG, "Languages: "+textToSpeech.getAvailableLanguages());

which would be :

[ko_KR, ru_RU, zh_TW, hu_HU, th_TH, nb_NO, da_DK, tr_TR, et_EE, bs,
  sw, vi_VN, en_US, sv_SE, su_ID, bn_BD, sk, el_GR, hi_IN, fi_FI, km_KH,
  bn_IN, fr_FR, uk_UA, en_AU, nl_NL, fr_CA, sr, pt_BR, si_LK, de_DE, ku,
  cs_CZ, pl_PL, sk_SK, fil_PH, it_IT, ne_NP, hr, zh_CN, es_ES, cy,
  ja_JP, sq, yue_HK, en_IN, es_US, jv_ID, la, in_ID, ro_RO, ca, ta,
  en_GB]

Trying out hi_IN instead of en_IN helped in my case, where I got the Indian accent.
Code below:
Locale locale = new Locale("hi_IN");
textToSpeech.setLanguage(locale);

Hope this helps more people in the future.


Python list comprehension for two values from the same list

Question: I can find answers for using list comprehension with multiple values from multiple lists but I can not find a solution to my specific case where all elements (coordinates) in the list should be matched with all other elemets once. The nested for loop for the problem looks as follows:
# rr = list of coordinates (2D)
meet_critera = []

for idx1 in range(len(rr)-1):
    for idx2 in range(idx1+1, len(rr)):
        if coordinate_distance(rr[idx1], rr[idx2]) < 6000: # Could be any criteria
            meet_critera.append([rr[idx1], rr[idx2]])
print(meet_critera)

The loops are a classic "all should shake hands with each other once" problem if that helps. What I want is a more elegant way of producing the same result using list comprehension. If possible.
Comment: Can you please [edit] your question to show what you have tried so far, and what specific problem you encountered? Any nested loops + append can be directly translated to a list comprehension.
Answer: You could use itertools.combinations.
In [16]: from itertools import combinations

In [17]: rr = [(0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (3, 4), (5, 6)]

In [18]: list(combinations(rr, 2))
Out[18]:
[((0, 1), (1, 1)),
 ((0, 1), (2, 1)),
 ((0, 1), (0, 2)),
 ((0, 1), (1, 2)),
 ((0, 1), (3, 4)),
 ((0, 1), (5, 6)),
 ((1, 1), (2, 1)),
 ((1, 1), (0, 2)),
 ((1, 1), (1, 2)),
 ((1, 1), (3, 4)),
 ((1, 1), (5, 6)),
 ((2, 1), (0, 2)),
 ((2, 1), (1, 2)),
 ((2, 1), (3, 4)),
 ((2, 1), (5, 6)),
 ((0, 2), (1, 2)),
 ((0, 2), (3, 4)),
 ((0, 2), (5, 6)),
 ((1, 2), (3, 4)),
 ((1, 2), (5, 6)),
 ((3, 4), (5, 6))]

Of course, you don't have to convert it to a list if you just want to iterate over the items. And I'm assuming the order of the coordinates is not important here since you are calculating distance; if it is, use permutations instead.
Answer: You simply write the loops in their order and the condition at the end.
meet_critera = [
    [rr[idx1], rr[idx2]]
    for idx1 in range(len(rr)-1)
    for idx2 in range(idx1+1, len(rr))
    if coordinate_distance(rr[idx1], rr[idx2]) < 6000
]

print(meet_critera)

Comment: Thank you, this was the solution I found in other threads but I must have made some typo becouse I could not get the ranges to work....


Orc and Light Armor

Question: Trying to play as Orc in Skyrim, the character would be a sort of dual 1 handed fighter using bows too, between warrior and thief so to speak.
I would be sneaking sometimes, but I would want to use blacksmithing too.
What kind of armor should I pick? Light or Heavy? Is it cool to have an Orc in Glass armor? Btw I bought the two expansions as well, perhaps they do have some cool Light Armor sets?
Thanks!
Comment: Orc's get +10 Heavy Armor & +5 Block, Enchanting, One-handed, Smithing, Two-handed so there's that to think about.
Answer: Being an orc in light armor is no different from being any other race in light armor, except you'll miss out on the racial +10 bonus to heavy armor, but that only means it will take very slightly longer to max your light armor skill than heavy armor skill, because first levels in a skill are so much easier to attain than higher levels. If you want to figure out which type of armor is best for you, there is a number of questions on this topic.

What advantages do the different armor types provide?
Melee Combat: Heavy Armor vs. Light Armor
Light or Heavy Armor specialization help
Answer: I personally was an Orc with heavy armor, mainly because of the +10 bonus which helped a lot. That and I weilded two handed weapons which for some reason works well with two-handed weapons.
I'd personally recommend heavy armor because of the bonus, means it wont take as long to level up, but if you like the light armor better and are gonna be sneaking a lot then try that.
The best thing to do is try both, try a bit of light armor doing as you normally would then try heavy armor for a bit - see what suits your play style.
Answer: I'm playing a lightly armoured orc berzerker with 2h weapons decent enchanting, alteration, smithing and alchemy. He's a straight up monster in a fight. High stamina and health enchantment cast stone/iron flesh before charging in. I'd advise you get yourself to the lover stone near kolskegger mine soon as if you go for an inbitweener. It's way more fun to play a unique character build instead of your usual mage, theif/assassin Or warrior it gives it more flavour. I'd say go for it light armour is amazing fully perked. But I hate seeing an orc in glass or elven armour personally, Soooo wrong. I'm using scale until I get 100 smithing

Orc and Light Armor


Collection_select not saving

Question: I'm trying to implement a collection select to create associations between my model group and user (join table: groups_user). But this association is not saving when i'm using a collection_select. And I have absolutely no idea what can be the problem
My code :
view :
<%= simple_form_for(group, remote: true) do |f| %>

  <%= f.collection_select :user_ids, @users.order(:pseudo), :id, :pseudo, {}, {multiple: true} %>

  <%= f.submit %>

<% end %>

& my controller(group) :
def group_params
  params.require(:group).permit(:name, :user_ids)
end

Just for info, i have a action to submit individually the association, and it's working perfectly !  But when i try to implement a collection to select collectively, is not working
Answer: This should work :
def group_params
  params.require(:group).permit(:name, :user_ids => [])
end

Collection_select not saving


Onkeydown what's the diference between return false and return super.onkeydown()?

Question: I put a list view inside a linearlayout,and I want to override onkeydown() method in ListView
,and I don't control the focus, just change some variables in onkeydown(),I want system do as if I haven't override the onkeydown method.what should I do?return false? or return super.onkeyDown()?.It will be very nice for any help. thank you in advance.

there are three listviews,and a b c are three item of listviews. when c is focused, when I press left arrow on keybord, then a get focus by default. And I want the first item in listview2 get focus how can I do?
Answer: ntc is not exactly correct.  OS does not use reflection to get your base class' handler.
If you return false, you explicitly tell OS that you do not want to handle this event; OS calls the View's parent handler then (as your test shows); this happens until event got handled or top View is reached.
If you call super.OnKeyDown() you allow your base class to process event. Note that it's a base class' handler serving same view, not parent view; don't confuse here.
So, using one or the other depends on your view's behavior desired.
I supose in your case you need return super.onKeyDown();
Comment: yes, you are right ,I got it.and in my case I should return super.onkeydown().But i have found that the focus changes always don not like what I want.
Comment: If UI does not allow you to, you may want to think twice if this is what you want. User should not be confused of unexpected UI behavior.
Comment: system's focus change by default can make users confused, what I want is only to adjust it normal..I will post a picture to make it clear
Comment: sorry for that my account's reputation is 5 less than 10 , I can not add a picture in my question....
Comment: This should now probably be another question :)  Note that Android works in two modes: focusable and focus-less. These two switch depending on user input: it user presses a key on a keypad - it turns into focusable mode; if user touches screen - it turns into focus-less mode. In focus-less mode there's **NO** list items focused.
Comment: em, it's my fault ,I didn't make it clear, it always be controled by keyboard not by touch screen .
Answer: super.onkeyDown()- this puts the burden on super class to handle the onKeyDown event by your own wish (You explicitly say to handle it). when you return false, android assumes  that you have not handled the onKeyDown event and super.onKeyDown() gets called by default (without you calling it).
Comment: em...maybe when return false, the parent view not parent class will handled the onkeyDown.
Comment: em..I just create a FileListView class which is extends listview.And I put it in a linearlayout. if onkeydow, retrun flase.then linearlayout will handle it,if return super.onkeydown,listView will handle it?right ?that it my comprehension which i'm not sure.


TreeViewItem using User Control and binding

Question: I searched the archives for help but I can't find anything quite specific enough for my particular issue.
I have a TreeView using MVVM to bind data and all seems good.  I want to extend the functionality such that I think using a user control for the TreeView items would be good.
Here is the XAML code for the hierarchical data template used by the TreeViewItems:
        <HierarchicalDataTemplate
          DataType="{x:Type vm:SiteViewModel}"
          ItemsSource="{Binding Children}">
          <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding SiteName}"/>
         </StackPanel>
        </HierarchicalDataTemplate>

I want to replace the TextBlock with my user control:
        <uc:MyTextBlock InternalText="{Binding SiteName}"/>

The user control (for now) just contains another TextBlock and has a dependency property called InternalText, i.e.
  <TextBlock Text="{Binding Path=InternalText}" />

and I set the DataContext in the constructor of the user control to itself:
public MyTextBlock ()
{
  InitializeComponent();
  DataContext = this;
}

This isn't working, but if I just change the template so that it specifies static text it seems to work fine:
        <uc:MyTextBlock InternalText="Some site name"/>

So how do I get the bound data to get passed to the user control?  It's probably something simple but I'm new to WPF so I've not worked it out yet.
Thanks!
Answer: InternalText seems to be a not dependency property. Try to convert it into one.
Answer: In the codebehind
public class MyUserControl : UserControl
{
    #region Text
    ///
    /// The <see cref="DependencyProperty"/> for <see cref="Text"/>.
    ///
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(
            RunningPropertyName,
            typeof(string),
            typeof(MyUserControl ),
            new UIPropertyMetadata(null));

    ///
    /// The name of the <see cref="Text"/> <see cref="DependencyProperty"/>.
    ///
    public const string TextPropertyName = "Text";

    ///
    /// The text to display
    ///
    public string Text
    {
        get { return (string)GetValue(TextProperty ); }
        set { SetValue(TextProperty , value); }
    }
    #endregion
}

In the xaml
<UserControl x:Class="Derp.MyUserControl"
             x:Name="root"
             SnippingXamlForBrevity="true"

and later...
<TextBlock Text="{Binding Text, ElementName=root}" />

Comment: Will, you are a star!  I've been looking at this since last week and made little progress.  Thanks a lot.  Now I'd just like to understand *why* it works!  I guess it's the ElementName=root so I'll have a look through my WPF books now.
Comment: @ChrisTrollen: The DP is defined on the class.  This class' public properties are found at the root of the UserControl's definition in xaml.  Therefore, you can access these public properties in bindings by somehow referencing the root node of the UserControl.  You can do this by either giving it a name `x:Name="something"` or by using a relative source `{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}`.
Comment: Ah, right - thanks.  I had tried using RelativeSource but I didn't think to set the AncestorType to the user control itself.


English Words for online dictionary MySQL

Question: I'm just building an online dictionary English to malayalam, Malayalam to english dictionary.
Here is the link http://www.vanmaram.com/
That website offers the user the option to add words.
I would like to add some words.
If anyone knows where to get english words, could you please give me directions.
It would be very helpful for me
Comment: @fivedigit I need English word list
Comment: @fivedigit then I can add appropriate Malayalam words
Answer: There are meany open dictionary files you can find on the internet, i would recommend using the ones from open office or something like that. They also have a Malayalam one.
Open office allso refers to a more up to date list of data from aspell.net.
Answer: you can check this out too : MySQL formatted english words list
dunno much about how many words are not in but it's a huge list anyway :)
There are about 128/129K words in


How to end custom game with 2 players

Question: I was trying out some things with a friend in a custom game. There were just the 2 of us.
Normally when I do it alone, I can exit the game, and then I can join a new game, since previous one disappears.
However, when there are 2 of us in a custom game, even if we both exit the game, it won't end. Meaning we can't join a different game. We either have to wait 20 minutes to /ff or destroy a nexus before that.
Question:
How can we end a custom game prematurely?
Comment: You're sure that when you've both left the match, it doesn't end it?  That sounds like a bug, it's supposed to end when no one is in it.
Comment: It is a bug, you can try to exit and reload the client, or if that doesn't work, email riot support.
Comment: @Namfuak We both exited several times and it wouldnt end the game. We were forced to play for 20 minutes. I guess I ll edit my question if more people can confirm that it is a bug.
Answer: This is a bug that is not supposed to happen. When a game has no more players in it the game is supposed to end because the server has no reason to keep the game alive when no one is in that game. You should email Riot support and tell them the problem, maybe with some screen shots including the time in the game (hopefully you won't get a auto-response back).

How to end custom game with 2 players


What's the default language for a Postgres function?

Question: What is the default language used for CREATE FUNCTION in Postgres?
i.e., The language used if I don't specify one.
Answer: There is no default.  Not specifying the language is an error.
create function adlsfjsdf() returns text as $$ sdlkj;djf;lskjdf;jasf $$;

ERROR:  no language specified

Comment: Interesting, at least it's explicit.


Can I scan a LEGO structure and generate a Minecraft world?

Question: I have a LEGO structure I would like to import into Minecraft. I have a digital camera, but no other specialist tools. Is there any way of doing this?
Comment: Try this:
http://www.orderofevents.com/MineCraft/KinectInfo.htm
Answer: I don't know of any way in particular. One potential problem with doing this would the the relative differences in height to width to length ratios. All of the blocks in Minecraft are cubes, whereas a 1x1 LEGO brick is taller than it is wide and long. A direct translation of brick to block would end up with a structure that is too short in Minecraft.
Comment: Wouldn't the structure be too 'tall'/narrow, not short?
Comment: @Muntoo The 1x1 brick is taller which would make the Minecraft block shorter relative to it.
Comment: @Pubby8 Oh, OK. I was thinking of 2x2 bricks being one Minecraft piece. (I haven't played Minecraft.)
Answer: I know of no existing tool. But for a surface scan your best bet would be to use a Microsoft Kinect with some framework like openFrameworks.
Projects involving this solution already exist for 3d printing, so why not making one for Minecraft.
You could try to get some developers on it. You could ask Mojang to create the tool.
Comment: Don't think, that Mojang would do that ;)
Comment: @Sibbo Who knows? They could get a partnership with LEGO and end up doing just that ;)
Comment: Something like that was on hackaday... I'll get the link
Answer: Here is a devilish little plan for doing a crazy stunt in Minecraft.
I see 2 ways of preparing useful geometries for Minecraft
1. Scanning
I would not try to scan in a LEGO model. Colors and block positioning would most likely be lost. The worst problem one would face is the detection of inside surfaces, concave shapes. In other words, scanning the inside of a LEGO house would be quite problematic. So for me it`s a no-no.
2. CAD
I would rather try to create the LEGO model using a visualization software. Let me suggest Autodesk 3ds Max software or Autodesk Maya software for achieving this.
You can find free bricks and models meshes right here.
Additional information on lego visualization can be found on the Okino's website.
Why am I suggesting these products?

because of their API and scripting abilities.  3ds Max and Maya have a C++ API (Max even has .net bindings which open up to any CLI language (Iron Python)). 3ds Max has Maxscript, Maya has MEL which are as easy to use as script languages can get.
because they have a one month trial period, which is surely enough
for throwing out a minecraft stunt.
Lego visualization is something already done using these products. see here

So, provided you follow these steps and are in one or the other software with your model, you will need to translate the geometry into minecraft unit. This is where API and scripting becomes handy. It should be a fun little algorithmic challenge.

compute the volume bounding box.
Iterate for each minecraft unit in the volume (1x1 cube, whatever the scale chosen)
.Figure out if there is something solid in there worth representing by a minecraft unit (I'd go for 50% occupancy). Figure out to most important color or compute the average
Serialize the newly computed minecraft geometry in a minecraft compatible geometry file
Smile. you've achieved quite a challenge even if some (including my wife) would consider it pointless

Note : The software solution above naturally solve the scaling incompatibility between LEGO and minecraft units. Enjoy.
Comment: Do you guys think the visualization part of my answer should go under it`s own question?