Q:

Android: Getting incorrect CheckBox value from another activity

In my mainActivity I'm trying to read the value of a checkbox in another activity. I however seem to get the opposite of what the value actually is. I suspect the problem is that I'm trying to get the value before I've opened the activity containing the checkbox.
In my mainActivity I have a
  public boolean checkValue;

that I want to give the value of the checkbox in the other activity like this
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkValue = SettingsActivity.getCheckValue();
}

which I later use like this
 public class JSONTask extends AsyncTask<String, String, String >{
...
}

 @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        checkValue = SettingsActivity.getCheckValue();

        if(checkValue != true) {
               TextView1.setVisibility(View.VISIBLE);
        }
        else{
                TextView1.setVisibility(View.INVISIBLE);

        }

The other activity looks like this
public class SettingsActivity extends AppCompatActivity {

private static CheckBox checkBox1;

public static boolean checkStatus;

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

    checkBox1 = (CheckBox) findViewById(R.id.checkBox);;

    loadSavedPreferences();
    savePreferences("CheckBox_Value", checkBox1.isChecked());

    checkStatus = checkBox1.isChecked();

}

private void loadSavedPreferences() {

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", true);

    if (checkBoxValue) {
        checkBox1.setChecked(true);
    } else {
        checkBox1.setChecked(false);
    }

}

private void savePreferences(String key, boolean value) {

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);
    editor.commit();

}

@Override
public void onDestroy(){
    super.onDestroy();
    savePreferences("CheckBox_Value", checkBox.isChecked());

}

public static Boolean getCheckValue(){
    return checkStatus;
}

I suspect a solution could be to initialize the settingActivity before opening it in the app, not sure if this is possible though.

A:

Your assumption is correct. If you call getCheckValue before creating your activity, you are just going to get the default value of your static variable checkStatus.
Usually you don't want to mix your logic with your UI.
Why not getting the correct value directly from your shared preference?
You are already doing that in loadSavedPreferences().
Instead of calling checkValue = SettingsActivity.getCheckValue();
Call:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
ceckValue = sharedPreferences.getBoolean("CheckBox_Value", true);


Q:

My Android Studio app crashes when trying to write to a text file

I am trying to write the contents of an ArrayList that is displayed in a ListView to a text file named list.txt.
MenuInflaterActivity.java:
package com.course.example.menuinflater;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.*;
import java.io.FileWriter;
import java.util.*;

import java.util.*;
import android.speech.tts.TextToSpeech;

public class MenuInflaterActivity extends Activity {

    //Define variabels
    private ArrayList<String> arrayList;
    private ArrayAdapter<String> adapter;
    private EditText textInput;
    String itemClick;
    int itemIndex;

    int counter = 0;

    TextToSpeech tts;

    String data;
    private String file = "mydata";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //hide title and icon in action bar
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayUseLogoEnabled(false);

        //Create list view, array list and adapter
        ListView listView = (ListView) findViewById(R.id.listv);
        String[] items = {};
        arrayList = new ArrayList<> (Arrays.asList(items));
        adapter = new ArrayAdapter<String>(this,R.layout.list_item,R.id.txtitem,arrayList);
        listView.setAdapter(adapter);

        //Create edit text field
        textInput = (EditText) findViewById(R.id.textInput);

        //Assign ItemList as the list view's on click listener
        listView.setOnItemClickListener(new ItemList());

        //Text to Speech
        tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    tts.setLanguage(Locale.US);
                }
            }
        });
    }

    class ItemList implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            ViewGroup vg = (ViewGroup) view;
            TextView tv = (TextView) vg.findViewById(R.id.txtitem);
            //Toast.makeText(MenuInflaterActivity.this, tv.getText().toString(),Toast.LENGTH_SHORT).show();

            //itemClick = the item that is clicked
            itemClick = tv.getText().toString();
            //Set the edit text field to display what was clicked
            textInput.setText(itemClick);
            //Get the index of the clicked item - used for update function
            itemIndex = arrayList.indexOf(itemClick);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.add:
                counter++;
                //If there is something entered in the edit text field it will be added to the list, if there is nothing entered nothing will be added
                if (textInput.getText().toString().length() > 0) {
                    String newItem = textInput.getText().toString();
                    arrayList.add(counter + ". " + newItem);
                    adapter.notifyDataSetChanged();
                    tts.speak(newItem + "Has been added to your to-do list.", TextToSpeech.QUEUE_FLUSH, null);
                }

                textInput.getText().clear();

                return true;

            case R.id.delete:
                arrayList.remove(itemClick);
                adapter.notifyDataSetChanged();
                int numberLocation = itemClick.indexOf(".");
                String speechText = itemClick.substring(numberLocation + 2, itemClick.length());
                tts.speak(speechText + "Has been deleted from your to-do list.", TextToSpeech.QUEUE_FLUSH, null);

                textInput.getText().clear();

                return true;

            case R.id.update:
                String updatedItem = textInput.getText().toString();
                arrayList.set(itemIndex, updatedItem);
                adapter.notifyDataSetChanged();

                textInput.getText().clear();

                return true;

            case R.id.save:
                //App crashes when trying to read/write to file
                try {
                    FileWriter writer = new FileWriter("list.txt");
                    for(String str: arrayList) {
                        writer.write(str);
                    }
                    writer.close();
                } catch (Exception e) {}

            case R.id.close:
                try {
                    FileWriter writer = new FileWriter("list.txt");
                    for(String str: arrayList) {
                        writer.write(str);
                    }
                    writer.close();
                } catch (Exception e) {}

                finish();

            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.course.example.menuinflater"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="17" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name=".MenuInflaterActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The problem arises when clicking my "Save List" button, the application closes immediately and doesn't display any sorts of errors in the Logcat.

A:

and doesn't display any sorts of errors in the Logcat.

Never catch an exception and fail to log it, as you are doing in your file I/O:
            try {
                FileWriter writer = new FileWriter("list.txt");
                for(String str: arrayList) {
                    writer.write(str);
                }
                writer.close();
            } catch (Exception e) {}

So, first, log the exception to LogCat, using Log.e().
Next, you need to fix your FileWriter to write to an actual location. As it stands, you are attempting to write to a list.txt file that is... nowhere. Your primary choices are internal storage and external storage.
Eventually, move this disk I/O to a background thread, so your UI is not frozen while that I/O is going on.
This sample app from this book demonstrates how to write to internal and external storage.


Q:

Trying to use a ViewModel on a partial view

So I'm editing the default ASP.NET MVC with authentication template, and I'm trying to create a ViewModel for _PartialLogin.cshtml in order to display a name instead of the user's e-mail. I searched a lot of things, but they were pretty outdated so I hope someone can help. I don't even know if creating a ViewModel is the best option.
Here's the LoginPartialViewModel:
namespace AplicacaoRoles2.Models.SharedViewModels
{
    public class PartialLoginViewModel
    {
        [Required]
        public string Nome { get; set; }
    }
}

_LoginPartial.cshtml:
@using Microsoft.AspNetCore.Identity
@using AplicacaoRoles2.Models

@model AplicacaoRoles2.Models.SharedViewModels.PartialLoginViewModel

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">

                Hello @Html.DisplayFor(model => model.Nome) !

(...)
HomeController:
public class HomeController : Controller
{
    private readonly ApplicationDbContext _context;

    public HomeController(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        PartialLoginViewModel model = new PartialLoginViewModel();
        var userName = User.Identity.Name;
        var applicationUser = await _context.ApplicationUser.SingleOrDefaultAsync(m => m.UserName == userName);

        model.Nome = applicationUser.Nome;

        return View(model);
    }

On _Layout.cshtml there's this portion useful:
@Html.Partial("_LoginPartial")

(the code is simplified to shorted this)
So this is working fine while I'm on Home/index because it as no Model, but as soon as I enter a page with a model it shows an model error thing.
I could replace:
@Html.Partial("_LoginPartial")

for
@Html.Partial("_LoginPartial", new AplicacaoRoles2.Models.SharedViewModels.PartialLoginViewModel())

But the problem is that I lose the information by creating a new instance...
Thank you.
**Some words like 'Nome' are not misspelled, they are in portuguese

A:

Let's first see what the issue is that your are running into and then we will apply a fix.
The Issue/Problem
The _LoginPartial.cshtml is called from the Shared/_Layout.cshtml unless you have changed it; it seems you have not changed it so it is using the defaults. That is fine, you do not have to change it. When you visit Home/Index, you create an instance of PartialLoginViewModel and pass it to the Home/Index.cshtml. By default, all .cshtml files use Shared/_Layout.cshtml so essentially this is how your PartialLoginViewModel is being passed around:
Home/Index (Controller) => Home/Index.cshtml => Shared/_Layout.cshtml
    => _LoginPartial.cshtml
So in the above, it is pretty clear that _LoginPartial.cshtml eventually gets a hold of PartialLoginViewModel and that is why it works when you visit Home/Index. All good and dandy :)
Now let's see what happens when you visit another page; say SomeController.SomeAction. Let's further imagine the other page has a model of type SomeModel. Here is how the SomeModel will be passed around:
Some/SomeAction (Controller) => Some/SomeAction.cshtml => Shared/_Layout.cshtml => _LoginPartial.cshtml
And boom it fails because _LoginPartial.cshtml is expecting a model which has the properties of PartialLoginViewModel but instead you have given it SomeModel.
Not a Fix
This will not work:
@Html.Partial("_LoginPartial", new AplicacaoRoles2.Models.SharedViewModels.PartialLoginViewModel())

because you are sending the correct model (PartialLoginViewModel) to the _LoginPartial but it is a new instance and the properties have not been set. Therefore, the Name (you spelled it Nome) will be empty.
This will also not work:
@Html.Partial("_LoginPartial", Model)

because you are sending it the model from your main view which is of a different type.
Fix
One way to fix your issue is to inherit all your models for your views (view models) from PartialLoginViewModel so the partial stays happy.
public class PartialLoginViewModel
{
    [Required]
    public string Nome { get; set; }
}

public class SomeModel : PartialLoginViewModel
{
    // Code ...
}

You would also need to populate the Name property in all your controller actions. So simply create a base class and inherit all your controllers from that. Like this:
public class CustomController : Controller
{
    protected virtual async Task<TModel> CreateModel<TModel>() where TModel : PartialLoginViewModel, new()
    {
        TModel model = new TModel();
        var userName = User.Identity.Name;
        var applicationUser = await _context.ApplicationUser.SingleOrDefaultAsync(m => m.UserName == userName);

        // Set common properties
        model.Nome = applicationUser.Nome;

        return model;
    }
}

Then inherit all your controllers from the above controller and always call the above controller's CreateModel method so it can populate the common properties as shown below:
public class EveryoneOfYourControllers : CustomController
{
    public async Task<IActionResult> Index()
    {
        var model = await base.CreateModel<SomeModel>();

        // Set other properties on your model

        return View();
    }
}

All the code is in one place. In the future if you decide to add another property to PartialLoginViewModel, you will only need the change the code in in one place to set the additional property.
Now that you know the issue, you can come up with different solutions.


Q:

AdvancedDatagrid column Itemeditor and issues with setting dataprovider value

I have an editable advanceddatagrid (editable column). I am providing the arraycollection as a dataprovider. (fname(string), lname(string), bdate(Date)). (3 columns)
I have created the VO for fname, lname, and bdate. Whenever I edit bdate and focus out , it will try to get saved the string value as a Date and got failed (which is obvious). By default, editor consider "TextInput" as an itemeditor and save the inserted date as a text and that text value getting refused by the VO which is expecting behavior.

I tried to update the value in "ItemEditEnd" event handler but it wont allow me to do that.
I also tried to put a check at VO but it never reached there. (I am not sure why)

I have to strictly keep the VO as Date instead of text.
Is there anyway we can convert string into Date ? Any other place ? Is there anything I can do at collection change ?
Please help me if possible.
thanks,

A:

For this, I would use another approach than the one you are suggesting.
<s:GridColumn headerText="Birth Date" dataField="bdate" rendererIsEditable="true">
     <s:itemRenderer>
         <fx:Component>
             <s:GridItemRenderer>
                 <mx:DateField selectedDate="@{data.bdate}"/>
             </s:GridItemRenderer>
         </fx:Component>
     </s:itemRenderer>
 </s:GridColumn>

In this example I am using an ItemRenderer which will also function as the ItemEditor.
In this case it is a DateField, which will be able to cope with the date property you have in your VO without the need to be parsing dates manually.
Suggested for you to read up:

http://www.adobe.com/devnet/flex/articles/itemeditors_pt1.html
http://livedocs.adobe.com/flex/3/html/help.html?content=cellrenderer_3.html


Q:

Sounds to describe the weather?

I'm trying to think of sounds that will help convey the time of day and weather condition. I'm not even sure of all the weather conditions I would consider, and some are obvious. Like if it's raining, the sound of rain. But then I'm thinking, what about for a calm day? If it's morning time, I could do birds chirping or something. Night time could be an owl or something. What are some good combinations of sounds/weather/time to have a good effect?

A:

How about using background music instead of sound effects?
Animal Crossing is a real-time game (meaning the game keeps track of the time), and it had a different background tune for each hour of the day; the tune in the middle of the day is upbeat, "friendly" sounding, and the night one is very quiet and slow with some extra percussion sounds thrown in. I don't recall any bird chirping sounds, though there is the sound of water running when you walk near a stream and the sound of your own footsteps when you walk around (specific to the material being walked on), and there definitely was the pitter-patter of rain when it was raining.

A:

The sound of rain, provided it is not too loud, is a good idea, as a rain visual without a rain sound is disconcerting.  Occasional playing of the sound of thunder can really help, but you would probably need to support some kind of lightning effect for that to work.
Is your game set in the country or the city?  This drastically alters the sound of a 'calm' day and a usual night.  Considering what you mentioned, I'm going to assume country.  The sound of an occasional wind gust or a wolf howl for such a situation is not out of the question.  Whatever enhances the overall feeling of being in the environment.  That is quite possibly the biggest problem with music and sound effects - they are at their best when you don't even notice them for what they are; their presence is just part of the scene and they don't stand out.
Whatever your choice, make sure to sufficiently space the sound effect between plays and provide a pretty decent number of sounds that are played.  Hearing the same hooting owl every three seconds at night could get really annoying.


Q:

JS or jQuery how to delete key-value pair

Using JS or jQuery how to delete the key-value pair which the value is of type “Null” & "".
e.g.
before:
Object {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null}

alter:
Object {style: "fruit", origin: "Thailand", day: "18d"}

A:

There are two parts to this:

Loop through the object's properties
Remove a property from an object

There are lots of ways to do the first, covered by this question's answers. Assuming you only care about "own" (non-inherited) properties, I'd probably use Object.keys to get an array of property names and then loop that.
The second is done with the delete operator.
So:
Object.keys(theObject).forEach(function(key) {
    var value = theObject[key];
    if (value === "" || value === null) {
        delete theObject[key];
    }
});

Live Example:

var theObject = {
  style: "fruit",
  origin: "Thailand",
  day: "18d",
  color: "",
  weight: null
};
console.log("Before:", JSON.stringify(theObject, null, 2));
Object.keys(theObject).forEach(function(key) {
  var value = theObject[key];
  if (value === "" || value === null) {
    delete theObject[key];
  }
});
console.log("After:", JSON.stringify(theObject, null, 2));


Q:

How to render html elements in Reactjs?

I am really new to reactjs and still learning it.
I am trying to return the file tree view but it is showing all the elements on the page like this..

 app

 index.html

 js

....

I want to return the list of all items inside folders on the page. I thought I could return it using the function inside the component. Am I doing it correctly?
My Code:
class Filetree extends Component {
  constructor({ props }) {
    super(props);
    this.state = {
      folders: [
        {
          type: "dir",
          name: "app",
          children: [
            {
              type: "file",
              name: "index.html"
            },
            {
              type: "dir",
              name: "js",
              children: [
                {
                  type: "file",
                  name: "main.js"
                },
                {
                  type: "file",
                  name: "app.js"
                },
                {
                  type: "file",
                  name: "misc.js"
                }
              ]
            }
          ]
        },
        {
          type: "dir",
          name: "css",
          children: [
            {
              type: "file",
              name: "reset.css"
            },
            {
              type: "file",
              name: "main.css"
            }
          ]
        }
      ]
    };
  }

  displayJsonTree(data) {
    var htmlRetStr = `<ul className='folder-container'>`;
    for (var key in data) {
      if (typeof data[key] === "object" && data[key] !== null) {
        htmlRetStr += this.displayJsonTree(data[key]);
        htmlRetStr += `</ul>`;
      } else if (data[key] === "dir") {
        htmlRetStr += `
 ${
          data["name"]
        }

`;
      } else if (key === "name" && data["type"] !== "dir") {
        htmlRetStr += `<li className='file-item'> ${data["name"]} </li>`;
      }
    }
    return htmlRetStr;
  }

  render() {
    const { folders } = this.state;

    return
{this.displayJsonTree(folders)}
;
  }
}

A:

You can use dangerouslySetInnerHTML if you have HTML in a string.
render() {
  const { folders } = this.state;

  return
;
}


Q:

NSFetchedResultsController didn't return data

I get stuck in some problem and after 2 days of seeking I've found solution but didn't get idea why does it work.
First, I'm initialized NSFetchedResultsController using following code (it look like a lot of automatically generated):
- (NSFetchedResultsController *)fetchedResultsController {

if (fetchedResultsController != nil)
    return fetchedResultsController;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Profile"
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
                                                         initWithFetchRequest:fetchRequest
                                                         managedObjectContext:self.managedObjectContext
                                                         sectionNameKeyPath:nil
                                                         cacheName:@"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
//[aFetchedResultsController performFetch:&error];

[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];

return fetchedResultsController;

}
Have a look at commented string - there wasn't any of these strings and when I asked for data - I didn't get any (and it was there!). When I've uncommented that line, it starts work. Seems evident, but all examples I saw before hadn't that line. And they work. How can it be? I just want to know what am I doing wrong.

A:

[aFetchedResultsController performFetch:&error]; has to be called at some point in order for the data to be fetched.  The examples probably fetched the data at some point other than the accessor (it's fine in the accessor, though).


Q:

On drag and drop element to div, add an id name to url

So, I didn't knew how to start working on it so I planned to ask first here.
I want to create something where you would have a list of things and you could drop it to one container div. After dropping it there it would add for example name of item's id into url, so that users could share their things with another by sharing the link. Is it possible to do with jquery?
If yes, how? :C
@edit
this is what I have so far.
Dragin and dropping from one div to another
$(document).ready(function () {
$(".merchandiser_image").draggable({ cursor: "crosshair", revert: "invalid" });
$(".selected_item").droppable({
    accept: ".merchandiser_image",
    drop: function (event, ui) {
        console.log("drop");

        var dropped = ui.draggable;
        var droppedOn = $(this);
        $(dropped).detach().css({ top: 0, left: 0 }).appendTo(droppedOn);

    },
    over: function (event, elem) {

        console.log("over");
    }
                ,
    out: function (event, elem) {

    }
});
$(".selected_item").sortable();

$(".klatka").droppable({
    accept: ".merchandiser_image", drop: function (event, ui) {
        console.log("drop");

        var dropped = ui.draggable;
        var droppedOn = $(this);
        $(dropped).detach().css({ top: 0, left: 0 }).appendTo(droppedOn);

    }
});

});

A:

It appears that you have everything set up for the drag and drop part. I have not tested it, but you might want to give this a try:
Part 1 - Update the ID list in the URL when items are moved around.
In both of your drop functions, you can call a function to update the URL:
drop: function (event, ui) {
    // ...
    updateURL();
},

Then, write this function:
function updateURL(){
    // Get all selected items
    var items = $('.selected_item .merchandiser_image'),
        id_list = [];
    // Gather their IDs into an Array
    for(var i=0; i<items.length; i++){ id_list.push( items[i].id ); }
    // Insert a hash in the URL, with the IDs, comma separated
    window.location.hash = id_list.join(',');
}

Part 2 - Read the list in the URL on page load, and place the items in their correct spot.
Anywhere inside your $(document).ready(), call this function:
updateListFromURL();

And declare it:
function updateListFromURL(){
    var hash = window.location.hash;
    if(hash){
        // replace `,` with `,#` to get a list of ID CSS selectors
        var list_of_ids = hash.split(',').join(',#');
        // Append them to your list of selected items
        $(list_of_ids).appendTo(".selected_item");
    }
}


Q:

Why does this chord progression function?

I'm learning music theory in school and I stumbled into this chord progression at home. I think it is cool but I want to know why it is cool.
The chord progression is: Cmaj7 Gmaj7 B&flatmaj Amin7
Is it just because I have heard the chord progression before?

A:

It's a common progression in classical harmony if the middle chords are in first inversion. One has C,B,Bb,A as a bass line with chords above, C,G6,Bb6,a (with appropriate sevenths if wanted). It's a portion of the "lament descent" which is often used to express sadness; with a different bass, this interpretation may not hold. A nice continuation would be f6m,G which moves chromatically from tonic to dominant.

A:

is it just because I have heard the chord progression before?

Probably because of this.
It is a most common progression in Pop music. It won't be easily described by functional harmony, even not by modes. I hear the progression in G-Major but it mustn't be.
It reminds me of the even more common "Don't go chasing waterfalls" (TLC) e.g. C-G-Bb-F!
(If we start this turn with Bb we get: Bb-F-C-G and this would be the circle of 5th in the direction of the sharps.)


Q:

Rails 3 ActionDispatch scope options

Do you know a resource which documents all the available options for the ActionDispatch scope method and their usage?
I'm quite tired of digging into each merge_X_scope method trying to understand the X option implications.

A:

After a long time, I found the solution. The options for Rails 3.1 are now described in the mapper.rb file.
Here is the documentation


Q:

scan array from center

I am making a photomosaic app, a simple solution is to scan though bitmap to parition the bitmap into small squares and replace each with small images. But in order to increase the quality of the resulting image, I want to scan the bitmap from the center instead of from the top left. Is there any existing algorithm to solve that?
for example:
In traditional method, we scan 2-D array from topleft:
1  2  3  4

5  6  7  8

9  10 11 12

13 14 15 16

But I want to scan from center to the border, spirally :
16 15 14 13

5  4  3  12

6  1  2  11

7  8  9  10

A:

bool between(int x, int low, int high) {
  return low <= x && x <= high;
}

// we use this constant array to help tweaking the (row,col) coordinate
const int D[4][2] = {
  {0, 1},   // 0 - right
  {1, 0},   // 1 - down
  {0, -1},  // 2 - left
  {-1, 0}   // 3 - up
};

int a[n][n]; // suppose the array is n times n in size
int row = 0, col = 0, dir = 0; // initial direction is "0 - right"

for (int m = n*n; m >= 1; m--) {
  a[row][col] = m;

  int old_row = row, old_col = col;  // remember current coordinate

  row += D[dir][0];
  col += D[dir][1];

  if (!(between(row,0,n-1) && between(col,0,n-1))) { // have to move back
    // move back
    row = old_row;
    col = old_col;

    // change direction
    dir++;
    dir %= 4;

    // move again
    row += D[dir][0];
    col += D[dir][1];
  }
}


Q:

Is there a way to share existing data between containers in a pod?

I have 2 containers in a pod.
1. Webapp
2. Nginx
I would like to share the data from Webapp container /var/www/webapp/ with the nginx container. /var/www/html
/var/www/webapp ( folder structure )
│   index.php
│
│
└───folder1
│   │   service1.php
│   │
│   └───subfolder1
│       │   app.php
│
└───folder2
    │   service2.php

The folder is mounted properly but all the files are missing.
apiVersion: apps/v1
kind: Deployment
    spec:
      volumes:
      - name: webapp-data
        persistentVolumeClaim:
          claimName: webapp-data
      containers:
      - name: webapp
        image: webapp
        imagePullPolicy: Always
        volumeMounts:
        - name: webapp-data
          mountPath: /var/www/webapp/
       - name: nginx
        imagePullPolicy: Always
        image: nginx
        volumeMounts:
        - name: webapp-data
          mountPath: /var/www/html/

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: webapp-data
spec:
  storageClassName: local
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi

When mounting a volume under docker all the folders and files from within the container are available but not in k8s.

A:

Kubernetes will not automatically populate an empty volume with contents from an image.  (This is a difference from docker run.)  Your application needs to figure out how to set up the shared-data directory itself, if it's empty.
For standard database containers this doesn't really matter since they typically start off with some sort of initdb type call which will create the required file structure.  Similarly, if you're using a persistent volume as a cache or upload space, it doesn't matter.
For the use case you're describing where you want one container to just have a copy of files from the other, you don't really need a persistent volume.  I'd use an emptyDir volume that can be shared between the two containers, and then an init container to copy data into the volume.  Do not mount anything over the application content.
This would roughly look like (in reality use a Deployment):
apiVersion: v1
kind: Pod
metadata:
  name: ...
spec:
  volumes:
    - name: webapp-data
      emptyDir: {}
  initContainers:
    - name: populate
      image: webapp
      volumeMounts:
        - name: webapp-data
          mountPath: /data
      command: [cp, -a, /var/www/webapp, /data]
  containers:
    - name: webapp
      image: webapp
      # no volumeMounts; default command
    - name: nginx
      image: nginx
      volumeMounts:
        - name: webapp-data
          mountPath: /var/www/html

With this setup there's also not a hard requirement that the two containers run in the same pod; you could have one deployment that runs the back-end service, and a second deployment that runs nginx (starting up by copying data from the back-end image).
(The example in Configure Pod Initialization in the Kubernetes docs is very similar, but fetches the nginx content from an external site.)


Q:

Search database for matching results, using PHP and MYSQLI

I am kind of new to all of this trying to figure out why things work and why things don't.
So I was aiming for a simple search form to display all of the database users with the same first name.
This code outputs all the names of the users in my table "users" and it works.
<?php
include 'connect.php'; //working connection to the DB

$sql="SELECT name FROM users ORDER BY name ASC";

$sqlresult=mysqli_query($con,$sql);

$afct=mysqli_affected_rows($con);

while($user=mysqli_fetch_array($sqlresult,MYSQLI_ASSOC)){
    $num[]=$user['name'];
    $num++;
}

$i=1;

while($i < $afct)
{
    echo $i.': '.$num[$i];
    echo'
';
    $i++;

}
?>

So now I wanted to add a variable that stores the user input, to match with the users first name.
<?php
include 'connect.php';    //working connection to the DB

$input = 'Marcus';       // later will be $input = $_GET(['name']);

$sql="SELECT name FROM users WHERE name='".$input."'  ORDER BY name ASC";

//tried with "SELECT * FROM users WHERE name='".$input."'" ORDER BY name ASC";
//also

$sqlresult=mysqli_query($con,$sql);

$afct=mysqli_affected_rows($con);

while($user=mysqli_fetch_array($sqlresult,MYSQLI_ASSOC)){
    $num[]=$user['name'];
    $num++;
}

$i=1;

while($i < $afct)
{
    echo $i.': '.$num[$i];
    echo'
';
    $i++;

}
?>

And all it dose is output a blank and sexy page. Thank You in Advance.
//Marcus

A:

The problem is that you initialize $i to 1. Array indexes in PHP start at 0, just like almost every other programming language. Since your second query only returns 1 row, the only element will be $num[0]. So you should initialize $i to 0.
Or use foreach:
foreach ($num as $i => $name) {
    echo "$i: $name
";
}

Your first script was also wrong, you just didn't notice that it skipped one of the users in the table.


Q:

Oracle Statement to sum a calculated column by another column

I am trying to add all the extended prices for a company.
Instead of my results being
Company_1 2000
Company_1 2000
Company_1 1000
Company_2 2000
Company_2 1000

I would like to see
Company_1 5000
Company_2 3000

here is my current statement.
SELECT COMPANIES.COMPANY_NAME,
       INVC_HEADER.INVOICE_DATE,
       (INVC_DETAIL.QTY_SHIP * INVC_DETAIL.UNIT_PRICE) as Ext_Price
  FROM ( INVC_DETAIL INVC_DETAIL
 INNER JOIN INVC_HEADER INVC_HEADER
    ON INVC_DETAIL.INH_AUTO_KEY = INVC_HEADER.INH_AUTO_KEY )
 INNER JOIN COMPANIES COMPANIES
    ON INVC_HEADER.CMP_AUTO_KEY=COMPANIES.CMP_AUTO_KEY
 ORDER BY COMPANIES.COMPANY_NAME, INVC_HEADER.INVOICE_DATE DESC

A:

You can do a SUM of the value you are looking for and GROUP BY Company Name
SELECT COMPANIES.COMPANY_NAME,
        SUM(INVC_DETAIL.QTY_SHIP * INVC_DETAIL.UNIT_PRICE) as SumExt_Price
FROM   (INVC_DETAIL INVC_DETAIL INNER JOIN INVC_HEADER INVC_HEADER ON INVC_DETAIL.INH_AUTO_KEY=INVC_HEADER.INH_AUTO_KEY)
        INNER JOIN COMPANIES COMPANIES ON INVC_HEADER.CMP_AUTO_KEY=COMPANIES.CMP_AUTO_KEY
GROUP BY COMPANIES.COMPANY_NAME


Q:

How to shrink the omniauth FB dialog

In my omniauth initializer file I have these settings:
provider :facebook, 'a_key', 'another_key',
     :scope => 'email', :display => 'popup'

But when the fb authentication dialog occurs, the login window is still full screen. I thought that the popup option would shrink the window. Is there another setting I need to set?

A:

Hey just check carefully how the page is displayed when the  :display => 'popup'
attribute is present and then remove that and again check how the page is displayed.
Check the difference between the views.
:display => popup changes the view so that it can be shown in popup.
In order to shrink the window refer this answer Turn omniauth facebook login into a popup


Q:

How to find out which derived class is processing

I have a BaseInterface class, with a virtual void execute() to be implemented by derived classes:
class BaseInterface
{
public:
    virtual void execute(int a) = 0;
}

And I have tons of derived classes overwriting the execute void:
class ProcessN : public BaseInterface
{
public:
    void execute(int a);
}

Execute void of one of my derived classes has a bug. But there are tons of derived classes. It is very difficult to check each of them one by one. I have difficulties in finding the bug.
Is there a method in C++ to find out via base class, which derived class is currently processing over it?
EDIT:
Ok I improve my question after a useful discussion on the comments:
May I implement something inside the constructor of the BaseInterface class, to print out the info of the current processing derived class?

A:

How is execute being invoked....May be you can introduce a static method in base class which takes a Baseclass pointer as argument and call this method before execute and print the necessary information from the derived object in this method using BasePointer to see which derived class object it is.
Per my understanding I suggested as below. If it does not help All the best.
class Base
{
   public:
   virtual void exec(int i) =0 ;
   static void check(Base* temp)
   {
     cout<<"Type of obj"<<typeid(*temp).name()<<endl;
    }
 };
class Derived1 : public Base
{
 public:
 void exec(int i)
 {
  cout<<"Der1 Exe "<<i<<endl;
  }
 };

class Derived2 : public Base
{
 public:
 void exec(int i)
 {
   cout<<"Der2 Exe "<<i<<endl;

 }
};
int main()
{
  Base *client = NULL;
  Derived1 lder1;
  Derived2 lder2;
  client= &lder2;
  Base::check(client);
  client->exec(0);

  client= &lder1;
  Base::check(client);
  client->exec(0);
 return 0;
}


Q:

In python how to update a value in CSV file which have more than 5K rows?

I'm a beginner to python, is there any way I can update the csv file while reading and writing in the same file, or is there any alternate way to do this. All the suggestions are welcomed.
NOTE: I have a CSV file with records 5k and above.

What I want to do is read the csv file line by line and if the value of msg_sent is False then update it to True

Here is the code snippet which I've tried but it is adding an new line at the end of CSV file instead of updating it,

with open('subscribers.csv', 'r+') as subscribers_csv:
reader = csv.DictReader(subscribers_csv)
writer = csv.DictWriter(subscribers_csv,
                        delimiter=",",
                        lineterminator="\n",
                        fieldnames=['user_id', 'name', 'msg_sent'])
    for subscriber in reader:
        if subscriber['msg_sent'] == 'False':
            subscriber_row = {'user_id': subscriber['user_id'],
                              'name': subscriber['name'],
                              'msg_sent': True}
            writer.writerow(subscriber_row)

A:

As per my comment above - use pandas.
If you want to update all rows with msg_sent==False to True just use df.loc[~df.msg_sent, 'msg_sent'] = True or even shorter df.msg_sent = True as there are only 2 possibilities True and False.
If you want to only write back rows that were False and set their msg_sent value to True use df = df.loc[~df.msg_sent].assign(msg_sent=True)
Complete example (for case 2):
import pandas as pd
df = pd.read_csv('subscribers.csv')
df = df.loc[~df.msg_sent].assign(msg_sent=True)
df.to_csv('subscribers.csv')


Q:

A closed extension of the Laplace operator with respect to the supremum norm

Let $X$ be a bounded connected open subset of the $n$-dimensional real euclidean space. Consider the Laplace operator defined on the space of infinitely differentiable functions with compact support in $X$. What is the closure of this operator in the space $C_0(X)$ endowed with the supremum norm? Does its closure generate a strongly continuous semigroup on $C_0(X)$?

A:

If $X$ has the so-called Wiener-regularity, then it generates an analytic semigroup, see the paper by Arendt and Bénilan.
The paper shows this even for unbounded domains, along with the fact that if the regularity assumption is not satisfied, then the Dirichlet-Laplace operator has empty resolvent (hence it is not even a semigroup generator).
For bounded domains and well-posedness (=semigroup generation), see Gilbarg-Trudinger, Section 2.8.


Q:

EntitySqlException when trying to access DbUpdateConcurrencyException's GetDatabaseValues() entity

I'm trying to do the tutorial here: http://www.asp.net/entity-framework/tutorials/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
In the ActionResult Edit, I have the following code:
public ActionResult Edit(Product product)
{
    try
    {
        if (ModelState.IsValid)
        {
            db.Entry(product).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch(DbUpdateConcurrencyException ex)
    {

                        var entry = ex.Entries.Single();
        var databaseValuesObj = entry.GetDatabaseValues().ToObject();
        var databaseValues = (Product)databaseValuesObj;
        var clientValues = (Product)entry.Entity;
        if (databaseValues.Name != clientValues.Name)
            ModelState.AddModelError("Name", "Current value: "
                + databaseValues.Name);
        if (databaseValues.Description != clientValues.Description)
            ModelState.AddModelError("Description", "Current value: "
                + String.Format("{0:c}", databaseValues.Description));
        if (databaseValues.ControllingStudentId != clientValues.ControllingStudentId)
            ModelState.AddModelError("ControllingStudentId", "Current value: "
                + String.Format("{0:d}", databaseValues.ControllingStudentId));
        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
            + "was modified by another user after you got the original value. The "
            + "edit operation was canceled and the current values in the database "
            + "have been displayed. If you still want to edit this record, click "
            + "the Save button again. Otherwise click the Back to List hyperlink.");
        product.Timestamp = databaseValues.Timestamp;
    }
    catch (DataException)
    {
        //Log the error (add a variable name after Exception)
        ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
    }

    return View(product);
}

On the var databaseValuesObj = entry.GetDatabaseValues().ToObject(); line, I get an exception like this:
System.Data.EntitySqlException was unhandled by user code
  Message=Type 'MvcApplication3.DAL.Product' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly. Near type name, line 1, column 119.
  Source=System.Data.Entity
  Column=119
  ErrorContext=type name, line 1, column 119
  ErrorDescription=Type 'MvcApplication3.DAL.Product' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly.
  Line=1
 ...

My question is, how can I show it where the Product class is?  Its in the project and I've got the using statement at the top.  Why can't it find it?
Edit:
Based on the response below, I changed my code to:
        var entry = ex.Entries.Single();
        var currentValues = entry.CurrentValues.Clone();
        entry.Reload();
        entry.CurrentValues.SetValues(currentValues);
        var clientValues = (Product)entry.Entity;
        var databaseValues = (Product)entry.OriginalValues.ToObject();

And that seemed to fix it.  But I think it will have issues if the row is deleted.  My current problem won't have that issue, so this is a good fix for me.  Thanks!

A:

This is a known issue when the context is in a different projects. No workarounds currently exist except for moving the context into the same project.
http://social.msdn.microsoft.com/Forums/en-HK/adodotnetentityframework/thread/fa67aa0e-3bca-44a5-9e00-af6362a539a7
EDIT
Actually I take that back - there is a workaround now listed there since the last time I read this. cool : )


Q:

"Indirect" isset()

function myCheck($in)
      { return isset($in); }

$var1='Something';
$var2='$var1';
$var3='$varNonExitant';

What I'm trying to achive is to use myCheck to evaluate the existance of the content like this:
myCheck($var2) return true;
myCheck($var3) return false;

A:

isset() is not really a function: it's a language construct. As such, it's allowed to do some magic that's not available to regular functions, such as being fed with non-existing variables.
To sum up: you cannot replicate it with a custom function.
Edit:
As DaveRandom pointed out in a comment below, all you can do is come close by checking if a variable isset for example:
function variable_isset(&$variable = NULL) {
    return isset($variable);
}

This approach offers two drawbacks though:

This works by passing the unset variable by reference, thus creating it when called. As it's NULL it is still not set.
It'll trigger an Undefined variable notice if the variable does not exist, ruining the whole concept of gracefully handling optional variables.

Most likely this should not be needed. So question remains why you can not use isset in the first place which would be much more needed to give you better guidance.

A:

When you cyall myCheck($abc), with set $abc = 123, it gets myCheck(123). It isn't any valid argument for isset.
You have to give the function a string with variable name:
function isset_global($variable_name)
{
    return isset($GLOBALS[$variable_name]);
}

Of course, I am also wondering, why to do this, but it answers the question as long as you check a global variable.


Q:

Cufon textShadow + hover problem

I only want the text-shadow to be on the hover state.
**JS**
Cufon.replace('.headerright', {hover: true,'fontFamily' : 'League Gothic',textShadow:'0px 1px #cccccc'});
**CSS**
.headerright{text-transform:uppercase; font-size:76px;color:#CD7674;}
.headerright a:hover{color:#444444;}

A:

Your code is defining textShadow from the get-go rather than for the hover event.
Looking at https://github.com/sorccu/cufon/wiki/styling, this should work for you:
Cufon.replace('.headerright', {
    'fontFamily': 'League Gothic',
    hover: {
        textShadow: '0px 1px #cccccc'
    }
});


Q:

how can i migrate virtuemart from VM2 to VM3?

Hello I would like to ask how is it possible to migrate VM2 to VM3. I want to update  my Joomla site from 2 to 3 and VM to be compatible.  I found only that http://docs.virtuemart.net/tutorials/installation-migration-upgrade/198-upgrade-virtuemart-2-to-virtuemart-3.html  please help I have many data on VM2 and I don't want to lose it.

A:

There are some ways to achieve that. My pattern is mostly like this.
First attempt, update all Joomla components, install VirtueMart 3 via normal installer, install Joomla 3. If that fails:
Second attempt, use Daycounts Migrator and use a fresh J3/VM3 installation on the same server to transfer files and database with the migrator. If that fails:
Third attempt, compare the databases from first attempt or second attempt and export single db tables and import with the changed column names into VM 3 db.
Use a standard template like Protostar in the beginning, change to a new template only after everything else works.
This question is not answered in one answer here, I suggest the VirtueMart forum.


Q:

Open UWP application from service

I am trying to Launch applications and processes using CreateProcessAsUser from a service I created. My attempts to open applications such as notepad, IE, etc. were successful. But I hit a roadblock when trying to open Groove Music, which is an UWP Application.
When I tried to open Groove Music from Command prompt, the folder was hidden and access was denied.
STARTUPINFO si;
PROCESS_INFORMATION pi;
LPTSTR szCmdline = _tcsdup(TEXT("C:\Program Files\WindowsApps\Microsoft.ZuneMusic_10.18102.10531.0_x64__8wekyb3d8bbwe\Music.UI.exe"));
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
HANDLE t1,t2;
OpenProcessToken(gethandle(_T("explorer.exe")), TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_ADJUST_PRIVILEGES , &t2);
DuplicateTokenEx(t2, 0, NULL, SecurityImpersonation,TokenPrimary, &t1);
CreateProcessAsUser(t1,NULL,szCmdline,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))

Is there any way to launch UWP applications from a program that I wrote? Or am I missing any apparent methods?

A:

You can do it with the IApplicationActivationManager::ActivateApplication method.
It needs to be called from a user process, so you'd have to do a two-step approach: From your service call CreateProcessAsUser to create a helper a process, which will then call ActivateApplication.


Q:

find a specific ObjectId in array of embedded docs with ref in it

This is my schema
var Schema = new Schema{
     name:String
     topics:[{item:{type: ObjectId, ref: 'tag'},comment:String}]
}

So 'topics' field contains an array of embedded docs. Each of those contains a ref and a string 'comment'.
There is a way I can find a specific ref id (the item field)?
I tried some projection but this make some sense don't you think? Obiouvsly doesn't work..:)
    Model
    .find(
        { topics: {
            $in: [{     item: ObjectId("56e0aa684e7c55c414a51d82")      }]
        }
        },{name:1})
    .exec(function(err, data) {
        res.json(data)
    });

EDIT: I came up with this solution:
           Model
            .find(
                {'topics':
                    {$elemMatch :
                        {
                            item: "56e0aa684e7c55c414a51d82"
                        }
                    }
                }
            )
    .exec(function(err, data) {
        res.json(data)
    });

A:

Please try this one
Model.find({'topics.item': "56e916772acfbbf805612555"}, {name: 1})
    .exec(function(err, data){
        if (err)
            console.log(err);
        else
            console.log(data);
    });

Test with data
{ "_id" : ObjectId("56e916772acfbbf805612559"),
  "name" : "topic1",
  "topics" : [
          { "item" : ObjectId("56e916772acfbbf805612555"),
            "comment" : "tag1",
            "_id" : ObjectId("56e916772acfbbf80561255b") },
          { "item" : ObjectId("56e916772acfbbf805612556"),
            "comment" : "tag2",
            "_id" : ObjectId("56e916772acfbbf80561255c") } ]
}

Return
[ { name: 'topic1', _id: 56e916772acfbbf805612559 } ]


Q:

The value '-1' cannot be parsed as the type 'Byte'

I have a byte Array in a string which I am trying to serialize into an object, the byte array was generated on an iPhone but the receiving service is VB.net I get the error The value '-1' cannot be parsed as the type 'Byte' when the serializer.ReadObject call is made and have managed to get c# to see the byte array as valid using
byte[] ba = new byte[] { 208, 125, 138, 15, unchecked((byte)-1), 211, 1, 74, 148, unchecked((byte)-9), 82, 10, 245, 193, 115, 64, 108, 12 };

but the unchecked element doesn't appear to exist in VB and I am pulling my hair out as to how to solve the problem.
Thanks in advance
The object is
Public Class GetVehicleListInput : Inherits BaseInput

End Class

BaseInput is
Public Class BaseInput

Private abyteExternalIdentifier As Byte() = Nothing

Public Property ExternalIdentifier() As Byte()
    Get
        Return abyteExternalIdentifier
    End Get
    Set(ByVal value As Byte())
        abyteExternalIdentifier = value
    End Set
End Property

Public Sub New()

End Sub

End Class

My Class is
Dim mystring As String = "{""ExternalIdentifier"":[208,125,138,15,-1,211,1,74,148,-9,82,10,245,193,115,64,108,12]}"
    Dim serializer As New Json.DataContractJsonSerializer(GetType(GetVehicleListInput))

    Dim thing As GetVehicleListInput
    Using stream As MemoryStream = New MemoryStream(Encoding.UTF8.GetBytes(mystring))

        thing = DirectCast(serializer.ReadObject(stream), GetVehicleListInput)
    End Using
 End Sub

A:

In .NET world, Byte values are unsigned, 8-bits integers. Therefore they are limited to be within 0 to 255.
Granted, c# does allow you to suppress the overflow checking, but even so you still won't have the -1 value stored as a Byte: the value will be 255.
You might want to use Int16 instead, although I'm not sure how this will work out with the serialization / deserialization mechanisms you're using.
Of course you also can use Plutonix's solution, but then I would wonder why you ever had to pass in -1 in the first place.


Q:

How to bind event for Canvas content?

I have Canvas panel with gradient background color, and i want to add there some buttons with png images. Using canvas is only one solution to make good transparent textured buttons. I am using create_image method but it returns int and i cant bind event to it. How can i bind event to Canvas content?
self.tab = tk.Canvas(width=xc,height=yc,bd=0, highlightthickness=0)
self.tab.pack(side=tk.BOTTOM, fill=tk.X)
bg = self.tab.create_image(xc/2, yc/2, image=self.toolbar_image)

For example i need to bind event to bg. I can't bind event to Canvas because in future there will be more buttons which i need to click.

A:

Canvas does this with tags:
tab.create_image(x, y, image=img, tags='item')
tab.tag_bind('item', '<Button-1>', click)


Q:

How to tell if forwarded inboundcalls in Twilio were missed?

I have a twilio app: When someone calls the Twilio number and forwards it to a verified phone number. I'd like to know if that forwarded call was missed.
Is this even possible? Is it possible to do  call progress events on forwarded inbound calls via Twiml? If so, what's the syntax?

A:

I work with the devangels at Twilio.
It seems like you might be looking for the 'no-answer' Status parameter as seen here: https://www.twilio.com/docs/api/rest/call#call-status-values
Also looks like you're using PHP so the syntax would be something like this for a loop of calls:
foreach ($client->account->calls->getIterator(0, 50, array(
        "Status" => "no-answer"
        )) as $call


Q:

Trouble reading this proof of characterization of continuous mappings by open sets.

Here's the first part of the proof—the part I have a question about.

Simply put, I don't see anything here precluding $x_0$ from being on the boundary of $S_0$. And if that's the case then $N_0 \not\subset S_0$. Here's a picture of what's in my brain:

I'm sure that it's somehow implied $x_0$ can't be on the boundary but I'm not seeing it for some reason. Can someone please expand on the proof? Thank you.

Note: this is from Kreyszig's Introductory Functional Analysis with Applications.

A:

The key part you are missing here is in the line

Since $T$ is continuous, $x_0$ has a $\delta$-neighborhood $N_0$ which is mapped into $\pmb N$.

Since $N$ is a subset of $S$, any subset of $\pmb X$ that is mapped into $\pmb N$ is a subset of $\pmb {S_0}$, since $S_0 = f^{-1}(S)$ is by definition the collection of points that get mapped into $S$. This is what forces the $\delta$-neighborhood to "not be on the boundary," since it must be wholly contained in $S_0$, by the definition of inverse image.


Q:

A category is discrete if and only if all its subcategories are full

I am trying prove this. It is stated on the wikipedia page about discrete categories.
One way of the proof is very easy and obvious: if a category is discrete then all its subcategories are also discrete and, hence, full (they all have the identities, wich are the only arrows in the first category. So they all have all the arrows relative to the objects in the first category).
The other way is trickier. We consider some category $C$. If all its subcategories are full, then $C$ must be discrete.
I think I can see why this must be so, but I can't state a general proof. I'm thinking this way:
Consider a category $C$ with only two objects, $a$ and $b$, and a single arrow $f: a\rightarrow b$ between them (besides the identities, of course). Then it has four subcategories, but one of them is not full, i.e., the subcategory that has both objects, but not the $f$ arrow. So it seems the only way for all subcategories of $C$ to be full is $C$ being discrete. Otherwise there will always be a discrete subcategory that is not full.
Is this reasoning correct? How can I make it more general?

A:

Consider the subcategory $D$ of $C$ which has the same set of objects and $Hom_D(X,Y)$ is empty if $X\neq Y$ and $Hom_D(X,X)=\{Id_X\}$ it is full. So $Hom_C(X,Y)=Hom_D(X,Y)$.


Q:

Getting rid of the tiny line of space below my footer image

The wooden plank with drop shadow is my footer image. The lighter shade of brown around it is my background image.
There's a tiny line of space in between the plank and the background at the bottom. I want to remove it to make the plank align exactly at the end of page.
When I tried adding border: 2px solid red to check, there's a tiny amount of padding which is causing the little space.
Are there any ways to clear it ? Thanks.
CSS:
#footerBg {
position: relative;
bottom:-63px;
left:-50px;
}

HTML:
<footer>
            <figure id="footerBg">
                <img src="images/BG_F_S3.png" alt="Footer Background" width="" height="" />

            </figure>

        </footer>

A:

Try setting display: block; in the page stylesheet for your img tag. I prefer this method, and it seems to be the most widely used.
You can also use line-height: 0; on your image container, or set vertical-align: bottom; on your img tag. I also see people suggesting that you use vertical-align: sub;, but this won't work in IE6 or IE7.
The solution will look something like this fiddle; http://jsfiddle.net/NdNGv/2/


Q:

Spring security cannot find AffirmativeBased class

Can anyone assist me with the following. I've configured spring authentication fine so - I can use spring to authenticate via a database and prevent access based on url etc... However I'm trying to implement an access decision manager and I cannot get the class it is throwing
2010-12-07 15:20:47,926 ERROR [main] FrameworkServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.ArticleController': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.security.access.vote.AffirmativeBased] for bean with name 'sgAccessDecisionManager' defined in class path resource [ScriptGang2-web-context.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.security.access.vote.AffirmativeBased
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1172)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4058)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4371)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.security.access.vote.AffirmativeBased] for bean with name 'sgAccessDecisionManager' defined in class path resource [ScriptGang2-web-context.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.security.access.vote.AffirmativeBased
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1250)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1319)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:315)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:296)
    at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:142)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:526)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:495)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:656)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:629)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:338)
    ... 33 more
Caused by: java.lang.ClassNotFoundException: org.springframework.security.access.vote.AffirmativeBased
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1271)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1242)
    ... 45 more
2010-12-07 15:20:47,926 ERROR [main] FrameworkServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.ArticleController': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.security.access.vote.AffirmativeBased] for bean with name 'sgAccessDecisionManager' defined in class path resource [ScriptGang2-web-context.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.security.access.vote.AffirmativeBased
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1172)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4058)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4371)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:516)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.security.access.vote.AffirmativeBased] for bean with name 'sgAccessDecisionManager' defined in class path resource [ScriptGang2-web-context.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.security.access.vote.AffirmativeBased
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1250)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1319)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:315)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:296)
    at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:142)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:526)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:495)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:656)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:629)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:338)
    ... 33 more
Caused by: java.lang.ClassNotFoundException: org.springframework.security.access.vote.AffirmativeBased
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1271)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1242)
    ... 45 more

And the config is:-
<?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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-2.5.xsd
      http://www.springframework.org/schema/jee
      http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
      http://www.springframework.org/schema/lang
      http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">

    <!-- ******************************************************************** -->
    <!-- This context file was generated and is not intended to be changed manually. -->
    <!-- ******************************************************************** -->

    <!-- ******************************************************************** -->
    <!-- Mark bean transactions as annotation driven -->
    <!-- ******************************************************************** -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- ******************************************************************** -->
    <!-- Bean Name View Resolver used to Redirect to Beans by id, required by Binary Content View -->
    <!-- ******************************************************************** -->
    <bean id="beanNameViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    </bean>

    <!-- ******************************************************************** -->
    <!-- Scan for all annotated beans -->
    <!-- ******************************************************************** -->
                <context:component-scan base-package="com.testit" scoped-proxy="interfaces" />

        <!-- ******************************************************************** -->
        <!-- Apply security for all beans where security was set -->
        <!-- ******************************************************************** -->
                <security:global-method-security secured-annotations="enabled" access-decision-manager-ref="sgAccessDecisionManager">
                    <security:protect-pointcut expression="execution(* com.testit..Test.*(..))" access="IS_AUTHENTICATED_REMEMBERED"/>
        </security:global-method-security>

<bean id="sgAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false" />
<property name="decisionVoters">
<list>
<bean class="org.springframework.security.vote.RoleVoter" />
<bean class="org.springframework.security.vote.AuthenticatedVoter" />
<bean class="com.testit.sgAccessVoter" />
</list>
</property>
</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
             <value>1000000000</value>
         </property>
</bean>

    <bean id="requestInterceptor"
          class="com.testit.RequestInterceptor">
    </bean>

</beans>

Any help very much appreciated.

A:

I guess you use Spring Security 2.x whereas org.springframework.security.access.vote.AffirmativeBased was moved to that package in Spring Security 3.x. In 2.x it was org.springframework.security.vote.AffirmativeBased.


Q:

Showing the $2$-sphere with antipodal points identified is homeomorphic to the upper hemisphere with antipodal points identified.

Let $S_+$ be the closed upper hemisphere of the $2$-sphere $S^2$. We can define an equivalence relation $\sim_+$ on $S_+$ as follows:
$x\sim_+ y\:\:\Leftrightarrow\:\:\begin{cases}x=x^\prime,&\text{ or}\\x,\,x^\prime\in\partial S_+\text{ and }x=-x^\prime.\end{cases}$
In other words, we identify antipodal points on the equator of $S_+$. We also have the equivalence relation $\sim$ on $S^2$ in which $x\sim y$ iff $x=y$ or $x=-y$. I want to show $S^2/\sim$ is homeomorphic to $S_+/\sim_+$. Here is what I have done so far:
First, we observe there is an inclusion $i:S_+\hookrightarrow S^2$ of the upper hemisphere $S_+$ into the whole $2$-sphere $S^2$. We also have the canonical maps to the quotient spaces given by $p:S_+\to(S_+)/\sim_+$ and $\pi:S^2\to S^2/\sim$. The map I am going to use is the map $\pi\circ i:S_+\to S^2/\sim$.
Now, we observe that any line through the origin intersects $S^2$ at two points. If we are in the upper hemisphere, then there is one unique intersection, while on the equator there are two points in the (closed) upper hemisphere. In $S^2/\sim$ we are identifying antipodal points, and for each pair of antipodal points, at least one belongs to $S_+$. It is therefore clear that $\pi\circ i$ is surjective. It is also continuous, since it is the composition of continuous functions.
Next, suppose $x\sim_+ y$, then either $x=y$, or $x,\,y$ are antipodal points on the boundary. In either case, $\pi\circ i(x)=\pi\circ i(y)$. Conversely, if $\pi\circ i(x)=\pi\circ i(y)$, then $x,\,y$ are antipodal points, or equal. Since both belong to the (closed) upper hemisphere, we therefore conclude $x\sim_+ y$. So $\pi\circ i$ respects $\sim_+$. By the universal property, there exists a bijection $\varphi:(S_+)/\sim_+\to S^2/\sim$. It therefore remains to show $\varphi$ has a continuous inverse. I suppose I could just do a similar argument, but starting from the map $q:S^2\to S_+$, but I thought it might be neater to show $\pi\circ i$ is an open map, i.e. sends open maps to open maps.
With this in mind, let $U$ be open in $S_+$. Then am I right in saying that $U$ is simply the open ball of a point of $S_+$ that does not lie on the boundary (the equator)? If so, then $i(U)=U$ is also open in $S^2$ and hence $\pi\circ i(U)$ is open in $S^2/\sim$. It is then certainly true that $\varphi$ is a homeomorphism. Is this all alright?

A:

There's an inclusion map $i:S_+\to S^2$. This induces a continuous
map $i':{S_+/\sim}\to {S^2/\sim}$. As you point out, this is bijective.
But both sides are compact Hausdorff spaces, and a continuous bijection
between compact Hausdorff spaces is necessarily a homeomorphism
(prove that it's a closed map).


Q:

mysql: stored function call + left join = very very slow

I have two tables:
module_339 (id,name,description,etc)
module_339_schedule(id,itemid,datestart,dateend,timestart,timeend,days,recurrent)

module_339_schedule.itemid points to module_339
fist table holds conferences
second one keeps the schedules of the conferences
module_339 has 3 items
module_339_schedule has 4000+ items - almost evenly divided between the 3 conferences

I have a stored function - "getNextDate_module_339" - which will compute the "next date" for a specified conference, in order to be able to display it, and also sort by it - if the user wants to. This stored procedure will just take all the schedule entries of the specified conference and loop through them, comparing dates and times. So it will do one simple read from module_339_schedule, then loop through the items and compare dates and times.
The problem: this query is very slow:
SELECT
distinct(module_339.id)
,min( getNextDate_module_339(module_339.id,1,false)) AS ND
FROM
module_339
LEFT JOIN module_339_schedule on module_339.id=module_339_schedule.itemid /* standard schedule adding */
WHERE 1=1 AND module_339.is_system_preview<=0
group by
module_339.id
order by
module_339.id asc

If I remove either the function call OR the LEFT JOIN, it is fast again.
What am I doing wrong here? Seems to be some kind of "collision" between the function call and the left join.

A:

I think the group by part can be removed from this query, thus enabling you to remove the min function as well. Also, there is not much point of WHERE 1=1 AND..., so I've changed that as well.
Try this:
SELECT DISTINCT module_339.id
               ,getNextDate_module_339(module_339.id,1,false) AS ND
FROM module_339
LEFT JOIN module_339_schedule ON module_339.id=module_339_schedule.itemid /* standard schedule adding */
WHERE module_339.is_system_preview<=0
ORDER BY module_339.id

Note that this might not have a lot of impact on performance.
I think that the worst part performance-wise is probably the getNextDate_module_339 function.
If you can find a way to get it's functionallity without using a function as a sub query, your sql statement will probably run alot faster then now, with or without the left join.
If you need help doing this, please edit your question to include the function and hopefully I (or someone else) might be able to help you with that.


Q:

How to output a view hierarchy & contents to file?

I'm writing a glorified 'paint' application where a user can paste in images, and draw a bunch of UIBezier curves, and move all these things around and rotate them.
Most of these are implemented by stacking UIImageViews and (sub-classed) UIViews as subviews onto the main view in the view controller.
I want the user to be able to save the state of their creation as some kind of  file and share it with others (e.g. via DropBox).
The saving itself isn't the issue (I know how to save files!), just the 'best' way to get all the information from the app into file(s) and then load it back in.
I'm guessing there are already well-established frameworks for doing exactly this, but oddly, haven't found anything that addresses this.
So, before I set about writing my own custom methods for doing all this, I thought I'd ask:
Is there some recommended, approved (and maybe even 'easy' ;-)) way to implement saving -- as in writing to files -- the state of all the subviews of a given UIView?
Your recommendations for what I'm "trying to do"?   Thanks.

A:

tl;dr
Going Down:NSKeyedArchiver.archiveRootObject(view, toFile: "/path/to/archive")
Coming Up:let view = NSKeyedUnarchiver.unarchiveObjectWithFile("/path/to/archive")
)
UIView conforms to  NSCoding

NSCoding enables the creation of archives, which

provide a means to convert objects and values into an architecture-independent stream of bytes.

Now we have all the pieces to the puzzle, let's put them together:
We know we're going to need an archiver, so let's search the docs until we find something promising:

Bingo! NSKeyedArchiver
Let's use this class to serialize a UIView to a file with archiveRootObject:toFile:. Then we'll deserialize it from a file with unarchiveObjectWithFile:.
Saving to file:NSKeyedArchiver.archiveRootObject(view, toFile: "/path/to/archive")
Reading from file: let view = NSKeyedUnarchiver.unarchiveObjectWithFile("/path/to/archive")


Q:

What are the guidelines and regulations for building a helipad for multiple aircraft?

Are there any guidelines and regulations governing the ownership and construction of a multiple aircraft type helipad in
a) the USA
b) Europe?

A:

The FAA publishes an Advisory Circular on heliport design.  It applies to heliports serving helicopters with a single rotor.  I don't believe that there are any regulations regarding "ownership".  They just have to be operated in compliance with appropriate FAA, state and local regulations (but these can get complicated)


Q:

Extending a measure

I need help with the following:
Let $(X, \mathcal{A}, \mu)$ be finite measure space and $D \subseteq X$ such that $D \notin \mathcal{A}$.
a) Check that $\sigma(\mathcal{A} \cup \{D\})=\mathcal{A}_D:=\{(A\cap D) \cup (B \cap D^C): A, B \in \mathcal{A}\}.$
b) Show for a set $E \in \mathcal{A}_D$ with representation $E=(A \cap D) \cup (B \cap D^C)$ that $\mu_D(E):=\mu(A \cap M) + \mu(B \cap M^C)$ is well-defined (although $A,B,M$ are not necessarily unique), where $M \in \mathcal{A}$ is a measurable hull of D, so $D \subseteq M$ and $\mu^*(D)=\mu^*(M)$ and $\mu^*$ is the outer measure generated by $\mu$.
c) Show that $\mu_D: \mathcal{A}_D \rightarrow [0, \infty]$ is a measure with $\mu_D(D)=\mu^*(D)$ which extends $\mu$.
For (a), I thought that "$\supseteq$" is clear and for "$\subseteq$" I shouwed for exapmle:
$$\bigcup_i ((A_i \cap D) \cup (A_i' \cap D^C))=((\bigcup_i A_i \cap D) \cup (\bigcup_i A_i') \cap D^C))$$
where the right hand side is contained in $\mathcal{A}_D$. The same can be shown for the intersection or for taking complements.
For (b), we had the proposition, that $\forall D \subseteq X \text{ } \exists M \in \mathcal{A}: D \subseteq M \text{ and } \mu^*(D)=\mu^*(M)$. Can I use this to show the claim of b?
Can someone help me or give me a hint?

A:

Your solution for (a) seems good. The basic idea is to show that: every element of $\mathcal{A}_D$ belongs to $\sigma(\mathcal{A}\cup\left\{D\right\})$ (which gives the inclusion $\supseteq$), and that $\mathcal{A}_D$ is indeed a $\sigma$-algebra containind $\mathcal{A}$ and $D$ (which gives the inclusion $\subseteq$).
For (b), you note that $\mu_D(E)$ depends on $A$, $B$ and $M$. In the very definition of $\mu_D$, you are already using the result of existence of a measurable hull, so you shouldn't really worry about that.
Now, to solve (b), I think the easier way is to first prove a lemma, which is basically the case where $M=X$.

Lemma: Let $(Y,\mathcal{M},\mu)$ be a finite measure space and $E\subseteq X$ be a subset with $\mu^*(E)=\mu(X)$. Consider the $\sigma$-algebra $\mathcal{M}_E=\left\{A\cap E:A\in\mathcal{M}\right\}$. Then $\mu^*(A\cap E)=\mu(A)$ for all $A\in\mathcal{A}$, hence the mapping $\mu_E(A\cap E)=\mu(A)$ ($A\in\mathcal{M}$) is well-defined, and it is a measure on $\mathcal{M}_E$.
Proof: Let $A\in\mathcal{M}$. Given any covering $\left\{C_n\right\}_{n=1}^\infty$, $C_n\in\mathcal{M}$, of $A\cap E$ (i.e., $A\cap E\subseteq \bigcup_n C_n$), then $\left\{C_n\right\}\cup\left\{Y\setminus A\right\}$ covers $E$, hence, by definition of the outer measure $\mu^*$,
$$\mu(Y)=\mu^*(E)\leq\mu(Y\setminus A)\sum_n \mu(C_n)=\mu(Y)-\mu(A)+\sum_n\mu(C_n),$$
so $\mu(A)\leq\sum_n\mu(C_n)$. Taking the infimum on the coverings $\left\{C_n\right\}$, we obtain $\mu(A)\leq \mu^*(A\cap E)$, and the reverse inequality is clear.
Hence, the mapping $\mu_E(A\cap E)=\mu^*(A\cap E)=\mu(A)$ is well-defined, clearly $\mu_E(\varnothing)=0$ and, if $\left\{A_n\right\}$ is a sequence of elements of $\mathcal{M}$ with the $A_n\cap E$ disjoint, then
\begin{align*}
\mu_E\left(\bigcup_{n=1}^\infty A_n\cap E\right)&=\mu\left(\bigcup_{n=1}^\infty A_n\right)=\mu\left(\bigcup_{n=1}^\infty (A_n\setminus \bigcup_{j=1}^{n-1} A_j)\right)\\
&=\sum_{n=1}^\infty \mu\left(A_n\setminus\bigcup_{j=1}^{n-1}A_j\right)=\sum_{n=1}^\infty\mu_E\left((A_n\setminus\bigcup_{j=1}^{n-1}A_j)\cap E\right)\\
&=\sum_{n=1}^\infty\mu_E\left((A_n\cap E)\setminus\bigcup_{j=1}^{n-1}(A_j\cap E)\right)=\sum_{n=1}^\infty \mu_E(A_n\cap E),
\end{align*}
so $\mu_E$ is a measure. Q.E.D.

(b) Here we should take a little care: Let $\mathcal{A}_M=\left\{A\in\mathcal{A}:A\subseteq M\right\}$. Note that $\mu$ restricted to $\mathcal{A}_M$ is a measure, which I'll denote $\mu_M$. The outer measure (on $M$) induced by $\mu_M$ is simply the outer measure $\mu^*$ restricted to subsets of $M$. If this is not clear, you should check this. This fact allows us to use the lemma above.
Let's show that $\mu_D$ as in the question independs on $A$ and $B$ (but at first we consider some measurable hull $M$ fixed). Suppose that $A,B,A',B'$ are sets in $\mathcal{A}$ with
$$(A\cap D)\cup(B\setminus D)=(A'\cap D)\cup(B'\setminus D).$$
If we take intersection with $M^c$ in the equality above, we obtain $B\setminus M=B'\setminus M$. On the other hand, if we intersect the equality above with $D$, we obtain $A\cap D=A'\cap D$. From the lemma, (with $D$ in place of $E$ and $M$ in place of $Y$),
$$\mu(A\cap M)=\mu^*(A\cap M\cap D)=\mu^*(A\cap D)=\mu^*(A'\cap D)=\cdots=\mu(A'\cap D)$$
therefore $\mu(A\cap M)+\mu(B\setminus M)=\mu(A'\cap M)+\mu(B'\setminus M)$, so $\mu_D$ independs of $A$ and $B$.
Now, suppose we had another measurable hull $M'$ of $D$. Then $M\cap M'$ covers $D$, hence
$$\mu(M)=\mu^*(D)\leq\mu(M\cap M')=\mu\left(M\setminus(M\setminus M')\right)=\mu(M)-\mu(M\setminus M')$$
so $\mu(M\setminus M')=0$. For all $A\in\mathcal{A}$,
$$\mu(A\cap M)=\mu(A\cap M\cap M')+\mu((A\cap M)\setminus M')\leq\mu(A\cap M')+\mu(M\setminus M')=\mu(A\cap M'),$$
and simetrically $\mu(A\cap M')\leq\mu(A\cap M)$. Similarly you show that $\mu(B\setminus M)=\mu(B\setminus M')$ for all $B\in\mathcal{A}$. This shows that $\mu_E$ also independs of $M$.
I'm just going to give some hints on part (c): If $\left\{(A_i\cap D)\cup(B_i\setminus D)\right\}$ is a disjoint family in $\mathcal{A}_D$, then the $(A_i\cap D)$ are all disjoint, and the $(B_i\setminus D)$ are also disjoint. You should use the equality you proved on item (a) to write the union as an element of $\mathcal{A}_D$. Using the lemma, you can obtain $\mu(\bigcup A_i\cap M)=\sum_i\mu(A_i\cap M)$. The analysis of the $B_i$'s is easier. Putting all together, you'll conclude that $\mu_D$ is a measure.


Q:

Getting true width of a nested DIV using jQuery?

In my sample page: http://j25.wasen.net/modules/mod_simplefilelisterv2.0/index.html
I have added a DIV as a wrapper at 200px wide.
I use jQuery to try and detect the width of DIV's inside this DIV but they all come out as 200px wide also even though they are wider (or narrower).
I have tried several different techniques found here at the site but all has failed this far... How can I get the TRUE width of the DIV's in the wrapper?

A:

Use display: inline-block as a style for the divs. At the moment display: block will make the divs as big as their parent while the tags inside are have a display value of inline.


Q:

How accurate is Bitcoin network time?

Have any observations been made to conclude the accuracy of Bitcoin network time?
It would be interesting to know if NIST or any other authority has tracked the phenomenon.

A:

From this blog post describing the timejacking attack:

Each node internally maintains a counter that represents the network time. This is based on the median time of a node's peers which is sent in the version message when peers connect. The network time counter reverts to the system time however if the median time differs by more than 70 minutes from the system time. A very reasonable way to estimate the median network time.

So block timestamps are based on "network time" which is in turn one of:

The median time advertised by peers (if between ±70 minutes from system time)
System time

The network time is used to validate new blocks. As a precaution, nodes reject any block timestamp that is greater than 2 hours from the current network time. Block timestamps that are earlier than the median time of the past 11 blocks are also rejected. This validation puts upper and lower bounds on the acceptable range of block timestamps.

So block timestamps are:

< 2 hours from "network time".
> median of last 11 blocks.

I have to refresh my error propagation lessons, but I guess this leads to an accuracy at around ±3 hours.
Of course this is just an upper bound on error, but the actual question remains: what is the real blockchain accuracy? (which is a very interesting question.) The only way to be sure is actually tracking it and comparing with a known perfect timestamp. I don't know if anyone has ever done that before and couldn't find any references.


Q:

What did Stitch say when he laughed after the arrival?

What did Stitch say when he laughed after the arrival in this scene:

A:

This transcript says it's just alien language

Maybe send me an angel...
  the nicest angel you have.
  (flames roaring)
  (shouting in alien language)
  (laughing maniacally)

According to the quotes on IMDB

Stitch: Poocha Chubugga Oom Chickee! Ha ha ha ha ha ha ha ha ha!

The alien language is used many times in the movie, but it's never translated. Most times we can guess the meaning by the situation or other people's reaction.
I have looked online, where people have made translations for the language, called Tantalog, but I couldn't find anything for this phrase or any of the words.

A:

The language Stitch speaks is Tantalog. It is a combination of Hawaiian, Chinese and Chezcreekian.
I think he is saying something along the line of "I came, I saw, and I conquered."
I don't know the exact meaning, but here are some dictionaries:
http://disneydestiny.proboards.com/thread/202/stitch-language
https://cavemanboo.deviantart.com/art/Stitch-s-Vocabulary-290229838


Q:

Convert columns into rows when importing .csv

I'm looking for an efficient way to use read.csv (or an alternative) when reading a .csv file that has 100,000s columns and virtually a single row.
The file with this structure is extracted from MATLAB which seems to prefer to add millions of rows rather than columns. When opening the file in Excel it does not load completely so I cannot simply transpose.
The following works in r, still slowly, but I'm wondering if there is a better way?
library(data.table)
dfr <- as.data.frame(t(fread('filename.csv')))

A:

If there is only a single row, we can read it with scan and convert to data.frame
data.frame(Col=scan('filename.csv', skip=1, what=numeric(), sep=','))


Q:

zip a list of files at command-line linux

If I have a list of files I want to zip, how can I pass the list to zip?
cookbook/application/views/index.php
cookbook/application/controller/index.php
cookbook/js/index.js
....
cookbook/css/index.css

To do the above list one by one at the command-line would be like zip -r my.zip cookbook/css/index.css, where my.zip is in the same root directory as cookbook

A:

Try
zip -r@ my.zip < listfile

The -@ flag tells zip to read file names from stdin.