Create Object Array in foreach Javascript

Question: I have an Array with these values, I need to create a loop on these values to return in alasql like this example:
http://jsfiddle.net/agershun/11gd86nx/5/
var data = {
  "business": [
{
  "order_contents": [
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 85,
      "name": "product 3",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 84,
      "name": "product 2",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 84,
      "name": "product 2",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    }
   ]
  }
 ]
};

here's my code..
    info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot){
      snapshot.forEach(function(item) {

           jsonObj = {
              "business": [
            {
              "order_contents": [
                {
                  "id": itemVal['id'],
                  "name": itemVal['name'],
                  "price": itemVal['price'],
                  "quantity": itemVal['quantity'],
                  "total": "itemVal['total']
                }
              ]
            }
          ]
        }

its not creating an array, only the last value..
can someone help me?
Comment: If this is Firebase-related, please tag it as such.
Comment: ok, its tagged! thanks
Comment: You're overwriting the same variable (`jsonObj`) on each iteration, that's why it ends up with the last item. Where do you define `jsonObj` and what are you using it for?
Comment: i define as var jsonObj = [];   and I use for alasql to create a 'database' of this object
Comment: @sealabr Unfortunately your question has not aged well.   jsFiddle sample is no longer available. It's unclear the return type of the startAt and endAt functions. By tailoring the payload and functions 'just enough to recreate the error questions will get faster responses and have greater longevity.
Answer: You have to define your array in the beginning and add each object to it later on in your loop:
var result = { business: [] }; // PLACEHOLDER
var jsonObj;
info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot) {
        snapshot.forEach(function(item) {
            jsonObj = {
                "order_contents": [
                    {
                        "id": itemVal['id'],
                        "name": itemVal['name'],
                        "price": itemVal['price'],
                        "quantity": itemVal['quantity'],
                        "total": "itemVal['total']
                    }
                ]
            };
            result.business.push(jsonObj);  // ADDING EACH OBJECT TO YOUR ARRAY
        });
    });

Comment: Hm wait, but you have an object like that already? Your `data` variable is structured in that way - `Object { business: Array[1] }`...
Comment: I updated my answer... Is that what you are looking for?
Comment: ok but its returns Array [ Object, Object, Object......] need to be .....Object { business: Array[1] }
Comment: yeah I need to create this object 'jsonObj' (in foreach) exactly like this 'data' ..because this 'data' is an example.
Comment: "never define variables inside a loop when possible" only pertains to regular `for` and `while` loops as they don't scope the variables properly. Defining variables in callbacks, as with `forEach`, is perfectly fine and definitely preferable to overwriting a variable in the outside closure.
Answer: You want to map the items in snapshot to a new array, so instead of using the forEach method, use the map method and the resulting array it returns:
  jsonObj = snapshot.map(function(item) {
    return {
      "business": [
        {
          "order_contents": [
            {
              "id": item['id'],
              "name": item['name'],
              "price": item['price'],
              "quantity": item['quantity'],
              "total": item['total']
            }
          ]
        }
      ]
    }
  });


After updating the metatag module I am unable to edit the metatag section of a taxonomy term

Question: Today I have updated the Metatag module to the latest version (7.x-1.0).
However, I try to edit the metatags of a taxonomy term and, after saving the change, nothing changes (it doesn't save the changes).
I have been researching into the issue and I have read that this can happen when the metatag module is not up to date.
A new development version (7.x-1.x-dev) has been released today. I have tried downloading and using the development version (7.x-1.x-dev) and I still have the same problem. Is the problem related with database corruption? What do I need to do to solve the problem?
Answer: Please try updating to the latest version, there were a few issues in 1.0 that were fixed in subsequent releases.
Disclaimer: I'm the module's maintainer.


Tree structure in C, for navigation in preorder depth-first manner

Question: How will you implement a tree structure in C for navigation in preorder depth-first manner?
Comment: A tree *is* a data structure.
Comment: I edited the question, is it more clear now ?
Comment: possible duplicate of [N-ary trees in C](http://stackoverflow.com/questions/189855/n-ary-trees-in-c)
Comment: I'll write a simple struct with two pointers in it and implement preorder as a recursive function unless there are other constraints you are not telling. Is it you need help about the terminology, i.e. what is a tree, what is preorder traversal, what is depth-first search or I don't get the question.
Answer: A tree can be represented by two arrays: one that holds pre-order traversal and the second hold in-order traversal. This thread discusses [among other things] how it can be done.
Since array traversal is usually faster then tree traversal [due to cache performance mainly], you can represent the tree as 2 arrays, and use the pre-order traversal one to iterate.


Error setting / reading environment variables in Flask App | Access env variable in another file

Question: In __init__.py, I set the environment variable.
import os

# set mkey environment variable
MKEY="xxxx"
os.environ["MKEY"] = MKEY

And then I try to read the environment variable in another file - file1.py
import os
token = os.environ["MKEY"]

When I attempt to run the app on localhost, I get an error:
Traceback:
token = os.environ["MKEY"]
  File "/Applications/Anaconda/anaconda3/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'MKEY'

It looks like the environment variables are not being set properly or are only accessible in the file they are being set. I don't see them here either:
for key in os.environ.keys():
    print(key + ": " + os.environ[key])

How do I set environment variables that can be accessed across all files in my Flask App? Is there a way to set this in one of the files versus using export in the root directory?
Comment: `os.environ` sets the variable for the current session only. Use export for Linux or do it via registry for Windows.
Comment: @user56700 - Is there a way to set this in one of the files?
Comment: https://stackoverflow.com/questions/716011/why-cant-environmental-variables-set-in-python-persist
Comment: you can use singleton object ie dictionary to store the env variables and use the data from there and can use decorator if there is any update then export the data to env file something like that
Comment: @sahasrara62 mind writing up an answer? i'm not sure if I follow your comment.
Comment: I think it's probably less related to *"being in the same file"* and more related to *"being in the same process"*. Environment variables can not be seen across different processes and WSGI and Nginx are both allowed to use multiple processes (and threads) to improve performance.
Answer: maybe write a config file, say config.py where load all env in object like
config = {'db': os.getenv('user', 'user_db')}

and
set env there like , you are doing
os.environ['mike'] = mike

then do
config['mike'] = os.environ['mike']

and use this config object in the other file like
from config import config

you can write a function to set and update the configs
something like this you can do


Add a link field to block form

Question: I've created a module with a custom block that extends BlockBase. To the block form I added multiple textfields and select boxes, by simply specifying the formatter in the '#type' configuration.
My next step is to add a button that links to internal/external content and I've tried adding different types, such as 'link' but without any luck.
I found LinkFormatter, but I can't figure out how to use it properly with block forms.
What has to be added to the blockForm method in order to create a link field (just like the link field that's selectable within a custom block type):

My current code:
public function blockForm($form, FormStateInterface $form_state) {
  //...
  $form['link'] = [
    '#type' => 'link',
    '#title' => $this->t('Link title'),
    '#url' => 'Hmm?',
    '#options' => ['external' => TRUE]
  ];

  return $form;
}

Comment: The code has nothing to do with the screenshot. The code tries to output an "<a href..." html tag. The screenshot contains two text inputs to enter a link. The first text input has a database lookup. If you want this input and no output, you have to define these inputs in code, where do they come from and how to submit them.
Comment: I changed some details in the question. What I want is the "Link" field that's available on custom block types.
Comment: The code you are looking for is here:
core/modules/link/src/Plugin/Field/FieldWidget/LinkWidget.php
Comment: I posted a solution for a related question: https://drupal.stackexchange.com/questions/213472/add-link-field-in-custom-form-drupal-8/272914#272914
Answer: You want to change '#type' => 'link' to '#type' => 'url'
public function blockForm($form, FormStateInterface $form_state) {
  //...
  $form['link'] = [
    '#type' => 'url',
    '#title' => $this->t('Link title'),
    '#options' => ['external' => TRUE]
  ];

  return $form;
}

Comment: This will only result in a `` and not the desired result shown in the screenshot.
Answer: You should try this code:
$form['group1'] = array(
  '#type' => 'fieldset',
  '#title' => $this->t('Link Field'),
  '#collapsible' => FALSE,
  '#collapsed' => FALSE,
);

$form['group1']['url'] = array(
  '#type' => 'url',
  '#title' => $this->t('URL'),
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
);

$form['group1']['label'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('Link Text'),
);

Add a link field to block form


Assessing goodness-of-fit between a dataset and its fitted distribution

Question: I have multi-sample data which comprises distances between successive points on a line (1D vector), to which a gamma-distribution is fitted (and maximum likelihood parameters obtained). I would like to assess the quality of this fit.
I've read that GoF-tests such as the one-sample Kolmogorov-Smirnov (KS) or Anderson-Darling (AD) are inapplicable in this case and will produce inaccurate p-values because the theoretical distribution being compared to has been derived from the data itself and thus is not independent. Could anybody explain this further as i'm not sure I quite understand why it would be an issue?
Secondly, is bootstrap resampling (iterative sampling with replacement) a viable solution in this case to obtain more-accurate p-values and assessment of the fit? Following the resampling process and obtaining of, for example, KS-stats for each sample - how would one then "average" the results into a final conclusion/assessment or interpret the outcome?
Answer: The standard KS test is built with an assumption that you know the underlying distribution. For instance, you are testing for the standard normal distribution with mean zero and variance one. See item #3 here. For instance, if you assume Student t-distribution and estimate its parameters from the data, then you can't use KS test as it is usually implemented. There's a degree of freedom parameter, which is a problem.
One way to overcome this limitation is by bootstrapping. It's described in this paper: Jogesh Babu, G., and C. R. Rao. "Goodness-of-fit tests when parameters are estimated." Sankhya: The Indian Journal of Statistics 66 (2004): 63-74 They explain how exactly to do it, and why it works for parametric distributions
Comment: take a look at [this answer](http://stats.stackexchange.com/a/126552/36041) with code. there are some other good code examples out there for Lilliefors approach, which I used
Comment: +1 informative and helpful answer. I will read this paper ASAP although may struggle with the equations/math. In practical terms, would a parametric bootstrap simply consist of obtaining MLE distribution parameters for the actual data and then randomly sampling (with replacement) off of the distribution fit? What is the main purpose of this? What would generally be the next step?
Comment: Great, thank you! So the bootstrapped KS-stat would be compared to the newly generated critical values rather than the standard ones?
Comment: The ks statistic is the same. You bootstrap to get new critical values.


Intern working for Indian NGO - Help with PHP 4, advising staff

Question: For the past three months I've been working for an Indian NGO, doing some volunteer work in the field but also trying to improve their website, which needs a ton of work. Recently I've been trying to fix the "subscribe to newsletter" button, which is broken. I used filter_var to filter the email input, but when I tried to test this out I got an error. Then I learned that the web host is still using php version 4.3.2 and register_globals is turned on.
I've mentioned that they should upgrade their web host before. That would add a lot of complexity for the IT staff of 3, who would have to update everyone's email information (I assume? this is a 250-person organization), and have me find a new web host and teach them about it. The staff isn't that sophisticated about web usage - the head guy still uses IE6, and the website's laid out in tables (they use Dreamweaver WYSIWYG to lay out pages).
So I've got two options - use regular expressions to filter the email, which I'm not that skilled at doing (and would be more vulnerable to exploitation after I leave), turn off register globals and then try to teach the staff what I'm doing, or try to get them to upgrade their versions of PHP and MySQL and/or change web host. I'd appreciate some advice.
Thanks for your help,
Kevin
Comment: I suggest anonymizing your requests some, not giving out sufficient information for targeted technical attacks or social engineering, and breaking down your queries into smaller, more focused questions.
Comment: What kmarsh says, or shorter: Better remove the domain name of your employer to prevent shenanigans.
Comment: disable `register_globals` ASAP, everything else can wait.
Comment: I only got a quick generalistic suggestion: the more you change those 3 people's environment, the more work will end up falling on your shoulders, and you're volounteering. Avoid doing programming first hand, (it will probably backfire on you, and - given their lack of proficency - they won't be able to mantain it any more) make them understand how the system can be improved and let them help, even if you think they cannot or that the way they offer to help seems too long and convoluted.
Answer: First, I'd make the application run properly and as safely as possible in that environment, with regexes if necessary.
Then, I'd talk to the IT people. They need to upgrade their web package at some point and that point is already long past. PHP 4.3.2 is out and not supported any more at all (see here). That means that if a vulnerability is detected, it's not guaranteed to get a fix (altough it's still pretty likely due to the number of hosts not having switched yet).
Better do the switch now than later.
It's not really clear from your description how the people in the organization use E-Mail (do they have their own mail clients? Do they use web mail) but if they use their own mail clients, the "only" issue will be moving the mailboxes to a new host.
While that may take a few painful days to move all the mailboxes and redirects, and get everything running - including setting up everybody's workplace with the new data - it is not impossible to do, and will hardly add any long-term strain.
Answer: What I would do :
- fix your main issue asap : parse the email using a regexp, you can find some quite easily with google
- Discuss with the team about upgrading/migrating your host. Fixing the email problem first is allowing you to take your time in this matter.
I won't turn off register globals, because you might face many more problems on the other pages of the website. But this can remain in your 'todo list' as it would be a good update.
Comment: I don't think there are any other forms on the website - there's one to send people to a Google site search page and one to send people to Paypal, but that's it.
Answer: If security is a real big deal, then you need to introduce a layer to tackle intrusion. There are a few options in PHP land, but they all seem to require >5.1.4. Therefore I'd look at maybe installing mod_security if the web server layer is running apache. That way your application will be protected not just from POST injections, but GET injections and COOKIE exploitations as well. Secondly it'll future proof the application if next week they add another form to it without your knowledge.
It does sound though as if you've got your hands tied, and I'll be honest with you, if the company holds, or intends to hold any personal information about their users, or sensitive information about the company in an area accessible by the application, security is not a series of hacks or hotfixes, it's a serious commitment to a graceful and correct solution.
Best of luck.
Answer: The standard regex to check for RFC822 compliance is VERY ugly:
/^(?:[A-Za-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[A-Za-z0-9-]*[A-Za-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/

from http://www.regular-expressions.info/email.html (hopefully it cut/pasted ok).
But implementing this will just delay your pain. A webhost still living in the register_globals = on days should be dumped as soon as possible. It's just begging to be subverted.


How to create a new resources on Rails

Question: I am using Ruby 1.9.3 and Rails (rubygems-1.8.24) on Windows 7.
I successfully created an application called 'blog'. So far I could
run a local server (WEBrick) and make Hello, Rails! appear at
localhost:3000
But now I try to create a new resource but to no avail.. Here is the
code in routes.rb
Blog::Application.routes.draw do

  resources :posts

  root to: "welcome#index"
end

When I type :
$ rake routes

I get this error message:
rake aborted!
c:/blog/config/routes.rb: syntax error, unexpected_keyword_end, expecting $end
c:65535:in 'execute_if_updated'
c:/blog/config/environment.rb:5:bin '<top (required)>'
Tasks: TOP => routes => environment
(see full trace by running task with --trace)

when it should show the following:
$ rake routes
    posts GET    /posts(.:format)          posts#index
          POST   /posts(.:format)          posts#create
 new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
     post GET    /posts/:id(.:format)      posts#show
          PATCH  /posts/:id(.:format)      posts#update
          PUT    /posts/:id(.:format)      posts#update
          DELETE /posts/:id(.:format)      posts#destroy
     root        /                         welcome#index

After running $ rake routes --trace, I get:
c:\blog>rake routes --trace
** Invoke routes (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
c:/blog/config/routes.rb:69: syntax error, unexpected keyword_end, expecting $end
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:223:in `load'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:223:in `block in load'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:223:in `load'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application/routes_reloader.rb:40:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application/routes_reloader.rb:40:in `load_paths'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application/routes_reloader.rb:16:in `reload!'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application/routes_reloader.rb:26:in `block in updater'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/file_update_checker.rb:75:in `call'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/file_update_checker.rb:75:in `execute'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application/routes_reloader.rb:27:in `updater'
C:65535:in `execute_if_updated'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application/finisher.rb:69:in `block in <module:Finisher>'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/initializable.rb:30:in `instance_exec'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/initializable.rb:30:in `run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/initializable.rb:55:in `block in run_initializers'
C:/Ruby193/lib/ruby/1.9.1/tsort.rb:150:in `block in tsort_each'
C:/Ruby193/lib/ruby/1.9.1/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'
C:/Ruby193/lib/ruby/1.9.1/tsort.rb:219:in `each_strongly_connected_component_from'
C:/Ruby193/lib/ruby/1.9.1/tsort.rb:182:in `block in each_strongly_connected_component'
C:/Ruby193/lib/ruby/1.9.1/tsort.rb:180:in `each'
C:/Ruby193/lib/ruby/1.9.1/tsort.rb:180:in `each_strongly_connected_component'
C:/Ruby193/lib/ruby/1.9.1/tsort.rb:148:in `tsort_each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/initializable.rb:54:in `run_initializers'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application.rb:215:in `initialize!'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/railtie/configurable.rb:30:in `method_missing'
c:/blog/config/environment.rb:5:in `<top (required)>'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application.rb:189:in `require_environment!'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/application.rb:250:in `block in run_tasks_blocks'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:236:in `call'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:236:in `block in execute'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:231:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:231:in `execute'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:175:in `block in invoke_with_call_chain'
C:/Ruby193/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:168:in `invoke_with_call_chain'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:197:in `block in invoke_prerequisites'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:195:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:195:in `invoke_prerequisites'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:174:in `block in invoke_with_call_chain'
C:/Ruby193/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:168:in `invoke_with_call_chain'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/task.rb:161:in `invoke'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:149:in `invoke_task'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:106:in `block (2 levels) in top_level'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:106:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:106:in `block in top_level'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:115:in `run_with_threads'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:100:in `top_level'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:78:in `block in run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:165:in `standard_exception_handling'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/lib/rake/application.rb:75:in `run'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rake-10.1.1/bin/rake:33:in `<top (required)>'
C:/Ruby193/bin/rake:23:in `load'
C:/Ruby193/bin/rake:23:in `'
Tasks: TOP => routes => environment

Comment: Which version of Rails?
Comment: You've missed an end keyword out since it says expecting $end
Comment: Rails 4.0.2 is the one installed
Comment: It looks fine, so maybe it's a red herring? Also the root path ought to come first...
Comment: sometime people writes > resources: posts
instead of > resources :posts
(Space between colon)
Answer: The error you're getting in your --trace output is:
c:/blog/config/routes.rb:69: syntax error, unexpected keyword_end, expecting $end

This says the error is on line 69 of your config/routes.rb file. The routes file content that you posted is only 6 lines long, so I'm guessing you haven't posted your whole routes.rb. If you post the whole file, then someone might be able to help you, but as-is, we can't.
Comment: bingo!! line 69 was 'end' not uncommented!! uncommented it and it runs like a charm!
Answer: The first line on your routes folder might be incorrect. You have routes in lowercase. Try replacing the first line of the routes.rb file with this:
Blog::Application.Routes.draw do

Comment: Would you run the command again with the --trace option and edit your question to add the results?
Answer: change your routes file to:
root "welcome#index"

Comment: nvm, i think this might be wrong.  I will do some more research and get back to you.
Answer: This how your config/routes.rb is supposed to look like
Rails.application.routes.draw do
  # get 'welcome/index'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end

end

Rails.application.routes.draw do

  resources :articles

  root 'welcome#index'
end

How to create a new resources on Rails


How to Deal with Unused MVC Routing Parameters

Question: I have an MVC application and the UI team has requested that urls for a careers page follow this format: mydomain.com/careers/{jobTitle}/{JobCode}. I can do that in the careers controller like this:
    public ActionResult Detail(string jobTitle, string jobCode)
    {
        var model = getModelFromDb(JobCode);
        return View(model);
    }

The problem is that we look up the career info by job code not title so we end up with an unused parameter. I don't think this is best practice. Especially since you can enter whatever you want for the career title and still get the job details back. A url like this would still work: mydomain.com/careers/yourmom/1234.
I suppose we could always look up careers by title and code but that seems kind of pointless since the codes are unique.
Is there a better way to implement the extra parameter in the url and keep from allowing invalid job titles from being put in the url?
Comment: One thing you could try is make jobTitle optional, but that means changing the url format to {JobCode}/{jobTitle} and i guess that's not an option?
Comment: have a look at this question and answer http://stackoverflow.com/questions/24678045/routing-optional-parameters-in-asp-net-mvc-5 . can use optional parameter in routing
Comment: I guessing you might be wanting a 'slug' route (where including only `jobCode` will result in a url with both the `jobcode` and `jobTitle`)? If so, refer [this answer](http://stackoverflow.com/questions/30349412/how-to-implement-url-rewriting-similar-to-so/30363600#30363600)
Answer: You can create your own custom route constraint, this will allow to match only routes that contain jobtitle that match the jobcode.
You will have to inherit from the IRouteConstraint interface and implement the Match method. One of the parameters that the method receive is a RouteValueDictionary.
It is a collection of key/value pairs containing the routing parameters. You can use them to look up the job title and make sure it is coherent with the job code.
See this example for more info.
In this way you will be able to receive only correct routes and reject incorrect routes like mydomain.com/careers/yourmom/1234
Answer: What we ended up doing is passing both parameters to the controller(jobTitle and jobCode), looking up the record by jobCode, and validating that the record's slug matches the jobTitle passed in(all case insensitive). This way we prevent bogus urls from returning job detail pages and we keep the UI team happy.


A header displays differently on ie/safari and on chrome. How to make it the same

Question: CSS
<code>.header {
    position: fixed;
    font-family:Arial, Helvetica, sans-serif;
    top: 0;
    left: 0;
    width: 100%;
    height: 80px;
    z-index: 10;
    -webkit-box-shadow: 0 10px 15px rgba(0, 0, 0, 0.12);
    -moz-box-shadow: 0 10px 15px rgba(0, 0, 0, 0.12);
    box-shadow: 0 10px 15px rgba(0, 0, 0, 0.12);
    color: #FC0;
    background-color: #FC0;
}
</code>
ie/safari (ie11)
chrome (77)
I want it to look like the ie screenshot on all platforms. Chrome on my iphone 8+ renders the same as ie but on pc it is different. What have I done wrong?
Comment: Welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour) and read about how to create a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve). It will make things easier for those trying to help you and increase your chances of quickly getting a solution to your problem.
Comment: Add your supporting HTML snippet as well.
Comment: add u r html code also
Comment: Please add full header html with css of each item.
Answer: I just added a php include for the header and miraculously every browser now looks the same. I don't know why. But it worked.


How to print JSON objects with inner key value objects

Question: I have the following structure of JSON objects. Each Mealplan consists of a key and a value which is an object meal.
id: 1,
mealsPerWeek: {
    Monday: {
       id: 4,
       name: "Burger",
    },
    Tuesday: {
       id: 3,
       name: "Salad",
    },
id: 2,
mealsPerWeek: {
    Monday: {
       id: 3,
       name: "Salad",
    },
    Tuesday: {
       id: 2,
       name: "Fishburger",
    },

And I want to create a list like this (as innerHTML):
ID: 1

 - Monday: Burger
 - Tuesday: Salad

ID 2:

 - Monday: Salad
 - Tuesday: Fishburger

I already created a loop, to get the mealplan ID's. The assets are coming through an XmlHttpRequest:
renderMealplan(assets) {
    let mealplan = [];
    for (let i = 0; i < assets.length; i++) {
        mealplan[i] = {
            id: assets[i].id,
            mealsPerWeek: assets[i].mealsPerWeek,
        }
    }
 }

I already tried getting getting a list of the meal names like this:
 let content = ''
        mealplan.forEach(mealplan => {
            content += '
' + mealplan.id + '
' + '
' +
                '
' + JSON.stringify(mealplan.mealsPerWeek.Monday) +'
' +
        }); + '
'

but the outcome is just:
1
{"id":4,"name":"Burger"}

Using JSON.stringify(mealplan.mealsPerWeek.Monday.name also does not print the name of the meal because it is undefined.
How do I get all the information seperated and print it in a list? Also I don't find the solution to extract the keys of mealsPerWeek.
Comment: can you put your whole json object, the one you posted makes no sense
Answer: Your input data did not seem to be syntactically correct. Below I tried to put it into some valid form:

const arr=[
{id: 1,
 mealsPerWeek: { Monday: {id: 4,name: "Burger"},
                Tuesday: {id: 3,name: "Salad" }}},
{id: 2,
 mealsPerWeek: { Monday: {id: 3,name: "Salad",},
                Tuesday: {id: 2,name: "Fishburger"}}}];

 document.getElementById('cont').innerHTML=arr.map(h=>
  `<h1>ID: ${h.id}</h1><ul>`
  +Object.entries(h.mealsPerWeek).map(([day,{name}])=>
  `<li>${day}: ${name}</li>`).join('\n')+'
').join('\n')

Let me know if this is of any value to you?
A few explanations:

You don't need to apply JSON.stringfy() on an object's property if you want to get its value. arr[0].mealsPerWeek.Monday.name should directly get you the value "Burger".
Object.entries(obj) will return an array of arrays. Each sub-array will contain the key and value for each property of object obj
I used ES6 destructuring in the argument list for map: .map(([day,{name}])=>.... This way I have direct access to the key as dayand the meal name in the value-object as name.
Answer: For extracting the keys of mealsPerWeek:
You simply add the following line:
this.mealPlans.forEach((mealPlan)={
 mealPlan.meals = Object.keys(mealPlan.mealsPerWeek)
})

And than you can add the following for your content:
 let content = ''
    essensplan.forEach(mealplan => {
        content += '
' + mealplan.id + '
' + '
' +
            '
' + JSON.stringify(mealplan.mealsPerWeek[mealPlan.meals[0]]) +'
' +
    }); + '
'

Further you already know how to add the for loop for mealPlan.meals too.


How to add, rotate and drag line in IOS?

Question: What would be the best way in accomplishing this? Let's say I have a method (not defined) that would allow a line with a fixed size and color to be drawn on the screen. This line would need to then accept rotate gestures and panning gestures in order to move around the screen. It won't resize, it only needs to rotate and translate.
What is the best way of going about this? Should lines be subviews or sublayers to parent view? What is the method for drawing a line in ios? How to handle multiple lines on screen? I just want someone to lead me down the right path in the ios graphics jungle.
Answer: Firstly, you need to consider how complex the whole drawing is. From your description it sounds like the task is relatively simple. If that is the case, then Core Graphics would be the way to go. If the drawing is significantly more complex, you should look at OpenGL ES and GLKit, though using OGL involves a fair bit more work
Assuming Core Graphics, I'd store the centre point, angle and length of the line, and change the angle and size using the gesture recognizers, and calculate the points to draw using basic trig. Loop over the points to draw in the view -drawRect method and draw each one with the appropriate CG functions - call [view setNeedsDisplay] or [view setNeedsDisplayInRect:areaToRedraw]to trigger the redraws. (The second method only redraws the part of the view you specify, and can be used to improved performance).
The first of a series of tutorials on Core Graphics is here.- the part on 'drawing lines' will be most relevant. I haven't done this one (I used the old edition of this book), but I've followed a lot of others from this site and found them very helpful
As a side note you'll probably need a way to focus on a particular line if you have more than one on the screen- an easy way would be to find the line centre point closest to the point the user touched.
Answer: It seems that the best API for drawing lines like you want is with Core Graphics. Put this code within your UIView's drawRect method:
/* Set the color that we want to use to draw the line */
[[UIColor redColor] set];
/* Get the current graphics context */
CGContextRef currentContext =UIGraphicsGetCurrentContext();
/* Set the width for the line */
CGContextSetLineWidth(currentContext,5.0f);
/* Start the line at this point */
CGContextMoveToPoint(currentContext,50.0f, 10.0f);
/* And end it at this point */
CGContextAddLineToPoint(currentContext,100.0f, 200.0f);
/* Use the context's current color to draw the line */
CGContextStrokePath(currentContext);

For the gesture recognition, use UIGestureRecognizers. Use the following methods
- (IBAction)handleRotate:(UIRotationGestureRecognizer *)recognizer
- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer


What is the proper terminology for the parts of a bayesian hierarchial model?

Question: Lets say I have the following JAGS model, what are the proper terms for the three parts and 1/tau?
<code>  model{
  #Term???
  for(n in 1:Ndata){
  y[n] ~ dnorm( mu[ subj[n] ], tau[ subj[n]] )
  }

  #Term???
  for(s in 1:Nsubj){
  mu[s] ~ dnorm( muG, tauG)
  tau[s] ~ dgamma( 5, 5)
  }

  #Term???
  muG ~ dnorm( 80, .01)
  tauG ~ dgamma( 1, 1)

  }
</code>
What would I call each of the three parts?
Also, for the parameters I would say:

mu= "Individual Level Mean"
tau= "Individual Level Precision"
muG= "Group Level Mean"
tauG= "Group Level Precision"

Now what would I call 1/tau? "Variance"?
Answer: Yes, see slide 12 of the following document:
http://www.stat.cmu.edu/~rsteorts/jags_present.pdf
Comment: Thanks. My problem is that it seems confusing to refer to the "error" of the fit as variance since variance is usually a property of the data.
Comment: @Flask The variance is a general definition that applies to distributions in general. For the normal model this quantity happens to be $\sigma^2$. The variance of a data set is an estimator of the distribution where they come from. This [link](http://www.biostat.jhsph.edu/~fdominic/teaching/bio656/labs/labs08/lab2.popular.pdf) may shed some light on this.
Comment: I just realized this example is not perfect for what I am thinking. If instead I was fitting a line and modelling the error of the fit as normally distributed it would be analogous to the mean squared error. You would say still use the term "variance" and if I report the square root it would be "standard deviation"?
Comment: @Flask I see your point. Indeed, if you have a linear regression model of the type ${\bf y} = {\bf X}{\bf \beta} + {\bf \varepsilon}$, where each entry $\varepsilon_j\stackrel{ind.}{\sim} \text{Normal}(0,\tau^{-1}= \sigma^2)$, then ${\bf \varepsilon}$ represents the residual errors, which is a random vector, $\tau$ is the precision of the entries of this random vector, $\sigma^2$ is the variance, and $\sigma$ is the standard deviation.
Comment: @Multis So... if I were to discuss in a publication perhaps I could say "residual error variance" and people would understand. Because there would also be a variance term for e.g. the slope parameter.
Comment: @Flask In a publication you can simply refer to $\sigma$ as a parameter of the Bayesian model. "We use the prior $\pi()$ for $\sigma$", "the posterior distribution of $\sigma$ is given by", "the posterior variance of $\sigma$", "the posterior variance of $\beta$" ... Things like that. In Bayesian linear regression $\beta$ and $\sigma$ are random variables, and therefore they are better described through their posterior distributions, rather than just their variances.
Comment: I understand but need to explain plots to people who do not know what a posterior distribution is and will glaze over if too many alien symbols are used.


How to get rid of "margin"

Question: I would like to know how to get rid of the white space at the very bottom of my webpage, it is really annoying me and it isn't meant to be there.
Code below:

<link rel="stylesheet" type="text/css" href="freeloves.css">

HTML Code :

Home

Album

Album Featured

No Space

Album 1 Column, No Space

Album 2 Columns, No Space

Album 3 Columns, No Space

Album 4 Columns, No Space

With Space

Album 1 Column With Space

Album 2 Columns With Space

Album 3 Columns With Space

Album 4 Columns With Space

Inside Album

Event

Event List

Event List With Month

Event Widget Style

Single Event

Members

Pages

404 Page

Features

New Page Builder

Parallax/Color Wrapper

Custom Skin

Sidebar Size Customizable

Scalable Container

Floating Navigation

Boxed/Full Style

Woocommerce Friendly

Mega Menu

Unlimited Sidebar

Font Uploader

Shop

Shop With Sidebar

Shop Full Width

Cart

Checkout

My Account

Contact Page 1

Contact Page 2

Video Tutorial

Installing theme and Setting as demo site

Page Builder

Creating Portfolio & Filterer

Creating Blog

Thumbnail Management

Creating Gallery

Gallery

Gallery 2 Columns

Gallery 3 Columns

Gallery 4 Columns

Gallery 5 Columns

Gallery 2 Columns With Caption

Gallery 3 Columns With Caption

Gallery 4 Columns With Caption

Gallery 5 Columns With Caption

Testimonial

Portfolio

Portfolio With Text

Portfolio 1 Column With Text And Space

Portfolio 2 Columns With Text And Space

Portfolio 3 Columns With Text And Space

Portfolio 4 Columns With Text And Space

Portfolio 2 Columns With Text, No Space

Portfolio 3 Columns With Text, No Space

Portfolio 4 Columns With Text, No Space

Portfolio Modern

Portfolio 1 Column Modern Style With Space

Portfolio 2 Columns Modern Style With Space

Portfolio 3 Columns Modern Style With Space

Portfolio 4 Columns Modern Style With Space

Portfolio 2 Columns Modern Style, No Space

Portfolio 3 Columns Modern Style, No Space

Portfolio 4 Columns Modern Style, No Space

Portfolio With Filter

Portfolio Grid 1 Columns With Filter

Portfolio Grid 2 Columns With Filter

Portfolio Grid 3 Columns With Filter

Portfolio Grid 4 Columns With Filter

Blog

Blog Full

Blog Full With Right Sidebar

Blog Full With Left Sidebar

Blog Full With Both Sidebar

Blog Full Without Sidebar

Blog Column

Blog 1 Column (Right Sidebar)

Blog 2 Columns (Right Sidebar)

Blog 3 Columns

Blog 4 Columns

Blog Masonry

Blog 2 Columns – Masonry (Right Sidebar)

Blog 3 Columns – Masonry

Blog 4 Columns – Masonry

Blog Medium

Blog Medium With Left Sidebar

Blog Medium With Right Sidebar

Blog Medium With Both Sidebar

Blog Medium Without Sidebar

Shortcodes

Set 1

Accordion/Toggle Box

Audio Shortcode

Button

Column Shortcode

Divider

Event Widget

Gallery Shortcode

Set 2

Heading Tag

icons & icon boxes

Lightbox & Frames

Notification Boxes

Members

Music Player

Post Slider

Set 3

Price Table

Process

Progress Circle

Skills

Slider Shortcode

Space

Set 4

Styled Box

Stunning Text

Table

Tabs

Testimonial & Quote

Typography

Video

Our Latest Album   /   Fresh from the house of Music Club Band

Javascript :

CSS :
body {
  margin: 0;
  padding: 0;
  overflow-y: scroll;
  font-family: Arial;
  font-size: 16px;
}

body, html {
  margin: 0;
  height: 100%;
  width: 100%;
}

.nav-wrapper {
width: 100%;
margin: 0;
text-align: left;
}

.nav {
  background-color: rgba(34,34,34,0.5);
  padding-bottom: 10px;
  padding-top: 10px;
  position: fixed;
  z-index: 2;
  width: 100%;
}

.nav ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
  position: relative;
}

.nav ul li {
  display: inline-block;
  margin-right: 0px;
}

.nav ul li a,visited {
  color: #ccc;
  display: block;
  padding: 15px;
  text-decoration: none;
}

.nav ul li a:hover {
  color: white;
  text-decoration: none;
  transition: color 0.2s ease-in;
}

.nav ul li:hover ul {
  display: block;
}

.nav ul li img.arrow {
  vertical-align: middle;
  padding-left: 5px;
  width: 17%;
  transform: rotate(270deg);
  transition-duration: 0.5s;
}

.nav ul li img.arrow3 {
  vertical-align: middle;
  padding-left: 5px;
  width: 24%;
  transform: rotate(270deg);
  transition-duration: 0.5s;
}

.nav ul li:hover img.arrow3 {
  vertical-align: middle;
  padding-left: 5px;
  width: 24%;
  transform: rotate(360deg);
  transition-duration: 0.5s;
}

.nav ul li:hover img.arrow4 {
  vertical-align: middle;
  padding-left: 5px;
  width: 12%;
  transform: rotate(360deg);
  transition-duration: 0.5s;
}

.nav ul li img.arrow4 {
  vertical-align: middle;
  padding-left: 5px;
  width: 12%;
  transform: rotate(270deg);
  transition-duration: 0.5s;
}

.nav ul li ul li:hover img.arrow2 {
  vertical-align: middle;
  padding-left: 5px;
  width: 7%;
  transform: rotate(360deg);
  transition-duration: 0.5s;
}

.nav ul li ul li img.arrow2 {
  vertical-align: middle;
  padding-left: 5px;
  width: 7%;
  transform: rotate(270deg);
  transition-duration: 0.5s;
}

.nav ul li:hover img.arrow {
  vertical-align: middle;
  padding-left: 5px;
  width: 17%;
  transform: rotate(360deg);
  transition-duration: 0.5s;
}

.nav ul ul {
  display: none;
  position: absolute;
  background-color: #222;
  border: 5px solid #222;
  min-width: 100px;
}

.nav ul ul li {
  display: block;
}

.nav ul ul li a,visited {
  color: #ccc;
}

.nav ul ul li a:hover {
  color: white;
  transition: color 0.2s ease-in;
}

.nav ul li ul li.submenu-item52 ul {
  min-width: 350px;
}

.nav ul ul li.submenu-item2 ul {
  left: 147px;
  top: 50px;
  min-width: 250px;
}

.nav ul ul li.submenu-item50 ul {
  left: 150px;
  top: 50px;
  min-width: 250px;
}

.nav ul ul li.submenu-item62 ul {
  left: 147px;
  top: 100px;
  min-width: 250px;
}

.nav ul ul li.submenu-item51 ul {
  left: 150px;
  top: 100px;
  min-width: 250px;
}

.nav ul ul li.submenu-item52 ul {
  left: 150px;
  top: 252px;
}

.nav ul ul li.submenu-item53 ul {
  left: 150px;
  top: 303px;
  min-width: 250px;
}

.nav ul ul li.submenu-item54 ul {
  left: 190px;
  top: -1px;
  min-width: 350px;
}

.nav ul ul li.submenu-item55 ul {
  left: 150px;
  top: 151px;
  min-width: 345px;
}

.nav ul ul li.submenu-item60 ul {
  left: 152px;
  top: 50px;
}

.nav ul ul li.submenu-item61 ul {
  left: 150px;
  top: -1px;
}

.nav ul ul li.submenu-item70 ul {
  left: 189px;
  top: 50px;
  min-width: 350px;
}

.nav ul ul li.submenu-item71 ul {
  left: 189px;
  top: 100px;
  min-width: 350px;
}

.nav ul ul li.submenu-item72 ul {
  left: 140px;
  top: -1px;
  min-width: 350px;
}

.nav ul ul li.submenu-item73 ul {
  left: 150px;
  top: 50px;
  min-width: 345px;
}

.nav ul ul li.submenu-item74 ul {
  left: 150px;
  top: 100px;
  min-width: 350px;
}

.nav ul ul li.submenu-item80 ul {
  left: 153px;
  top: 100px;
  min-width: 350px;
}

.nav ul ul li.submenu-item81 ul {
  left: 153px;
  top: 151px;
  min-width: 350px;
}

.menu-code {
  max-width: 200px;
  min-width: 150px;
}

.menu-code ul li {
  max-width: 300px;
  min-width: 250px;
}

.logo {
  width: 75%;
  height: 75%;
  vertical-align: middle;
  margin-left: 100px;
}

.nav ul li ul {
  border-top: 1px solid #D4941F;
}

ul li ul li {
border-bottom: 1px solid #111;
}

ul li ul {
  border-right: 5px solid #111;
}

.slider {
    overflow: hidden;
    position: relative;
    margin-bottom: 0;
}
.slides, .slide {
    list-style: none;
    margin: 0;
    padding: 0;
}
.slides img {
    margin: auto;
    width: 100%;
    height: 971px;
    -webkit-filter: brightness(1);
    filter: brightness(1);
}
.slide {
    float: left;
}
.slider .toggles {
    color: #000;
    height: 48px;
    margin: auto;
    opacity: 0;
    position: absolute;
    top: 0;
    bottom: 0;
    transition: all .3s linear;
    width: 48px;
    z-index: 3;
}
.slider .toggles:hover {
    cursor: pointer;
}
.slider:hover .toggles {
    opacity: 1;
}
.slider .toggles i:before {
    margin: auto;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
}
.slider #toggle-right i:before, #slider #toggle-left i:before {
    height: 20px;
    width: 18px;
}

#toggle-right {
    right: 0;
    margin-right: 100px;
    margin-bottom: auto;
}
#toggle-left {
    left: 0;
    margin-bottom: auto;
    margin-left: 75px;
}

#left-arrow {
  transform: rotate(180deg);
}

.toggle-arrow {
  width: 100px;
  height: 180px;
  opacity: 0.6;
}

.music {
    position:fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    opacity: 0.5;
    width: 50%;
    margin-right: 100px;
    margin-top: 800px;
    transition: opacity 0.5s;
}

.music:hover {
    position:fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    opacity: 0.9;
    width: 50%;
    margin-right: 100px;
    margin-top: 800px;
    transition: opacity 0.5s ease-in;
}

.content1 {
  background-image: url("http://www.thefreeloves.com/prototype/test/wp-content/uploads/2014/02/album-title.jpg");
  color: white;
  text-align: center;
  width: 100%;
  height: 10%;
  display: block;
  float: left;
}

.text1 {
  font-family: "Goudy Old Style", Optima, sans-serif;
  font-size: 40px;
}

.text2 {
  font-size: 30px;
  color: #6CB9D9;
}

.slash {
  color: white;
  font-size: 50px;
}

Comment: better create a demo?
Comment: I created plunkr for OP. Here it is: http://plnkr.co/edit/I2V0PoUri5o8tzjzeDHt?p=preview
Comment: Hey. I couldn't really see the margin you're referring to!
Comment: Have you tried removing the `` tag? :-)
Comment: @paxdiablo OHHHHHH. That would be it, thanks!
Comment: AMorris, I transferred your pastebin directly into this page since it's usually better to have it self-contained. However, there appears to be some naked CSS at the end of your HTML. What was your intent there?
Answer: The white space is because of that code:

Our Latest Album   /   Fresh from the house of Music Club Band

If you remove that, the whitespace is gone.

But if you like it, you can solve by adding margin-bottom: 0 and margin-top: 0 to the h3.text1:
.text1 {
  font-family: "Goudy Old Style", Optima, sans-serif;
  font-size: 40px;
  margin-top: 0;
  margin-bottom: 0;
}

So beautiful!
Answer: Most likely, this stems from the default margin/padding of body. Try adding
html,body {padding:0; margin:0;}

Refer This Page

How to get rid of "margin"


filtering results, manipulating data aspnet mvc

Question: I was wondering if anyone can suggest me a book or tutorial in order to enhance knowledge on data manipulation or filtering data results.
I would like to know how to create a query on Entity framework, pass that info to the controller and then manipulate data in a grid or list using checkboxes - eg only results with photo, etc - , price range sliders and more data results filtering from the UI.
Thank you so much.
ps: I have a tutorial in ajax but I`m looking in plain c#.
Answer: I won't suggest any book in particular but to do the things you've mentioned you should look into the following things:

Learn about ASP.Net MVC's default Model Binder: that's how you get data to your controller in a clean way, any proper ASP.Net MVC should cover this
Learn LINQ to SQL or LINQ to Entities: that's how you query the data. There are quite a few LINQ to Entities books out there.

Here's an up-to-date tutorial from Microsoft that covers pretty much what you are asking for: http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part1-cs.
Once your have mastered this, I suggest you look into the Model View-View Model pattern. It will help with much more complex stuff but don't rush into it.
Cheers
Comment: thank you for you answer. I´ve been trying to find an example or tutorial displaying data filtering. At the moment I found datatables.net with an ajax example. Guys from rolla published some info at http://www.codeproject.com/KB/database/Building_Dynamic_SQL.aspx , sommarks place some details at http://www.sommarskog.se/dyn-search-2008.html for sql server 2008.
Comment: My pleasure! If you are using EF, stay away from dynamic SQL. You won't need it. What you want is EF, LINQ to EF, and the EF WHERE/SORT/TAKE/SKIP commands: http://msdn.microsoft.com/en-us/library/bb738636.aspx.
Answer: Here's an up-to-date tutorial from Microsoft that covers all that what you are asking for:
Also ,There is Complete project available in the link below you can go through it hope it will help you understanding all that you want to learn.
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application


Showing that $(x,y)=\left(\frac{c\sin t+d}{a+b\cos t},\frac{e\cos t+f}{a+b\cos t}\right)$ parameterizes an ellipse

Question: I want to show that
$$\mathbf{P}(t) = (X, Y) =  \left( \dfrac{ c \sin t + d}{a + b \cos t} , \dfrac{ e \cos t + f }{a + b \cos t } \right)$$
is actually an ellipse, given that $ | b | \lt | a | $
How can I prove this?
What I have tried:
Guided by @orangeskid solution to a recent problem, I've defined the vector
$ \mathbf{r}(t) = (x(t),y(t), z(t)) = (c \sin t + d , e \cos t + f , a + b \cos t ) $
which is an ellipse in $3D$ space whose parametric equation is
$ \mathbf{r}(t) = [d, f, a]^T + \cos t \ [ 0, e, b ]^T + \sin t \ [c , 0, 0 ]^T $
Using matrix-vector notation, this can be written as
$ \mathbf{r}(t) = M \mathbf{v}(t) \hspace{50pt}(1) $
where
$ M = \begin{bmatrix} 0 && c && d \\ e && 0 && f \\ b && 0 && a \end{bmatrix} $
and
$ \mathbf{v}(t) = \begin{bmatrix} \cos t \\ \sin t \\ 1 \end{bmatrix} $
Now, we note that
$ \mathbf{v}^T(t) Q_0 \mathbf{v}(t) = 0 \hspace{50pt}(2) $
where
$Q_0 = \begin{bmatrix} 1 && 0 && 0 \\ 0 && 1 && 0 \\ 0 && 0 && -1 \end{bmatrix} $
From eq. $(1)$,
$ \mathbf{v}(t) = M^{-1} \mathbf{r}(t) \hspace{50pt} $
Substituting this into $(2)$,
$\mathbf{r}^T (t) Q \mathbf{r}(t) = 0 \hspace{50pt}(3) $
where
$ Q = M^{-T} Q_0 M^{-1} $
Thus, $(3)$ becomes
$\begin{bmatrix} x && y && z \end{bmatrix} \begin{bmatrix} Q_{11} && Q_{12} && Q_{13} \\ Q_{12} && Q_{22} && Q_{23} \\ Q_{13} && Q_{23} && Q_{33} \end{bmatrix} \begin{bmatrix} x \\ y \\ z \end{bmatrix} = 0 $
Dividing both sides of the above equation by $z^2$, we get
$\begin{bmatrix} \dfrac{x}{z} && \dfrac{y}{z} && 1 \end{bmatrix} \begin{bmatrix} Q_{11} && Q_{12} && Q_{13} \\ Q_{12} && Q_{22} && Q_{23} \\ Q_{13} && Q_{23} && Q_{33} \end{bmatrix} \begin{bmatrix} \dfrac{x}{z} \\ \dfrac{y}{z} \\ 1 \end{bmatrix} = 0 $
But, $ \dfrac{x}{z} = P_x = X, \dfrac{y}{z} = P_y = Y $, hence,
$\begin{bmatrix} X && Y && 1 \end{bmatrix} \begin{bmatrix} Q_{11} && Q_{12} && Q_{13} \\ Q_{12} && Q_{22} && Q_{23} \\ Q_{13} && Q_{23} && Q_{33} \end{bmatrix} \begin{bmatrix} X \\ Y \\ 1 \end{bmatrix} = 0 $
And this an equation of a conic in $X$ and $Y$.  Further investigation is needed to determine if it is indeed an ellipse.
Comment: When $|b| < |a|$, it's easy to see that the curve given by your initial parametric equations is bounded; if you already know it's a conic section, that's it, isn't it?
Comment: Yes.  I guess.  But still one can argue that it could a segment of a parabola or a hyperbola.
Answer: Try to solve $\cos t$ and $\sin t$ in terms of $x$ and $y$:
\begin{align}
  \cos t &= \frac{f-ay}{by-e} \\
  \sin t &= \frac{(ae-bf)x+bdy-de}{c(e-by)} \\
  \cos^2 t+\sin^2 t &=
  \left(
    \frac{f-ay}{by-e}
  \right)^2+
  \left[
    \frac{(ae-bf)x+bdy-de}{c(e-by)}
  \right]^2 \\
  c^2(by-e)^2 &=c^2(f-ay)^2+[(ae-bf)x+bdy-de]^2 \\
\end{align}
Now,
$0=
\begin{pmatrix}
  x & y & 1
\end{pmatrix}
\begin{pmatrix}
  (ae-bf)^2 & (ae-bf)bd & (bf-ae)de \\
  (ae-bf)bd & c^2(a^2-b^2)+b^2d^2 & c^2(be-af)-bd^2e \\
  (bf-ae)de & c^2(be-af)-bd^2e & c^2(f^2-e^2)+d^2e^2
\end{pmatrix}
\begin{pmatrix}
  x \\ y \\ 1
\end{pmatrix}$
and discriminants
$$\delta = (ae-bf)^2 (a^2-b^2)c^2 > 0$$
$$\Delta = -c^4 (ae-bf)^4 < 0$$
which gives a real ellipse providing $ae\ne bf$ and $c\ne 0$.


How to normalize log-likelihoods?

Question: I have referred to this post here. In my case, I am trying to normalize the log-likelihoods I obtained from the same data set. However, the approach in the top answer did not work out for me. Below are n = 100 of my log-likelihoods.
ll <-
c(-35480.7118796417, -2739.42871153509, -8362.32845821982, -8365.34260282213,
-9094.89673916007, -21270.2045379339, -12580.518821136, -13783.8037118782,
-42712.3278071616, -423837.36571571, -1805.78632985328, -2002.85063426255,
-3762.76492409086, -6849.63087008593, -11956.7406803718, -20976.5170841893,
-135949.201113163, -31498.4171087018, -15446.7854298957, -5120.27102265426,
-27618.8855708366, -1181406.765207, -80867.7262649035, -816098.492721317,
-10945.0893400045, -1628417.58006139, -16482.9909028172, -65197.3708076204,
-67871.4208617162, -77627.4857483449, -17479.5870536702, -93579.8562141009,
-5281.94699357017, -5554.87325489942, -15628.8543639877, -10632.6082887688,
-6489.97791129332, -11988.4625382098, -9170.39131516501, -9339.36646353115,
-113156.200514024, -2567.90247055723, -14467.0183704268, -48650.137758317,
-10495.0548182032, -2889.13562818923, -115485.747589673, -80143.5433253561,
-5428.78386244051, -15449.3451561719, -25609.2870701355, -3832.78432518107,
-24152.3367051411, -2272.05842004831, -3184.3778786079, -2727.35587110321,
-2416.5798834696, -31118.8156319793, -51467.1989404669, -1847.91304055039,
-75179.9905124732, -55387.6390729858, -6217.46116602578, -80167.2789661716,
-2262.83239548126, -7967.86416890192, -203981.847720651, -5348.68097367683,
-35539.3623924968, -29740.7965097703, -145107.587483733, -16038.5130132878,
-30534.4376362393, -164907.15448187, -18269.9830224852, -10168.7453829144,
-86431.7638673747, -30391.9503748769, -2836.02770007675, -5544.75647729347,
-4392.30776454182, -215937.960800752, -28141.7740166936, -7439.99455094574,
-13708.5567616969, -9908.51651663084, -46267.2625988753, -5158.62658552135,
-5521.97889928275, -1485.65777356592, -464662.123874468, -30866.4651125434,
-14037.8604686386, -4754.14972171724, -13552.1743710923, -4674.74137872854,
-6890.68419568385, -12060.9906749138, -5763.51938836069, -3472.01636104686
)

#Subtract everything by maximum of the log likelihoods
ll2 <- ll - max(ll)
#Throw away anything that is < log(10e-16/n)
ll3 <- subset(ll2, ll2 > log(10e-16/100))
> exp(ll3)
> 1

When I'm calculating ll3, I threw away my entire vector of log-likelihoods, which is problematic. Even when I was subtracting ll by its maximum, the resulting ll2 still contains values that are extremely small. So if I were to exponentiate them, I would get 0.
Comment: As  explained in Gordon Smyth's answer, your largest likelihood is $10^{139}$ times higher than any of the others -- is there any practical difference to $\infty$ times higher? If you think yes, you may need to explain the intended use-case
Comment: Why do you need to exponentiate them? Maybe that's where the answer is.
Answer: You haven't explained why you want to convert log-likelihoods into unlogged probabilities that add to one. Contexts in which you would need to convert log-likelihoods into weights like this are rare.
Anyway, you can get the probabilities simply by:
> p <- exp(ll - max(ll))
> p <- p/sum(sort(p))

It is impossible to do any better than this if you want unlogged numbers.
From the log-likelihoods you give in your post, it is obvious that the largest probability will be exactly 1 and most of the rest will be exactly 0. The largest log-likelihood that you give is -1485.658. The next largest is -1805.786.
Now
$$\exp(1805.786-1485.658) = 10^{139}$$
so your largest (unlogged) likelihood is bigger than the second largest by 139 orders of magnitude!
This shows that the second largest normalized probability will be about $10^{-139}$.
By the same reasoning, the 3rd largest $p$ will be $10^{-158}$, the 4th largest will be $10^{-225}$ and all the remainder will be zero because numbers below $10^{-300}$ are zero in double-precision arithmetic.
On the other hand, you could compute non-zero probabilities for all the log-likelihoods if you were willing to represent them on the natural log-scale.
For this data, the log-probabilities are simply
> logp <- ll - max(ll)

correct to machine accuracy.
If the largest log-likelihood wasn't so dominant, then you would need to add an extra step:
> sump <- sum(sort(exp(logp))
> logp <- logp - log(sump)

From a statistical inference point of view, it all seems very simple. One log-likelihood is very much larger than all the others. What could be simpler?
Assuming that the statistical models from which the log-likelihoods have been computed are comparable in some sense, then the parameters values that lead to the largest log-likelihood are the only ones that can be entertained. All the other parameter combinations lead to log-likelihoods that are so small they can be ruled out (unless the prior probabilities are truly dramatic, and you don't seem to have prior probabilities anyway).
Comment: I see. So in this case there is no way to normalize this set of log-likelihoods?
Comment: Re the first paragraph: does the question state these are from different datasets ?
Comment: No, these values are what I obtain after plugging in different parameter values into a function that returns the log likelihood.
Comment: @GordonSmyth The previous post is from 2013 and by a different OP (this issue may arise, say, in computing a conditional distribution for Gibbs sampling over a finite set, or for normalizing particle filter weights)
Comment: I'm computing different log-likelihoods for the same dataset. Sorry for the confusion.
Comment: @JuhoKokkala Thanks, I overlooked it was a different OP. I've edited my answer.
Comment: @GordonSmyth why do you say that needing to convert log likelihoods to probability is rare? Isn't this done when normalizing log likelihoods calculated from bayes' theorem?
Comment: For the record, scientific numerical libraries typically have a "logsumexp" function (or similarly named) for calculating the `sump` value. eg: in [pytorch](https://pytorch.org/docs/stable/generated/torch.logsumexp.html) and [scipy](https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.logsumexp.html).

How to normalize log-likelihoods?


JSTL forEach loop optimal way of next index value

Question: I have a request headers map where one of the header key value contains again a string as below shown example.
headerkey = abc=227,de_f=AE,ghf=ABCD,ijk=25.25,lmn=55.28,opq=GMT+4,rst=AS,uvw=vhigh,xyz=5000

Now I want to fetch only the de_f value i.e AE in an optimized loop condition

<c:forEach var="nextHeader" items="${header}"> <c:if test =
  "${nextHeader.key == 'headerkey'}"> <c:set var="headerkeystring"
  value="${nextHeader.value}"/> <c:set var="splitstring"
  value="${fn:split(headerkeystring, ',')}" /> <c:forEach var="i"
  items="${splitstring}"> <c:set var="subsplit" value="${fn:split(i,
  '=')}" /> <c:forEach var="k" items="${subsplit}"> <c:if test = "${k ==
  'de_f'}"> <c:out value="${k + 1}" />   </c:if> </c:forEach> </c:forEach> </c:if> </c:forEach>
Answer: Change the inner c:forEach and c:out as shown below that should give your result
<c:forEach var="k" items="${subsplit}" varStatus="status">
<c:if test = "${k == 'de_f'}">
<c:out value="${subsplit[status.index+1]}" />
</c:if>
</c:forEach>


How to show has_many component in Ruby on Rails

Question: my show.html.erb file is like below.

details of policyid: <%= @policies.id %>

<%= @policies.receipts.receipt_day %>

my controller is like below.
def show
    @policies=Policy.find(params[:id])
end

Model is like below
class Policy < ApplicationRecord
    has_many :receipts
end

class Receipt < ApplicationRecord
  belongs_to :policy
  has_many :outpatients
  has_many :hospitalizations
  has_many :surgeries
  has_many :others
end

Receipt Model has some record like this.
2.6.3 :005 > Receipt.all
  Receipt Load (0.3ms)  SELECT `receipts`.* FROM `receipts`
 => #<ActiveRecord::Relation [#<Receipt id: 1, receipt_day: "2019-11-01", policy_id: 1, created_at: "2019-11-20 08:21:21", updated_at: "2019-11-20 08:21:21">]>

I would like to show receipt_day in policy show file. is this possible?
I suffered some errors like below.
If someone has experienced the same issue,please let me know.
NoMethodError in Policies#show
Showing /home/ec2-user/environment/calendar_test/app/views/policies/show.html.erb where line #3 raised:
undefined method `receipt_day' for #<Receipt::ActiveRecord_Associations_CollectionProxy:0x00007f67fc0664e8>

Answer: The problem is you're trying to access a Reciept attribute by calling it on the collection. Your controller should look like
def show
    @policy = Policy.find(params[:id])
end

And then in your view where you want to see receipt_days on each receipt you can iterate through the collection

details of policyid: <%= @policy.id %>

<% @policy.receipts.each do |receipt| %>

<%= receipt.receipt_day %>

<% end %>

As @jvillian stated about N+1. If you're going to access any of the relationships on the receipt model you could eager load which ever ones you need to reduce hits to the db.
It'd change the controller/view like:
def show
    @policy = Policy.find(params[:id])
    @receipts = @policy.receipts.includes(:outpatients,...) #include any relationship that you're going to access in the view
end

details of policyid: <%= @policy.id %>

<% @receipts.each do |receipt| %>

<%= receipt.receipt_day %>

<% end %>

Comment: You might want to comment on eager loading to avoid an N+1 problem.


Can I use a HashMap to pick which interface (DAO) to autowire in SpringBoot?

Question: I will try to be as detailed as possible. I have many DAO and my service needs to use one of them based on the key i get. For instance -
if(key.equals("abc") {
   obj = abcDAO.getOne(id);
} else if(key.equals("xyz") {
   obj = xyzDAO.getOne(id);
}

The object is of type parent class and abc, xyz.. are all child classes.
My idea is to create a Map<String, ParentCLass> to get the object just by passing the key instead of If-else so that it will be easy to add for further changes. In case it would've been a normal class, I wouldv'e initialized the map as
Map<String, ParentClass> map.
map.put("abc", new Abc());

But since DAO are interfaces and require to be @Autowired for using them, I don't know how to proceed. I am a beginner. Any help appreciated.
Comment: you can use polymorphism instead, check this [exemple](https://refactoring.guru/replace-conditional-with-polymorphism)
Answer: Spring is able to inject all beans with the same interface in a map if the map has String as key (will contain the bean names) and the interface as value.
public interface MyDao {

}

@Autowired
private Map<String, MyDao> daos;

EDIT: If you use Spring Data Repository, there is already a tagging Interface: Repository. You can use below code to inject all DAOs in one bean.
@Autowired
private Map<String, Repository> daos;

EDIT2: Example
public interface UserRepo extends JpaRepository<User, Long> { ... }

@Service
public class MyService {

    @Autowired
    private Map<String, Repository> daos;

    public List<User> findAll() {
        return daos.get("userRepo").findAll();
    }
}

Comment: interesting, but what do I put in the map? like daos.put("key", new AbcDAO()) won't work right? since it would mean instantiating abstract class..
Comment: nothing Spring will fill the map with all beans implemting the same interface for you. You can get them by bean name. My mistake, I updated no need to new HashMap.
Comment: umm, i am confused now. I have different repositories.  In your example, My User will be User1, User2 , etc for all the repositories. I want to pick that using map, I will be defining a key which is a string and value as the repository that I want. A design like that..
Comment: sorry, I am lost too... If you can add a sample of 2 repository you want to retrieve with their key.
Comment: See.. i have 2 repositories with classes  public interface AbcDAO extends JpaRepositor and public interface XyzDao extends JpaRepository Now based on input value, I will select which dao to autowire. So my idea is to use Map the string is the key(suppost "pick abc") and value will be the dao obj. so I need a statement like map.put("pick abc", new AbcDao()). But this will give me an error since I cannot instantiate. Is there a way to accomplish adding the dao to the map?
Comment: If you use my sample, you can retrieve keys: abcDAO or xyzDao. If you want custom bean name to have keys like "pick abc" this is much more complex here is a post about this: https://stackoverflow.com/questions/38337453/customizing-spring-data-repository-bean-names-for-use-with-multiple-data-sources As an alternative you can have a map with aliases for the daos: daos.get(aliases.get("pick abc"))
Comment: okay, then for the sample that you have written, what would be "userRepo" ? for my scenario. I mean how would I be using the map in my service to get one dao?
Answer: You can create different bean for each of your Dao with a specific name
@Bean(name = "daoImpl1")
public Dao daoImpl1(){
return new DaoImpl1();

@Bean(name = "daoImpl2")
public Dao daoImpl2(){
return new DaoImpl2();

And then @Autowire them using @Qualifier with that name
@Autowired
@Qualifier("daoImpl1")
private Dao daoImpl1;

@Autowired
@Qualifier("daoImpl2")
private Dao daoImpl2;

Answer: i made methods to make simple jpa things,
i stored all of repositories in the HashMap
you just have to pass the child class and you get the corresponding JpaRepository
you can see more at https://github.com/fajaralmu/base_web_app
example :
public List<Page> getAllPages() {
        List<Page> allPages = entityRepository.findAll(Page.class);

        return   allPages;
    }

Comment: which is the webconfigservice that you are using to get JpaRepository?
Comment: class i made.. please check my repo https://github.com/fajaralmu/base_web_app/blob/master/src/main/java/com/fajar/entitymanagement/service/WebConfigService.java


Finding Probability of picking one ball out of N balls.

Question: presented with n identical balls, one with a prize in it. Picks each ball out  idependently one at a time till gets prize. I need to find the mean and variance of the number of balls needed to pick out the prize, if the balls are not replaced.
I can work it out with replacement, and i have been told to not work it out with hypergeometric series.
I know that there are going to be $\frac{n!}{2(n-2)!}$ combinations due to the formula for unordered non replacment.
I'm thinking so far it has to also do with the series from $k= 1 \ldots n$ of $\frac{1}{k} + \frac{1}{k}\frac{1}{(k-1)} + \frac{1}{k}\frac{1}{(k-1)}\frac{1}{(k-2)}$ etc but I can't think of a way to neaten that series either.
Please help!
Comment: Hint:  compute the probability that it take one draw.  Then two draws.  Then three.  Look for a pattern.
Comment: struggling to find the pattern
Comment: What's the probability that you get it in one?  two?
Comment: 1/n and 2/n-1 didn't mean to put k
Comment: $\frac 1n$ is correct, but the other isn't.  Why would it be (roughly) twice as likely that the winner be in the second slot?  To be in the second slot you need the first slot to be a loser (probability $\frac {n-1}{n}$) then you need the second to be the winner (probability $\frac {1}{n-1}$).
Comment: Sorry i derped, it would be 1/n and 1/n*1/n-1 = 1/n^2-1
Comment: No...think about it.  With $n=100$ you are suggesting that it is roughly $100$ times more likely that the ball is in the first slot than in the second.  Why would that be?
Comment: true true. 1/n, 1/n
Comment: Ah, good.  Have you spotted the (not especially subtle) pattern?
Comment: Yep I have, thanks
Comment: one small remark...while drawing the $(n-1)$st ball you will know where the prize is, no matter if the $(n-1)$st ball was a loser or a winner, so you don't have to draw the last ball at all
Comment: Yeah I mentally acknowledged that one already, thanks user190080
Comment: so does this mean that the mean is just the sum of 1/n + 2/n + 3/n etc up to n
Comment: Indeed it does.  The distribution is uniform...the winner has an equal chance of being in any of the slots.
Comment: any tips on computing that? or am i going to go on a quest to find out what it converges to
Answer: Let $X$ be the random variable equal to the number of balls that must be picked to win the prize.
As long as the winning ball has not been picked, the probability to get the winning ball at the $k$-th pick is the product of the probabilities not to win at the first pick, at the second pick, &c., at the $k-1$-th pick, and finally to win at the $k$-th pick. As there is one less ball after each pick, using the formula of composed probabilities, this gives:
$$P(X=k)=\frac{n-1}{n}\cdot\frac{n-2}{n-1}\dotsm\frac{n-k+1}{n-k+2}\cdot\frac1{n-k+1}=\frac1n$$
Thus the law of $X$ is the uniform law, and it is known that:
$$E(X)=\frac{n+1}2,\quad V(X)=\frac{n^2-1}{12}.$$


Codeigniter calling a view

Question: I'm new to CodeIgniter and i wonder what is best way to load a page without need to call  header and footer views always this way
$this->load->view('header');
$this->load->view('something');
$this->load->view('footer');

for example i successfully logged in and was redirected to dashboard page .
Answer: For that, you need to have a common function/method.
class My_Controller extends CI_Controller{

    public function __construct() {
       parent::__construct();
    }

    public function load_view($view_name,$data=Null){
         $this->load->view('header');
         $this->load->view($view_name,$data);
         $this->load->view('footer');
    }
}

Now extend all your controller with My_Controller(Not with CI_Controller)
From your controller call the function directly to load the view and pass $data array if you want to pass any data to the view.
$this->load_view('test_view',$data);

In case you have nothing to send to the view just send the view name
$this->load_view('test_view');

Hope that helps you.
Comment: You are most welcome. If it helped, please upvote and accept my answer so that others can get help out of it.
Comment: i meant before i ask this question here  i used it thanks
Comment: I meant this can help others if you accept or upvote my answer. Even if your problem is solved, other developers in the community can use it.
Answer: For that I'm using easy way like PHP:
Controller :
class My_Controller extends CI_Controller{

    public function __construct() {
       parent::__construct();
    }

    public function load_view(){
         $data=array();
         $this->load->view('dashboard_view',$data);

    }
    public function get_data(){

         $data['welcome_text']="Wooh ! I've a Something...";
         $this->load->view('dashboard_view',$data);
    }
}

View dashboard_view.php:

        <?php include('header.php');?>

welcome to the dashboard

        <?php include('footer.php');?>

Note:
In this you don't need to call each and everytime header and footer just change the controller methods.
Same dashboard_view.php for the edit function :

        <?php include('header.php');?>

        <?php
        // you can use here any checking method whether it is
        // I'll use isset() method to check  data is set or not
        //if you don't use isset then it will give you an error when you call the load_view() method
        echo (isset($welcome_text) ? $welcome_text : '');

        ?>

        <?php include('footer.php');?>

Codeigniter calling a view


PHP HTML email class selector not working GMAIL

Question: I have code to send HTML email via PHP. It has a table. I want to bold the rounded  in the screenshot. But the arrived email to Gmail is not showing bold and other changes that should be applied to the class selector of "about".
received email screenshot
Can I use class or ID selector in my style sheet in PHP HTML emails? I do not like to use inline CSS because it is inefficient. I have used them between body.
Here is the code;
$to = "email@example.com, email@example.com"; //multiple recipients with comma separated
$subject = "Here is the subject"; //cannot contain newline characters

$message = "
This is Heading H1
";
$message .= "This is my first line of text.
This is my second line of text

"; //each line should be separated with (\n).
$message .= "

                             About
                             Description

                             Name
                             Andreas

                             Address
                             Germany

                             Message
                             I like your 8 day tour package. What are the rates?

            ";

//headers like From, Cc, Bcc, Reply-to, Date ???????????
//$header = "From:email@example.com \r\n";
$header = "From: RXXXXX CXXXXX <firstname.lastname@example.com> \r\n"; //additional headers should be separated with (\r\n)
//$header .= "Cc: firstname.lastname@example.com \r\n";
//$header .= "Bcc: firstname.lastname@example.com \r\n";

//always specify MIME version, content type, and character set when sending HTML email
$header .= "MIME-Version: 1.0 \r\n";
$header .= "Content-type:text/html;charset=UTF-8 \r\n";
//$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; //////////////////////////////Pls Delete later

$retval = mail( $to, $subject, $message, $header );

if( $retval == true ){
    echo "Message sent successfully";
}
else{
    echo "Message could not be sent!";
}

Comment: The short answer is that, for HTML emails, you will _need_ to inline your CSS to get some semblance of consistency amongst different email clients. HTML email is notoriously tricky because each email client will render CSS and formatting in a different manner.
Comment: Have you tried only `.about{...`on your css ?
Comment: @PedroLobito sir, I checked all these variations: .ab{...    ,     td.ab{...      . But gmail do not identify class name. But the Yahoo shows correctly
Comment: Inlining CSS manually is indeed inefficient. You'll want a premailer (there are a bunch, http://premailer.dialect.ca/ is an example) to do that for you.
Comment: @ceejayoz very useful information. thanks
Comment: @ChrisForrence, sir is there any online services that make easy organizing HTML message to be used in PHP mail ?
Answer: HTML emails are notoriously tricky to get correct; each email client will handle styling in a different manner. Quoting from Lee Munroe's Things I've Learned About Building & Coding HTML Email Templates (emphasis is the author's):

Email clients use different rendering engines to render HTML emails:

Apple Mail, Outlook for Mac, Android Mail and iOS Mail use WebKit
Outlook 2000/02/03 use Internet Explorer
Outlook 2007/10/13 use Microsoft Word (yes, Word!)
Web clients use their browser's respective engine e.g. Safari uses WebKit, Chrome uses Blink

Gmail strips out <link> tags and any CSS in the


How to get AzureAD user principalId in ARM template

Question: I want to set AzureAD admin for Azure SQL database. To do it I need to set both login (email) and principalId.
Instead of passing both email and principalId as ARM template input parameters I want to pass user email only. Then inside a template I want to get user principalId by email. For managed identity it's possible to do it like this:
[reference(resourceId('Microsoft.Web/sites', variables('web-app-name')), '2019-08-01', 'full').identity.principalId]

But I can't find how to do the similar for the user.
Answer: You'll probably need to use a script to get the id and then pass it as parameter to the ARM template.
You can use for example the AzureAD PowerShell module: https://learn.microsoft.com/en-us/powershell/module/azuread/?view=azureadps-2.0
Get-AzureADUser -Filter "userPrincipalName eq 'firstname.lastname@example.com'"

Comment: Is there a way to do the same user lookup inside ARM template?
Answer: It's not pretty, and it's still in preview, but ARM templates now have support for executing scripts.


Unexpected Error at Installing CS6 on macOS 10.12

Question: I want re-install my licensed CS6 Web & Design Premium os macOS 10.12 Sierra. However, installer says "Could not start the installation. Any file may be missing."
I got the PDapp.log which created by installer in /Libary/Logs.
The Log:
<code>Wed Oct 12 19:34:00 2016    [INFO] Setup - Build Version - 6.0.335.0
Wed Oct 12 19:34:00 2016    [INFO] Setup - Logging Level verbosity Set  to 4
Wed Oct 12 19:34:00 2016    [INFO] Setup - TimeLog: Bootstrapper Start
Wed Oct 12 19:34:00 2016    [INFO] Setup - TimeLog: Start initial checks
Wed Oct 12 19:34:00 2016    [INFO] Setup - Launch Path set to /var/folders/ln/ljj38hdx5f13q0db1q58bpsr0000gp/T/AppTranslocation/E0C66AE8-34B2-4A80-A424-D031D2709AEA/d
Wed Oct 12 19:34:00 2016    [INFO] Setup - Found 6 packages in setup manifest
Wed Oct 12 19:34:00 2016    [INFO] PIM - Build Version - 6.0.335.0
Wed Oct 12 19:34:00 2016    [INFO] PIM - Logging Level verbosity Set  to 4
Wed Oct 12 19:34:00 2016    [WARN] PIM - Detected Old content in USF trying to delete it...
Wed Oct 12 19:34:00 2016    [WARN] PIM - Successfully deleted old content...
Wed Oct 12 19:34:00 2016    [INFO] PIM - Build Version - 6.0.335.0
Wed Oct 12 19:34:00 2016    [INFO] PIM - Logging Level verbosity Set  to 4
Wed Oct 12 19:34:00 2016    [INFO] PIM - CREATE PIM Instance ...
Wed Oct 12 19:34:00 2016    [INFO] PIM - trying to createOrUpdatePIMDbSchema.
Wed Oct 12 19:34:00 2016    [INFO] PIM - SUCCESS Created Tables.
Wed Oct 12 19:34:00 2016    [INFO] PIM - PIM Database is Up To Date.
Wed Oct 12 19:34:00 2016    [INFO] PIM - Updater Inventory location:/var/folders/ln/ljj38hdx5f13q0db1q58bpsr0000gp/T/AppTranslocation/E0C66AE8-34B2-4A80-A424-D031D2709AEA/d/Install.app/Contents/Frameworks/UpdaterInventory.framework/UpdaterInventory
Wed Oct 12 19:34:00 2016    [FATAL] PIM - ERROR invalid xml file path. Could not read data from path /var/folders/ln/ljj38hdx5f13q0db1q58bpsr0000gp/T/AppTranslocation/E0C66AE8-34B2-4A80-A424-D031D2709AEA/d/packages/core/PDApp.pimx
Wed Oct 12 19:34:00 2016    [FATAL] PIM - Error Description Error Domain=NSCocoaErrorDomain Code=260 "The file "PDApp.pimx" couldn't be opened because there is no such file." UserInfo={NSFilePath=/var/folders/ln/ljj38hdx5f13q0db1q58bpsr0000gp/T/AppTranslocation/E0C66AE8-34B2-4A80-A424-D031D2709AEA/d/packages/core/PDApp.pimx, NSUnderlyingError=0x23add0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Wed Oct 12 19:34:00 2016    [ERROR] PIM - Error couldnot initialize XML. Improper xml file.
Wed Oct 12 19:34:00 2016    [ERROR] Setup - Error in initialization. Manifest parsing failed.
Wed Oct 12 19:34:00 2016    [INFO] Setup - TimeLog: End initial checks
Wed Oct 12 19:34:02 2016    [INFO] Setup - =================  Exiting Installer with Code: 0  =================
Wed Oct 12 19:34:02 2016    [INFO] PIM - PIMSqlite closeDB status 0
Wed Oct 12 19:34:02 2016    [INFO] PIM - FREE PIM Instance ...
</code>
How can I fix this error?
Thanks.
Comment: Try http://apple.stackexchange.com, not stackoverflow
Answer: For OSX 10.12.X (Sierra) run installer directly from Install.app/Contents/MacOS/Install


how to override the timeline-twitter css

Question: I embedded a feed from twitter into a block and I am trying to override the size of font by adding this to my css , but it still only picks up the css that is coming from twitter.  is there any way to override this on my drupal site without logging into their twitter page?
.timeline-Tweet-text {
       font-size: 18px; !important;
       line-height: 24px;
       font-weight: 300;
   }
Answer: In order to be able to style it, you'll need to stop using the standard twitter embed code and use another solution.
I suggest using the Twitter (https://www.drupal.org/project/twitter) and Oauth (https://www.drupal.org/project/oauth) modules for this.
This will allow you to create a view of your feed which you will be able to style easily.
There looks to be a pretty good recipe here: http://polso.info/integrating-twitter-feed-your-drupal-site
Good luck!
Anne
Comment: thanks the problem is i dont have the user name and password of the twitter feed.
Comment: Hmm - that's a tough one. There are other modules like Tweet Feed, but I think all of them are going to require the API key of the account(s) in question. I'm not aware of one that doesn't.
Comment: Hey - I think I was mistaken: I had a chance to work with the Twitter module today. Based on the UI options and instructions (see this screenshot: http://imgur.com/2U9ydni), it looks like you just have to add one Twitter key (e.g., your own account) and then you can "add an unauthenticated account". You can then create views based on feeds, which you will have greater control over when styling.


is not coming properly

Question: Below is HTML which will render the text with superscript value, the statement is rendering correctly, but second statement is not coming properly because 2 is outside the
 tag, basically inside
 tag html is generating dynamically and I am appending  tag for each statement, but some of the value contains like the second statement that start with the

 etc. tag so it does not render superscript value.

1This is the first disclosure.

2

    Test div asdf klasfjd sdklafj asdfasdf adsf sdafjhsd aklfjasdf kjasdfasd f sdavfg asdf asdf asdf sdaf sdf sda f asdf

To resolving this I have written jquery like below
 jQuery('.disclosurelist').find('sup').each(function () {

    jQuery(this).prependTo(jQuery(this).next());
});

but now it is creating problem with first statement.
Comment: Why don't you simply put the `` inside the `` where it belongs?? If you can't, for whatever strange reason, you can use some css, like in [this fiddle](http://jsfiddle.net/24uDJ/). (Maybe it will need some more specificity for more complex situations, but this works for this HTML.)
Comment: It *IS* rendering the superscript, but because of the `div`'s `block` display it appears as a next line.
Comment: what exactly are you trying to do ?
Comment: @Mr Lister, actually this data is coming from database, so some of the statement have  some have  or some tag doesn't have any tag like first statement in above html
Comment: @Irshad So does the fiddle help?
Comment: @Mr Lister, but what will happen if I have html like this
1This is the first disclosure.
2

    Test div asdf klasfjd sdklafj asdfasdf adsf sdafjhsd aklfjasdf kjasdfasd f sdavfg asdf asdf asdf sdaf sdf sda f asdf
3
Test div asdf klasfjd sdklafj asdfasdf adsf sdafjhsd aklfjasdf kjasdfasd f sdavfg asdf asdf asdf sdaf sdf sda f asdf
Comment: You can test for yourself. The fiddle is all yours.
Comment: I checked but it is not working
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/41705/discussion-between-irshad-and-mr-lister)
Answer: just add second sup tag inside the div tag and then Test div asdf......

is not coming properly


Desktop application with wonderful UI - Platform Decision

Question: We have started to build a desktop application. The UI is ready on photoshop along with all the functionality decision's. On paper the UI looks stunning and we hope to replicate the same  inside the application.
Now the issue is: We are a team of 3 (2 developers + 1 designer). Building a separate application for Mac and Windows is just isn't feasible at all.
So the option is:

To do it on Java Swing. Saves time. But god! I will go crazy building it.
Use SWT or other toolkit. Tough to start, but can do if it can give the desired product.

Any other options?? Language no barrier (But the same code needs to function on both the platforms Mac and Windows). Product needs to be awesome
Comment: Are there "awesome" UIs written with Swing or SWT? Serious question, I haven't seen any so far.
Comment: OP said that the language is not a barrier.
Comment: Whichever toolkit you use, you'll need some effort to make it look & feel native, and thus "awesome" on all platforms. There's more to native feel than the style of a button, it's the whole UI design that's different on each platform. So whether you go Swing, SWT, Qt or native, no toolkit will give you 100% awesomeness out of the box.
Comment: Why do you tag this with qt if you are planning to implement in java?
Comment: @Fildor Qt has Java bindings.
Comment: Use Swing & give it an 'awesome' PLAF.
Answer: There are people (including me) who actually managed to build Swing applications without going crazy :) The Filthy Rich Clients book is a good start for creating "awesome" GUIs in Swing.
A newer alternative is JavaFX, which is supposed to be easier to use (I have no experience with it)
Answer: Maybe QT? There is a project QT Jambi (http://qt-jambi.org/)