How multiple join to the same table with other table?

Question: I am not sure of the question title!, but i have this problem
 table1
   id    |  from  |  to
   1         A       B
   2         C       A
   3         B       A

 table2
   id    |  table1_id
   1         1
   2         1
   3         1
   4         3
   5         3
   6         2
   7         2
   8         2

I need to get data from table1 considering rows with ids (2,3) as one row and joined with table2
 fetch the last id between them which is 5
the result
   id    |  from     |   to     |   table2_id
   3         B       |    A     |    5
   2         C       |    A     |    8

Comment: You show id 1, but id 3's from/to. Is this correct?
Comment: Are 1 and 3 considered the same because they have the same from/to, just reversed?
Comment: This is not clear. Use enough words, sentences & references to parts of examples to clearly & fully say what you mean. When giving a business relation(ship)/association or table (base or query result), say what a row in it states about the business situation in terms of its column values. Show what you are able to do. Please don't ask us to write your code. See [ask], other [help] links, hits googling 'stackoverflow homework' & the voting arrow mouseover texts.
Comment: Please in code questions give a [mre]--cut & paste & runnable code; example input (as initialization code) with desired & actual output (including verbatim error messages); tags & versions; clear specification & explanation. For errors that includes the least code you can give that is code that you show is OK extended by code that you show is not OK. (Debugging fundamental.) For SQL that includes DBMS & DDL, which includes constraints & indexes & tabular initialization.
Comment: @MariaNazari If you notice an inconsistency, don't presume to know what the correct version is & edit, comment to the post owner about it. Your edit should not have been approved.
Comment: Sorry guys, it is a chat system that have two tables `conversation` which has fields `id, from_user, to_user` and `messages` that has `id, conversation_id, text, created_at`, and I am using `codeigniter` so I need `SQL QUERY` to list all conversation of specific user that shows last text message between that user and the others.
Comment: I am half away though, I get this `query`
   `SELECT messages.*, conversation.to_user, conversation.from_user
            FROM messages
            JOIN conversation ON (conversation.id = messages.conversation_id AND (conversation.from_user='.$this->user_id.'  OR conversation.to_user='.$this->user_id.'))
            WHERE messages.id IN (
                        SELECT MAX(id)
                        FROM messages
                        GROUP BY conversation_id
                    )
            )`
Answer: As you have not mentioned database, I have written SQL in SQL Server
WITH TAB_FLAT AS
(
SELECT TAB_1.table1_id , COALESCE ( TAB_2.table2_id , TAB_1.table2_id ) max_id , TAB_1.table2_id FROM
( select table1_id , max(id) table2_id from table2 group by table1_id ) TAB_1
LEFT JOIN
( select table1_id , max(id) table2_id from table2 group by table1_id ) TAB_2
ON TAB_1.table2_id = TAB_2.table1_id
)
select TAB_FLAT.table1_id AS ID, COALESCE(C.frm ,COALESCE(B.frm,A.frm) ) AS 'FROM' ,
COALESCE(C.to2 ,COALESCE(B.to2,A.to2) ) AS 'TO' ,
TAB_FLAT.max_id AS table2_id
FROM TAB_FLAT
LEFT JOIN table1 A ON A.id = TAB_FLAT.table1_id
LEFT JOIN table1 B ON B.id = TAB_FLAT.table2_id
LEFT JOIN table1 C ON C.id = TAB_FLAT.max_id
WHERE  TAB_FLAT.table1_id IN (1,2)

Demo --> https://rextester.com/DCHUN74655
Explanation:
SELECT TAB_1.table1_id , COALESCE ( TAB_2.table2_id , TAB_1.table2_id ) max_id , TAB_1.table2_id FROM
( select table1_id , max(id) table2_id from table2 group by table1_id ) TAB_1
LEFT JOIN
( select table1_id , max(id) table2_id from table2 group by table1_id ) TAB_2
ON TAB_1.table2_id = TAB_2.table1_id

We are doing a self left join to get the largest table 2 ID for each table 1 ID
AND corresponding intermediate level.
select TAB_FLAT.table1_id AS ID, COALESCE(C.frm ,COALESCE(B.frm,A.frm) ) AS 'FROM' ,
COALESCE(C.to2 ,COALESCE(B.to2,A.to2) ) AS 'TO' ,
TAB_FLAT.max_id AS table2_id
FROM TAB_FLAT
LEFT JOIN table1 A ON A.id = TAB_FLAT.table1_id
LEFT JOIN table1 B ON B.id = TAB_FLAT.table2_id
LEFT JOIN table1 C ON C.id = TAB_FLAT.max_id

We are joining to table 1 based on table1 id , intermediate id and largest  id
WHERE  TAB_FLAT.table1_id IN (1,2)

Filtering out records with ID = 1 or 2
Answer: First, write a query to get each row's max ID in table 2.
select t1.*, max(t2.id) as table2_id
from table2 t2
join table1 t1 on t2.table1_id = t1.id
group by t1.id

Then use that as a CTE for two queries. One to get all the rows except 1 and 3. And one to get 1 or 3, whichever has a greater table2_id. union them together.
with max_table2 as (
  select t1.*, max(t2.id) as table2_id
  from table2 t2
  join table1 t1 on t2.table1_id = t1.id
  group by t1.id
)
select *
from max_table2
where id not in (1,3)
union
(
  select *
  from max_table2
  where id in (1,3)
  order by table2_id desc
  limit 1
)

If the combined 1/3 row must have the ID of 1, despite 3 having the larger table2_id, this can be done by hard coding the ID in the select query.
with max_table2 as (
  select t1.*, max(t2.id) as table2_id
  from table2 t2
  join table1 t1 on t2.table1_id = t1.id
  group by t1.id
)
select *
from max_table2
where id not in (1,3)
union
(
  select 1 as id, "from", "to", table2_id
  from max_table2
  where id in (1,3)
  order by table2_id desc
  limit 1
)

Try it.

I suspect rather than hard coding rows 1 and 3, you're actually counting them as equivalent because they have the same path, just reversed. We can make this query more generic.
First, normalize the from/to so they're in the same order. While we're at it, also get their max table2 id.
select
  t1.id,
  case when "from" < "to" then "from" else "to" end as "from",
  case when "from" < "to" then "to" else "from" end as "to",
  max(t2.id) as max_table2_id
from table2 t2
join table1 t1 on t2.table1_id = t1.id
group by t1.id

id  from    to  max_table2_id
2   A       C   8
3   A       B   5
1   A       B   3

Then rank the paths with the same from/to.
with normalized_max_table2 as (
select
  t1.id,
  case when "from" < "to" then "from" else "to" end as "from",
  case when "from" < "to" then "to" else "from" end as "to",
  max(t2.id) as table2_id
from table2 t2
join table1 t1 on t2.table1_id = t1.id
group by t1.id
)
select *,
  rank() over (partition by "from", "to" order by table2_id desc) as "rank"
from normalized_max_table2

id  from    to  table2_id   rank
3   A       B   5           1
1   A       B   3           2
2   A       C   8           1

And, finally, select only the first ranks.
with normalized_max_table2 as (
select
  t1.id,
  case when "from" < "to" then "from" else "to" end as "from",
  case when "from" < "to" then "to" else "from" end as "to",
  max(t2.id) as table2_id
from table2 t2
join table1 t1 on t2.table1_id = t1.id
group by t1.id
),
ranked_max_table2 as (
  select *,
    rank() over (partition by "from", "to" order by table2_id desc) as "rank"
  from normalized_max_table2
)
select id, "from", "to", table2_id
from ranked_max_table2
where "rank" = 1

id  from    to  table2_id
3   A       B   5
2   A       C   8

That's a long-hand way of doing it. There may be a more compact way.
Try it.


Capistrano/RVM rake not found

Question: I'm trying to deploy the first rails application using Capistrano.
I'm getting an error while capistrano tries to run rake db:migrate.
To be more clear this is the traceback of the exception:
[ip] executing command
*** [err :: ip] bash: rake: command not found
command finished in 124ms
failed: "env RAILS_ENV=production bash -c 'cd /home/deployer/website/current && rake RAILS_ENV=production  db:migrate'" on ip

And this is the config/deploy.rb I'm using actually. On the server I've installed RVM (single user installation).
# config/deploy.rb
$:.unshift(File.expand_path('./lib', ENV['rvm_path']))

require "rvm/capistrano"

set :scm,             :git
set :repository,      "email@example.com:user/project.git"
set :branch,          "origin/master"
set :migrate_target,  :current
set :ssh_options,     { :forward_agent => true }
set :rails_env,       "production"
set :deploy_to,       "/home/deployer/website"
set :normalize_asset_timestamps, false
set :rvm_type, :user  # Don't use system-wide RVM
set :rvm_ruby_string, "ruby-1.9.3-p194@global"

set :user,            "deployer"
set :group,           "staff"
set :use_sudo,        false

role :web,    "IP"
role :app,    "IP"
role :db,     "IP2", :primary => true

set(:latest_release)  { fetch(:current_path) }
set(:release_path)    { fetch(:current_path) }
set(:current_release) { fetch(:current_path) }

set(:current_revision)  { capture("cd #{current_path}; git rev-parse --short HEAD").strip }
set(:latest_revision)   { capture("cd #{current_path}; git rev-parse --short HEAD").strip }
set(:previous_revision) { capture("cd #{current_path}; git rev-parse --short HEAD@{1}").strip }

default_environment["RAILS_ENV"] = 'production'

default_run_options[:shell] = 'bash'

namespace :deploy do
  desc "Deploy your application"
  task :default do
    update
    restart
  end

  desc "Setup your git-based deployment app"
  task :setup, :except => { :no_release => true } do
    dirs = [deploy_to, shared_path]
    dirs += shared_children.map { |d| File.join(shared_path, d) }
    run "#{try_sudo} mkdir -p #{dirs.join(' ')} && #{try_sudo} chmod g+w #{dirs.join(' ')}"
    run "git clone #{repository} #{current_path}"
  end

  task :cold do
    update
    migrate
  end

  task :update do
    transaction do
      update_code
    end
  end

  desc "Update the deployed code."
  task :update_code, :except => { :no_release => true } do
    run "cd #{current_path}; git fetch origin; git reset --hard #{branch}"
    finalize_update
  end

  desc "Update the database (overwritten to avoid symlink)"
  task :migrations do
    transaction do
      update_code
    end
    migrate
    restart
  end

  task :finalize_update, :except => { :no_release => true } do
    run "chmod -R g+w #{latest_release}" if fetch(:group_writable, true)

    # mkdir -p is making sure that the directories are there for some SCM's that don't
    # save empty folders
    run <<-CMD
      rm -rf #{latest_release}/log #{latest_release}/public/system #{latest_release}/tmp/pids &&
      mkdir -p #{latest_release}/public &&
      mkdir -p #{latest_release}/tmp &&
      ln -s #{shared_path}/log #{latest_release}/log &&
      ln -s #{shared_path}/system #{latest_release}/public/system &&
      ln -s #{shared_path}/pids #{latest_release}/tmp/pids &&
      ln -sf #{shared_path}/database.yml #{latest_release}/config/database.yml
    CMD

    if fetch(:normalize_asset_timestamps, true)
      stamp = Time.now.utc.strftime("%Y%m%d%H%M.%S")
      asset_paths = fetch(:public_children, %w(images stylesheets javascripts)).map { |p| "#{latest_release}/public/#{p}" }.join(" ")
      run "find #{asset_paths} -exec touch -t #{stamp} {} ';'; true", :env => { "TZ" => "UTC" }
    end
  end

  desc "Zero-downtime restart of Unicorn"
  task :restart, :except => { :no_release => true } do
    run "kill -s USR2 `cat /tmp/unicorn.my_site.pid`"
  end

  desc "Start unicorn"
  task :start, :except => { :no_release => true } do
    run "cd #{current_path} ; bundle exec unicorn_rails -c config/unicorn.rb -D"
  end

  desc "Stop unicorn"
  task :stop, :except => { :no_release => true } do
    run "kill -s QUIT `cat /tmp/unicorn.my_site.pid`"
  end

  namespace :rollback do
    desc "Moves the repo back to the previous version of HEAD"
    task :repo, :except => { :no_release => true } do
      set :branch, "HEAD@{1}"
      deploy.default
    end

    desc "Rewrite reflog so HEAD@{1} will continue to point to at the next previous release."
    task :cleanup, :except => { :no_release => true } do
      run "cd #{current_path}; git reflog delete --rewrite HEAD@{1}; git reflog delete --rewrite HEAD@{1}"
    end

    desc "Rolls back to the previously deployed version."
    task :default do
      rollback.repo
      rollback.cleanup
    end
  end
end

def run_rake(cmd)
  run "cd #{current_path}; #{rake} #{cmd}"
end

How can I make this run properly?
Of course I already tried to run rake on the server, and it is found properly.
Thanks
Comment: also make sure you remove `$:.unshift(File.expand_path('./lib', ENV['rvm_path']))` as the message should warn you already
Answer: you break rvm/capistrano integration by adding this line:
default_run_options[:shell] = 'bash'

You need to remove it.
Also I see a lot of over-engineering in your script, please check my example script which I run from time to time to confirm RVM works as expected:
https://github.com/mpapis/ad/blob/master/config/deploy.rb
Comment: I downloaded it from a tutorial online since it's the 1st time I ever run capistrano. I like your script, it seems much simpler (and I like it). I was scared by have to write each time all that file from scratch... Maybe it could take less lines to do it using plain scp, git and remote shell.

Capistrano/RVM rake not found


Add custom styles for printing taxonomy terms

Question: I'm using print module for generating a PDF file. Here, the node that I'm printing has a field that lists all the taxonomy terms for that specific node.
When the page is printed, the taxonomy terms are displayed in an unordered list with bullets, leaving an empty line between field name and taxonomy terms as:
Field name:

 - term1
 - term2

But, I wish to display the terms next to field name in the generated pdf. I tried using taxonomy menu module, but i anticipate it doesn't work with print module. Is there any way to get this done.
Answer: If you go to the display settings for your node (eg. admin/structure/types/manage/article/display) and in the "Custom display settings" fieldset check the box for "Print" and the save.
Then click the tab for the "Print" display settings.
Then configure your field with an inline label.
If this is not sufficient for your requirements you could also then override node or field templates specifically for that print display mode.
I can provide more information on that if you require it.
For node and field templates you can either use an if statement in the template to specify a specific view mode or you can add specific template suggestions so that you can have specific templates, like node--print.tpl.php
For the if statement method there are variables already available in those tempaltes:
node.tpl.php
<?php if ($view_mode == 'print'): ?>
  Your code goes here.
<?php endif; ?>

field.tpl.php
<?php if ($element['#view_mode'] == 'print'): ?>
  Your code goes here.
<?php endif; ?>

Or you can add template suggestions like this in your template.php file:
node.tpl.php
/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_node(&$vars) {
  // Template suggestions for node--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['view_mode'];
  // Template suggestions for node--NODE-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__' . $vars['view_mode'];
}

field.tpl.php
/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_field(&$vars) {
  $element = $vars['element'];

  // Template suggestions for field--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_type'] . '__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-NAME--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_name'] . '__' . $element['#view_mode'];
}

Those are examples. You can make other suggestions based on pretty much anything you want.
You can also just do a specific template suggestion for the print view mode instead of doing dynamic ones for all view modes like the above examples.
If using the above examples be careful that you don't have conflicts, for example if you have a node type that is the same as a view mode.
Comment: How can i override node or field templates? Do i need to create something like node--print.tpl.php
Comment: I added examples above.


Polymorphic inline model forms in django

Question: I have a Person model which has many Animal models as pets. Dog is an Animal with a "favorite bone" field, and Cat is an Animal with a "likes catnip?" field and a "favorite fish" field.
<code>#models
class Person(db.model):
   pass

class Animal(db.model):
   models.ForeignKey(Person) #owner
   name = CharField()

class Dog(Animal):
   favorite_bone = CharField()

class Cat(Animal):
    favorite_fish = CharField()
    likes_catnip = BooleanField()
</code>
I would like to inline edit all of a Persons pets, in the Person admin form however, I've read that Django inline admin forms don't support polymorphic inline forms[1], in that, you will only get the parent class fields (e.g. not the favorite_bone or favorite_fish and likes_catnip fields.
Where does this problem come from?
What changes could be made to the framework to accommodate this?
If these changes should not be made, why not?
[1] http://email@example.com/msg66410.html
Comment: +1: good question.do you have posted it on djangos 'bug'tracker?
Answer: (This is an old question, but I thought I'd add an answer in case it is still useful.  I've been working on a similar question recently.)
I believe it would be challenging to change Django form-generation to do what you want.  The reason is that the inline formset uses a single class/form for all rows of the inline -- there are no configuration options that are evaluated per-row of the inline form.  I have convinced myself of this by reading the code itself --- look for "inline" and "formset" in django.contrib.admin.options.py, especially lines 1039-1047 (version 1.5.1).   This is also the reason why you can't have some fields read-only in existing items and changeable in new items (see this SO question, for example).
The workarounds found for the readonly case have involved a custom widget that produces the desired behavior such as this one.  That still won't directly support polymorphism, however.   I think you would need to end up mapping your divergent types back to a common ancestor (e.g. have all pet classes able to return a dict of their unique attributes and values), and then create a single custom widget that renders out the polymorphic part for you.  You'd then have to map the values back on save.
This might be more challenging than it is worth, and may lead back to the suggestion in the other answer to not use admin for this :-)
Answer: may have a look here.
but i think the modeladmin is currently not able todo such things.
you are able to create a custom edit view for your model...
there is almost everything possible.
Answer: It may be possible to do this with Generic Relations.
Comment: generic relations does not fit here.they help to associate models via contenttypes.


Hosted file is downloaded damaged by IE

Question: I have a ZIP file hosted via Apache with Akamai as CDN, the problem is when trying to download it with IE (and just IE) it is damaged and I'm unable to open it.
Since the problem occurs in other computers in different locations I've discarded network settings (firewall, proxy, etc).
I don't even know where start to look? What would be a possible cause for this to happen?
UPDATE
I'm trying to solve the problem in the server (or CDN), I've verified it's not a client error
Comment: Which version of IE? Have you tried doing a binary diff on what IE downloads vs. the original file?
Comment: How did you confirm that the original file was not damaged?
Comment: I downloaded by SSH directly from the server and with Firefox it downloads fine
Comment: What size is the file?
Comment: It's about 30MB
Answer: First thing I'd suggest is to try opening the "zip" file in notepad or your favorite plain text editor. You may find that IE has an HTML page instead of a zip file (you'll need to read the page to see why)
Comment: Why is this a -? This has happened to me quite a few times, especially with incorrect content-type headers
Comment: In fact, FireFox is actually a horrible offender of this, but the other way around. If the content-type is not set correct (or missing) it dumps a .html extension onto the end of the download, doesn't tell you about it, and then you're stumped as to why when you open your ZIP file you get a webpage full of gobbeldygook
Comment: Thanks, the content-type is fine. I tried what you told me though

Hosted file is downloaded damaged by IE


Let Z:G->H be a group Homomorphism and g an element of G. Prove that Z(g)^|g| = e?

Question: I know that A group homomorphism is a map between two groups such that the group operation is preserved: for all , where the product on the left-hand side is in and on the right-hand side in. But i dont know how to prove the above statement.
Comment: I took the liberty of writing explicitely the definition of a group homomorphism (it seemed you wanted to do so and then forgot?)
Comment: Later, you use this to prove that the images of a character of a finite group are roots of unity.  (See the first 40 pages of J.-P. Serre's *Linear Representations of Finite Groups*.)
Answer: $$Z(g)^{|g|} = \underbrace{Z(g) \cdot Z(g) \cdots Z(g)}_{|g|} = Z(\underbrace{g \cdot g \cdots g}_{|g|})$$
Comment: @remal Can you provide us with your attempts to solve the problem or whether you understand our hints or whether a particular step confuses you?
Comment: Can you provide me with the detailed solution
Answer: Hint By induction on $n$ you can prove that
$$Z(g)^n=Z(g^n)$$


Duplicate content in views

Question: I implemented the media browser module for image uploading and changed one of the image fields to utilise the media browser for a particular content type. After which, the views which displays a list of that particular content type is showing duplicate content.
After googling I found some one who had a similar problem to mine, however, I don't understand how he solved his problem. https://drupal.org/node/1764042
I would greatly appreciate any help given.
Thanks a lot.
Update:
Figured out the problem. I was using a file:usage relationship to generate the path url for rewriting the output. Hence having multiple files linked to that node would generate multiple views.
Comment: Post your answer separately and accept it as a solution to own question. That way the solution will be clear for others with the same problem.
Comment: Please post your answer separately and don't include the your answer in question.
Comment: Unfortunately, I can only post an answer to my own question after 8 hours. Will transfer the answer into a proper answer once I am able to do so.
Answer: This may happen if you are have applied filters on any date field. I had similar problem, try this, in Views Advanced Settings under OTHER options, select "Query Setting" and check "Distinct" option.
Answer: Figured out the problem. I was using a file:usage relationship to generate the path url for rewriting the output. Hence having multiple files linked to that node would generate multiple views.

Duplicate content in views


Trouble sending redirect after logout

Question: I'm trying to send a redirect after logout, but it is not sending properly. I tried using the hook_user_logout in a module as follows:
use Drupal\Core\Routing\TrustedRedirectResponse;

function module_user_logout($account) {
  $redirect = new TrustedRedirectResponse($url);
  $redirect->send();
}

The send() call causes the page to crash with the message: "The __ page isn't working"
Comment: maybe because the $url is empty ? Or maybe because you need to add return at the end of the function. Cheers
Comment: To add what @DenisK said, `hook_user_logout()` implementations aren't supposed to redirect users. That would not allow other `hook_user_logout()` implementations to be invoked.
Answer: To resolve current issue we need to create RouteSubscriber
my_custom/src/EventSubscriber/MyCustomRouteSubscriber.php :
<?php

namespace Drupal\my_custom\EventSubscriber;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;

    /**
     * MyCustom Route subscriber.
     */
    class MyCustomRouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = parent::getSubscribedEvents();
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -300];
        return $events;
      }

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('user.logout')) {
          $route->setDefaults([
            '_controller' => '\Drupal\my_custom\Controller\MyCustomUserLogoutController::logout',
          ]);
        }
      }

    }

Then add entry into my_custom.services.yml:
  my_custom.route_subscriber:
    class: Drupal\my_custom\EventSubscriber\MyCustomRouteSubscriber
    tags:
      - { name: event_subscriber }

Then create actual controller which will replace users module logout method.
my_custom/src/Controller/MyCustomUserLogoutController.php
<?php

namespace Drupal\my_custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class MyCustomUserLogoutController.
 */
class MyCustomUserLogoutController extends ControllerBase {

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    $logout_url = 'https://google.com'
    return new TrustedRedirectResponse($logout_url);
  }

}

Hope it will save your time.
Thanks

Trouble sending redirect after logout


How to Delete all history that contains only one word in Chrome

Question: I am using Google Chrome, I have a history of a certain word (Like Google).
I want to delete it. Please tell me.
Answer: Finally, I got Answer, In History search Word (Like Google) you want to delete, check mark the first item you want to delete and scroll to the bottom and hold down the SHIFT key on your keyboard and click the last item. All items are now checked and click removed selected items.
Answer: You have a search bar above history. Type there for example "youtube" and you can mark all youtube history to be deleted
Comment: mark all option is not available in Google Chrome.
Comment: @RameshR  Click for search result ( check it ) then hold CTRL and go to the bottom and click the last element and BAM all are selected


Is the projection $\pi_{i_1,i_2,\ldots ,i_k}:\Pi_{i=1}^n X_i \to \Pi_{j=1}^k X_{i_j}$ always a continuous function in the product topology?

Question: Let $X_i,\; i=1,2,\ldots,n$ be topological spaces. It is well know that the canonical projections $\pi_m:\Pi_{i=1}^nX_i\to X_m$ are continuous functions for any $m\in \{1,2,\ldots,n \}$.
My question is: Is the projection $\pi_{i_1,i_2,\ldots ,i_k}:\Pi_{i=1}^n X_i \to \Pi_{j=1}^k X_{i_j}$ given with $\pi_{i_1,i_2,\ldots ,i_k}(x_1,x_2,\ldots,x_n)=(x_{i_1},x_{i_2},\ldots ,x_{i_k})$, for $i_1,i_2,\ldots ,i_k\in\{1,2,\ldots,n\}$ always a continuous function in the product topology?
I expects an affirmative answer, but I'm asking for a proof. My idea is to use the fact that canonical projections are continuous mappings and to see the new projection as an ordered pair whose coordinates are the respective canonical mappings, but I'm not sure if this guaranties the continuity of the new projection.
Answer: You just have to check whether $\pi^{-1}_{i_1,\dots,i_k}(U_{i_1} \times \dots \times U_{i_k})$ is open, where $U_{i_j}$ are open in $X_{i_j}$. But this set is simply the product of $X_{r}$'s and $U_{s}$'s (where the $X_r$ appear if $r \notin \{i_1,\dots, i_k\})$, and that is clearly open in the product topology since it's a product of open sets.
Comment: Oh! That's so obvious, but my brain simply blocks sometimes. Thanks :)
Answer: A nice lemma:
A function $f:Z\to\prod_{j=1}^n Y_i$ is continuous if and only if $\pi_j\circ f:Z\to Y_j$ is continuous for every $i\in\{1,\dots,k\}$.
Applying that on $Z=\prod_{i=1}^nX_i$ and $Y_j=X_{i_j}$ you will find immediately that your function is continuous.


Difference between multilevel modelling and mixed effects models?

Question: What is the difference between Multilevel/Hierarchical Modelling and Mixed Effects Models?
Wikipedia considers them to be the same, i.e. two different names for the same thing. But I think they are not exactly the same. Could anybody explain the theoretical difference?
Maybe the "Mixed Effects Models" is just one approach to solve Multilevel problems?
Comment: While wikipedia states that [multilevel models](https://en.wikipedia.org/wiki/Multilevel_model) are also called [mixed models](https://en.wikipedia.org/wiki/Mixed_model), it does make a distinction as they each have their own page.
Comment: Why would you "think they are not exactly the same"?
Answer: Section 184.108.40.206 from lme4 book

Because each level of sample occurs with one and only one level of batch we
  say that sample is nested within batch. Some presentations of mixed-effects
  models, especially those related to multilevel modeling˜[Rasbash et˜al., 2000]
  or hierarchical linear models˜[Raudenbush and Bryk, 2002], leave the impression
  that one can only define random effects with respect to factors that
  are nested. This is the origin of the terms "multilevel", referring to multiple,
  nested levels of variability, and "hierarchical", also invoking the concept of
  a hierarchy of levels. To be fair, both those references do describe the use
  of models with random effects associated with non-nested factors, but such
  models tend to be treated as a special case.
The blurring of mixed-effects models with the concept of multiple, hierarchical
  levels of variation results in an unwarranted emphasis on "levels"
  when defining a model and leads to considerable confusion. It is perfectly legitimate
  to define models having random effects associated with non-nested
  factors. The reasons for the emphasis on defining random effects with respect
  to nested factors only are that such cases do occur frequently in practice and
  that some of the computational methods for estimating the parameters in
  the models can only be easily applied to nested factors
Comment: Also related: http://stats.stackexchange.com/questions/34642/difference-between-panel-data-mixed-model


Bitbucket Git - Understanding the diff between two branches in a pull request?

Question: Say that a pull request is created in bit bucket to merge branch-2 into branch-1. The pull request has a diff tab to show the difference between these branches. I'd like to know the order of the comparison in the diff tab. Is it like git branch-1 branch-2, OR is it git branch-2 branch-1 ? Thanks.
Comment: Also refer - https://community.atlassian.com/t5/Bitbucket-questions/Understanding-the-diff-between-two-branches-in-a-pull-request/qaq-p/1206332#M48385
Answer: The diff you are seeing in Bitbucket will represent the changes which would be introduced into the target branch from the source branch which is being merged.  To be specific, for some source file, you would be looking at the version of that file in branch-1 with the diff/changes corresponding to what the branch-2 version did to the same file.
In general, you would not have the situation where both the remote branch-1 and branch-2 are both ahead of some common commit.  Rather, in this situation, usually Bitbucket would force you to update your local branch-2 with changes from the upstream branch-1 before allowing the pull request to happen.


Prove Confidence of Rule

Question: Using Association.
I want to prove the confidence of the rule $B'->(A\B')$ can't be more than the confidence of $B->(A\B)$
Given:

frequent itemset $A$ and subsets $B$ of $A$.
$B'$ is a subset of $B$.

"\" is the Set Difference Operator Sometimes written like this: $(X-Y)$

I found the exact question on this book: Data Mining: Concepts and Tenchniques by Jiawei Han online, under Mining Frequent Patterns, Association, and Correlations chapter
6.3 (c) on this book.
Doesn't say anything on how to solve it though.
Comment: This may be drawing on definitions in some literature. It does not seem related at all to the mainstream statistical sense in which "confidence" implies "confidence interval". Giving some sources and/or more explanation would help greatly. Otherwise $(X|Y)$ suggests only $X$ given $Y$; are you reaching towards conditional probability? In any case, how does your last sentence relate to the rest of the question?
Comment: I got it from an example, which now makes me think it is wrong. So I am removing that line.
Comment: Sorry, but that does not make the overall question clear. Remove _my_ last sentence above, but the rest stands.
Comment: Sorry, not to me. You are giving the impression that you are giving your own definition to a word that already has an established technical meaning in statistical science.  Someone else may be able to help.
Comment: Yeah I am probably giving my own definition because I am lost. Sorry for confusion you so much. I found the exact same question on this online book. I posted the link above. They use $B$ as $s$ and use $-$ to represent the set difference.
Answer: In association rule learning, the confidence of a rule is defined as follows:
$$conf(X\Rightarrow Y) = \frac{support(X\cup Y)}{support(X)}$$
The confidence is the amount of times a rule has been encountered in the data, conditional on the amount of times its left hand side was encountered. $100\%$ confidence implies that any record containing $X$ also contains $Y$. Confidence is one of the key criteria used to filter rules.
Unless I am misinterpreting parts of your question, it looks flawed to me, since the following rule is a paradox: $X\Rightarrow Y\setminus X$. Here you are asking for records which contain $X$ (left hand side) which also do not contain $X$ (right hand side). Long story short: the confidence of any such rule is exactly $0$, because an itemset cannot be present and absent at the same time.
Comment: I think it is some trick question/sick joke. I keep finding the question online, nobody knows how to solve it.

Prove Confidence of Rule


If $X$ is beta distributed, what is the distribution of $X^2$?

Question: Let $X\sim \text{Beta}(\alpha,\beta)$, what is the distribution of $X^2$?
I've seen some papers on the product of two independent beta random variables, but things get quite ugly there. I'm hoping the squared case is simpler.
Answer: If $X\ge0$ and $Y=X^2$, for any $y\ge0$ we have$$P(Y\le y)=P(X\le\sqrt{y})\implies f_Y(y)=\frac{1}{2\sqrt{y}}f_X(\sqrt{y}).$$In the case at hand, the PDF on $[0,\,1]$ is$$\frac{1}{2\operatorname{B}(\alpha,\,\beta)}y^{\alpha/2-1}(1-\sqrt{y})^{\beta-1}.$$


Check for port in use when there are multiple interfaces

Question: I know that For TCP, we can only have one application listening on a single port at one time. Now if you had 2 network cards, you could have one application listen on the first IP and the second one on the second IP using the same port number.
Now in this case If I have to check whether a particular port is in use, how do I do that?
My intention is a port should be used by only one application even though there are multiple interfaces. Is it Ok if I list all the interfaces and bind with the port number with all those interfaces in a loop, or is there any better way to do this checking.
Answer:
I know that For TCP, we can only have one application listening on a single port at one time.

Except as below.

Now if you had 2 network cards, you could have one application listen on the first IP and the second one on the second IP using the same port number.

Correct.

Now in this case If I have to check whether a particular port is in use, how do I do that?

See below.

My intention is a port should be used my only one application even though there are multiple interfaces. Is it Ok if I list all the interfaces and bind with the port number with all those interfaces in a loop, or is there any better way to do this checking.

Just bind it to 0.0.0.0:port. In Java that means a null InetAddress and a non-zero port number. If there are any applications listening at specific interfaces and the same port number, you will get a BindException. Conversely, if you are first, it will preclude any other applications from binding to that port in any way at all.
Comment: I guess this relates to only IPv4 address... what if there are IPv6 address? can I see any example as well
Comment: A null `InetAddress` works for IPv6 as well as IPv4 in Java. I don't know what makes you guess otherwise.
Comment: I just read here http://stackoverflow.com/a/11110685/134713 and am getting some doubts about ipv6
Comment: Have you actually *tried* a null `InetAddress`? Or are you just going  to keep reading and accumulating 'doubts' forever?
Comment: NB there is nothing in your link about using a null `InetAddress` *at all,* let alone anything that says it won't work in IPv6.


Can you show this is a bilinear form?

Question: I'm reading Scharlau's Quadratic and Hermitian forms.
In it he defines a quadratic form as
"Let V be a vector space over a field K. A map $q:V\mapsto K$ is called a quadratic form on $V$ if $$q(\alpha x)=\alpha^2q(x)$$ for all $x\in V,\alpha \in K$ and $b_q(x,y)=\frac{1}{2}(q(x+y)-q(x)-q(y))$ is a (necessarily symmetric) bilinear form".
However I'm having trouble verifying it's a bilinear form.Here is my attempt.\
$$b(x+x',y)=\frac{1}{2}((q(x+x'+y)-q(x+x')-q(y))$$
here I get stuck as I don't see how I can get this to split any further so I get $b(x+x',y)=b(x,y)+b(x',y)$
I'm also stuck on the scalar multiplication property of bilinear forms. Here is my attempt. $$b(\alpha x,y)=\frac{1}{2}(q(\alpha x+y)-q(\alpha x)-q(y)= \frac{1}{2}(q(\alpha x+y)-\alpha ^2q(x)-q(y))$$ again I don't see how I can split this any further to show $b(\alpha x,y)=\alpha b(x,y)$
Can anyone give me an idea how to progress into showing this is a bilinear form?
Comment: I don't understand why anybody would downvote this question. It is clearly an earnest attempt to use the site exactly as the site claims it is intended to be used. (+1, btw)
Answer: Your question doesn't seem to make sense. Of course that you cannot verify in general that $b_q$ is bilinear. That can only be done for a concrete function $q$. If you provide a concrete example of a potential quadratic form $q$ then, yes, we can help you to check whether or not $b_q$ is bilinear.
Comment: I was under the impression that it is a general theorem in this situation that if $q$ is a quadratic form, $b_q$ is bilinear.
Comment: @BenBlum-Smith It is *not* a theorem The OP stated that it is a definition.
Comment: I see. That $b_q$ is bilinear is a requirement of calling $q$ quadratic.
Comment: So using the properties of quadratic forms it is not possible to show that this is in fact a bilinear forrm? there is no concrete function q given. If I assume $b_q$ is a bilinear form can I show $q$ is a quadratic form for general $b_q$ and $q$?
Comment: @user24907 - you will be able to show that as long as the characteristic of $K$ is not 2 so that the definition of $b_q$ makes sense.
Comment: @user24907 Sure. The function $q$ is a quadratic form if and only if $q(\alpha x)=\alpha^2 q(x)$ and $b_q$ is bilinear.
Comment: but if it is an if and only if statement the shouldnt I be able to show that if $q$ is a quadratic form then $q(\alpha x)=\alpha ^2 q(x)$ and $b_q$ is bilinear?
Comment: @JoséCarlosSantos - It's clear the OP asked the question under the same misimpression I was under. Perhaps it would improve the answer to explicitly address this misimpression in the answer?
Comment: @user24907 Evey definition is actualy a "if and only if" statement. Like: $n$ is even if and only if $2\mid n$. Often, the "and only if" part is omitted, but it's as if it was there.
Comment: Ok so then I dont understand why assuming q is quadratic doesnt allow me to show $b_q$ is bilinear ?
Comment: @user24907 Of course you can use it to show that $b_q$ is bilinear, but it is tautological, because that's part of what being bilinear means.
Comment: But I cant do it for general $q_b$ and $q$?
Comment: @user24907 *How* do you want to do it in general? What does that even *mean*?
Comment: Assume $q(x)$ is quadraric and show $b_q (x,y)=\frac{1}{2}(q(x+y)-q(x)-q(y))$ is bilinear that is linear in each argument ?
Comment: @user24907 If $q$ is quadratic then, by the definition of quadratic form, $b_q$ is bilinear.
Comment: I see the isssue. By assuming $q$ is quadratic I'm also assuming $b_q$ is bilinear. Thanks for clearing that up.
Comment: @user24907 I'm glad I could help, but please note that I had already said that in my second comment.
Answer: Here's what's going on.
Per the comments under Jose Carlos Santos' answer, in order to be called a quadratic form, the function $q:V\rightarrow K$ must satisfy 2 distinct requirements:
(1) $q(\alpha x) = \alpha^2 q(x)$ for all $\alpha\in K, x\in V$.
(2) The function $b_q:V\times V\rightarrow K$ defined by the equation $b_q(x,y) = \frac{1}{2}(q(x+y) - q(x) - q(y))$ must be a bilinear function.
The second requirement is part of the definition of being called a quadratic form. If $q$ satisfies (1) but not (2), it is not a quadratic form.
So what's going on is just that you were mildly misreading Scharlau's definition. (I was too, at first.)
To see that it is possible to satisfy (1) without satisfying (2), observe that (1) only exerts any control over how $q$ behaves when you scale its input with a scalar factor. It doesn't exert any control on how $q$'s values on a pair of linearly independent vectors are related. (Whereas the bilinearity of $b_q$ clearly requires some sort of relationship of this kind.)
Exploiting this idea to build a concrete example:
Let $V=\mathbb{R}^2$ and let $K=\mathbb{R}$. Construct a candidate $q$ as follows: take an absolutely arbitrary function $g$ on the half-open interval $[0,\pi)$. Now every line through the origin goes through exactly one of the points $(\cos\theta,\sin\theta)$ for $\theta \in [0,\pi)$. This implies that for any nonzero $v\in \mathbb{R}^2$, there is a unique $\beta \in \mathbb{R}$ and a unique $\theta\in [0,\pi)$ such that $v = (\beta\cos\theta,\beta\sin\theta)$. Now define $q(v)$ by the formula $q(v) := \beta^2 g(\theta)$. (And define $q(0)= 0$.)
I claim that the $q$ so defined satisfies $q(\alpha v) = \alpha^2 q(v)$ for any $v\in \mathbb{R}^2$ and any $\alpha\in \mathbb{R}$. Indeed, if $v = (\beta\cos\theta, \beta\sin\theta)$ for some $\beta\in\mathbb{R},\theta\in[0,\pi)$, then for any $\alpha\in\mathbb{R}$ we have
$$q(\alpha v) = q(\alpha\beta\cos\theta,\alpha\beta\sin\theta) = (\alpha\beta)^2 g(\theta) = \alpha^2(\beta^2g(\theta)) =\alpha^2 q(v).$$
Since the original function $g$ was completely arbitrary, $q$ is potentially a mess. (For example, we could let $g$ be some form of the Dirichlet function - $1$ when $\theta$ is a rational fraction of $\pi$, $0$ when it's an irrational fraction of $\pi$.) Then $b_q$ can't hope to be bilinear.
Comment: Ok thanks, I didnt realise this was necessarily part of the definition. Most sources just state (1) or that it is a homogenous polynomial of degree 2. Thanks for clearing it up.
Comment: Adding an example to show it is possible to satisfy (1) without satisfying (2) (or being a homogeneous polynomial of degree 2).
Comment: "Being a homogeneous poly. of deg 2" is also a correct definition and is equivalent to Scharlau's (as long as the field characteristic is not 2). The advantage of Scharlau's definition is that it is not married to any specific set of coordinates on $V$, whereas to define a polynomial we need coordinates.

Can you show this is a bilinear form?


Recycler view doesn't show data in Portrait mode in Android nougat

Question: I am developing an app with RecyclerView showing a set of data. But the RecyclerView is not showing data (While the device is is PORTRAIT mode) in NOUGAT but it's working fine in Marshmallow (both in LANDSCAPE AND PORTRAIT). I checked this [link][1] and updated my code as per this but still I am facing this issue. I don't know where I am wrong.
Here is my xml code:
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:scrollbars="vertical">

        </android.support.v7.widget.RecyclerView>
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

Activity code:
   RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
   recyclerView.setLayoutManager(mLayoutManager);
   recyclerView.setNestedScrollingEnabled(false); // added as per the link
   recyclerView.setItemAnimator(new DefaultItemAnimator());
   recyclerView.setAdapter(mAdapter);
   mAdapter.notifyDataSetChanged();

GitHub link
This code shows data in LANDSCAPE MODE in NOUGAT but not in PORTRAIT MODE.Works in both mode in MARSHMALLOW.
Any help would be great. Thanks in advance
Comment: did you get any logcat warning in nought device?
Comment: No , I am not getting any @DivyeshPatel
Comment: make NestedScrollview height match_parent and remove fillviewport.
Comment: Not working @DivyeshPatel
Answer: make NestedScrollview height match_parent and use
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

instead of your line of code. why are you using notifyDataSetChanged() after just setting up the adapter?
Comment: Getting same issue @Payam Kokabi
Comment: in your xml if you dont have another view use RecyclerView alone instead of implementing it in NestedScrollView and LinearLayout @Anusha
Comment: I tried even that. Still the same problem. @Payam Kokabi


Ajax (pjax) pagination breaks after other ajax request

Question: I am using pjax for main navigation and pagination (kaminari). Within the page I make ajax calls to change the state to some of the items on the page. The ajax call updates a partial which contains the pagination. The problem is that after an ajax request, the pjaxified pagination breaks. Instead of showing the links to the next/previous pages, all the links in the pagination is now the same as the last ajax call.
Here's the template being called after the ajax request, toggle_state.js.erb:
$("#link-list").html("<%= escape_javascript(render 'links') %>")

Here's the partial 'links', being rendered after the ajax call:
<%= render @links %>
<%= paginate @links %>

Comment: Can you provide some code examples please?
Answer: Forcing some of the parameters set by the ajax request to nil made it work:
<%= paginate @links, :params => {:controller => 'links', :action => 'index', :id => nil, :toggle_to => nil} %>

It kind of makes sense when you think about it, but I also think there must be a more elegant way to do it.


Programmatically call a ViewController PopOver with custom UIButton

Question: I have defined the width, height and position of a custom UIButton in the viewDidLoad section of my implementation file. If I were to drag and drop this button in the IB, I could ctrl and drag it to another View Controller and select PopOver.
Unless there is a way to attach an IBOutlet to this custom UIButton which I'm unaware of, as my custom button doesn't show in the Interface Builder, how do I go about calling a PopOver of a UIViewController within the action of clicking my custom UIButton in my implementation file?
This is how I defined my custom button:
self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];
[self.hard1 setFrame:CGRectMake(884, 524, 105, 60)]; // set the x,y,width and height
UIImage *buttonImage = [UIImage imageNamed:@"green.jpg"];
self.hard1.layer.cornerRadius = 10;
self.hard1.clipsToBounds = YES;
[self.hard1 addTarget: self
          action: @selector(buttonTapped:)
forControlEvents: UIControlEventTouchUpInside];
[self.hard1 setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:self.hard1];

Comment: Are you asking about storyboard segues?
Comment: yes, I am, can I use those within my code?
Comment: I've edited my answer to show how to call a segue programmatically, but I don't really understand what is so custom about your button.  Why can't you just put it in using IB?
Comment: because I change the colour of it under a certain condition, so unfortunately I had to code it. Thanks very much for your help, could you just clarify what I drag the segue to?
Comment: Drag the segue to the view you want as a popover.  Like you would do from the button, only there is no button so you have to do it from the ViewController.
Comment: It might be easier to set up a reference outlet to this button and change the colour that way, rather than create the whole thing custom.
Comment: where does mySegue come into it? Sorry if I'm sounding stupid I'm just struggling to grasp this. Thanks for your patience.
Comment: Also I wasn't aware of any other way to change the colour of the button
Answer: If i understood you correctly, your custom button is a subclass of UIButton. So in IB, put a regular button in the right place, then navigate to the Identity inspector in the right-side pane, and in the class field enter your custom button class name, so that IB button becomes CustomUIButton. You work everything else as if it was regular button.
You have to have you custom class imported in the view controller's .h-file.
Hope it helps.
Comment: My button is called hardButton1, if I enter that in the class field it just retains the same properties of a normal button, not the ones I have written in the implementation file. Thanks for the response.
Comment: Ok man, then just make sure you didn't misspell methods you have rewritten, and that they are declared in the .h file.
Answer: Connect the action touchupinside to the method buttonTapped: via interface builder.
To do so

Right click on the button on the Interfacebuider ,
In the window there will be list of actions.
click and drag teh touchUpInside and put it on the viewcontroller object
then another window shows the methods and connect it with the desired method .Thats it

Go through this tutorial
EDIT :
  [hardButton1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

self is where you defined the method buttonPressed:
EDIT 2:
From the comments i think the problem may be button image
or frame.Set a background color for the image and test .Also check you set the proper imagename with extension.Put a breakpoint and test the method is hit if button is visible
Comment: I defined my button programatically, so it doesn't display in the Interface Builder, only when it runs the app.
Comment: that's what I did, I still don't understand how to use the Interface Builder to do this when my button doesn't show up there
Comment: "button doesnt show up there ? what do you meant by that? can you explain more?
Comment: where I defined the UIButton in my implementation file, I set the width, height and its position on the screen, so I see it when I run the application, but I can't see it in the Interface Builder
Comment: well you have to add a button in the IB and make its custom class your button class.See implementation will not bring button in IB.We have to add it and connect it to make the compiler know this button in IB represent this Reference in Class.For that we user IBOutlets
Comment: That makes sense, thank you. I'm not entirely sure what to write in the class field though..
Comment: what is your custom class name? give it there if you are using one.Otherwise just drag in a button and connect the outlet
Answer: Something like this:
- (IBAction) buttonTapped:(id) sender
{
    [self performSegueWithIdentifier:@"mySegue" sender:self];
}

where mySegue is a popover segue that you have dragged from the containing viewController to the one you want to pop over.  You create the segue and then type a name in the 'Identifier' box for the segue in IB, then you use the same name here where I've put 'mySegue'.

I've ringed the two buttons you have to press to see this display; then you just have to select the segue that you want to work on.  You can select it in the picture (click on the middle of the arrow), or in the list of items in your storyboard.
Comment: can I refer to a ViewController in the Interface Builder? Or do I have to programatically define one?
Comment: You can call up a particular layout designed using IB with method `initWithNibName:` on the ViewController.  I'm not sure I understand what you want.  Maybe if you took a step back and described at a higher level?
Comment: how do I change the properties of the IB like you have in that picture?
Comment: I expanded the picture a bit and tried to explain in the answer.
Comment: Sorry Bryan, thanks a lot for the help. I'm now receiving an error 'Popover segue with no anchor'
Comment: Yes, that is a complication.  Various people have solved that problem, e.g: http://stackoverflow.com/questions/7787119/creating-button-for-popover-view-anchor-at-run-time


intuitive set theory / empty set intersection question

Question: Let's say A=empty set and every element of A also a set, what is the intersection of all elements of A?
real answer:?
possible answer: universal set (I found it via using  Russel paradox. And then I thought backward.)
Comment: I think you want to proove $\forall i, X_i\subseteq X$, then
 $\bigcap_{i\in\emptyset}X_i=X$ holds. Is it right?
Comment: Yeah, it's right.
Answer: Every element of the empty set is a set, no need to assume that. But the intersection of the elements of the empty set is undefined; the definition of intersections applies only to non-empty families of sets.
(Why is it undefined? If we try to apply the definition, with $I$ being the intersection of the elements of the empty set, we get $$x\in I\iff\forall y\in \emptyset\,\,\,\, x\in y.$$But that says that every $x$ is in $I$, and there is no "universal set" in modern set theory)
Answer: Proof of $\forall i, X_i\subseteq X$, then
$\bigcap_{i\in\emptyset}X_i=X$ is like this. However, to avoid Russell's paradox, it must first be implicitly assumed that all actions take place under a particular set(in this case, $X$).
For all $x\in X$, $i\in\emptyset \Rightarrow\bigcap_{i\in\emptyset} x\in X_i$ holds, because it is vacuous truth, since antecedent $i\in\emptyset$ is false.
Comment: Your proof shows $X\subseteq \bigcap_{i\in\varnothing }X_i$. For equality, you need to show the other inclusion. But the other inclusion is not true unless you *define* $\bigcap$ in such a way that only elements of $X$ are considered. To illustrate the issue, note that all sets in the empty family are subsets of $\mathbb{N}$, so your assertion is that the empty intersection is equal to $\mathbb{N}$. But also all sets in the empty family are subsets of $\mathbb{R}$. Is the empty intersection also equal to $\mathbb{R}$?
Comment: @AlexKruckman I added the corresponding explanation.
Comment: that explanation doesn't help - what you say is simply **false**. How does saying "all actions take place under a particular set invalidate the counterexamples you've been given?


Can interface type variable call methods from that interface in a class that doesn't implement it?

Question: I'm trying to understand this just for my own knowledge. Here is a broken down version of my code:
interface ILightningPhone {
    void recharge();
    void useLightning();
}

interface IMicroUsbPhone {
    void recharge();
    void useMicroUsb();
}

class LightningToMicroUsbAdapter implements IMicroUsbPhone {
    private final ILightningPhone lightningPhone;

    public LightningToMicroUsbAdapter(ILightningPhone lightningPhone) {
        this.lightningPhone = lightningPhone;
    }

    @Override
    public void useMicroUsb() {
        System.out.println("MicroUsb connected");
        lightningPhone.useLightning();
    }

    @Override
    public void recharge() {
        lightningPhone.recharge();
    }
}

I'm trying to understand interfaces and I just need an explanation on the following:

I notice that a variable private final ILightningPhone lightningPhone; is declared within a class of type ILightningPhone interface. but this class doesn't implement that interface. How is it able to do this?

Next I notice that in the following method:
public void useMicroUsb() {
    System.out.println("MicroUsb connected");
    lightningPhone.useLightning();

the variable lightningPhone is able to call the useLightning() method from the ILightningPhone interface. Even though the ILightningPhone interface is not implemented in the class LightningToMicroUsbAdapter. Why is it able to do this?

Overall, I'm just trying to understand why we are able to create a variable of a interface type in a class that doesn't implement that interface? And why when declaring that variable of that interface type are we able to use the methods from that interface in a class that doesn't implement that interface?
Here is the full code if needed: https://en.wikipedia.org/wiki/Adapter_pattern
Comment: You don't have to *be* a phone to *have* a phone.
Comment: You are confused because this example is confusing! If your `LightningToMicroUsbAdapter` was just a `Person` class (without an interface) It would be easier to understand how Person could call the methods of ILightningPhone on the ILightingPhone
Comment: You may want to revisit the basics of Java. I'm not sure what thinking process can even lead to a theory that a type that doesn't implement X cannot have fields of type X or call methods on that field. Composition is one of the fundamentals of object oriented programming.
Comment: Think about if you swapped `private final ILightningPhone lightningPhone;` with `private final String s;`. You can still call `s.length()` even though `LightningToMicroUsbAdapter ` doesn't implement `CharSequence`
Answer: The LightningToMicroUsbAdapter class (or any class for that matter) can have any type of member - be it a String, a List, or even a ILightningPhone. Having a members is a "hasA" relationship, not an "isA" relationship.
Since the lightningPhone is an instance of ILightningPhone, it can call the useLightning method defined by that interface.

Can interface type variable call methods from that interface in a class that doesn’t implement it?


Set in the middle a div inside another div

Question: I have the following piece of HTML page:

        Some text

With the following CSS:
#main {
    height:600px;
    vertical-align:middle;
}

#description {
    display:block;
    height:50%;
    width: 50%;
    margin: auto;
    font-size:18px;
}

With this code, description div is centered horizontally, but I want to center it vertically.
Do you know how can I do that?
Answer: You can use relative-absolute positioning to achieve this:
#main
{
    height: 200px;
    position: relative;
    background-color: lime;
}
#description
{
    width: 50%;
    height: 50%;
    position: absolute;
    left: 25%; /* (100 - width)/2 */
    top: 25%; /* (100 - height)/2 */
    background-color: cyan;
}

Demo here
Answer: You can use css display:table-cell write like this
 #main {
    height:600px;
    vertical-align:middle;
    display:table-cell;
}

Check this http://jsfiddle.net/sandeep/weGGn/9/
You can also use position:absolute but in this case you have to define height of that div. check this article http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
Check this article http://www.student.oulu.fi/~laurirai/www/css/middle/ may be that's help your
Answer: You can use table-cell - but it is only supported in newer browsers. I'm not sure on the version numbers (but I think it's like IE8+ and FF6+)
But if you're not worried about compatibility with old browsers use table-cell. Otherwise you have to use negative margins and stuff like that.
You can read about it here: http://phrogz.net/css/vertical-align/index.html
Answer: Here:
#main {
   height:600px;
   width:600px;
   background-color: blue;
   position: absolute;
}

#description {
   display:block;
   height:50%;
   width: 50%;
   margin: 25% auto;
   position:relative;
   font-size:18px;
   background-color: red;

}
jsfiddle  Here


Find where a NumPy array is equal to any value in a list of values

Question: I have an array of integers and want to find where that array is equal to any value in a list of multiple values.
This can easily be done by treating each value individually, or by using multiple "or" statements in a loop, but I feel like there must be a better/faster way to do it. I'm actually dealing with arrays of size 4000 x 2000, but here is a simplified edition of the problem:
fake = arange(9).reshape((3,3))

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

want = (fake==0) + (fake==2) + (fake==6) + (fake==8)

print want

array([[ True, False,  True],
       [False, False, False],
       [ True, False,  True]], dtype=bool)

What I would like is a way to get want from a single command involving fake and the list of values [0, 2, 6, 8].
I'm assuming there is a package that has this included already that would be significantly faster than if I just wrote a function with a loop in Python.
Answer: The function numpy.in1d seems to do what you want. The only problems is that it only works on 1d arrays, so you should use it like this:
In [9]: np.in1d(fake, [0,2,6,8]).reshape(fake.shape)
Out[9]:
array([[ True, False,  True],
       [False, False, False],
       [ True, False,  True]], dtype=bool)

I have no clue why this is limited to 1d arrays only. Looking at its source code, it first seems to flatten the two arrays, after which it does some clever sorting tricks. But nothing would stop it from unflattening the result at the end again, like I had to do by hand here.
Comment: Hmm. I wrote this very simple function to do this job:

 `def EqualsAny(ar,vals):
         out=zeros(ar.shape,dtype=bool)
         for val in vals:
                 out+=(ar==val)
         return out`

I thought that `numpy.in1d` would be faster, but it actually takes longer (for same result):

 `In [11]: %timeit EqualsAny(badlabels,smallnum)
 1 loops, best of 3: 519 ms per loop
 In [7]: %timeit in1d(badlabels, smallnum).reshape(badlabels.shape)
 1 loops, best of 3: 871 ms per loop`

 Shouldn't `numpy.in1d` be way faster since it's written in C? Am I not using `%timeit` properly?
Comment: No, `in1d` is not written in c but in python, see the link to the source code I gave. It uses various numpy functions like `sort`, which should hopefully be written in C. It even has some optimized algorithm for when `vals` is short, which is pretty similar to your solution (but with `|=` in stead of `+=`). I don't know why your version is faster, this might depend on the length of both inputs.
Answer: NumPy 0.13+
As of NumPy v0.13, you can use np.isin, which works on multi-dimensional arrays:
>>> element = 2*np.arange(4).reshape((2, 2))
>>> element
array([[0, 2],
       [4, 6]])
>>> test_elements = [1, 2, 4, 8]
>>> mask = np.isin(element, test_elements)
>>> mask
array([[ False,  True],
       [ True,  False]])

NumPy pre-0.13
The accepted answer with np.in1d works only with 1d arrays and requires reshaping for the desired result. This is good for versions of NumPy before v0.13.
Answer: @Bas's answer is the one you're probably looking for.  But here's another way to do it, using numpy's vectorize trick:
import numpy as np
S = set([0,2,6,8])

@np.vectorize
def contained(x):
    return x in S

contained(fake)
=> array([[ True, False,  True],
          [False, False, False],
          [ True, False,  True]], dtype=bool)

The con of this solution is that contained() is called for each element (i.e. in python-space), which makes this much slower than a pure-numpy solution.


Basic topology of a 4 point set

Question: Let $X=\{1,2,3,4\}$ be given by the topology $\tau=\{\emptyset,X,\{1\},\{1,2\},\{1,3\},\{1,2,3\}\}$.
Show that any two disjoint closed sets have disjoint neighborhoods.
So I define my closed sets (as complements of the given open sets) as
$\mathcal{C}=\{X,\emptyset,\{2,3,4\},\{3,4\},\{2,4\},\{4\}\}$
So my question is, since $4$ is an element of every closed set except $\emptyset$, is there even anything to show because every closed set except for $\emptyset$ is contained in the neighborhood $X$ (because $X$ is the only member of $\tau$ who contains the element $4$). Is there even anything to show or?
Comment: No, that's all. One of the closed sets must be empty.
Answer: Since @Hossien Sahebjame already answered your question in the comments, let formulate the same answer in a slightly more general context, because why not.
Let $\bar{X} = X \cup \{a\}$ be a set and define the open sets of the excluded point topology on $\bar{X}$ to be all subsets, not containing $a$ and the whole set, so $\tau = \mathcal{P}(X) \cup \bar{X}$. In every such topological space every closed set contains the point $a$ and hence there are no non-trivial disjoint closed sets which implies that "any two disjoint closed sets have disjoint neighborhoods" by means of a vacuous truth (as pointed out by you and in the comments already).
Now, having a coarser topology $\sigma \subset \tau$ can only reduce the number of closed sets; therefore all topologies that are coarser than an excluded point topology have this property. Since the topology you described is coarser than the excluded point topology $\bar{X} = \{1,2,3\} \cup \{4\}$, this completes this unnecessarily overcomplicated "answer".
Comment: ok so it is by vacuous truth then

Basic topology of a 4 point set


efeito de trasição em menu não funciona no chrome no firefox funciona normal

Question: Esse é o código CSS:
*{
margin:0;
padding:0;
}
header{
margin-top:10px;

}
nav{

margin:0px auto;
max-width:1000px;
width:100%;

}
nav ul {
list-style:none;
}

nav > ul {
display:table;
overflow:hidden;
width:100%;
background:#E8E8E8;
position:relative;

}

nav > ul li {
display:table-cell;

}
/* Sub-menu*/
nav > ul > li:hover > ul{
display:inline;
height:100%;
}

nav > ul > li > ul {
display:block;
position:absolute;
background:#CDCDC1;
left:0;
right:0;
overflow:hidden;
height:0%;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
transition: all .3s ease;
}

nav > ul li a {
color:#000;
display:block;
line-height:20px;
padding:20px;
position:relative;
text-align:center;
text-decoration:none;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
transition: all .3s ease;
}
nav > ul > li > ul >li a:hover{
background:#87CEFF;
}

nav > ul > li > a span{
background:#174459;
display:block;
height:100%;
width:100%;
left:0;
position:absolute;
top:-55px;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
transition: all .3s ease;
}
nav > ul > li > a span .icon {
display:block;
line-height:80px;
}
nav > ul > li > a:hover > span {
top:0;
}
/* Cores*/
nav ul li a .primeiro{
background:#00BFFF;
}
nav ul li a .segundo{
background:#00BFFF;
}
nav ul li a .terceiro{
background:#00BFFF;
}
nav ul li a .quarto{
background:#00BFFF;
}
nav ul li a .quinto{
background:#00BFFF;
}
nav ul li a .sexto{
background:#00BFFF;
}

Esse é o HTML:
<!DOCTYPE HTML>

   <meta charset="UTF-8">
   <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">
   <link rel="stylesheet" href="css/estilo_menu5.css">

Escola

Cadastro

Coordenação Pedagógica

LSE

Relatórios

Usuários

Aluno

Pesquisar Aluno

Relatórios

Turmas

Cadastrar Turma

Listar Turma

Professor

Carga Horária

Enturmar Professor

Pendência

Download

Comment: dvd sua solução foi brilhante porém quando executo o código aqui pela pagina stackOVERFLOW kkk olha a ironia meu problema é o overflow...bem funciona corretamente quando faço as mudanças na minha página a faixa branca não SOBREPÕE das figuras. :(
Comment: ajustei a altura e top e funcionou...obrigado!
Answer: O problema está no overflow:hidden; em nav > ul. O Chrome, diferentemente dos outros navegadores, interpreta isso de forma diferente.
Quando você seta overflow no elemento, o Chrome delimita todos os elementos-filhos a área do elemento-pai. O que ultrapassar os limites, não serão exibidos. A sua transição está funcionando corretamente, mas não aparece porque fica fora dos limites do elemento-pai.
A única forma que encontrei de solucionar isso de forma visual foi criando uma nova div com fundo branco e de altura de 10px que irá sobrepor e para esconder parte das
 que descem do topo. E, claro, deletando a linha overflow do nav > ul.
Criei uma div e dei id de faixa logo após a abertura da div principal:

*{
margin:0;
padding:0;
}
header{
margin-top:10px;
}
nav{

margin:0px auto;
max-width:1000px;
width:100%;

}
nav ul {
list-style:none;
}

nav > ul {
display:table;
width:100%;
background:#E8E8E8;
position:relative;

}

nav > ul li {
display:table-cell;

}
/* Sub-menu*/
nav > ul > li:hover > ul{
display:inline;
height:100%;
}

nav > ul > li > ul {
display:block;
position:absolute;
background:#CDCDC1;
left:0;
right:0;
overflow:hidden;
height:0%;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
transition: all .3s ease;
}

nav > ul li a {
color:#000;
display:block;
line-height:20px;
padding:20px;
position:relative;
text-align:center;
text-decoration:none;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
transition: all .3s ease;
}
nav > ul > li > ul >li a:hover{
background:#87CEFF;
}

nav > ul > li > a span{
background:#174459;
display:block;
height:100%;
width:100%;
left:0;
position:absolute;
top:-55px;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
transition: all .3s ease;
}
nav > ul > li > a span .icon {
display:block;
line-height:80px;
}
nav > ul > li > a:hover > span {
top:0;
}
/* Cores*/
nav ul li a .primeiro{
background:#00BFFF;
}
nav ul li a .segundo{
background:#00BFFF;
}
nav ul li a .terceiro{
background:#00BFFF;
}
nav ul li a .quarto{
background:#00BFFF;
}
nav ul li a .quinto{
background:#00BFFF;
}
nav ul li a .sexto{
background:#00BFFF;
}

#faixa{
   display: block;
   width: 100%;
   background: #fff;
   height: 10px;
   position: absolute;
   top: 0;
   left: 0;
   z-index: 9;
}

Escola

Cadastro

Coordenação Pedagógica

LSE

Relatórios

Usuários

Aluno

Pesquisar Aluno

Relatórios

Turmas

Cadastrar Turma

Listar Turma

Professor

Carga Horária

Enturmar Professor

Pendência

Download

Comment: @fabrito Tenta aumentando o valor do z-index. Em vez de 9, coloca 99999999 (vários noves).


What is the optimal investing solution for the given simulated market?

Question: I have come across an artificial, simulated, stock-market type of situation, whose rules, I find, create a rather interesting problem.  I want to know if there is a mathematically optimal solution for "trading" on this simplified market, and if not, what may be a good approximation of this optimal solution.
Here are the rules we are aware of for the market:
1. There are two commodities, gold coins and oil.
2. The price of a barrel of oil cannot exceed 6.4 coins.
3. The price of a barrel of oil cannot be less than 4.8 coins.
4. The price of a barrel of oil is evaluated every 5 minutes.
5. Trades placed within these 5 minutes are guaranteed at the current price.
It is observed that the price of oil changes as a large number of purchases or sells are made, and any individual "trader" cannot make a trade large enough to influence the price of oil.
A graph of a typical "day" of trading on this market is here.
Actual numbers of the given graph are available in the first comment below (until I have 10 reputation).
The first, very simple, solution that I came up with, was as follows:
1.  If current oil price is greater than previous oil price, sell 10% of oil owned.
2.  If current oil price is less than previous oil price, spend 10% of gold coins to buy oil.
3.  If there is no change in oil price, do nothing.
However, I feel that this solution does not make good use of the conditions of the market.
Comment: I guess the best one could do in that case, if we don't have the details of the transactions and price mechanism, is to model the price as a random variable and try to fix the parameters of our random variable model from the data on the webpage you linked to.
Comment: Actual numbers of the given graph are available at http://pastebin.com/WARLKE5M
Comment: What determines the price? Since there are limits on the price of oil, I guess it's not just the actions of selling and buying. But, I think the optimal strategy would be to sell more oil as you get closer to the top price, since you know it is probably unlikely to raise much more, and on the other hand buy more oil the closer the price is to the bottom price.
Comment: You can also try to simulate a market where everybody has certain strategies, if at least you know more precisely what the price-forming mechanism is.
Comment: I don't have access to the algorithm that determines the price, but from observation, it increases as "traders" purchase oil, up to the 6.40 maximum, at which point it holds steady until "traders" sell it, at which point it will continue to drop until there is more purchasing than selling of oil, or it hits the 4.8 minimum.
Answer: One thing you may consider to be a problem with the algorithm is that will be forced towards 50% cash, 50% investments over time.
Clarification:
Say you start with 100 gold pieces, none invested, if a buy decision takes place then 10 gold will be invested. Then next time either 1 gold from investment to purse or 9 gold from purse into investment. You would need a very strange probability distribution for that to not approach 50/50 in the long run.
Answer: Needless to say, this is a very unrealistic market. Typical investment tools, like the kelly criterion, don't apply. It is intuitive to me that with a 100% chance to recoup your investment given the appropriate time horizon, you should be leveraging your bankroll much more than 10%; you should use 50 or 100% in order to make more off of the "market".
Clearly, The range of prices oil can take on is $$6.4-4.8 = 1.6$$
The midpoint of this range is $$4.8+\frac {1.6} 2 = 5.6$$
Without consideration, it stands to reason that oil is a buy when at its minimum of 4.8 and a sell / not a buy when at its maximum of 6.4.
Assuming a random bounded walk, the price is more likely to increase in the near future when below 5.6. To be more precise, the expected value of the time oil takes to move to a higher number than the buy-in number becomes less as the value of the buy-in number gets closer to 4.8, and becomes 5 minutes at 4.8. I don't know what the step distance is because the images are no longer visible, but I'm assuming it is 0.2, with equal chances of staying, lowering, or raising within the confines of 4.8 and 6.4. The ev(x) can be derived using a markov chain, but I don't have the time to do that right now. Whatever the expected time taken is, it decreases proportionally with proximity to 4.8. ev(4.8) must be 10 minutes, because at that low bound there is equal chance of staying at 4.8 and ticking up to 5, which would each take 5 minutes. If it becomes 5, then the time was 5 minutes, which had probability 0.5. If it becomes 4.8 again, the time will now become 10 minutes, value becoming 4.8 or 5 with equal probability. There is a chance that the value remains 4.8 ad infinitum, but with diminishingly small probability. Thus the ev(4.8) is:
$$\sum_{i=1}^{i=\inf} (\frac 1 2)^i (5i \min) = 10 \min$$
I don't have time now but I aim to revisit this answer mapping out the problem with markov chains.
By a quick back-of-the-hand calculation, it appears that ev(5) = 15 min.


linear algebra foundation of Riemann integrals

Question: Let $V$ be the vector space of real functions $f\colon [a,b]\to \mathbb R$ and let $X$ be the set of characteristic (indicatrix) functions of subintervals: $X=\{\mathbb 1_I\colon I\subset [a,b] $ interval $\}$. We define $T\colon X \to \mathbb R$ as $T(\mathbb 1_I) = |I|$ where $|I|$ is the length of the interval $I$. Notice that $X$ is not a set of independent vectors because the sum of adjacent intervals is again an interval, but in that case $T$ is defined to be additive.
So it is clear that $T$ can be extended as a linear map on the vector space generated by $X$ (which is the space of so called simple functions).
What are the abstract properties of $X$ and $T$ (in the setting of linear algebra) which can be applied to the above example to prove that $T$ is linear on $X$?
For example $X$ and $T$ have the following property: $x,y,x+y\in X \implies T(x+y) = T(x)+T(y)$ and $x,\lambda x \in X \implies \lambda=1$. Is this enough to prove that $T$ is linear i.e. that $x,y,\lambda x +\mu y \in X \implies T(\lambda x + \mu y) = \lambda T(x) + \mu T(y)$? And is this enough to prove that $T$ has a linear extension to the span of $X$?
Comment: What is the desired result?
Comment: I hope I have clarified the question, which is by its nature a little bit vague. The point is that it seems to me obvious that the map $T\colon X \to \mathbb R$ is linear on $X$ (notice however that $X$ is not a vector space) and it should be a consequence of the additivity of the measure of intervals. However I'm not able to abstract the conditions which give the result.
Comment: I think it is not relevant if the intervals are open, closed or half-open. In general I would like to take all of them but I can restrict the questions to intervals of the kind $[a,b)$ if this helps.
Comment: @PeteL.Clark I don't see the relevance. For example the intervals $[0,1)$, $[0,2)$ and $[1,2)$ are not independent.
Comment: @Emanuele: Right...so in order for what you wrote about independence to be correct, it seems that you want to consider more than just closed intervals.
Comment: Of course one cannot take only closed or only open intervals. Either one should consider half-open intervals [a,b) or a mixture of closed, open, half-open etc...
Answer: I'm not entirely sure I've understood your question properly, but here's an attempt.
Proposition: Let $V$ be a real vector space, let $X \subset V$, let $W = \operatorname{span} X$, and let $f: X \rightarrow \mathbb{R}$ be a function.  Then:
a) There is at most one linear function $F: W \rightarrow \mathbb{R}$ such that $F|_X = f$.
b) If such a function exists, there is at least one linear function $G: V \rightarrow \mathbb{R}$ such that $G|_X = f$.
c) The following are equivalent:
(i) There is a linear extension $F$ to $W$, namely: for $x_1,\ldots,x_k \in X$ and $\alpha_1,\ldots,\alpha_k \in \mathbb{R}$,
$F(\alpha_1 x_1 + \ldots + \alpha_k x_k) = \alpha_1 f(x_1) + \ldots + \alpha_k f(x_k)$.
(ii) For all $x_1,\ldots,x_k \in X$ and $\alpha_1,\ldots,\alpha_k \in \mathbb{R}$, if
$\alpha_1 x_1 + \ldots + \alpha_k x_k = 0$, then $\alpha_1 f(x_1) + \ldots + \alpha_k f(x_k) = 0$.
Proof: a) If there is such a linear extension $F$ to $W$, then it is uniquely determined by the formula of condition (i) of part c), so it is unique.  b) Every linear map on a subspace $W$ extends to a linear map on the entire space $V$: just choose a basis for the subspace, extend it to a basis for the entire space, and define the map arbitrarily on the basis vectors lying outside of $W$.  c) The implication (i) $\implies$ (ii) is immediate.  For (ii) $\implies$ (i): we would like to define the extension $F$ by the formula of (i):
$F(\alpha_1 x_1 + \ldots + \alpha_k x_k) = \alpha_1 f(x_1) + \ldots + \alpha_k f(x_k)$.
But we need to check that this is well-defined: suppose $x \in W$ has two expressions
$\alpha_1 x_1 + \ldots + \alpha_k x_k = x = \beta_1 x_1 + \ldots + \beta_k x_k$
for $\alpha_1,\ldots,\alpha_k,\beta_1,\ldots,\beta_k \in \mathbb{R}$.  Then
$(\alpha_1 - \beta_1)x_1 + \ldots + (\alpha_k - \beta_k) x_k = 0$, so using (iii) we get
$0 = (\alpha_1-\beta_1)f(x_1) + \ldots + (\alpha_k-\beta_k)f(x_k)$,
and thus
$\alpha_1 f(x_1) + \ldots + \alpha_k f(x_k) = \beta_1 f(x_1) + \ldots + \beta_k f(x_k)$.
Notice that condition (ii) of part c) is certainly satisfied if $X$ is linearly independent.
I invite you to verify criterion (ii) in the example you've given.
Comment: This part is clear to me. What I don't understand is what are the requirements to check that the function $F$ is linear on $X$ (so that it can be extended). For example I know that when $x,y,x+y \in X$ then $F(x+y)=F(x)+F(y)$, but I would say that this is not enough...
Comment: It doesn't make sense to say that $f$ is linear on $X$, because $X$ is not a subspace.  But the condition (ii) in my answer gives a sense in which $f$ is linear on $X$.  I can see that you want a weaker condition.  I'm not sure that's possible without some additional structure in your setup, as e.g. in the setting of Caratheodory's Theorem.
Comment: What about these assumptions: Let $X$ be a well-ordered set such that $x,y\in X, x \le y \implies y - x \in X$. And let $T\colon X \to \mathbb R$ be such that $x,y,x+y \in X \implies T(x+y) = T(x) + T(y)$ and $x,\lambda x \in X \implies T(\lambda x) = \lambda T(x)$. Then $T$ can be extended to a linear operator on $span(X)$
Answer: I think the only thing that needs to be proved for $T$ to be extendable to a linear map on the vector space generated by $X$ is the following. Assume $f=\mathbb{1}_{[c,d)}$ and $g = \mathbb{1}_{[d,e)}$ with $f,g \in X$. Then $f+g$ is also in $X.$ (I am assuming that half-open intervals are used here.) It is then needed that $T(f+g) = T(f) + T(g)$ for all such $f$ and $g$ in $X.$
This is because if the above is true (which it is!), then you can show that any function that can be written as a linear combination of elements of $X$ (i.e. a simple function) maps to a unique value by the extension of $T$, regardless of how it is written as a linear combination.
Comment: this is exactly what I'm asking for... What is the only thing to be proved for T to be extended? But I want to express it in the abstract setting, without mentioning the fact the my vectors are functions.


Mysql Strict Mode?

Question: Is Drupal 7 running in mysql strict mode?
I am getting errors such as:

Invalid datetime format: 1292

Is there a way to turn this off?
Answer: Yes it is. It is documented on this issue: http://drupal.org/node/303054

Mysql Strict Mode?


Using Coldfusion's CFFILE tag to monitor a progress log from FFMpeg

Question: I want to learn how to use the CFFILE tag from ColdFusion to read the contents of a text file.  In my case, that text file is a progress log that is generated by FFMpeg while it transcodes a media file.  I want to write a ColdFusion script that will poll the progress log periodically, until the log indicates that FFMpeg has finished its transcoding operation.  On the client side I can then use Ajax to hit that ColdFusion script and show the user a "percentage completed" while FFMpeg does its work.
I got FFMpeg to generate the log file by using a new "progress" flag that recent versions of FFMpeg now support.  Below I'll show you the way to use this flag, and also the generated output within the log file.
Here's the FFMpeg command:
ffmpeg -i c:\my_original_file.ogg c:\my_converted_file.mp3 -progress c:\my_progress.txt

The above command will cause FFMpeg to generate a log file called my_progress.txt.
Here's what it generates in the log file:
total_size=206150
out_time_ms=51410044
out_time=00:00:51.410044
dup_frames=0
drop_frames=0
progress=continue

The above 6 lines are generated repeatedly in the log file, with increasing values.
total_size=206150
out_time_ms=51410044
out_time=00:00:51.410044
dup_frames=0
drop_frames=0
progress=continue
total_size=412413
out_time_ms=102975756
out_time=00:01:42.975756
dup_frames=0
drop_frames=0
progress=continue
total_size=618363
out_time_ms=154463111
out_time=00:02:34.463111
dup_frames=0
drop_frames=0
progress=continue
total_size=824939
out_time_ms=206107189
out_time=00:03:26.107189
dup_frames=0
drop_frames=0
progress=continue

Finally, when the job completes, the final block of 6 lines are the last ones in the log file.  Notice the "progress=end" on the last line:
total_size=9725902
out_time_ms=2431348011
out_time=00:40:31.348011
dup_frames=0
drop_frames=0
progress=end

I want to write a Coldfusion script using the CFFILE tag to read only the last 6 lines of the file (no matter how large the file has become), and to do this each time the script is called, by the browser, via Ajax.  Finally I need to parse the values on these lines into variables so I can return some data to the caller.
I've researched progress bars for FFMpeg but they're in PHP which is hard for me, and besides, they parse the older formatted versions of FFMpeg's log files, and I would like to use the above newer formatting.  Can anyone please help?
Comment: *using the CFFILE tag to read only the last 6 lines of the file* Just to clarify, none of the CF file tags/functions really support reading *only* the end of a file. You must read in the entire file, and loop backwards. Hence Peter's suggestion of using an external program like `tail` (which was specifically designed for this purpose).
Answer: To get the last six lines tail will be faster, since it works backwards and only loads what you ask for (rather than reading in the whole file then looping through it). It'll obviously also use less memory, no matter the file size.
<cfexecute
    name      = "tail"
    arguments = "--lines=6 #Filename#"
    timeout   = 30
    variable  = "LastSixLines"
    />

<cfset Data = {} />
<cfloop index="CurLine" array=#LastSixLines.trim().split('\n')# >
    <cfset Data[ListFirst(CurLine,'=')] = ListRest(CurLine,'=') />
</cfloop>

As you appear to be on Windows, you likely need to install tail (it's pre-installed for Linux and MacOS). The simplest option to get it would be MSYS, which you may already have depending on what other software you use - for example, Git for Windows uses MSYS, and has tail.exe in its bin folder.
In that case, the second line above changes to something like:
    name      = "C:/Program Files/Git/bin/tail"

If you need the code to work on multiple systems, you can make that part a variable, (or put the appropriate directory onto the system PATH so it can be called from anywhere).
Answer: This will read your file and create a structure with the last 6 lines.
<cffile action="read" file="myfile.txt" variable="myfile">

<cfoutput>
    <cfset linecount = listlen(myfile,chr(10))>
    #linecount# lines

    <cfset count = 0>
    <cfset stData = {}>
    <cfloop list="#myfile#" index="i" delimiters="#chr(10)#">
        <cfset count++>
        <cfif count GT linecount - 6>
            #i#

            <cfset stData[listfirst(i,'=')] = listlast(i,'=')>
        </cfif>
    </cfloop>
</cfoutput>
<cfdump var="#stData#">

The code above will output the raw data from the text file and create a structure based on the = being a delimiter
You could also store your file into an array and pull out the last 6 rows like so. This option is about 2x as fast with smaller files (<200k lines), but as the file size grows the two options are nearly identical and then the first option becomes faster at around 1M lines
<cffile action="read" file="c:\ColdFusion10\cfusion\wwwroot\myfile.txt" variable="myfile">

<cfset filearray = listToArray(myfile,chr(10))>
<cfset linecount = arrayLen(filearray)>
<cfset stData = {}>
<cfloop from="0" to="5" index="i">
   <cfset stData[listfirst(filearray[linecount - i],'=')] = listlast(filearray[linecount - i],'=')>
</cfloop>

Comment: The file would need to be huge before CF can't handle it. Each log set is approx ~110 bytes, so for the 40 minute example file, that's ~5KB of data. It would takes _days_ of audio just to get into MB territory (which is still far from too big for CF), and a log file could easily be cycled before that point. However, loading an entire file just for the last ~110 bytes _isn't_ the most efficient way, hence my tail suggestion.
Comment: This looks backwards.  Instead of starting your loop at the front of your variable, why don't you start at the end and step backwards 6 times?
Comment: @DanBracuk how would you loop backwards through it without causing a lot of extra processing? I added 1 million lines to the txt file and it reads in 300ms.
Comment:
Comment: @DanBracuk i updated my answer to only loop through the last 6 lines. It's a lot faster (100ms vs 15ms) with smaller files (200k lines), but as the file size grows (1 million lines) the first option becomes a better option
Comment: Actually, if the file grows too big ColdFusion won't be able to open it.
Comment: @DanBracuk I was able to open a file with a million lines, so I don't think he needs to worry about that


Guitar left hand fingering - how play this phrase?

Question: I stumbled upon this phrase, not knowing how to play it. I'm trying to get comfortable with this middle finger barre (it's hard to keep all strings pressed, especially D), which seems the only way not using thumb on bass note.

    1
    3
    2  2  4  2
E|--------------
B|--1-----4-----
G|--3-----------
D|-----2-----4--
A|--------------
E|--2-----------
Answer: It all depends how you many notes you want to ring on, and for how long. Using the approach you describe (with a middle-finger barre) you can keep all the notes (except the C on string 2) ringing until you get to the last note, where you will have to lift the middle-finger barre to get to the F#.
And yes, this is a little tricky, and would just need practice!
It is a little difficult to tell what effect you want, and so why you would use your suggested fingering, without seeing the phrase in context, and seeing what rhythm it has.  This would give a better idea of how to move-to and move-away-from this phrase, which would suggest fingerings. Also, seeing the phrase in context would suggest how long different notes in this phrase would ring for.
The first 3-note chord and the next note produce an F#7(b5) chord.  This is a reasonably common shape, which could simply be played with: finger 1 on string 2; 2 on string 6; 4 on string 3; the following E on string 4 with finger 3.  You would then probably need to move to play the next two fret 4 notes. If keeping the bass note F# ringing under all of this phrase is important, then yes, you could use your L.H. thumb (I'm useless at this!), or finger 2 as I suggest. Whether using your thumb or finger 2 on the low F#, you can then reach the next two fret 4 notes with your little finger (4), or if you want them both to ring, a little-finger barre! In either case, it would be very difficult to keep any of the previous notes (apart from the bass F#) ringing.
While maybe not a definitive answer, I hope this suggests some useful approaches. As I said before, it helps if the rhythm/context of the phrase is shown - sometimes TAB is not so great for this…
EDIT: Just one other thing… If you do use your thumb on the bass F#, you can then use: finger 1 on string 2; finger 2 on string 4; and finger 3 on string 3, for the first four notes.
EDIT TWO (!): You could even use a "wonky-barre" here, where your L.H. index finger plays the low F# (string 6, fret 2), and also plays fret 1 string 2, by being placed diagonally! In the end, I found all these fingerings in just a few minutes by experimenting. My second guitar teacher was a big fan of trying out many different fingerings, to see ones that improve the tone, or allow you play a piece/phrase more fluently. As with many aspects of guitar playing, fingering is very personal - although some fingerings will be more sensible or orthodox, it is a good idea to experiment, to find something that works for you.  I sometimes change fingerings several times while learning a piece/song, until I find one I'm really happy with.
Comment: Well, yes. But not necessarily an orthodox technique for all types of guitar playing. I would generally advise my guitar pupils not use their thumb on string 6 unless there is no alternative, and certainly not for classical guitar. Thanks for the up vote though!!
Comment: It's quite a personal choice this, but I would always advise players to weigh up the advantage of "gaining an extra finger for bass notes" against the technical benefits of keeping the thumb behind the neck. (Allowing fingers to avoid touching adjacent strings, having the thumb able to press against the fingers and the freedom gained by keeping the palm of the hand off the neck.)


Get List of files from directory in Scala

Question: I have a directory "/local/dath/mi/" which is including many files
03_ssa_fruits.csv
03_ssa_can.csv
03_ssa_veg.csv
sxattru.csv
sxprod.csv
sxstore.csv

I need to extract the list of specific files from that directory :
/local/dath/mi/03_ssa_fruits.csv
/local/dath/mi/03_ssa_can.csv
/local/dath/mi/03_ssa_veg.csv

I have tried the below code ,but it is not working.What I am doing wrong .Can anyone help me
def getListOfFiles(dir: String , naming: String): List[String] = {
      File(dir).toJava.listFiles.filter(_.isFile).toList.filter { file =>
        file.getName.startsWith("03_ss*")
      }.map(_.toString)
    }

   val listOfFile = getListOfFiles(parentDir, File(data.salFilePath).toJava.getName())

Comment: Try to remove `*` in file.getName.startsWith("03_ss*")
Comment: look into documentation https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#startsWith-java.lang.String-
String object method `startsWith ` has no support of regexp including wildcard so you need to specify just prefix `03_ss`
Comment: thanks ,it is working now.My mistake.Apologies !!
Comment: [os-lib](https://github.com/lihaoyi/os-lib) is the best modern solution for performing filesystem operations like this with Scala.  os-lib makes listing files so much easier and hides all the complexity of the underlying Java libs.  See my answer for more details.
Answer: Here is a simple example
import java.io.File

def getListOfFiles(dir: String): List[String] = {
  val file = new File(dir)
  file.listFiles.filter(_.isFile)
    .filter(_.getName.startsWith("03_ss"))
    .map(_.getPath).toList
}
getListOfFiles("dirrectory path")

Hope this helps!
Answer: os-lib is the easiest, most elegant way to perform Scala filesystem operations.
Here's how to list the files that start with "03_ss":
os.list(os.pwd/"local_data").filter(_.segments.toList.last.startsWith("03_ssa"))

This solution is powerful because it lets you perform additional filesystem operations on the files that start with "03_ssa".  You can move these files to an other directory, get the file sizes, rename them, delete them, whatever you want.
It's not like the other solutions that simply returns a list of strings.  See here for more info on how to harness the power of os-lib.
Here's the code snippet to setup a folder with OP's files if you'd like to experiment on your own machine:
os.makeDir(os.pwd/"local_data")
os.write(os.pwd/"local_data"/"03_ssa_fruits.csv", "")
os.write(os.pwd/"local_data"/"03_ssa_can.csv", "")
os.write(os.pwd/"local_data"/"03_ssa_veg.csv", "")
os.write(os.pwd/"local_data"/"sxattru.csv", "")
os.write(os.pwd/"local_data"/"sxprod.csv", "")
os.write(os.pwd/"local_data"/"sxstore.csv", "")

Answer: def pathStringToPath(pathString: String): Path = Paths.get(pathString)

def pathStringToDir(pathString: String): Option[File] = pathToDir(pathStringToPath(pathString))

def pathToDir(path: Path): Option[File] = {
  val file = path.toFile
  file.isDirectory match {
    case true => Some(file)
    case false => None
  }
}

def filesInDir(pathString: String): List[File] = {
  val dirOption = pathStringToDir(pathString)
  dirOption.fold(List.empty[File])(dir => dir.listFiles().toList)
}

def filesWithPrefixInDir(dirPathString: String, fileNamePrefix: String): List[File] =
  filesInDir(dirPathString).filter(file => file.getName.startsWith(fileNamePrefix))

filesWithPrefixInDir(parentDir, "03_ss")

Answer: def fetchFilesFromLocalDirectory(path : String) : List[File] = {
        val path = Paths.get(path)

        val file = path.toFile
        if(file.isDirectory){
            file.listFiles().filter(_.getName.endsWith(".txt")).toList
        }else List[File]() // TODO: If is not a directory, it should throw an error
    }


How do I use a loop statement to change specific values in a dictionary given an if statement?

Question: If I have a dictionary with each key having a list of values for example:
my_dict={'key1':[1, 6, 7, -9], 'key2':[2, 5, 10, -5,], 'key3':[-8, 1, -2, 6]}

And I want to create a loop statement to go through each value within the lists and change the value within my dictionary to 0 for each negative value. I can create a loop statement to go through each value and check if the value is negative but I can't figure out how to amend the dictionary directly:
for keys, values in my_dict.items():
    for value in values:
        if value < 0:
            value=0

How to I alter that last line (or do I have to change more lines) to be able to amend my dictionary directly to replace the negative values with 0?
Thanks in advance
Answer: One approach is to iterate over the .items of the dictionary and override each value directly using enumerate to keep track of the indices:
my_dict={'key1':[1, 6, 7, -9], 'key2':[2, 5, 10, -5,], 'key3':[-8, 1, -2, 6]}

for key, value in my_dict.items():
    for i, val in enumerate(value):
        value[i] = 0 if val < 0 else val

print(my_dict)

Output
{'key1': [1, 6, 7, 0], 'key2': [2, 5, 10, 0], 'key3': [0, 1, 0, 6]}

Alternative using the slicing operator and a list comprehension:
for key, value in my_dict.items():
    value[:] = [0 if val < 0 else val for val in value]

Some other useful resources:

Looping Techniques, discusses pythonic approaches to looping
Python names and values for understanding how variables work in Python
Slice assignment some light on how the second approach works
Comment: Thank you very much it has solved my issue and thank you for the resource on looping techniques!
Answer: Using max in a nested comprehension:
my_dict = {k: [max(0, v) for v in vals] for k, vals in my_dict.items()}