text:
# UI Elements

  Basscss can be used to create many different user interface elements out of the box.
  With utility styles and a thoughtfully-architected templating system,
  you can keep CSS bloat to a minimum, while making iterative design changes to partials and components.
  You don't need to make CSS do your templating engine's job.

Note: this guide makes use of the optional
UI Utility Groups
module that is not included in the default Basscss package.

# Button Sizes
Button font sizes can be adjusted with font size utilities.

```html
<button type="button" class="h3 btn btn-primary">Burgers</button>
<button type="button" class="h4 btn btn-primary">Fries</button>
<button type="button" class="h6 btn btn-primary">Shakes</button>
```

To change the line-height and padding but leave the font-size the same,
use button size extensions in the optional basscss-button-sizes module.
Font size utilities and button size extensions can be combined for more options.

```html
<button type="button" class="btn button-big">Burgers</button>
<button type="button" class="btn">Fries</button>
<div class="mb1 md-hide"></div>
<button type="button" class="btn button-narrow">Onion Rings</button>
<button type="button" class="btn button-small">Shakes</button>
```

# Navigation

In HTML, navigation is essentially just groups of links.
By using the same styles as buttons,
you can ensure that navigation links are evenly spaced and have large, easy-to-hit targets.
Negative margin utilities can help line up text elements with other elements on the page.
The `.btn` style can be used for navigation items.
This button style inherits color from its parent, or it can be set with color utilities.

```html
<div class="mxn1">
  <a href="#!" class="btn button-narrow">Burgers</a>
  <a href="#!" class="btn button-narrow">Fries</a>
  <a href="#!" class="btn button-narrow">Shakes</a>
  <a href="#!" class="btn button-narrow">Onion Rings</a>
</div>
```

The flex object can be used to create justified navigation.
Be sure to test your specific navigation across a range of devices to ensure that
labels fit within the viewport.

```html
<div class="sm-flex center nowrap">
  <div class="flex-auto">
    <a href="#!" class="btn block">Burgers</a>
  </div>
  <div class="flex-auto">
    <a href="#!" class="btn block">Fries</a>
  </div>
  <div class="flex-auto">
    <a href="#!" class="btn block">Shakes</a>
  </div>
  <div class="flex-auto">
    <a href="#!" class="btn block">Onion Rings</a>
  </div>
</div>
```
To stack navigation elements, use the `.block` utility.

```html
<div class="sm-col-6 mxn2">
  <a href="#!" class="btn block">Burgers</a>
  <a href="#!" class="btn block">Fries</a>
  <a href="#!" class="btn block">Shakes</a>
  <a href="#!" class="btn block">Onion Rings</a>
</div>
```

Standard color styles can be applied to create a variety of navigation styles.

```html
<div class="sm-col-6 bg-white border rounded">
  <a href="#!" class="btn block border-bottom">Burgers</a>
  <a href="#!" class="btn block border-bottom">Fries</a>
  <a href="#!" class="btn block border-bottom">Shakes</a>
  <a href="#!" class="btn block">Onion Rings</a>
</div>
```

The default `.btn-primary` style can be used to create a pill navigation.

```html
<div>
  <a href="#!" class="btn btn-primary">Burgers</a>
  <a href="#!" class="btn">Fries</a>
  <a href="#!" class="btn">Shakes</a>
  <a href="#!" class="btn">Onion Rings</a>
</div>
```

If you'd like to wrap your navigation in a `ul` use the `.list-reset`
style to remove bullets and padding.

```html
<ul class="list-reset mxn1 mb0">
  <li class="inline-block">
    <a href="#!" class="btn button-narrow">Burgers</a>
  </li>
  <li class="inline-block">
    <a href="#!" class="btn button-narrow">Fries</a>
  </li>
  <li class="inline-block">
    <a href="#!" class="btn button-narrow">Shakes</a>
  </li>
  <li class="inline-block">
    <a href="#!" class="btn button-narrow">Onion Rings</a>
  </li>
</ul>
```

# Breadcrumbs

Breadcrumbs are a common and well-understood wayfinding pattern used in multi-level hierarchies.
Stylistically, these are essentially the same as navigation, but with separators between items.

```html
<div class="mxn1">
  <a href="#!" class="btn button-narrow">Home</a> /
  <a href="#!" class="btn button-narrow">Hot Dogs</a> /
  <span class="btn button-narrow">Frank</span>
</div>
```

```html
<div class="mxn1">
  <a href="#!" class="btn button-narrow">Home</a>
  <svg class="icon gray" data-icon="chevron-right"></svg>
  <a href="#!" class="btn button-narrow">Hot Dogs</a>
  <svg class="icon gray" data-icon="chevron-right"></svg>
  <span class="btn button-narrow">Frank</span>
</div>
```

  Note: the icons used in this example are from
  Geomicons Open.

# Pagination

Pagination is used to split up large lists in a user-friendly way and allows for deep linking.
Use a combination of layout utilities and button styles to create navigation that suites your design.

```html
<div class="clearfix">
  <a href="#!" class="left btn">
    <svg class="icon" data-icon="chevron-left"></svg>
    Previous
  </a>
  <a href="#!" class="right btn">
    Next
    <svg class="icon" data-icon="chevron-right"></svg>
  </a>
</div>
```

Responsive state utilities can be used to progressively enhance pagination
with numbers on devices with wider viewports.

```html
<div class="clearfix">
  <a href="#!" class="left btn button-narrow">
    <svg class="icon" data-icon="chevron-left"></svg>
    Previous
  </a>
  <a href="#!" class="right btn button-narrow">
    Next
    <svg class="icon" data-icon="chevron-right"></svg>
  </a>
  <div class="overflow-hidden sm-show center">
    <a href="#!" class="btn btn-primary bg-gray">1</a>
    <a href="#!" class="btn">2</a>
    <a href="#!" class="btn">3</a>
    <a href="#!" class="btn">4</a>
    <a href="#!" class="btn">5</a>
  </div>
</div>
```

Standard color styles can be used to control the appearance.

```html
<div class="center">
  <div class="inline-block overflow-hidden border rounded">
    <a href="#!" class="left btn border-right">
      <svg class="icon" data-icon="chevron-left"></svg>
      Previous
    </a>
    <a href="#!" class="right btn">
      Next
      <svg class="icon" data-icon="chevron-right"></svg>
    </a>
    <div class="overflow-hidden sm-show">
      <a href="#!" class="left btn border-right">1</a>
      <a href="#!" class="left btn border-right">2</a>
      <a href="#!" class="left btn border-right">3</a>
    </div>
  </div>
</div>
```

# Button Groups

Button groups allow for more flexibility in establishing gestalt and controlling information density.
Use a combination of layout utilities and color extensions to create button groups.
The utilities `.rounded-left`, `.rounded-right`,
and `.not-rounded` can be used to override button and form field border radii.

```html
<div class="inline-block clearfix">
  <button type="button" class="left btn btn-primary rounded-left is-active">Burgers</button>
  <button type="button" class="left btn btn-primary border-left not-rounded">Fries</button>
  <button type="button" class="left btn btn-primary border-left rounded-right">Shakes</button>
</div>
```

## Justified Button Group
The flex object can be used to create justified button groups.

```html
<div class="flex center">
  <a href="#!" class="flex-auto btn btn-primary rounded-left is-active">Burgers</a>
  <a href="#!" class="flex-auto btn btn-primary border-left not-rounded">Fries</a>
  <a href="#!" class="flex-auto btn btn-primary border-left rounded-right">Shakes</a>
</div>
```

Normally, buttons with borders would double up when placed next to each other.
The optional `.x-group-item` utility adjusts negative margins and focus states to visually collapse borders.
Functionally, this is similar to how other frameworks handle button and form input groups,
but with more direct control over styling.

```html
<div class="inline-block clearfix blue">
  <button type="button" class="left btn btn-primary x-group-item rounded-left">Burgers</button>
  <button type="button" class="left btn btn-outline x-group-item not-rounded">Fries</button>
  <button type="button" class="left btn btn-outline x-group-item rounded-right">Shake</button>
</div>
```

Use `.y-group-item` to group elements vertically.

```html
<div class="inline-block blue">
  <button type="button" class="block col-12 btn btn-primary y-group-item rounded-top">Burgers</button>
  <button type="button" class="block col-12 btn btn-outline y-group-item not-rounded">Fries</button>
  <button type="button" class="block col-12 btn btn-outline y-group-item rounded-bottom">Shake</button>
</div>
```

# Input Groups

Input groups can be created by removing margins, adjusting border radii, and using the group utilities.
The `.hide` utility visually hides labels, while keeping them accessible to screen readers.

```html
<form class="sm-col-6">
  <label class="hide">Pancakes</label>
  <input type="text" class="block col-12 field rounded-top y-group-item" placeholder="Pancakes">
  <label class="hide">Making</label>
  <input type="password" class="block col-12 field not-rounded y-group-item" placeholder="Making">
  <label class="hide">Bacon</label>
  <input type="text" class="block col-12 mb2 field rounded-bottom y-group-item" placeholder="Bacon">
  <button type="submit" class="btn btn-primary">Pancake</button>
</form>
```

The grid system can be used to control button or input group widths.

```html
<form class="clearfix">
  <label class="hide">Bacon</label>
  <input type="text" class="col col-4 md-col-5 field rounded-left x-group-item" placeholder="Bacon">
  <label class="hide">Pancakes</label>
  <input type="password" class="col col-4 md-col-5 field not-rounded x-group-item" placeholder="Pancakes">
  <button type="submit" class="col col-4 md-col-2 btn btn-primary rounded-right">Pancake</button>
</form>
```

# Dropdowns

Dropdown menus are used to group secondary or sensitive actions
behind a two-step progressive disclosure,
while conserving screen real estate.
Dropdowns can be created with basic positioning utilities.

The wrapping elements uses relative positioning to anchor the dropdown body.
An invisible fixed position element is used as an overlay to dismiss the dropdown.
The dropdown body uses absolute positioning and margin top to align with the trigger element,
without affecting the document flow.
Be sure dropdowns don't expand beyond the viewport when used near edges or at small screen sizes.

```html
<div class="relative inline-block" data-disclosure>
  <button type="button" class="btn btn-primary">
    Burger ▾
  </button>
  <div data-details class="fixed top-0 right-0 bottom-0 left-0"></div>
  <div data-details class="absolute left-0 mt1 nowrap white bg-blue rounded">
    <a href="#!" class="btn block">Rare</a>
    <a href="#!" class="btn block">Medium Rare</a>
    <a href="#!" class="btn block">Medium</a>
    <a href="#!" class="btn block">Well Done</a>
  </div>
</div>
```

  Note: this example uses a custom JavaScript function for the disclosure mechanism.
  Use a similar function, component, or directive in your own JavaScript to control behavior.

# Navbars

Navbars are used to visually group global or sub navigation
and to separate actions and navigation from content.
Using a combination of layout utilities and color styles,
you can create a wide range of navbars that are simple to customize and update.

This example uses a double sided media object to create a flexible center with a search input
that stacks at narrow viewport widths.
By applying the `.py2` utility to the link buttons,
they become the height of normal buttons and inputs plus `.py1`.

```html
<div class="clearfix mb2 white bg-black">
  <div class="left">
    <a href="#!" class="btn py2 m0">Burgers</a>
    <a href="#!" class="btn button-narrow py2 m0">Fries</a>
  </div>
  <div class="right">
    <a href="#!" class="btn py2 m0">My Account</a>
  </div>
  <div class="clearfix sm-hide"></div>
  <div class="overflow-hidden px2 py1">
    <input type="text" class="right fit field white bg-darken-1" placeholder="Search">
  </div>
</div>
```

By using rgba-based color utilities, the color can quickly be changed
using background color utilities.

```html
<div class="clearfix mb2 white bg-blue">
  <div class="left">
    <a href="#!" class="btn py2 m0">Burgers</a>
    <a href="#!" class="btn button-narrow py2 m0">Fries</a>
  </div>
  <div class="right">
    <a href="#!" class="btn py2 m0">My Account</a>
  </div>
  <div class="clearfix sm-hide"></div>
  <div class="overflow-hidden px2 py1">
    <input type="text" class="right fit field white bg-darken-1" placeholder="Search">
  </div>
</div>
<div class="clearfix mb2 white bg-gray">
  <div class="left">
    <a href="#!" class="btn py2 m0">Burgers</a>
    <a href="#!" class="btn button-narrow py2 m0">Fries</a>
  </div>
  <div class="right">
    <a href="#!" class="btn py2 m0">My Account</a>
  </div>
  <div class="clearfix sm-hide"></div>
  <div class="overflow-hidden px2 py1">
    <input type="text" class="right fit field white bg-darken-1" placeholder="Search">
  </div>
</div>
<div class="clearfix mb2 white bg-green">
  <div class="left">
    <a href="#!" class="btn py2 m0">Burgers</a>
    <a href="#!" class="btn button-narrow py2 m0">Fries</a>
  </div>
  <div class="right">
    <a href="#!" class="btn py2 m0">My Account</a>
  </div>
  <div class="clearfix sm-hide"></div>
  <div class="overflow-hidden px2 py1">
    <input type="text" class="right fit field white bg-darken-1" placeholder="Search">
  </div>
</div>
<div class="clearfix mb2 white bg-red">
  <div class="left">
    <a href="#!" class="btn py2 m0">Burgers</a>
    <a href="#!" class="btn button-narrow py2 m0">Fries</a>
  </div>
  <div class="right">
    <a href="#!" class="btn py2 m0">My Account</a>
  </div>
  <div class="clearfix sm-hide"></div>
  <div class="overflow-hidden px2 py1">
    <input type="text" class="right fit field white bg-darken-1" placeholder="Search">
  </div>
</div>
```

Because Basscss is built with inter-operable styles,
things like a user account dropdown can be added anywhere in the navbar.

```html
<div class="clearfix white bg-black">
  <div class="left">
    <a href="#!" class="btn py2 m0">Burgers</a>
    <a href="#!" class="btn button-narrow py2 m0">Fries</a>
  </div>
  <div class="right">
    <div id="account-menu" class="inline-block" data-disclosure>
      <div data-details class="fixed top-0 right-0 bottom-0 left-0"></div>
      <div class="relative">
        <a href="#!" class="btn py2 m0">My Account ▾</a>
        <div data-details class="absolute right-0 nowrap black bg-white rounded" style="min-width:128px">
          <ul class="h5 list-reset mb0">
            <li><a href="#!" class="btn block">Profile</a></li>
            <li><a href="#!" class="btn block">Settings</a></li>
            <li><a href="#!" class="btn block">Sign Out</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
  <div class="clearfix sm-hide"></div>
  <div class="overflow-hidden px2">
  </div>
</div>
```

More complex
[Priority Plus](http://bradfrostweb.com/blog/web/complex-navigation-patterns-for-responsive-design/#priority-plus)
navigations can also be created using responsive utilities.

```html
<div class="relative clearfix white bg-black">
  <div class="left">
    <a href="#!" class="btn py2 m0">Burgers</a>
  </div>
  <div class="left md-show">
    <a href="#!" class="btn button-narrow py2 m0">Hot Dogs</a>
    <a href="#!" class="btn button-narrow py2 m0">Fries</a>
    <a href="#!" class="btn button-narrow py2 m0">Shakes</a>
    <a href="#!" class="btn button-narrow py2 m0">Onion Rings</a>
  </div>
  <div class="right">
    <div id="account-menu" class="inline-block" data-disclosure>
      <div data-details class="fixed top-0 right-0 bottom-0 left-0"></div>
      <a href="#!" class="btn py2 m0">
        <span class="md-hide">Menu ▾</span>
        <span class="md-show">More ▾</span>
      </a>
      <div data-details class="absolute right-0 xs-left-0 sm-col-6 md-col-4 lg-col-3 nowrap black bg-gray rounded-bottom">
        <ul class="h5 list-reset py1 mb0">
          <li class="md-hide"><a href="#!" class="btn block">Hot Dogs</a></li>
          <li class="md-hide"><a href="#!" class="btn block">Fries</a></li>
          <li class="md-hide"><a href="#!" class="btn block">Shakes</a></li>
          <li class="md-hide"><a href="#!" class="btn block">Onion Rings</a></li>
          <li><a href="#!" class="btn block">Bacon</a></li>
          <li><a href="#!" class="btn block">Pancakes</a></li>
          <li><a href="#!" class="btn block">Sausages</a></li>
          <li><a href="#!" class="btn block">Waffles</a></li>
        </ul>
      </div>
    </div>
  </div>
</div>
<style>
/* Responsive positioning extension example */
@media (max-width:40em) {
  .xs-left-0 { left: 0 }
}
</style>
```

# Boxes

Boxes are used to group content and collections of application resources.
Use combinations of layout utilities and color styles to create boxes.

```html
<div class="md-col-6">
  <div class="p2 bg-white border rounded">
    <h1 class="h2 mt0">Bacon</h1>
    <p class="mb0">Bacon ipsum dolor sit amet chuck prosciutto landjaeger ham hock filet mignon shoulder hamburger pig venison. Ham bacon corned beef, sausage kielbasa flank tongue pig drumstick capicola swine short loin ham hock kevin.</p>
  </div>
</div>
```

To create headers and footers, set padding on nested divs then use color styles to control appearance.

```html
<div class="md-col-6">
  <div class="overflow-hidden bg-white border rounded">
    <div class="p2 bg-silver">
      <h1 class="h2 m0">Bacon with Header</h1>
    </div>
    <div class="p2">
      <p class="m0">Bacon ipsum dolor sit amet chuck prosciutto landjaeger ham hock filet mignon shoulder hamburger pig venison. Ham bacon corned beef, sausage kielbasa flank tongue pig drumstick capicola swine short loin ham hock kevin.</p>
    </div>
  </div>
</div>
```

```html
<div class="md-col-6">
  <div class="p2 bg-white border rounded">
    <img src="http://d2v52k3cl9vedd.cloudfront.net/assets/images/placeholder-square.svg" class="mb2" />
    <h1 class="h2 mt0">Bacon with Image</h1>
    <p class="mb0">Bacon ipsum dolor sit amet chuck prosciutto landjaeger ham hock filet mignon shoulder hamburger pig venison.</p>
  </div>
</div>
```

```html
<div class="md-col-6">
  <div class="overflow-hidden bg-white border rounded">
    <div class="p2 white bg-blue">
      <h1 class="h2 m0">Bacon with Header and Footer</h1>
    </div>
    <div class="p2">
      <p class="m0">Bacon ipsum dolor sit amet chuck prosciutto landjaeger ham hock filet mignon shoulder hamburger pig venison. Ham bacon corned beef, sausage kielbasa flank tongue pig drumstick capicola swine short loin ham hock kevin. Bacon t-bone hamburger turkey capicola rump short loin.</p>
    </div>
    <div class="p2 bg-darken-1">
      <p class="m0 h5">Turkey short loin tenderloin jerky.</p>
    </div>
  </div>
</div>
```

# Flash Messages

Flash messages are used to provide feedback after the user has performed an action.
Create custom flash messages with utilities and color styles.

```html
<div class="bold center p2 mb2 white bg-red rounded">
  Warning! Half-pound burger will be deleted
</div>
<div class="bold center p2 mb2 bg-yellow rounded">
  Onion rings cannot connect to the network
</div>
<div class="bold center p2 white bg-green rounded">
  Fries added to order
</div>
```

# Badges

Badges are used to represent properties and states and
to tease quantities of resources behind navigation links.
Use basic utilities and color styles to create badges.

```html
<h1>Hamburger
  <span class="h2 inline-block px1 white bg-red rounded">Fries</span>
</h1>
<h2>Hamburger
  <span class="h3 inline-block px1 white bg-red rounded">Fries</span>
</h2>
<h3>Hamburger
  <span class="h4 inline-block px1 white bg-red rounded">Fries</span>
</h3>
<h4>Hamburger
  <span class="inline-block px1 white bg-red rounded">Fries</span>
</h4>
<h5>Hamburger
  <span class="inline-block px1 white bg-red rounded">Fries</span>
</h5>
<h6>Hamburger
  <span class="inline-block px1 white bg-red rounded">Fries</span>
</h6>
```

Color semantics can be controlled with color styles
to represent different qualities of states.

```html
<div>
  <span class="bold inline-block px1 white bg-blue rounded">Blue</span>
  <span class="bold inline-block px1 white bg-red rounded">Red</span>
  <span class="bold inline-block px1 bg-yellow rounded">Yellow</span>
  <span class="bold inline-block px1 white bg-green rounded">Green</span>
  <span class="bold inline-block px1 white bg-gray rounded">Gray</span>
  <span class="bold inline-block px1 border rounded">Bordered</span>
</div>
```


text:
title: "There's duplicate content on my site"
kb_categories:
  - Troubleshooting Common Scenarios
id: 4d1c5fe8-1b58-4384-931f-aaee97677c05
---
Are you seeing two of the same entries? (or pages, assets, etc) If so, there may have been two files with the same
ID in the front matter.

This is fairly common to see when people copy/paste files and forget to remove the IDs.

The solution is usually to just remove the duplicate ID and [clear your cache][clear_cache].

If it wasn't a duplicate ID causing the problem, it may just have been a glitch in the matrix. Let us know what went
wrong and what you were doing, and we'll get that fixed up.

[clear_cache]: /knowledge-base/clear-cache

redpajama_set_name: RedPajamaGithub


text:
"""Implementation of an ensemble of classification predictors trained
using the AdaBoost.M1 algorithm."""

import math
import operator
import random

def increment_counter(dictionary, key, value=1):
    """Increments the counter for a given key in the given dictionary or
    sets the counter to 1 if it does not yet exist."""
    if key in dictionary:
        dictionary[key] += value
    else:
        dictionary[key] = value

class AdaBoostEnsemble:
    """An ensemble of classification predictors trained using the
    AdaBoost.M1 algorithm."""

    def __init__(self):
        self.weak_learners = []
        self.learner_weights = []
        self.weights = []

    def train(self, data_points, subset_size, ensemble_size, trained_learner,
              evaluate):
        """Builds the ensemble from the given data set.
        :param data_points: List of tuples representing the data points.
        Last tuple component must corresponds to output label.
        :param subset_size: AdaBoost uses resampled training sets for
        each predictor. Resampled training sets can be smaller than
        original data set. This parameter determines its size in number
        of tuples.
        :param ensemble_size: Number of weak learners in the ensemble.
        :param trained_learner: Function that given a training set returns a
        trained weak learner.
        :param evaluate: Function that given a predictor and an input
        returns the predictor's prediction. """
        # Initialize weights uniformly
        self.weights = [1.0/len(data_points) for _ in range(len(data_points))]
        # Add weak learners one by one
        for _ in range(ensemble_size):
            self.__add_weak_learner(data_points, subset_size, trained_learner,
                                    evaluate)

    def evaluate(self, input, evaluate):
        """Evaluates the ensemble for a given input using majority voting.
        :param input: Input to evaluate.
        :param evaluate: Function that given a weak learner and an input
        returns the weak learner's corresponding prediction.
        :return: Ensemble prediction."""
        votes = {}
        for weak_learner, weight in zip(self.weak_learners,
                                        self.learner_weights):
            prediction = evaluate(weak_learner, input)
            increment_counter(votes, prediction, weight)
        prediction = max(votes.items(), key=operator.itemgetter(1))[0]
        return prediction

    def __training_subset(self, data_points, size):
        """Returns a random set of samples where each sample in the
        entire data set is drawn with a probability determined by its
        value in the weights array."""
        subset_indices = random.choices(range(len(data_points)),
                                        weights=self.weights, k=size)
        return [data_points[index] for index in subset_indices]

    def __error(self, prediction_results):
        """Given the prediction results of a weak learner, returns the
        corresponding error.
        :param prediction_results: Array of boolean values where true denotes
        that the training sample in the entire data set at the
        same index was predicted correctly."""
        error = 0.0
        for prediction_correct, weight in zip(prediction_results,
                                              self.weights):
            if not prediction_correct:
                error += weight
        return error

    @staticmethod
    def __correction(error):
        """Given the error for a weak learner, calculates the corresponding
        correction term."""
        correction = error / (1.0 - error)
        if correction == 0:
            correction = 0.0000001
        return correction

    def __update_weights(self, prediction_results, correction):
        """Updates each the weight of each sample in the entire training
        set if necessary."""
        for index, prediction_correct in enumerate(prediction_results):
            if prediction_correct:
                self.weights[index] *= correction
        # Normalize weights to get a valid probability distribution
        normalisation_const = sum(self.weights)
        for index, prediction_correct in enumerate(prediction_results):
            self.weights[index] /= normalisation_const

    def __add_weak_learner(self, data_points, subset_size, trained_learner,
                           evaluate):
        """Trains a new weak learner, evaluates it, determines its
        weight within the ensemble and updates the entire data set's
        weights."""
        # Create and train weak learner
        subset = self.__training_subset(data_points, subset_size)
        weak_learner = trained_learner(subset)
        # Evaluate weak learner
        prediction_results = [evaluate(weak_learner, point) == point[-1]
                              for point in data_points]
        # Update sample weights based on weak learner's error
        error = self.__error(prediction_results)
        if error > 0.5:
            print("Training unsuccessful")
            return
        correction = self.__correction(error)
        self.__update_weights(prediction_results, correction)
        # Add weak learner to ensemble with corresponding weight
        self.weak_learners.append(weak_learner)
        self.learner_weights.append(math.log(1.0 / correction))


text:
/**
 *
 */
package org.jasig.schedassist.impl.ldap;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.Name;

import org.jasig.schedassist.model.AbstractCalendarAccount;

/**
 * {@link AbstractCalendarAccount} implementation to represent a
 * person sourced from LDAP.
 *
 * @author Nicholas BlairNicholas Blair
 * @version $Id: LDAPPersonCalendarAccountImpl.java $
 */
class LDAPPersonCalendarAccountImpl extends AbstractCalendarAccount implements HasDistinguishedName {

	/**
	 *
	 */
	private static final long serialVersionUID = 1794331642591042311L;

	private Map<String, List<String>> attributesMap = new HashMap<String, List<String>>();
	private Name distinguishedName;

	/**
	 * Default implementation.
	 *
	 * @param attributes
	 * @param ldapAttributesKey
	 */
	public LDAPPersonCalendarAccountImpl(Map<String, List<String>> attributes, LDAPAttributesKey ldapAttributesKey) {
		this.attributesMap = attributes;
		// populate fields first
		setCalendarUniqueId(getSingleAttributeValue(attributes.get(ldapAttributesKey.getUniqueIdentifierAttributeName())));
		setDisplayName(getSingleAttributeValue(attributes.get(ldapAttributesKey.getDisplayNameAttributeName())));
		setEmailAddress(getSingleAttributeValue(attributes.get(ldapAttributesKey.getEmailAddressAttributeName())));
		setUsername(getSingleAttributeValue(attributes.get(ldapAttributesKey.getUsernameAttributeName())));
		// set eligibility
		setEligible(ldapAttributesKey.evaluateEligibilityAttributeValue(attributes));
	}

	/* (non-Javadoc)
	 * @see org.jasig.schedassist.model.AbstractCalendarAccount#getAttributes()
	 */
	@Override
	public Map<String, List<String>> getAttributes() {
		return this.attributesMap;
	}

	/* (non-Javadoc)
	 * @see org.jasig.schedassist.model.AbstractCalendarAccount#getCalendarLoginId()
	 */
	@Override
	public String getCalendarLoginId() {
		return getUsername();
	}

	/*
	 * (non-Javadoc)
	 * @see org.jasig.schedassist.impl.ldap.HasDistinguishedName#getDistinguishedName()
	 */
	public Name getDistinguishedName() {
		return distinguishedName;
	}

	/**
	 * @param distinguishedName the distinguishedName to set
	 */
	public void setDistinguishedName(Name distinguishedName) {
		this.distinguishedName = distinguishedName;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "LDAPPersonCalendarAccountImpl [attributesMap=" + attributesMap
				+ ", distinguishedName=" + distinguishedName +", toString()=" + super.toString() + "]";
	}

}


text:
layout: post
date:	2011-09-17 05:31:00
title:  Happy Birthday, <LJ user=pondhopper>
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
Wishing Donna the very best for the years ahead!

Since you wish everyone on your LJ, I thought I'd do the same thing :)


text:
'use strict';

const Snoocore = require('snoocore');
const config = {
  userAgent: 'AllHail_Bot-sidebar-updater / v0.1.0 (by /u/AllHail_Bot)',
  oauth: {
    type: 'script',
    key: process.env.REDDIT_CLIENT_ID,
    secret: process.env.REDDIT_CLIENT_SECRET,
    username: process.env.REDDIT_USERNAME,
    password: process.env.REDDIT_PASSWORD,
    scope: ['wikiread', 'wikiedit'],
  },
  requestTimeout: 10000,
  retryAttempts: 0,
};

module.exports = new Snoocore(config);


text:
package xyz.cloudkeeper.model.runtime.type;

import xyz.cloudkeeper.model.bare.type.BarePrimitiveType;

public interface RuntimePrimitiveType extends BarePrimitiveType, RuntimeTypeMirror { }


text:
/**
 * An enum of query types used by `sequelize.query`
 *
 * @see {@link Sequelize#query}
 *
 * @property SELECT
 * @property INSERT
 * @property UPDATE
 * @property BULKUPDATE
 * @property BULKDELETE
 * @property DELETE
 * @property UPSERT
 * @property VERSION
 * @property SHOWTABLES
 * @property SHOWINDEXES
 * @property DESCRIBE
 * @property RAW
 * @property FOREIGNKEYS
 * @property SHOWCONSTRAINTS
 */
export enum QueryTypes {
  SELECT = 'SELECT',
  INSERT = 'INSERT',
  UPDATE = 'UPDATE',
  BULKUPDATE = 'BULKUPDATE',
  BULKDELETE = 'BULKDELETE',
  DELETE = 'DELETE',
  UPSERT = 'UPSERT',
  VERSION = 'VERSION',
  SHOWTABLES = 'SHOWTABLES',
  SHOWINDEXES = 'SHOWINDEXES',
  DESCRIBE = 'DESCRIBE',
  RAW = 'RAW',
  FOREIGNKEYS = 'FOREIGNKEYS',
  SHOWCONSTRAINTS = 'SHOWCONSTRAINTS',
}


text:
<!DOCTYPE article SYSTEM "sdocbook-custom.dtd">
<article><title>Article Title</title>
<para>Paragraph.</para>
</article>


text:
package gov.nasa.pds.entities;

import java.util.List;

import com.topcoder.json.object.JSONObject;

/**
 * This class represents an object's validation rules.
 *
 * Thread Safety: This class is mutable and not thread safe.
 */
public class ObjectValidation extends NamedEntity {
    /**
     * Represents the names of objects that are required to be in this object. It is managed with a getter and setter.
     * It may have any value. It is fully mutable.
     */
    private List<String> requiredObjects;
    /**
     * Represents the names of objects that are optional to be in this object. It is managed with a getter and setter.
     * It may have any value. It is fully mutable.
     */
    private List<String> optionalObjects;
    /**
     * Represents the names of properties that are required to be in this object. It is managed with a getter and
     * setter. It may have any value. It is fully mutable.
     */
    private List<String> requiredElements;
    /**
     * Represents the names of properties that are accepted to be in this object. It is managed with a getter and
     * setter. It may have any value. It is fully mutable.
     */
    private List<String> optionalElements;
    /**
     * Represents the flag of globallyAllowableElements. It is managed with a getter and setter. It may have any value.
     * It is fully mutable.
     */
    private boolean globallyAllowableElements;

    /**
     * Empty constructor.
     */
    public ObjectValidation() {
    }

    /**
     * Constructor. Create the instance with name.
     *
     * @param name
     *            - the given name to set.
     */
    public ObjectValidation(String name) {
        super(name);
    }

    /**
     * Gets the requiredObjects value.
     *
     * @return - the requiredObjects value.
     */
    public List<String> getRequiredObjects() {
        return requiredObjects;
    }

    /**
     * Sets the given value to requiredObjects.
     *
     * @param requiredObjects
     *            - the given value to set.
     */
    public void setRequiredObjects(List<String> requiredObjects) {
        this.requiredObjects = requiredObjects;
    }

    /**
     * Gets the optionalObjects value.
     *
     * @return - the optionalObjects value.
     */
    public List<String> getOptionalObjects() {
        return optionalObjects;
    }

    /**
     * Sets the given value to optionalObjects.
     *
     * @param optionalObjects
     *            - the given value to set.
     */
    public void setOptionalObjects(List<String> optionalObjects) {
        this.optionalObjects = optionalObjects;
    }

    /**
     * Gets the requiredElements value.
     *
     * @return - the requiredElements value.
     */
    public List<String> getRequiredElements() {
        return requiredElements;
    }

    /**
     * Sets the given value to requiredElements.
     *
     * @param requiredElements
     *            - the given value to set.
     */
    public void setRequiredElements(List<String> requiredElements) {
        this.requiredElements = requiredElements;
    }

    /**
     * Gets the optionalElements value.
     *
     * @return - the optionalElements value.
     */
    public List<String> getOptionalElements() {
        return optionalElements;
    }

    /**
     * Sets the given value to optionalElements.
     *
     * @param optionalElements
     *            - the given value to set.
     */
    public void setOptionalElements(List<String> optionalElements) {
        this.optionalElements = optionalElements;
    }

    /**
     * Gets the globallyAllowableElements value.
     *
     * @return - the globallyAllowableElements value.
     */
    public boolean isGloballyAllowableElements() {
        return globallyAllowableElements;
    }

    /**
     * Sets the given value to globallyAllowableElements.
     *
     * @param globallyAllowableElements
     *            - the given value to set.
     */
    public void setGloballyAllowableElements(boolean globallyAllowableElements) {
        this.globallyAllowableElements = globallyAllowableElements;
    }

    /**
     * Gets the JSONObject instance.
     *
     * @return - the JSONObject for this instance.
     */
    @Override
    public JSONObject toJSONObject() {
        JSONObject object = super.toJSONObject();

        EntityHelper.setArray(object, "requiredObjects", requiredObjects);
        EntityHelper.setArray(object, "optionalObjects", optionalObjects);
        EntityHelper.setArray(object, "requiredElements", requiredElements);
        EntityHelper.setArray(object, "optionalElements", optionalElements);

        EntityHelper.setBoolean(object, "globallyAllowableElements", globallyAllowableElements);
        return object;
    }
}


text:
/**
 * General purpose utilities.
 *
 * @author Alex Ruiz
 */
package org.fest.util;


text:
package rules

import (
	"testing"
)

func TestNameSuffix(t *testing.T) {
	if pass, suggestion := checkNameSuffix("author_name"); !pass {
		t.Error("Given \"author_name\", checkNameSuffix() returned false, expected true")
	} else if suggestion != "author" {
		t.Errorf("Expected suggestion \"author\", received %s instead", suggestion)
	}

	if pass, suggestion := checkNameSuffix("author"); pass {
		t.Error("Given \"author\", checkNameSuffix() returned true, expected false")
	} else if suggestion != "author" {
		t.Errorf("Expected suggestion \"author\", received %s instead", suggestion)
	}

}


text:
using System;
using System.Linq.Expressions;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;

namespace Atata
{
    /// <summary>
    /// Represents the base class for the page objects.
    /// Also executes <see cref="TriggerEvents.Init"/> and <see cref="TriggerEvents.DeInit"/> triggers.
    /// </summary>
    /// <typeparam name="TOwner">The type of the owner page object.</typeparam>
    public abstract class PageObject<TOwner> : UIComponent<TOwner>, IPageObject<TOwner>, IPageObject
        where TOwner : PageObject<TOwner>
    {
        private readonly AtataContext _context;

        private Control<TOwner> _activeControl;

        protected PageObject()
        {
            _context = AtataContext.Current
                ?? throw new InvalidOperationException(
                    $"Cannot instantiate {GetType().Name} because {nameof(AtataContext)}.{nameof(AtataContext.Current)} is null.");

            NavigateOnInit = true;
            ScopeLocator = new PlainScopeLocator(CreateScopeBy);

            Owner = (TOwner)this;

            Report = new Report<TOwner>((TOwner)this, Log);

            PageUri = new UriProvider<TOwner>(this, GetUri, "URI");

            UIComponentResolver.InitPageObject<TOwner>(this);
        }

        /// <inheritdoc/>
        public sealed override AtataContext Context => _context;

        /// <summary>
        /// Gets the source of the scope.
        /// The default value is <see cref="ScopeSource.PageObject"/>.
        /// </summary>
        public override ScopeSource ScopeSource
            => ScopeSource.PageObject;

        /// <summary>
        /// Gets the assertion verification provider that has a set of verification extension methods.
        /// </summary>
        public new PageObjectVerificationProvider<TOwner> Should
            => new PageObjectVerificationProvider<TOwner>((TOwner)this);

        /// <summary>
        /// Gets the expectation verification provider that has a set of verification extension methods.
        /// </summary>
        public new PageObjectVerificationProvider<TOwner> ExpectTo
            => Should.Using<ExpectationVerificationStrategy>();

        /// <summary>
        /// Gets the waiting verification provider that has a set of verification extension methods.
        /// Uses <see cref="AtataContext.WaitingTimeout"/> and <see cref="AtataContext.WaitingRetryInterval"/> of <see cref="AtataContext.Current"/> for timeout and retry interval.
        /// </summary>
        public new PageObjectVerificationProvider<TOwner> WaitTo
            => Should.Using<WaitingVerificationStrategy>();

        /// <summary>
        /// Gets a value indicating whether the navigation should be performed upon initialization.
        /// </summary>
        protected internal bool NavigateOnInit { get; internal set; }

        /// <summary>
        /// Gets a value indicating whether this instance is temporarily navigated using <see cref="GoTemporarilyAttribute"/> or other approach.
        /// </summary>
        protected internal bool IsTemporarilyNavigated { get; internal set; }

        /// <summary>
        /// Gets the previous page object.
        /// </summary>
        protected internal UIComponent PreviousPageObject { get; internal set; }

        /// <summary>
        /// Gets the instance that provides reporting functionality.
        /// </summary>
        public Report<TOwner> Report { get; }

        /// <summary>
        /// Gets the title provider of the current HTML page.
        /// </summary>
        public ValueProvider<string, TOwner> PageTitle =>
            CreateValueProvider("title", GetTitle);

        /// <summary>
        /// Gets the URL provider of the current HTML page.
        /// </summary>
        public ValueProvider<string, TOwner> PageUrl =>
            CreateValueProvider("URL", GetUrl);

        /// <summary>
        /// Gets the URI provider of the current HTML page.
        /// </summary>
        public UriProvider<TOwner> PageUri { get; }

        /// <summary>
        /// Gets the page source provider of the current HTML page.
        /// </summary>
        public ValueProvider<string, TOwner> PageSource =>
            CreateValueProvider("page source", GetPageSource);

        /// <summary>
        /// Gets the active control.
        /// </summary>
        public Control<TOwner> ActiveControl =>
            _activeControl ?? (_activeControl = Controls.Create<Control<TOwner>>(
                "<Active>",
                new DynamicScopeLocator(_ => Driver.SwitchTo().ActiveElement())));

        /// <summary>
        /// Creates the <see cref="By"/> instance for Scope search.
        /// </summary>
        /// <returns>The <see cref="By"/> instance.</returns>
        protected virtual By CreateScopeBy()
        {
            string scopeXPath = Metadata.ComponentDefinitionAttribute?.ScopeXPath ?? "body";

            return By.XPath($".//{scopeXPath}").Visible();
        }

        private string GetTitle() =>
            Driver.Title;

        private string GetUrl() =>
            Driver.Url;

        private Uri GetUri()
        {
            string url = GetUrl();
            return new Uri(url);
        }

        private string GetPageSource() =>
            Driver.PageSource;

        internal void Init()
        {
            if (string.IsNullOrEmpty(ComponentName))
                ComponentName = UIComponentResolver.ResolvePageObjectName<TOwner>();

            ComponentTypeName = UIComponentResolver.ResolvePageObjectTypeName<TOwner>();

            Log.Info($"Go to {ComponentFullName}");

            InitComponent();

            if (NavigateOnInit)
                Navigate();

            OnInit();
            Context.EventBus.Publish(new PageObjectInitEvent(this));

            ExecuteTriggers(TriggerEvents.Init);

            OnInitCompleted();
            Context.EventBus.Publish(new PageObjectInitCompletedEvent(this));

            OnVerify();
        }

        protected virtual void OnVerify()
        {
        }

        protected virtual void Navigate()
        {
            string url = Metadata.Get<UrlAttribute>()?.Url;

            if (url != null || !Context.IsNavigated)
            {
                Go.ToUrl(url);
            }
        }

        void IPageObject.SwitchToWindow(string windowHandle) =>
            SwitchToWindow(windowHandle);

        /// <summary>
        /// Switches to the browser window by the window handle.
        /// </summary>
        /// <param name="windowHandle">The handle of the window.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner SwitchToWindow(string windowHandle)
        {
            Log.ExecuteSection(
                new LogSection($@"Switch to window ""{windowHandle}""", LogLevel.Trace),
                (Action)(() => Driver.SwitchTo().Window(windowHandle)));

            return (TOwner)this;
        }

        /// <summary>
        /// Switches to frame represented by <paramref name="component"/> parameter.
        /// </summary>
        /// <param name="component">The component representing frame element.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner SwitchToFrame(IUIComponent<TOwner> component)
        {
            string message = component is Frame<TOwner>
                ? $"Switch to {component.ComponentFullName}"
                : $"Switch to frame of {component.ComponentFullName}";

            Log.ExecuteSection(
                new LogSection(message, LogLevel.Trace),
                (Action)(() => SwitchToFrame(component.Scope)));

            return (TOwner)this;
        }

        /// <summary>
        /// Switches to frame represented by <paramref name="element"/> parameter.
        /// </summary>
        /// <param name="element">The frame element.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner SwitchToFrame(IWebElement element)
        {
            Log.ExecuteSection(
                new LogSection($"Switch to frame of {Stringifier.ToString(element).ToLowerFirstLetter()}", LogLevel.Trace),
                (Action)(() => Driver.SwitchTo().Frame(element)));

            return (TOwner)this;
        }

        /// <summary>
        /// Switches to frame page object using <see cref="By"/> instance that represents the selector for <c><iframe></c> tag element.
        /// </summary>
        /// <typeparam name="TFramePageObject">The type of the frame page object.</typeparam>
        /// <param name="frameBy">The frame <see cref="By"/> instance.</param>
        /// <param name="framePageObject">
        /// The frame page object.
        /// If equals <see langword="null"/>, creates an instance of <typeparamref name="TFramePageObject"/> using the default constructor.</param>
        /// <param name="temporarily">If set to <see langword="true"/> navigates temporarily preserving current page object state.</param>
        /// <returns>The instance of the frame page object.</returns>
        public TFramePageObject SwitchToFrame<TFramePageObject>(By frameBy, TFramePageObject framePageObject = null, bool temporarily = false)
            where TFramePageObject : PageObject<TFramePageObject>
        {
            IWebElement frameElement = Scope.GetWithLogging(frameBy);
            return SwitchToFrame(frameElement, framePageObject, temporarily);
        }

        /// <summary>
        /// Switches to frame page object using <see cref="IWebElement"/> instance that represents <c><iframe></c> tag element.
        /// </summary>
        /// <typeparam name="TFramePageObject">The type of the frame page object.</typeparam>
        /// <param name="frameElement">The frame element.</param>
        /// <param name="framePageObject">
        /// The frame page object.
        /// If equals <see langword="null"/>, creates an instance of <typeparamref name="TFramePageObject"/> using the default constructor.</param>
        /// <param name="temporarily">If set to <see langword="true"/> navigates temporarily preserving current page object state.</param>
        /// <returns>The instance of the frame page object.</returns>
        public virtual TFramePageObject SwitchToFrame<TFramePageObject>(IWebElement frameElement, TFramePageObject framePageObject = null, bool temporarily = false)
            where TFramePageObject : PageObject<TFramePageObject>
        {
            SwitchToFrame(frameElement);

            return Go.To(framePageObject, navigate: false, temporarily: temporarily);
        }

        /// <summary>
        /// Switches to the root page using WebDriver's <c>SwitchTo().DefaultContent()</c> method.
        /// </summary>
        /// <returns>The instance of this page object.</returns>
        public TOwner SwitchToRoot()
        {
            Log.ExecuteSection(
                new LogSection($"Switch to page root", LogLevel.Trace),
                (Action)(() => Driver.SwitchTo().DefaultContent()));

            return (TOwner)this;
        }

        /// <summary>
        /// Switches to the root page using WebDriver's <c>SwitchTo().DefaultContent()</c> method.
        /// </summary>
        /// <typeparam name="TPageObject">The type of the root page object.</typeparam>
        /// <param name="rootPageObject">
        /// The root page object.
        /// If equals <see langword="null"/>, creates an instance of <typeparamref name="TPageObject"/> using the default constructor.</param>
        /// <returns>The instance of the root page object.</returns>
        public virtual TPageObject SwitchToRoot<TPageObject>(TPageObject rootPageObject = null)
            where TPageObject : PageObject<TPageObject>
        {
            SwitchToRoot();

            return Go.To(rootPageObject, navigate: false);
        }

        /// <summary>
        /// Refreshes the current page.
        /// </summary>
        /// <returns>The instance of this page object.</returns>
        public virtual TOwner RefreshPage()
        {
            Log.Info("Refresh page");
            Driver.Navigate().Refresh();
            return Go.To<TOwner>(navigate: false);
        }

        /// <summary>
        /// Refreshes the current page until the condition specified by <paramref name="predicateExpression"/> argument is met.
        /// </summary>
        /// <param name="predicateExpression">The predicate expression to test the page.</param>
        /// <param name="timeout">The timeout in seconds.</param>
        /// <param name="retryInterval">The retry interval in seconds.</param>
        /// <returns>The instance of this page object.</returns>
        /// <example>
        /// <code>
        /// PageObject.RefreshPageUntil(x => x.SomeControl.IsVisible, timeout: 60, retryInterval: 5);
        /// </code>
        /// </example>
        public TOwner RefreshPageUntil(Expression<Func<TOwner, bool>> predicateExpression, double? timeout = null, double? retryInterval = null)
        {
            var predicate = predicateExpression.CheckNotNull(nameof(predicateExpression)).Compile();

            TimeSpan timeoutTime = timeout.HasValue
                ? TimeSpan.FromSeconds(timeout.Value)
                : Context.WaitingTimeout;

            TimeSpan retryIntervalTime = retryInterval.HasValue
                ? TimeSpan.FromSeconds(retryInterval.Value)
                : Context.WaitingRetryInterval;

            TOwner activePageObject = (TOwner)this;

            string predicateMessage = Stringifier.ToString(predicateExpression);

            string actionMessage = $"Refresh page until {predicateMessage} within {timeoutTime.ToShortIntervalString()} with {retryIntervalTime.ToShortIntervalString()} retry interval";

            Log.ExecuteSection(
                new LogSection(actionMessage),
                () =>
                {
                    bool isOk = Driver
                        .Try(timeoutTime, retryIntervalTime)
                        .Until(x =>
                        {
                            activePageObject = activePageObject.RefreshPage();
                            return predicate(activePageObject);
                        });

                    if (!isOk)
                        throw new TimeoutException($"Timed out after {timeoutTime.ToShortIntervalString()} waiting for: {actionMessage.ToLowerFirstLetter()}.");
                });

            return activePageObject;
        }

        /// <summary>
        /// Navigates back to the previous page.
        /// </summary>
        /// <typeparam name="TOther">The type of the page object that represents the previous page.</typeparam>
        /// <param name="previousPageObject">
        /// The instance of the previous page object.
        /// If equals <see langword="null"/>, creates an instance of <typeparamref name="TOther"/> using the default constructor.</param>
        /// <returns>The instance of the previous page object.</returns>
        public virtual TOther GoBack<TOther>(TOther previousPageObject = null)
            where TOther : PageObject<TOther>
        {
            Log.Info("Go back");
            Driver.Navigate().Back();
            return Go.To(previousPageObject, navigate: false);
        }

        /// <summary>
        /// Navigates forward to the next page.
        /// </summary>
        /// <typeparam name="TOther">The type of the page object that represents the next page.</typeparam>
        /// <param name="nextPageObject">
        /// The instance of the next page object.
        /// If equals <see langword="null"/>, creates an instance of <typeparamref name="TOther"/> using the default constructor.</param>
        /// <returns>The instance of the next page object.</returns>
        public virtual TOther GoForward<TOther>(TOther nextPageObject = null)
            where TOther : PageObject<TOther>
        {
            Log.Info("Go forward");
            Driver.Navigate().Forward();
            return Go.To(nextPageObject, navigate: false);
        }

        /// <summary>
        /// Closes the current window.
        /// </summary>
        public virtual void CloseWindow()
        {
            string nextWindowHandle = ResolveWindowHandleToSwitchAfterClose();

            Log.Info("Close window");
            Driver.Close();

            if (nextWindowHandle != null)
                SwitchToWindow(nextWindowHandle);
        }

        private string ResolveWindowHandleToSwitchAfterClose()
        {
            string currentWindowHandle = Driver.CurrentWindowHandle;
            int indexOfCurrent = Driver.WindowHandles.IndexOf(currentWindowHandle);
            if (indexOfCurrent > 0)
                return Driver.WindowHandles[indexOfCurrent - 1];
            else if (Driver.WindowHandles.Count > 1)
                return Driver.WindowHandles[1];
            else
                return null;
        }

        /// <summary>
        /// Executes the action passing specified owner's component.
        /// </summary>
        /// <typeparam name="TComponent">The type of the component.</typeparam>
        /// <param name="componentSelector">The component selector.</param>
        /// <param name="action">The action.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner Do<TComponent>(Func<TOwner, TComponent> componentSelector, Action<TComponent> action)
        {
            componentSelector.CheckNotNull(nameof(componentSelector));
            action.CheckNotNull(nameof(action));

            TComponent component = componentSelector((TOwner)this);

            action(component);

            return (TOwner)this;
        }

        /// <summary>
        /// Executes the navigation action passing specified owner's component.
        /// </summary>
        /// <typeparam name="TComponent">The type of the component.</typeparam>
        /// <typeparam name="TNavigateTo">The type of the page object to navigate to.</typeparam>
        /// <param name="componentSelector">The component selector.</param>
        /// <param name="navigationAction">The navigation action.</param>
        /// <returns>The instance of the page object to navigate to.</returns>
        public TNavigateTo Do<TComponent, TNavigateTo>(Func<TOwner, TComponent> componentSelector, Func<TComponent, TNavigateTo> navigationAction)
            where TNavigateTo : PageObject<TNavigateTo>
        {
            componentSelector.CheckNotNull(nameof(componentSelector));
            navigationAction.CheckNotNull(nameof(navigationAction));

            TComponent component = componentSelector((TOwner)this);

            return navigationAction(component);
        }

        /// <summary>
        /// Executes the action passing current page object.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner Do(Action<TOwner> action)
        {
            action.CheckNotNull(nameof(action));

            action((TOwner)this);

            return (TOwner)this;
        }

        /// <summary>
        /// Executes the navigation action passing current page object.
        /// </summary>
        /// <typeparam name="TNavigateTo">The type of the navigate to.</typeparam>
        /// <param name="navigationAction">The navigation action.</param>
        /// <returns>The instance of the page object to navigate to.</returns>
        public TNavigateTo Do<TNavigateTo>(Func<TOwner, TNavigateTo> navigationAction)
            where TNavigateTo : PageObject<TNavigateTo>
        {
            navigationAction.CheckNotNull(nameof(navigationAction));

            return navigationAction((TOwner)this);
        }

        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner Do(Action action)
        {
            action.CheckNotNull(nameof(action));

            action();

            return (TOwner)this;
        }

        /// <summary>
        /// Executes aggregate assertion for the current page object using <see cref="AtataContext.AggregateAssert(Action, string)" /> method.
        /// </summary>
        /// <param name="action">The action to execute in scope of aggregate assertion.</param>
        /// <param name="assertionScopeName">
        /// Name of the scope being asserted.
        /// Is used to identify the assertion section in log.
        /// If it is <see langword="null"/>, <see cref="UIComponent.ComponentFullName"/> is used instead.
        /// </param>
        /// <returns>The instance of this page object.</returns>
        public TOwner AggregateAssert(Action<TOwner> action, string assertionScopeName = null)
        {
            action.CheckNotNull(nameof(action));

            assertionScopeName = assertionScopeName ?? ComponentFullName;

            Context.AggregateAssert(() => action((TOwner)this), assertionScopeName);

            return (TOwner)this;
        }

        /// <summary>
        /// Executes aggregate assertion for the component of the current page object using <see cref="AtataContext.AggregateAssert(Action, string)" /> method.
        /// </summary>
        /// <typeparam name="TComponent">The type of the component.</typeparam>
        /// <param name="componentSelector">The component selector.</param>
        /// <param name="action">The action to execute in scope of aggregate assertion.</param>
        /// /// <param name="assertionScopeName">
        /// Name of the scope being asserted.
        /// Is used to identify the assertion section in log.
        /// If it is <see langword="null"/>, component full name is used instead.
        /// </param>
        /// <returns>The instance of this page object.</returns>
        public TOwner AggregateAssert<TComponent>(Func<TOwner, TComponent> componentSelector, Action<TComponent> action, string assertionScopeName = null)
        {
            componentSelector.CheckNotNull(nameof(componentSelector));
            action.CheckNotNull(nameof(action));

            TComponent component = componentSelector((TOwner)this);

            assertionScopeName = assertionScopeName
                ?? UIComponentResolver.ResolveComponentFullName<TOwner>(component) ?? ComponentFullName;

            Context.AggregateAssert(() => action(component), assertionScopeName);

            return (TOwner)this;
        }

        /// <summary>
        /// Presses the specified keystrokes.
        /// </summary>
        /// <param name="keys">The keystrokes to send to the browser.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner Press(string keys)
        {
            if (!string.IsNullOrEmpty(keys))
            {
                Log.ExecuteSection(
                    new PressKeysLogSection(this, keys),
                    () => Driver.Perform(x => x.SendKeys(keys)));
            }

            return (TOwner)this;
        }

        /// <summary>
        /// Performs the specified set of actions.
        /// </summary>
        /// <param name="actionsBuilder">The actions builder.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner PerformActions(Func<Actions, Actions> actionsBuilder)
        {
            Driver.Perform(actionsBuilder);

            return (TOwner)this;
        }

        /// <summary>
        /// Waits the specified time.
        /// </summary>
        /// <param name="time">The time to wait.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner Wait(TimeSpan time)
        {
            Thread.Sleep(time);

            return (TOwner)this;
        }

        [Obsolete("Use " + nameof(WaitSeconds) + " instead.")] // Obsolete since v2.0.0.
        public TOwner Wait(double seconds) =>
            WaitSeconds(seconds);

        /// <summary>
        /// Waits the specified time in seconds.
        /// </summary>
        /// <param name="seconds">The time to wait in seconds.</param>
        /// <returns>The instance of this page object.</returns>
        public TOwner WaitSeconds(double seconds)
        {
            Thread.Sleep((int)(seconds * 1000));

            return (TOwner)this;
        }

        /// <summary>
        /// Scrolls up.
        /// </summary>
        /// <returns>The instance of this page object.</returns>
        public TOwner ScrollUp()
        {
            Log.Info("Scroll up");

            return Script.Execute(
                "document.body.scrollTop = 0;" +
                "document.documentElement.scrollTop = 0;");
        }

        /// <summary>
        /// Scrolls down.
        /// </summary>
        /// <returns>The instance of this page object.</returns>
        public TOwner ScrollDown()
        {
            Log.Info("Scroll down");

            return Script.Execute(
                "var height = document.body.scrollHeight;" +
                "document.body.scrollTop = height;" +
                "document.documentElement.scrollTop = height;");
        }

        void IPageObject.DeInit()
        {
            ExecuteTriggers(TriggerEvents.DeInit);
            Context.EventBus.Publish(new PageObjectDeInitEvent(this));
        }

        protected override string BuildComponentProviderName() => null;
    }
}


text:
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.advanced_construction import SurfacePropertyHeatTransferAlgorithmMultipleSurface

log = logging.getLogger(__name__)

class TestSurfacePropertyHeatTransferAlgorithmMultipleSurface(unittest.TestCase):

    def setUp(self):
        self.fd, self.path = tempfile.mkstemp()

    def tearDown(self):
        os.remove(self.path)

    def test_create_surfacepropertyheattransferalgorithmmultiplesurface(self):

        pyidf.validation_level = ValidationLevel.error

        obj = SurfacePropertyHeatTransferAlgorithmMultipleSurface()
        # alpha
        var_name = "Name"
        obj.name = var_name
        # alpha
        var_surface_type = "AllExteriorSurfaces"
        obj.surface_type = var_surface_type
        # alpha
        var_algorithm = "ConductionTransferFunction"
        obj.algorithm = var_algorithm

        idf = IDF()
        idf.add(obj)
        idf.save(self.path, check=False)

        with open(self.path, mode='r') as f:
            for line in f:
                log.debug(line.strip())

        idf2 = IDF(self.path)
        self.assertEqual(idf2.surfacepropertyheattransferalgorithmmultiplesurfaces[0].name, var_name)
        self.assertEqual(idf2.surfacepropertyheattransferalgorithmmultiplesurfaces[0].surface_type, var_surface_type)
        self.assertEqual(idf2.surfacepropertyheattransferalgorithmmultiplesurfaces[0].algorithm, var_algorithm)


text:
"use strict";
/**
 * Creates a socket instance for interacting with thisisoon.fm
 * Event handles can be passed to fmSocket using
 * 'fmSocket.addListener("fm:player:play", eventHandler)' the service will
 * call the event handler with the arguments (data) every time a matching
 * socket event is received. `data` is a data object passed with the event,
 * this will contain event and track data. The handlers can be removed by
 * using 'fmSocket.removeListener("fm:player:play", eventHandler)'
 *
 * @module FM.sockets
 * @author SOON_
 */
angular.module("FM.sockets", [
    "config",
    "btford.socket-io"
])
/**
 * @method run
 * @param  {Factory} fmSocket socket instance
 * @param  {Array}   FM_SOCKET_EVENTS   list of available socket events
 */
.run([
    "fmSocket",
    "FM_SOCKET_EVENTS",
    function(fmSocket, FM_SOCKET_EVENTS){
        /**
         * Forwards all fm.socket events to angular event system
         */
        fmSocket.forward(FM_SOCKET_EVENTS);
    }
])

/**
 * @constant {Array} list of available socket events
 */
.constant("FM_SOCKET_EVENTS", [
    "fm:player:play",
    "fm:player:end",
    "fm:player:pause",
    "fm:player:resume",
    "fm:player:add",
    "fm:player:deleted",
    "fm:player:setMute",
    "fm:player:setVolume"
])
/**
 * @constructor
 * @param   {Object}  $window
 * @param   {Factory} socketFactory     socket instance factory
 * @param   {Object}  env               environment variables
 * @returns {Object}  socket.io instance
 */
.factory("fmSocket", [
    "$window",
    "socketFactory",
    "env",
    function ($window, socketFactory, env) {

        return socketFactory({
            prefix: "",
            ioSocket: $window.io.connect(env.FM_SOCKET_ADDRESS)
        });

    }
]);


text:
Spanish language pack for Flarum.

# Paquete de idioma Español para Flarum (es)

Como no existía una versión del paquete de idioma para la versión 0.1.0-beta6, he decidido crearlo. Si encontrais algún error o quereis proponer algún cambio notificarlo y lo arreglaré cuanto antes.

## Instalación con Composer:

Flarum usa composer para gestionar sus dependencias y extensiones, por lo que es el sistema de instalación recomendado. El paquete de idioma Epañol está disponible en Packagist. Para instalarlo sólo necesitamos Composer instalado y después ejecutar el comando:

`composer require zeokat/flarum-ext-spanish`

Este mismo comando se puede emplear para actualizar de forma independiente el paquete de idioma Español.

He decidido mantener el archivo `validation.yml` en inglés ya que contiene los mensajes de error. Si en algún momento nos encontramos con un mensaje de error, siempre es más sencillo encontrar una solución en Google buscando el mensaje de error original, por este motivo voy a mantener este archivo en su idioma original.

De todas formas facilito una versión del archivo [validation.yml en español](https://gist.github.com/Zeokat/e2465a8ef131f8bc49f041d0583b87fb), que no está incluido en el paquete de traducción. Os la facilito por si alguien quiere crearse su paquete de idioma personalizado con los mensajes de validación y de error, traducidos al español.

# Flarum Spanish language pack (es)

https://discuss.flarum.org

Complete; Flarum version 0.1.0-beta6. Spanish (Spain). Español (España), ES

## Installation using Composer (recommended):

Flarum use Composer to manage its dependencies and extensions. The Spanish language pack is available on Packagist and can be managed that way. Make sure that Composer is installed on your machine, then run the following command in the location where Flarum is installed:

`composer require zeokat/flarum-ext-spanish`

The same command can be used to update independently the Spanish language pack, without updating anything else. Note that because the Spanish language pack will be added as a Flarum's dependency, it will also be automatically updated when updating Flarum and its dependencies via Composer.


text:
package org.apache.spark.sql.hive

import java.util.Locale

import scala.util.{Failure, Success, Try}
import scala.util.control.NonFatal

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.hive.ql.exec.{UDAF, UDF}
import org.apache.hadoop.hive.ql.exec.{FunctionRegistry => HiveFunctionRegistry}
import org.apache.hadoop.hive.ql.udf.generic.{AbstractGenericUDAFResolver, GenericUDF, GenericUDTF}

import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.FunctionIdentifier
import org.apache.spark.sql.catalyst.analysis.FunctionRegistry
import org.apache.spark.sql.catalyst.catalog.{CatalogFunction, FunctionResourceLoader, GlobalTempViewManager, SessionCatalog}
import org.apache.spark.sql.catalyst.expressions.{Cast, Expression}
import org.apache.spark.sql.catalyst.parser.ParserInterface
import org.apache.spark.sql.hive.HiveShim.HiveFunctionWrapper
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{DecimalType, DoubleType}

private[sql] class HiveSessionCatalog(
    externalCatalog: HiveExternalCatalog,
    globalTempViewManager: GlobalTempViewManager,
    val metastoreCatalog: HiveMetastoreCatalog,
    functionRegistry: FunctionRegistry,
    conf: SQLConf,
    hadoopConf: Configuration,
    parser: ParserInterface,
    functionResourceLoader: FunctionResourceLoader)
  extends SessionCatalog(
      externalCatalog,
      globalTempViewManager,
      functionRegistry,
      conf,
      hadoopConf,
      parser,
      functionResourceLoader) {

  /**
   * Constructs a [[Expression]] based on the provided class that represents a function.
   *
   * This performs reflection to decide what type of [[Expression]] to return in the builder.
   */
  override def makeFunctionExpression(
      name: String,
      clazz: Class[_],
      input: Seq[Expression]): Expression = {

    Try(super.makeFunctionExpression(name, clazz, input)).getOrElse {
      var udfExpr: Option[Expression] = None
      try {
        // When we instantiate hive UDF wrapper class, we may throw exception if the input
        // expressions don't satisfy the hive UDF, such as type mismatch, input number
        // mismatch, etc. Here we catch the exception and throw AnalysisException instead.
        if (classOf[UDF].isAssignableFrom(clazz)) {
          udfExpr = Some(HiveSimpleUDF(name, new HiveFunctionWrapper(clazz.getName), input))
          udfExpr.get.dataType // Force it to check input data types.
        } else if (classOf[GenericUDF].isAssignableFrom(clazz)) {
          udfExpr = Some(HiveGenericUDF(name, new HiveFunctionWrapper(clazz.getName), input))
          udfExpr.get.dataType // Force it to check input data types.
        } else if (classOf[AbstractGenericUDAFResolver].isAssignableFrom(clazz)) {
          udfExpr = Some(HiveUDAFFunction(name, new HiveFunctionWrapper(clazz.getName), input))
          udfExpr.get.dataType // Force it to check input data types.
        } else if (classOf[UDAF].isAssignableFrom(clazz)) {
          udfExpr = Some(HiveUDAFFunction(
            name,
            new HiveFunctionWrapper(clazz.getName),
            input,
            isUDAFBridgeRequired = true))
          udfExpr.get.dataType // Force it to check input data types.
        } else if (classOf[GenericUDTF].isAssignableFrom(clazz)) {
          udfExpr = Some(HiveGenericUDTF(name, new HiveFunctionWrapper(clazz.getName), input))
          udfExpr.get.asInstanceOf[HiveGenericUDTF].elementSchema // Force it to check data types.
        }
      } catch {
        case NonFatal(e) =>
          val analysisException =
            new AnalysisException(s"No handler for UDF/UDAF/UDTF '${clazz.getCanonicalName}': $e")
          analysisException.setStackTrace(e.getStackTrace)
          throw analysisException
      }
      udfExpr.getOrElse {
        throw new AnalysisException(s"No handler for UDF/UDAF/UDTF '${clazz.getCanonicalName}'")
      }
    }
  }

  override def lookupFunction(name: FunctionIdentifier, children: Seq[Expression]): Expression = {
    try {
      lookupFunction0(name, children)
    } catch {
      case NonFatal(_) =>
        // SPARK-16228 ExternalCatalog may recognize `double`-type only.
        val newChildren = children.map { child =>
          if (child.dataType.isInstanceOf[DecimalType]) Cast(child, DoubleType) else child
        }
        lookupFunction0(name, newChildren)
    }
  }

  private def lookupFunction0(name: FunctionIdentifier, children: Seq[Expression]): Expression = {
    val database = name.database.map(formatDatabaseName)
    val funcName = name.copy(database = database)
    Try(super.lookupFunction(funcName, children)) match {
      case Success(expr) => expr
      case Failure(error) =>
        if (functionRegistry.functionExists(funcName)) {
          // If the function actually exists in functionRegistry, it means that there is an
          // error when we create the Expression using the given children.
          // We need to throw the original exception.
          throw error
        } else {
          // This function is not in functionRegistry, let's try to load it as a Hive's
          // built-in function.
          // Hive is case insensitive.
          val functionName = funcName.unquotedString.toLowerCase(Locale.ROOT)
          if (!hiveFunctions.contains(functionName)) {
            failFunctionLookup(funcName)
          }

          // TODO: Remove this fallback path once we implement the list of fallback functions
          // defined below in hiveFunctions.
          val functionInfo = {
            try {
              Option(HiveFunctionRegistry.getFunctionInfo(functionName)).getOrElse(
                failFunctionLookup(funcName))
            } catch {
              // If HiveFunctionRegistry.getFunctionInfo throws an exception,
              // we are failing to load a Hive builtin function, which means that
              // the given function is not a Hive builtin function.
              case NonFatal(e) => failFunctionLookup(funcName)
            }
          }
          val className = functionInfo.getFunctionClass.getName
          val functionIdentifier =
            FunctionIdentifier(functionName.toLowerCase(Locale.ROOT), database)
          val func = CatalogFunction(functionIdentifier, className, Nil)
          // Put this Hive built-in function to our function registry.
          registerFunction(func, overrideIfExists = false)
          // Now, we need to create the Expression.
          functionRegistry.lookupFunction(functionIdentifier, children)
        }
    }
  }

  // TODO Removes this method after implementing Spark native "histogram_numeric".
  override def functionExists(name: FunctionIdentifier): Boolean = {
    super.functionExists(name) || hiveFunctions.contains(name.funcName)
  }

  /** List of functions we pass over to Hive. Note that over time this list should go to 0. */
  // We have a list of Hive built-in functions that we do not support. So, we will check
  // Hive's function registry and lazily load needed functions into our own function registry.
  // List of functions we are explicitly not supporting are:
  // compute_stats, context_ngrams, create_union,
  // current_user, ewah_bitmap, ewah_bitmap_and, ewah_bitmap_empty, ewah_bitmap_or, field,
  // in_file, index, matchpath, ngrams, noop, noopstreaming, noopwithmap,
  // noopwithmapstreaming, parse_url_tuple, reflect2, windowingtablefunction.
  // Note: don't forget to update SessionCatalog.isTemporaryFunction
  private val hiveFunctions = Seq(
    "histogram_numeric"
  )
}


text:
(function(angular) {
  "use strict";

  angular.module('trends', ['firebase', 'ngRoute', 'authRequired'])

  .config(function($routeProvider) {
    $routeProvider
      .when('/', {
        controller: 'LoginCtrl',
        templateUrl: 'views/login.html'
      })
      .when('/trends', {
        controller: 'TrendsCtrl',
        templateUrl: 'views/trends.html',
        authRequired: true,
        resolve: {
          tags: function(Tags, TagsRef) {
            var $tagsArray = Tags(TagsRef);
            return $tagsArray.$loaded();
          }
        }
      })
      .when('/entries/:id', {
        controller: 'EntriesCtrl',
        templateUrl: 'views/entries.html',
        authRequired: true,
        resolve: {
          entries: function($entries, $route) {
            return $entries($route.current.params.id).$asArray().$loaded();
          }
        }
      })
      .when('/404', {
        templateUrl: 'views/404.html'
      })
      .otherwise('/404');
  })

  .constant('FBURL', 'https://trends.firebaseio.com/')

  .constant('TAGS_URL', 'https://trends.firebaseio.com/tags')

  .constant('TRENDS_URL', 'https://trends.firebaseio.com/trends')

  .constant('USERS_URL', 'https://trends.firebaseio.com/users')

  // Helper factory for changing routes
  .factory('routeTo', function($window) {

    function route(path) {
      $window.location.href = '#' + path;
    }

    return route;

  })

  .service('Root', ['FBURL', Firebase])

  .service('TagsRef', ['TAGS_URL', Firebase])

  .service('TrendsRef', ['TRENDS_URL', Firebase])

  .service('UsersRef', ['USERS_URL', Firebase])

  .run(function($rootScope, routeTo) {
    // if the user does not belong send the home
    $rootScope.$on('authRequired:unauthorized', function(e, name) {
      routeTo('/');
    });
  });

}(window.angular));

(function(window, angular) {
  "use strict";

  window.config = (function() {
    var settings = {
      name: 'trends',
      app: function() {
        return angular.module(settings.name);
      }
    }
    return settings;
  }());

}(window, window.angular));

(function(angular, config) {
  "use strict";

  var user = {
    uid: '1',
    email: 'david@firebase.com',
    providerid: '024112'
  };

  angular.module('$firebaseMockAuth', [])

  .constant('MockLoginError', false)

  .constant('MockUser', user)

  .constant('MockUserError', 'Invalid Email')

  // Mock service for logging in with third party auth
  .factory('$firebaseAuth', function(MockUser, MockUserError, MockLoginError) {
    var willError = MockLoginError;

    // create a fake user depending on the login
    function prepMockUser(provider, mockUser) {
      if(!mockUser) { return; }
      var user = {};
      user.uid = mockUser.uid;
      user[provider] = {
        email: mockUser.email
      };
      user[provider][provider + 'id'] = mockUser.providerid;
      return user;
    }

    // fake the user returned
    function mockThen(fn, user) {
      fn.call(this, user);
    }

    // fake the error message
    function mockCatch(errFn, msg) {
      errFn.call(this, new Error(msg));
    }

    function $authWithOAuthRedirect(provider) {

      return {

        then: function(fn) {
          var user = prepMockUser(provider, MockUser);

          // if there is a user fire then
          if(user) {
            mockThen(fn, user);
          }

          return {

            catch: function(errorFn) {
              // no user returns an error
              if(!user) {
                mockCatch(errorFn, MockUserError);
              }
            }

          };

        }

      };

    }

    function $getAuth() {
      return prepMockUser('google', MockUser);
    }

    return function(ref) {
      return {
        $authWithOAuthRedirect: $authWithOAuthRedirect,
        $getAuth: $getAuth,
        _firebase: ref
      };
    };

  });

}(angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.factory('Auth', function(FireAuth, $q) {
    var auth = FireAuth;
    var deferred = $q.defer();
    return {
      authWithGoogle: function() {
        auth.$authWithOAuthPopup('google', { scope: 'email' }).then(function(authData) {
          var googleUser = authData.google;
          if (!googleUser.email || !googleUser.email.match(/@google.com$/) ) {
            throw new Error('Invalid email; not a google.com account');
          }
          deferred.resolve(authData);
        }).catch(function(error) {
          deferred.reject(error);
        });

        return deferred.promise;
      },
      STATUS: {
        ANON: 'ANON',
        SUCCESS: 'SUCCESS',
        ERROR: 'ERROR',
        UNK: 'UNK'
      },
      STATUS_MESSAGE: {
        ANON: 'Log in',
        SUCCESS: 'Logging In...',
        ERROR: 'Error logging in.',
        UNK: 'Unknown error.'
      }
    };
  });

}(window.angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.factory('FireAuth', function($firebaseAuth, Root) {
    return $firebaseAuth(Root);
  });

}(window.angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.controller('LoginCtrl', function($scope, $window, Auth, routeTo) {

    // no user before logged in
    $scope.user = null;

    // Change status of message screen based on passed ENUM
    // Can provide custom message if desired
    function changeStatus(status, msg) {
      var returnStatus;

      returnStatus = {
        status: status,
        message: msg || Auth.STATUS_MESSAGE[status]
      };

      return returnStatus;
    };

    $scope.loginStatus = changeStatus(Auth.STATUS.ANON);

    Auth.authWithGoogle()
    .then(function(user) {
      // set the user when logged in
      $scope.user = user;
      // change the status message on the view
      $scope.loginStatus = changeStatus(Auth.STATUS.SUCCESS);
      // route to the trends page
      routeTo('/trends');
    })
    .catch(function(error) {
      $scope.loginStatus = changeStatus(Auth.STATUS.ERROR, error.message);
    });

  });

}(window.angular, config));

(function(angular, config) {
  "use strict";

  angular.module('authRequired', ['firebase'])

  .service('Root', ['FBURL', Firebase])

  .run(function($firebaseAuth, Root, $rootScope, $window) {
    var auth = $firebaseAuth(Root);

    $rootScope.$on('$routeChangeStart', function(e, route) {
      var nextRoute = route.$$route;
      var user;
      if(nextRoute && nextRoute.authRequired) {
        user = auth.$getAuth();
        if(!user) {
          $rootScope.$emit('authRequired:unauthorized', new Error('Unauthorized access.'));
        }
      }
    });

  });

}(window.angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.factory('$entries', function($base, $FirebaseArray, UsersRef, $q) {

    var EntriesFactory = $FirebaseArray.$extendFactory({

      // Return the user info and the entry as one object
      getUserInfo: function() {
        var deferreds = [];
        angular.forEach(this.$list, function(entry) {
          var deferred = $q.defer();

          UsersRef.child(entry.userid).once('value', function(snap) {
            var entryUser = {};
            angular.extend(entryUser, entry, snap.val());
            deferred.resolve(entryUser);
          });

          deferreds.push(deferred.promise);
        });
        return $q.all(deferreds);
      }
    });

    return function $entries (id) {
      return $base('/entries/' + id, { arrayFactory: EntriesFactory });
    };

  });

}(angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.controller('EntriesCtrl', function($scope, entries) {
    entries.getUserInfo().then(function(userEntries) {
      $scope.entries = userEntries;
    });
  });

}(angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.factory('$base', function($firebase, Root) {
    return function $base(path, factory) {
      // if the path is provided then append and return binding
      if(path) {
        var $base;
        if(factory) {
          $base = $firebase(Root.child(path), factory);
        } else {
          $base = $firebase(Root.child(path));
        }
        return $base;
      }

      // if no path is provided return the binding from the Root ref
      return $firebase(Root);
    };
  });

}(angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.factory('Tags', function($FirebaseArray, $firebase, TrendsRef, $timeout) {

    function getTrends(trendsRef, allTheTags, onComplete) {
      var allTheTrends = {};

      trendsRef.on('value', function(snap) {

        snap.forEach(function(ss) {
          var trendObject = ss.val();
          var trendName = ss.key();

          trendObject.tags = allTheTags[trendName]||[];
          allTheTrends[trendName] = trendObject;
          allTheTrends[trendName].id = trendName;

        });

        if (onComplete) {
          $timeout(function() {
            onComplete.call(this, allTheTrends);
          });
        }

      });

    }

    var TagsFactory = $FirebaseArray.$extendFactory({
      getTrends: function(params) {
        var allTheTags = [];
        angular.forEach(this.$list, function(tag) {
          // $id
          var tagId = tag.$id;
          angular.forEach(tag, function(value, key) {
            if(key.indexOf('$') === 0) { return; } // no $ props

            if(!allTheTags[key]) {
              allTheTags[key] = [];
            }

            allTheTags[key].push(tagId);

          });

          getTrends(TrendsRef, allTheTags, params.onComplete);

        });
      }
    });

    return function(listRef) {
      var sync = $firebase(listRef, {arrayFactory: TagsFactory});
      return sync.$asArray();
    }
  });

}(angular, config));

(function(angular, config) {
  "use strict";

  var app = config.app();

  app.controller('TrendsCtrl', function($scope, tags) {

    tags.getTrends({
      onComplete: function(trends) {
        $scope.trends = trends;
      }
    });

  });

}(angular, config));


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/examples/tabbed_pane_example.h"

#include <memory>
#include <utility>

#include "base/strings/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/examples/examples_window.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/grid_layout.h"

using l10n_util::GetStringUTF16;
using l10n_util::GetStringUTF8;

namespace views {
namespace examples {

TabbedPaneExample::TabbedPaneExample()
    : ExampleBase(GetStringUTF8(IDS_TABBED_PANE_SELECT_LABEL).c_str()) {}

TabbedPaneExample::~TabbedPaneExample() = default;

void TabbedPaneExample::CreateExampleView(View* container) {
  auto tabbed_pane = std::make_unique<TabbedPane>();
  tabbed_pane->set_listener(this);
  auto add = std::make_unique<LabelButton>(
      this, GetStringUTF16(IDS_TABBED_PANE_ADD_LABEL));
  auto add_at = std::make_unique<LabelButton>(
      this, GetStringUTF16(IDS_TABBED_PANE_ADD_1_LABEL));
  auto select_at = std::make_unique<LabelButton>(
      this, GetStringUTF16(IDS_TABBED_PANE_SELECT_1_LABEL));

  GridLayout* layout =
      container->SetLayoutManager(std::make_unique<views::GridLayout>());

  const int tabbed_pane_column = 0;
  ColumnSet* column_set = layout->AddColumnSet(tabbed_pane_column);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1.0f,
                        GridLayout::ColumnSize::kUsePreferred, 0, 0);
  layout->StartRow(1 /* expand */, tabbed_pane_column);
  tabbed_pane_ = layout->AddView(std::move(tabbed_pane));

  // Create a few tabs with a button first.
  AddButton(GetStringUTF16(IDS_TABBED_PANE_TAB_1_LABEL));
  AddButton(GetStringUTF16(IDS_TABBED_PANE_TAB_2_LABEL));
  AddButton(GetStringUTF16(IDS_TABBED_PANE_TAB_3_LABEL));

  // Add control buttons horizontally.
  const int button_column = 1;
  column_set = layout->AddColumnSet(button_column);
  for (size_t i = 0; i < 3; i++) {
    column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1.0f,
                          GridLayout::ColumnSize::kUsePreferred, 0, 0);
  }

  layout->StartRow(0 /* no expand */, button_column);
  add_ = layout->AddView(std::move(add));
  add_at_ = layout->AddView(std::move(add_at));
  select_at_ = layout->AddView(std::move(select_at));
}

void TabbedPaneExample::ButtonPressed(Button* sender, const ui::Event& event) {
  if (sender == add_) {
    AddButton(GetStringUTF16(IDS_TABBED_PANE_ADDED_LABEL));
  } else if (sender == add_at_) {
    const base::string16 label = GetStringUTF16(IDS_TABBED_PANE_ADDED_1_LABEL);
    tabbed_pane_->AddTabAtIndex(1, label,
                                std::make_unique<LabelButton>(nullptr, label));
  } else if (sender == select_at_) {
    if (tabbed_pane_->GetTabCount() > 1)
      tabbed_pane_->SelectTabAt(1);
  }
  PrintCurrentStatus();
}

void TabbedPaneExample::TabSelectedAt(int index) {
  // Just print the status when selection changes.
  PrintCurrentStatus();
}

void TabbedPaneExample::PrintCurrentStatus() {
  PrintStatus("Tab Count:%" PRIuS ", Selected Tab:%" PRIuS,
              tabbed_pane_->GetTabCount(), tabbed_pane_->GetSelectedTabIndex());
}

void TabbedPaneExample::AddButton(const base::string16& label) {
  tabbed_pane_->AddTab(label, std::make_unique<LabelButton>(nullptr, label));
}

}  // namespace examples
}  // namespace views


text:
import React, { Component } from 'react';

import { translate } from '../../base/i18n';

/**
 * React component for labeling speaker stats column items.
 *
 * @extends Component
 */
class SpeakerStatsLabels extends Component {
    /**
     * SpeakerStatsLabels component's property types.
     *
     * @static
     */
    static propTypes = {
        /**
         * The function to translate human-readable text.
         */
        t: React.PropTypes.func
    };

    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const { t } = this.props;

        return (

                    { t('speakerStats.name') }

                    { t('speakerStats.speakerTime') }

        );
    }
}

export default translate(SpeakerStatsLabels);


text:
@implementation MLBatteryInfoModel

- (instancetype)initWithData:(NSData *)data {
    self = [super init];
    if (self) {
        MLDataReader *reader = [[MLDataReader alloc] initWithData:data];
        _level = [reader readInt:1];
        _lastCharge = [reader readDate];
        _chargesCount = [reader readInt:2];
        _status = [reader readInt:1];
    }
    return self;
}

- (NSData *)data {
    MLDataBuilder *builder = [[MLDataBuilder alloc] init];
    [builder writeInt:_level bytesCount:1];
    [builder writeDate:_lastCharge];
    [builder writeInt:_chargesCount bytesCount:1];
    [builder writeInt:_status bytesCount:1];
    return [builder data];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"level = %tu%%, lastCharge = %@, chargesCount = %tu, status = %tx", _level, _lastCharge, _chargesCount, _status];
}

@end


text:
<!DOCTYPE HTML>

		<title>Contact - Alpha by HTML5 UP</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />

		<link rel="stylesheet" href="assets/css/main.css" />

Alpha by HTML5 UP

Home

								Layouts

Generic

Contact

Elements

										Submenu

Option One

Option Two

Option Three

Option Four

Sign Up

Contact Us

Tell us what you think about our little operation.

						<form method="post" action="#">

									<input type="text" name="name" id="name" value="" placeholder="Name" />

									<input type="email" name="email" id="email" value="" placeholder="Email" />

									<input type="text" name="subject" id="subject" value="" placeholder="Subject" />

									<textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea>

<input type="submit" value="Send Message" />

						</form>

Twitter

Facebook

Instagram

Github

Dribbble

Google+

© Untitled. All rights reserved.

Design: HTML5 UP


text:
<?php
/*
 * Generated by CRUDigniter v3.0 Beta
 * www.crudigniter.com
 */

class State_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    /*
     * Get state by province_state_code
     */
    function get_state($province_state_code)
    {
        $state = $this->db->query("
            SELECT
                *

            FROM
                `state`

            WHERE
                `province_state_code` = ?
        ",array($province_state_code))->row_array();

        return $state;
    }

    /*
     * Get all state
     */
    function get_all_state()
    {
        $state = $this->db->query("
            SELECT
                *

            FROM
                `state`

            WHERE
                1 = 1
        ")->result_array();

        return $state;
    }

    /*
     * function to add new state
     */
    function add_state($params)
    {
        $this->db->insert('state',$params);
        return $this->db->insert_id();
    }

    /*
     * function to update state
     */
    function update_state($province_state_code,$params)
    {
        $this->db->where('province_state_code',$province_state_code);
        $response = $this->db->update('state',$params);
        if($response)
        {
            return "state updated successfully";
        }
        else
        {
            return "Error occuring while updating state";
        }
    }

    /*
     * function to delete state
     */
    function delete_state($province_state_code)
    {
        $response = $this->db->delete('state',array('province_state_code'=>$province_state_code));
        if($response)
        {
            return "state deleted successfully";
        }
        else
        {
            return "Error occuring while deleting state";
        }
    }
}


text:
package org.wildfly.camel.test.jmx;

import javax.management.monitor.MonitorNotification;

import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.test.common.DMRUtils;
import org.wildfly.extension.camel.CamelContextRegistry;

/**
 * Deploys a test which monitors an JMX attrbute of a route.
 *
 * @author thomas.diesler@jboss.com
 * @since 03-Jun-2013
 */
@RunWith(Arquillian.class)
@ServerSetup({JMXIntegrationTest.SystemContextSetupTask.class})
public class JMXIntegrationTest  {

    @ArquillianResource
    CamelContextRegistry contextRegistry;

    static class SystemContextSetupTask implements ServerSetupTask {

        @Override
        public void setup(final ManagementClient managementClient, String containerId) throws Exception {
            String contextXml = "" +
                    "\t\t     <route>\n" +
                    "\t\t       <from uri=\"direct:start\"/>\n" +
                    "\t\t       <transform>\n" +
                    "\t\t         <simple>Hello #{body}</simple>\n" +
                    "\t\t       </transform>\n" +
                    "\t\t     </route>\n" +
                    "";

            // Add a system context
            ModelNode contextOpAdd = DMRUtils.createOpNode("subsystem=camel/context=jmx-context-1/", "add");
            contextOpAdd.get("value").set(contextXml);
            managementClient.getControllerClient().execute(DMRUtils.createCompositeNode(new ModelNode[]{contextOpAdd}));
        }

        @Override
        public void tearDown(final ManagementClient managementClient, String containerId) throws Exception {
            // Removes a system context
            ModelNode contextOpAdd = DMRUtils.createOpNode("subsystem=camel/context=jmx-context-1/", "remove");
            managementClient.getControllerClient().execute(DMRUtils.createCompositeNode(new ModelNode[]{contextOpAdd}));
        }
    }

    @Deployment
    public static JavaArchive deployment() {
        final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "jmx-integration-tests");
        return archive;
    }

    @Test
    public void testMonitorMBeanAttribute() throws Exception {
        CamelContext context = contextRegistry.getCamelContext("jmx-context-1");
        Assert.assertNotNull("Camel context jmx-context-1 was null", context);
        final String routeName = context.getRoutes().get(0).getId();

        CamelContext camelctx = new DefaultCamelContext();
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("jmx:platform?format=raw&objectDomain=org.apache.camel&key.context=jmx-context-1&key.type=routes&key.name=\"" + routeName + "\"" +
                "&monitorType=counter&observedAttribute=ExchangesTotal&granularityPeriod=500").
                to("direct:end");
            }
        });

        camelctx.start();
        try {
            ConsumerTemplate consumer = camelctx.createConsumerTemplate();
            MonitorNotification notifcation = consumer.receiveBody("direct:end", MonitorNotification.class);
            Assert.assertEquals("ExchangesTotal", notifcation.getObservedAttribute());
        } finally {
            camelctx.stop();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AdventureWorks.Mvc
{
    public class AppSettings
    {
        public string SiteTitle { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<GlassEventLog>

  <Command name="bp py_mod.py 5"/>

  <Command name='launch "native {EC1375B7-E2CE-43E8-BF75-DC638DE1F1F9}" %PythonExe% py_mod.py'>
    <!-- Use entry point filename as a sanity check that we've got Python symbols loaded correctly. -->
    <Event name="IDebugEntryPointEvent2" expected="True">
      <functionName Volatile="True" />
      <function Volatile="True"/>
      <file>python.c</file>
      <line Volatile="True"/>
      <col Volatile="True"/>
    </Event>
  </Command>

  <Command name="go">
    <Event name="IDebugBreakpointEvent2" expected="True">
      <functionName/>
      <function><module></function>
      <file>py_mod.py</file>
      <line>5</line>
      <col Volatile="True"/>
    </Event>
  </Command>

  <Command name="eval o">
    <EvalResult RegEx="<ObjectWithDict object at 0x[0-9A-F]+>"/>
    <EvalType>ObjectWithDict</EvalType>
    <EvalIsExpandable>True</EvalIsExpandable>
    <EvalName Volatile="True"/>
    <EvalFullName Volatile="True"/>
  </Command>
  <Command name="expandn 1 o">
    <ExpandResult RegEx="<ObjectWithDict object at 0x[0-9A-F]+>"/>
    <ExpandType>ObjectWithDict</ExpandType>
    <ExpandIsExpandable>True</ExpandIsExpandable>

    <ChildName>__dict__</ChildName>
    <ChildFullName>o.__dict__</ChildFullName>
    <ChildResult RegEx="\{('x': 1, 'y': 2)|('y': 2, 'x': 1)\}"/>
    <ChildType>dict</ChildType>
    <ChildIsExpandable>True</ChildIsExpandable>

    <ChildName>x</ChildName>
    <ChildFullName>o.x</ChildFullName>
    <ChildResult>1</ChildResult>
    <ChildType>int</ChildType>
    <ChildIsExpandable>False</ChildIsExpandable>

    <ChildName>y</ChildName>
    <ChildFullName>o.y</ChildFullName>
    <ChildResult>2</ChildResult>
    <ChildType>int</ChildType>
    <ChildIsExpandable>False</ChildIsExpandable>
  </Command>

  <Command name="go">
    <Event name="IDebugSessionDestroyEvent2" expected="True" />
  </Command>
  <Command name="quit"/>

</GlassEventLog>