text:
class Course::Condition::Achievement < ActiveRecord::Base
  acts_as_condition
  belongs_to :achievement, class_name: Course::Achievement.name, inverse_of: false

  default_scope { includes(:achievement) }

  validate :validate_achievement_condition, if: :achievement_id_changed?

  delegate :title, to: :achievement

  # Checks if the user has the required achievement.
  #
  # @param [CourseUser] course_user The user that the achievement condition is being checked on. The
  #   user must respond to `achievements` and returns an ActiveRecord::Association that
  #   contains all achievements the subject has obtained.
  # @return [Boolean] true if the user has the required achievement and false otherwise.
  def satisfied_by?(course_user)
    course_user.achievements.exists?(achievement)
  end

  private

  # Given an achievement, returns all its achievement conditions.
  #
  # @param [Course::Achievement] achievement The achievement to return achievement conditions for.
  # @return [Array<Course::Achievement>]
  def achievement_conditions(achievement)
    # Course::Condition::Achievement.
    #   joins { condition.conditional(Course::Achievement) }.
    #   where { condition.conditional.id == achievement.id }.
    #   map(&:achievement)

    # Workaround, pending the squeel bugfix (activerecord-hackery/squeel#390) that will allow
    # allow the above query to work without #reload
    Course::Achievement.joins(
      "INNER JOIN
        (SELECT cca.achievement_id
          FROM course_condition_achievements cca INNER JOIN course_conditions cc
            ON cc.actable_type = 'Course::Condition::Achievement' AND cc.actable_id = cca.id
            WHERE cc.conditional_id = #{achievement.id}) ids
    ON ids.achievement_id = course_achievements.id")
  end

  def validate_achievement_condition
    validate_references_self
    validate_unique_dependency
  end

  def validate_references_self
    return unless achievement == conditional
    errors.add(:achievement, :references_self)
  end

  def validate_unique_dependency
    return unless achievement_conditions(conditional).include?(achievement)
    errors.add(:achievement, :unique_dependency)
  end
end


text:
<?php
$language["SUBFORUM"]="SubForum";
$language["SUBFORUMS"]="SubForums";
$language["NEW_TOPIC"]="Neues Thema";
$language["NO_TOPICS"]="Sorry, kein Thema vorhanden.";
$language["LOCKED"]="Gesperrtes Thema";
$language["LOCKED_NEW"]="Gesperrtes Thema (Neu)";
$language["UNLOCKED"]="Keine neuen Antworten";
$language["UNLOCKED_NEW"]="Neue Antworten";
$language["ERR_CANT_START_TOPICS"]="Du darfst in diesem Forum kein neues Thema eröffnen";
$language["BAD_FORUM_ID"]="Ungültige Forum ID";
$language["MOD_OPTION"]="Moderations Optionen";
$language["SET_STICKY"]="Setzen/Lösen Sticky";
$language["SET_LOCKED"]="Sperren/Entsperren Thema";
$language["RENAME_TOPIC"]="Thema umbenennen";
$language["DELETE_TOPIC"]="Thema löschen";
$language["MOVE_TOPIC"]="Thema verschieben nach";
$language["MOVE"]="Verschieben";
$language["ADD_REPLY"]="Antwort hinzufügen";
$language["BAD_TOPIC_ID"]="Ungültige Themen ID";
$language["LAST_10_POSTS"]="10 letzte Beiträge, in umgekehrter Reihenfolge";
$language["LAST_EDITED_BY"]="Zuletzt geändert durch";
$language["ERR_POST_ID_NA"]="Post ID ist N/A";
$language["ERR_FORUM_TOPIC"]="Ungültige Forum oder Themen ID";
$language["ERR_POST_NOT_FOUND"]="Beitrag nicht gefunden";
$language["ERR_POST_UNIQUE"]="Kann den Beitrag nicht löschen; es ist der einzige Beitrag in diesem Thema. Du solltest es tun";
$language["ERR_POST_UNIQUE_2"]="Beitrag löschen";
$language["ERR_POST_UNIQUE_3"]="stattdessen";
$language["TOPIC_LOCKED"]="Dieses Thema ist gesperrt; es sind keine Beiträge erlaubt";
$language["TOPIC_NOT_FOUND"]="Thema nicht gefunden";
$language["TOPIC_UNREAD_POSTS"]="Themen mit ungelesenen Beiträgen";
$language["POST"]="Beitrag";
$language["SEARCH_AGAIN"]="Erneut suchen";
$language["SEARCH_HELP"]="Gib ein oder mehrere Wörter zum suchen ein
Einfache Wörter, oder solche mit weniger als 3 Buchstaben werden ignoriert";
$language["SEARCHED_FOR"]="Gesucht nach";

?>

redpajama_set_name: RedPajamaGithub


text:
class CommandPixel : public ICommand {
	public:
		CommandPixel();
		virtual bool isMultiLine();
		virtual ICommand *create();
		virtual QString name();
		virtual void setParams(QStringList list);
		virtual bool check();
		virtual bool check(QString &strResult);
		virtual QString code();
		virtual void appendCode(QString);
		virtual void run(ICore *pCore);
	private:
		QString m_strName;
		QStringList m_listParams;
		QStringList m_strCode;
		int m_nX1;
		int m_nY1;
		int m_nColor;
		bool m_bCheck;
		QString m_sCheck;
};

#endif // COMMAND_PIXEL_H


text:
'use strict';

var angular = require('angular');
var HyRes = require('hy-res');

angular.module('hrCore', [])
  .factory('hrHttp', ['$http', function($http) {
    var headersProcessor = function(resp) {
      resp.headers = resp.headers();
      return resp;
    };

    return function(options) {
      return $http(options).then(headersProcessor, function(resp) {
        throw headersProcessor(resp);
      });
    };
  }])
  .provider('hrRoot', function() {
    this.extensions = [];
    this.$get = ['hrHttp', '$injector', function(hrHttp, $injector) {
      var exts = [];
      angular.forEach(this.extensions, function(val) {
        exts.push($injector.get(val));
      });

      return function(url) {
        return new HyRes.Root(url, hrHttp, exts);
      };
    }];
  });

module.exports = 'hrCore';


text:
<?php

namespace App\Model;

use Datalaere\PHPMvcFramework\Model;
use Datalaere\PHPScrud\DB;

class PostsModel extends Model
{

    // object instance
    protected static $instance = null;
    private $db;
    private $table;
    private $attributes;
    private $total;
    private $pages;
    private $perPage;

    public function __construct()
    {
        $this->table      = DB_PREFIX . 'Posts';
        $this->attributes = "$this->table.ID, $this->table.Created, $this->table.Updated, $this->table.Posts.Start, $this->table.End, $this->table.Title, $this->table.Slug, $this->table.Content, $this->table.Excerpt, $this->table.I18n, $this->table.Status_ID, $this->table.User_ID";
        $this->db         = DB::load();
    }

    public static function load()
    {
        if (!isset(self::$instance)) {
            self::$instance = new PostsModel();
        }
        return self::$instance;
    }
    public function setModel($name, $value)
    {
        $this->$name = $value;
    }

    public function search($query)
    {
        return $this->db->search($this->table, $this->rows, $query, array($this->attributes));
    }

    // create
    public function create($fields = array())
    {
        return $this->db->insert($this->table, $fields);
    }

    // read
    public function read($paging = null, $where = array(array()))
    {
        if (!empty($paging)) {
            return $this->paging($paging['start'], $paging['end'], $paging['max'], $where);
        } else {
            $this->db->select(array($this->attributes), $this->table, $where);
            return $this->db->results();
        }
    }

    // get page by specific search
    public function get($where =array(array()), $paging = array(), $options = array())
    {
        if (!empty($paging)) {
            return $this->paging($paging['start'], $paging['end'], $paging['max'], $where);
        } else {
            $this->db->select(array($this->attributes), $this->table, $where, $options);
            return $this->db->results();
        }
    }

    public function join($sql, $params = array(), $paging = false, $where = array(array()))
    {
        if ($paging) {
            $this->paging($paging['start'], $paging['end'], $paging['max'], $where);
            $params = array_merge($params, array($this->pages, $this->perPage));
        }

        $this->db->query($sql, $params);
        return $this->db->results();
    }

    // get last ind fro SQL INSERT
    public function getLastInsertId()
    {
        return $this->db->lastInsertId();
    }

    public function paging($start, $end, $max, $where =array(array()))
    {
        $page          = isset($start) ? (int) $start : 1;
        $this->perPage = isset($end) && $end <= $max ? (int) $end : 5;

        $this->pages = ($page > 1) ? ($page * $this->perPage) - $this->perPage : 0;

        $this->total = (ceil($this->count($where)[0]->Total / $this->perPage));
    }

    public function count($where = array(array()))
    {
        $this->db->select(array("count(*) AS Total"), $this->table, $where);
        return $this->db->results();
    }

    public function total()
    {
        return $this->total;
    }

    // update page by id
    public function update($fields = array(), $ID = null)
    {
        return $this->db->update($this->table, 'ID', $ID, $fields);
    }

    // delete
    public function delete($where = array(array()))
    {
        return $this->db->delete($this->table, $where);
    }
}


text:
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System;
using Xamarin.Forms;
using Colors = System.Drawing.Color;

namespace ArcGISRuntime.Samples.DisplayGrid
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Display grid",
        category: "MapView",
        description: "Display coordinate system grids including Latitude/Longitude, MGRS, UTM and USNG on a map view. Also, toggle label visibility and change the color of grid lines and grid labels.",
        instructions: "Select type of grid from the types (LatLong, MGRS, UTM and USNG) and modify its properties like label visibility, grid line color, and grid label color. Press the button to apply these settings.",
        tags: new[] { "MGRS", "USNG", "UTM", "coordinates", "degrees", "graticule", "grid", "latitude", "longitude", "minutes", "seconds" })]
    public partial class DisplayGrid : ContentPage
    {
        public DisplayGrid()
        {
            InitializeComponent();

            // Create the UI, setup the control references and execute initialization
            Initialize();
        }

        private void Initialize()
        {
            // Set up the map view with a basemap.
            MyMapView.Map = new Map(BasemapStyle.ArcGISImagery);

            // Configure the UI options.
            gridTypePicker.ItemsSource = new[] { "LatLong", "MGRS", "UTM", "USNG" };
            string[] colorItemsSource = { "Red", "Green", "Blue", "White", "Purple" };
            gridColorPicker.ItemsSource = colorItemsSource;
            labelColorPicker.ItemsSource = colorItemsSource;
            haloColorPicker.ItemsSource = colorItemsSource;
            labelPositionPicker.ItemsSource = Enum.GetNames(typeof(GridLabelPosition));
            labelFormatPicker.ItemsSource = Enum.GetNames(typeof(LatitudeLongitudeGridLabelFormat));
            foreach (Picker combo in new[]
                {gridTypePicker, gridColorPicker, labelColorPicker, labelPositionPicker, labelFormatPicker})
            {
                combo.SelectedIndex = 0;
            }

            // Update the halo color to have a good default.
            haloColorPicker.SelectedIndex = 3;

            // Handle grid type changes so that the format option can be disabled for non-latlong grids.
            gridTypePicker.SelectedIndexChanged += (o, e) =>
            {
                labelFormatPicker.IsEnabled = gridTypePicker.SelectedItem.ToString() == "LatLong";
            };

            // Subscribe to the button click event.
            applySettingsButton.Clicked += ApplySettingsButton_Clicked;

            // Enable the action button.
            applySettingsButton.IsEnabled = true;

            // Zoom to a default scale that will show the grid labels if they are enabled.
            MyMapView.SetViewpointCenterAsync(
                new MapPoint(-7702852.905619, 6217972.345771, SpatialReferences.WebMercator), 23227);

            // Apply default settings.
            ApplySettingsButton_Clicked(this, null);
        }

        private void ApplySettingsButton_Clicked(object sender, EventArgs e)
        {
            Esri.ArcGISRuntime.UI.Grid grid;

            // First, update the grid based on the type selected.
            switch (gridTypePicker.SelectedItem.ToString())
            {
                case "LatLong":
                    grid = new LatitudeLongitudeGrid();
                    // Apply the label format setting.
                    string selectedFormatString = labelFormatPicker.SelectedItem.ToString();
                    ((LatitudeLongitudeGrid)grid).LabelFormat =
                        (LatitudeLongitudeGridLabelFormat)Enum.Parse(typeof(LatitudeLongitudeGridLabelFormat),
                            selectedFormatString);
                    break;

                case "MGRS":
                    grid = new MgrsGrid();
                    break;

                case "UTM":
                    grid = new UtmGrid();
                    break;

                case "USNG":
                default:
                    grid = new UsngGrid();
                    break;
            }

            // Next, apply the label visibility setting.
            grid.IsLabelVisible = labelVisibilitySwitch.IsToggled;

            // Next, apply the grid visibility setting.
            grid.IsVisible = gridVisibilitySwitch.IsToggled;

            // Next, apply the grid color and label color settings for each zoom level.
            for (long level = 0; level < grid.LevelCount; level++)
            {
                // Set the line symbol.
                Symbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid,
                    Colors.FromName(gridColorPicker.SelectedItem.ToString()), 2);
                grid.SetLineSymbol(level, lineSymbol);

                // Set the text symbol.
                Symbol textSymbol = new TextSymbol
                {
                    Color = Colors.FromName(labelColorPicker.SelectedItem.ToString()),
                    OutlineColor = Colors.FromName(haloColorPicker.SelectedItem.ToString()),
                    Size = 16,
                    HaloColor = Colors.FromName(haloColorPicker.SelectedItem.ToString()),
                    HaloWidth = 3
                };
                grid.SetTextSymbol(level, textSymbol);
            }

            // Next, apply the label position setting.
            grid.LabelPosition =
                (GridLabelPosition)Enum.Parse(typeof(GridLabelPosition), labelPositionPicker.SelectedItem.ToString());

            // Apply the updated grid.
            MyMapView.Grid = grid;
        }
    }
}


text:
using FluentValidation;

namespace AspNetCoreSpa.Application.Features.Customers.Queries.GetCustomerDetail
{
    public class GetCustomerDetailQueryValidator : AbstractValidator<GetCustomerDetailQuery>
    {
        public GetCustomerDetailQueryValidator()
        {
            RuleFor(v => v.Id).NotEmpty().Length(5);
        }
    }
}


text:
from joke.spider.task import sync_joke_pengfu_task

def test_sync_joke_pengfu_task():
    #sync_joke_pengfu_task()
    assert True
    # assert False


text: bash ./gradlew -PideaVersion="2019.1.3" -PideaBranch="191" runIde


text:
There are three main classes:

 * The Init class, which creates the signed security packets to initialise the JavaScript APIs;
 * The Remote class, which encapsulates remote calls to the APIs and their responses;
 * The DataAPI class, which allows your app to interact with the Data API from PHP code.

### Example

A Data API example, showing how to pull specific data from the system is included in the `docs/quickstart/analytics` folder. You can run it like so:

    php docs/quickstart/analytics/init_data.php

You can find a complete PHP site with more examples of Learnosity API integration in our [demos site](https://demos.learnosity.com/).

You can also download the entire demo site or browse the code directly on [GitHub](https://github.com/Learnosity/learnosity-demos/).

### Init

The Init class is used to create the necessary *security* and *request* details used to integrate with a Learnosity API. Most often this will be a JavaScript object.

``` php
//Include the Init and Uuid classes.
use LearnositySdk\Request\Init;
$user_id = Uuid::generate();
```

The Init constructor takes up to 5 arguments:

 * [string]  service type
 * [array]   security details (**no secret**)
 * [string]  secret
 * [request] request details *(optional)*
 * [string]  action *(optional)*

``` php
<?php

// Instantiate the SDK Init class with your security and request data:
$Init = new Init(
   'questions',
   [
       'consumer_key' => 'yis0TYCu7U9V4o7M',
       'domain'       => 'localhost',
       'user_id'      => $user_id // Never transmit the student names or personally identifiable information over the wire. Instead, we use an anonymized UUID string.
   ],
   'superfragilisticexpialidocious',
   [
       'type'      => 'local_practice',
       'state'     => 'initial',
       'questions' => [
           [
               'response_id'        => '60005',
               'type'               => 'association',
               'stimulus'           => 'Match the cities to the parent nation.',
               'stimulus_list'      => ['London', 'Dublin', 'Paris', 'Sydney'],
               'possible_responses' => ['Australia', 'France', 'Ireland', 'England'],
               'validation' => [
                   'valid_responses' => [
                       ['England'], ['Ireland'], ['France'], ['Australia']
                   ]
               ]
           ]
       ]
   ]
);

// Call the generate() method to retrieve a JavaScript object
$request = $Init->generate();
?>

// Pass the object to the initialisation of any Learnosity API, in this example the Questions API
<script src="//questions.learnosity.com"></script>
<script>
    var questionsApp = LearnosityApp.init(<?php echo $request; ?>);
</script>
```

#### Init() Arguments
**service**

A string representing the Learnosity service (API) you want to integrate with. Valid options are:

* assess
* author
* data
* events
* items
* questions
* reports

**security**

An array^ that includes your *consumer_key* but does not include your *secret*. The SDK sets defaults for you, but valid options are:

* consumer_key
* domain (optional - defaults to *localhost*)
* timestamp (optional - the SDK will generate this for you)
* user_id (optional - not necessary for all APIs)

^Note – the SDK accepts a JSON string and native PHP arrays.

**secret**

Your private key, as provided by Learnosity.

**request**

An optional associative array^ of data relevant to the API being used. This will be any data minus the security details that you would normally use to initialise an API.

^Note – the SDK accepts a JSON string and native PHP arrays.

**action**

An optional string used only if integrating with the Data API. Valid options are:

* get
* set
* update
* delete

### Remote

The Remote class is used to make server side, cross domain requests. Think of it as a cURL wrapper.

You'll call either `get()` or `post()` (mimicking the HTTP request type you want to make) with the following arguments:

* [string] URL
* [array]  Data payload
* [array]  Options

``` php
//Include the Remote classes.
use LearnositySdk\Request\Remote;
```

``` php
// Instantiate the SDK Remote class:
$Remote = new Remote();
// Call get() or post() with a URL:
$response = $Remote->get('http://schemas.learnosity.com/latest/questions/templates');

// getBody() gives you to body of the request
$requestPacket = $response->getBody();
```

#### Remote() arguments

**URL**

A string URL, including schema and path. Eg:

    https://schemas.learnosity.com/latest/questions/templates

**Data**

An optional array of data to be sent as a payload. For GET it will be a URL encoded query string.

**Options**

An optional array of [cURL parameters](http://www.php.net/manual/en/curl.constants.php).

#### Remote methods
The following methods are available after making a `get()` or `post()`.

**getBody()**

Returns the body of the response payload.

**getError()**

Returns an array that includes the error code and message (if an error was thrown)

**getHeader()**

Currently only returns the *content_type* header of the response.

**getSize()**

Returns the size of the response payload in bytes.

**getStatusCode()**

Returns the HTTP status code of the response.

### DataApi

This is a helper class for use with the Data API. It creates the initialisation packet and sends a request to the Data API, returning an instance of Remote. You can then interact as you would with Remote, e.g., `getBody()`

#### request()

Used for a single request to the Data API. You can call as many times as necessary. It will return a `Remote` object, on which `getBody()` needs to be called to get the contents of the response.

``` php
$DataApi = new DataApi();
$response = $DataApi->request(
    'https://data.learnosity.com/v1/itembank/items',
    [
       'consumer_key' => 'yis0TYCu7U9V4o7M',
       'domain'       => 'localhost'
    ],
    'superfragilisticexpialidocious',
    [
       'limit' => 20
    ],
    'get' // optional, will default to 'get' in the backend if unspecified
);
```

#### requestRecursive()

Used to make recursive requests to the Data API, using the *next* token, for as much data is returned based on the request filtering provided.

You can pass a callback as the 6th argument, that will be executed upon completion of every request.

``` php
$DataApi = new DataApi();

$response = $DataApi->requestRecursive(
    'https://data.learnosity.com/v1/itembank/items',
    [
       'consumer_key' => 'yis0TYCu7U9V4o7M',
       'domain'       => 'localhost'
    ],
    'superfragilisticexpialidocious',
    [
       'limit' => 20
    ],
    'get',
    function ($data) {
        $this->processData($data);
    }
);

function processData($data)
{
    // Do something with $data
}
```

#### Overriding the remote options

You can send an array to the DataAPI constructor to override any remote (cURL) options, e.g.:

``` php
$options = array(
    'connect_timeout' => 20
    'timeout' => 60
);

$dataapi = new DataApi($options);
```

## Further reading
Thanks for reading to the end! Find more information about developing an app with Learnosity on our documentation sites:

help.learnosity.com -- general help portal and tutorials,

reference.learnosity.com -- developer reference site, and

authorguide.learnosity.com -- authoring documentation for content creators.

Back to [README.md](README.md)


text:
layout: default
---

The Golden rule

“Every line of code should appear to be written by a single person, no matter the number of contributors.”

Table of contents

HTML

Syntax

HTML5 doctype

Language attribute

Character encoding

Internet Explorer compatibility mode

CSS and JavaScript includes

Practicality over purity

Attribute order

Boolean attributes

Reducing markup

JavaScript generated markup

Sass

Syntax

Selectors

Nesting

Variables

@includes vs @extends

Comments

Media query placement

Rules with single declarations

Shorthand notation

Classes

Organization

Maintainability

Declaration order

JavaScript (ES6)

Syntax

Variables

Comparison

Type casting

Naming conventions

Comments

Destructuring

Modules

Strings

Arrays

Functions

Objects

Classes

Events

jQuery

Liquid

An Introduction to Shopify

Syntax

Whitespace in Expressions and Statements

Variables

Debugging Tips

PHP

Introduction

Basics

Namespace and Use Declarations

Methods and Function Calls

Control Structures

Closures

WordPress

Introduction

Single and Double Quotes

Indentation

Brace Style

Function Guards

Regular Expressions

Space Usage

Formatting SQL statements

Database Queries

Naming Conventions

Self-Explanatory Flag Values for Function Arguments

Ternary Operator

Yoda Conditions

Miscellaneous

CoffeeScript

Code layout

Module Imports

Whitespace in Expressions and Statements

Comments

Naming Conventions

Functions

Strings

Conditionals

Looping and Comprehensions

Annotations

Miscellaneous

Git

An introduction to Git

Repo Naming

Setup

Branches and Pull Requests

Commits

Pushing

Merging

Tagging and Releasing

{% include section-html.html %}

{% include section-sass.html %}

{% include section-javascript.html %}

{% include section-liquid.html %}

{% include section-php-apps.html %}

{% include section-php-wordpress.html %}

{% include section-coffeescript.html %}

{% include section-git.html %}


text:
package com.gooddata.sdk.model.md;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.gooddata.sdk.common.util.GoodDataToStringBuilder;

import java.io.Serializable;

/**
 * Display form
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DisplayForm extends AbstractObj {

    private static final long serialVersionUID = 8719802319193893780L;

    @JsonProperty("content")
    protected final Content content;

    @JsonProperty("links")
    private final Links links;

    @JsonCreator
    protected DisplayForm(@JsonProperty("meta") Meta meta, @JsonProperty("content") Content content,
            @JsonProperty("links") Links links) {
        super(meta);
        this.content = content;
        this.links = links;
    }

    @JsonIgnore
    public String getFormOf() {
        return content.getFormOf();
    }

    @JsonIgnore
    public String getExpression() {
        return content.getExpression();
    }

    @JsonIgnore
    public String getLdmExpression() {
        return content.getLdmExpression();
    }

    @JsonIgnore
    public String getType() {
        return content.getType();
    }

    @JsonIgnore
    public String getElementsUri() {
        return links.getElements();
    }

    @Override
    public String toString() {
        return GoodDataToStringBuilder.defaultToString(this);
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected static class Content implements Serializable {

        private static final long serialVersionUID = 6865880678569437635L;
        private final String formOf;
        private final String expression;
        private final String ldmExpression;
        private final String type;

        @JsonCreator
        public Content(@JsonProperty("formOf") String formOf, @JsonProperty("expression") String expression,
                       @JsonProperty("ldmexpression") String ldmExpression, @JsonProperty("type") String type) {
            this.formOf = formOf;
            this.expression = expression;
            this.ldmExpression = ldmExpression;
            this.type = type;
        }

        public String getFormOf() {
            return formOf;
        }

        public String getExpression() {
            return expression;
        }

        @JsonProperty("ldmexpression")
        public String getLdmExpression() {
            return ldmExpression;
        }

        public String getType() {
            return type;
        }

        @Override
        public String toString() {
            return GoodDataToStringBuilder.defaultToString(this);
        }
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    protected static class Links implements Serializable {

        private static final long serialVersionUID = 1704085675250093860L;
        private final String elements;

        @JsonCreator
        protected Links(@JsonProperty("elements") String elements) {
            this.elements = elements;
        }

        public String getElements() {
            return elements;
        }

        @Override
        public String toString() {
            return GoodDataToStringBuilder.defaultToString(this);
        }
    }

}


text: alter table "userinfo" add column if not exists "dataviewmaxorgunitlevel" int4 null;


text:
InfoBarObserver::InfoBarObserver(infobars::InfoBarManager* manager, Type type)
    : type_(type) {
  // There may be no |manager| if the browser window is currently closing.
  if (manager)
    infobar_observation_.Observe(manager);
}

InfoBarObserver::~InfoBarObserver() {}

void InfoBarObserver::Wait() {
  // When there is no manager being observed, there is nothing to wait on, so
  // return immediately.
  if (infobar_observation_.IsObserving())
    run_loop_.Run();
}

void InfoBarObserver::OnInfoBarAdded(infobars::InfoBar* infobar) {
  OnNotified(Type::kInfoBarAdded);
}
void InfoBarObserver::OnInfoBarRemoved(infobars::InfoBar* infobar,
                                       bool animate) {
  OnNotified(Type::kInfoBarRemoved);
}
void InfoBarObserver::OnInfoBarReplaced(infobars::InfoBar* old_infobar,
                                        infobars::InfoBar* new_infobar) {
  OnNotified(Type::kInfoBarReplaced);
}

void InfoBarObserver::OnManagerShuttingDown(infobars::InfoBarManager* manager) {
  if (run_loop_.running())
    run_loop_.Quit();
  DCHECK(infobar_observation_.IsObservingSource(manager));
  infobar_observation_.Reset();
}

void InfoBarObserver::OnNotified(Type type) {
  if (type == type_)
    run_loop_.Quit();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
    <stroke
        android:width="1px"
        android:color="@color/dk_color_337CC4" />
    <padding
        android:bottom="1px"
        android:left="1px"
        android:right="1px"
        android:top="1px" />

    <corners android:topRightRadius="4dp" android:bottomRightRadius="4dp" />
</shape>


text:
package org.apache.spark.sql.execution.datasources.json

import com.fasterxml.jackson.core._

import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.analysis.HiveTypeCoercion
import org.apache.spark.sql.execution.datasources.json.JacksonUtils.nextUntil
import org.apache.spark.sql.types._

private[sql] object InferSchema {
  /**
   * Infer the type of a collection of json records in three stages:
    * 推断JSON记录集合的类型分为三个阶段:
   *   1. Infer the type of each record 推断每条记录的类型
   *   2. Merge types by choosing the lowest type necessary to cover equal keys
    *   通过选择覆盖相等键所需的最低类型来合并类型
   *   3. Replace any remaining null fields with string, the top type
    *   用字符串(顶部类型)替换任何剩余的空字段
   */
  def apply(
      json: RDD[String],
      samplingRatio: Double = 1.0,
      columnNameOfCorruptRecords: String): StructType = {
    require(samplingRatio > 0, s"samplingRatio ($samplingRatio) should be greater than 0")
    val schemaData = if (samplingRatio > 0.99) {
      json
    } else {
      json.sample(withReplacement = false, samplingRatio, 1)
    }

    // perform schema inference on each row and merge afterwards
    //在每一行上执行模式推断并在之后合并
    val rootType = schemaData.mapPartitions { iter =>
      val factory = new JsonFactory()
      iter.map { row =>
        try {
          val parser = factory.createParser(row)
          parser.nextToken()
          inferField(parser)
        } catch {
          case _: JsonParseException =>
            StructType(Seq(StructField(columnNameOfCorruptRecords, StringType)))
        }
      }
    }.treeAggregate[DataType](StructType(Seq()))(compatibleRootType, compatibleRootType)

    canonicalizeType(rootType) match {
      case Some(st: StructType) => st
      case _ =>
        // canonicalizeType erases all empty structs, including the only one we want to keep
        //canonicalizeType删除所有空结构,包括我们想要保留的唯一结构
        StructType(Seq())
    }
  }

  /**
   * Infer the type of a json document from the parser's token stream
    * 从解析器的令牌流中推断出json文档的类型
   */
  private def inferField(parser: JsonParser): DataType = {
    import com.fasterxml.jackson.core.JsonToken._
    parser.getCurrentToken match {
      case null | VALUE_NULL => NullType

      case FIELD_NAME =>
        parser.nextToken()
        inferField(parser)

      case VALUE_STRING if parser.getTextLength < 1 =>
        // Zero length strings and nulls have special handling to deal
        // with JSON generators that do not distinguish between the two.
        //零长度字符串和空值具有处理JSON生成器的特殊处理,这些生成器不区分两者
        // To accurately infer types for empty strings that are really
        // meant to represent nulls we assume that the two are isomorphic
        // but will defer treating null fields as strings until all the
        // record fields' types have been combined.
        NullType

      case VALUE_STRING => StringType
      case START_OBJECT =>
        val builder = Seq.newBuilder[StructField]
        while (nextUntil(parser, END_OBJECT)) {
          builder += StructField(parser.getCurrentName, inferField(parser), nullable = true)
        }

        StructType(builder.result().sortBy(_.name))

      case START_ARRAY =>
        // If this JSON array is empty, we use NullType as a placeholder.
        //如果此JSON数组为空,我们使用NullType作为占位符。
        // If this array is not empty in other JSON objects, we can resolve
        // the type as we pass through all JSON objects.
        //如果此数组在其他JSON对象中不为空,我们可以在通过所有JSON对象时解析该类型
        var elementType: DataType = NullType
        while (nextUntil(parser, END_ARRAY)) {
          elementType = compatibleType(elementType, inferField(parser))
        }

        ArrayType(elementType)

      case VALUE_NUMBER_INT | VALUE_NUMBER_FLOAT =>
        import JsonParser.NumberType._
        parser.getNumberType match {
          // For Integer values, use LongType by default.
            //对于Integer值,默认情况下使用LongType
          case INT | LONG => LongType
          // Since we do not have a data type backed by BigInteger,
          // when we see a Java BigInteger, we use DecimalType.
            //由于我们没有BigInteger支持的数据类型,
          //因此当我们看到Java BigInteger时,我们使用DecimalType。
          case BIG_INTEGER | BIG_DECIMAL =>
            val v = parser.getDecimalValue
            DecimalType(v.precision(), v.scale())
          case FLOAT | DOUBLE =>
            // TODO(davies): Should we use decimal if possible?
            DoubleType
        }

      case VALUE_TRUE | VALUE_FALSE => BooleanType
    }
  }

  /**
   * Convert NullType to StringType and remove StructTypes with no fields
    * 将NullType转换为StringType并删除没有字段的StructType
   */
  private def canonicalizeType: DataType => Option[DataType] = {
    case at @ ArrayType(elementType, _) =>
      for {
        canonicalType <- canonicalizeType(elementType)
      } yield {
        at.copy(canonicalType)
      }

    case StructType(fields) =>
      val canonicalFields = for {
        field <- fields
        if field.name.nonEmpty
        canonicalType <- canonicalizeType(field.dataType)
      } yield {
        field.copy(dataType = canonicalType)
      }

      if (canonicalFields.nonEmpty) {
        Some(StructType(canonicalFields))
      } else {
        // per SPARK-8093: empty structs should be deleted
        None
      }

    case NullType => Some(StringType)
    case other => Some(other)
  }

  /**
   * Remove top-level ArrayType wrappers and merge the remaining schemas
    * 删除顶级ArrayType包装器并合并剩余的模式
   */
  private def compatibleRootType: (DataType, DataType) => DataType = {
    case (ArrayType(ty1, _), ty2) => compatibleRootType(ty1, ty2)
    case (ty1, ArrayType(ty2, _)) => compatibleRootType(ty1, ty2)
    case (ty1, ty2) => compatibleType(ty1, ty2)
  }

  /**
   * Returns the most general data type for two given data types.
   * 返回两个给定的数据类型最常用的数据类型
   */
  private[json] def compatibleType(t1: DataType, t2: DataType): DataType = {
    HiveTypeCoercion.findTightestCommonTypeOfTwo(t1, t2).getOrElse {
      // t1 or t2 is a StructType, ArrayType, or an unexpected type.
      //t1或t2是StructType,ArrayType或意常类型。
      (t1, t2) match {
        // Double support larger range than fixed decimal, DecimalType.Maximum should be enough
        // in most case, also have better precision.
          //Double支持比固定小数范围更大的范围,DecimalType.Maximum在大多数情况下应该足够,也有更好的精度
        case (DoubleType, t: DecimalType) =>
          DoubleType
        case (t: DecimalType, DoubleType) =>
          DoubleType
        case (t1: DecimalType, t2: DecimalType) =>
          val scale = math.max(t1.scale, t2.scale)
          val range = math.max(t1.precision - t1.scale, t2.precision - t2.scale)
          if (range + scale > 38) {
            // DecimalType can't support precision > 38
            DoubleType
          } else {
            DecimalType(range + scale, scale)
          }

        case (StructType(fields1), StructType(fields2)) =>
          val newFields = (fields1 ++ fields2).groupBy(field => field.name).map {
            case (name, fieldTypes) =>
              val dataType = fieldTypes.view.map(_.dataType).reduce(compatibleType)
              StructField(name, dataType, nullable = true)
          }
          StructType(newFields.toSeq.sortBy(_.name))

        case (ArrayType(elementType1, containsNull1), ArrayType(elementType2, containsNull2)) =>
          ArrayType(compatibleType(elementType1, elementType2), containsNull1 || containsNull2)

        // strings and every string is a Json object.
          //字符串和每个字符串都是Json对象
        case (_, _) => StringType
      }
    }
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Fill a nested logical list with TRUEs before or after the first TRUE — boolean_fill • stagerunner</title>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

<link href="../pkgdown.css" rel="stylesheet">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">

      </button>
      stagerunner

  Reference

  News

Fill a nested logical list with TRUEs before or after the first TRUE

This is a helper function to implement the to parameter
in the run method on a stageRunner object.

boolean_fill(el, forward = TRUE)

 Arguments

    <colgroup><col class="name" /><col class="desc" /></colgroup>

      el

list. A nested list of logicals with exactly one entry TRUE.

      forward

logical. FALSE for backwards, and TRUE for forwards.
The default is TRUE.

Value

the filled list

See also

run

Contents

Arguments

Value

See also

Developed by Robert Krzyzanowski.

Site built with pkgdown.


text:
/* global Screen, Client */
(function () {
  'use strict';

  var client;

  document.getElementById('disconnect-btn').addEventListener('click', function () {
    client.disconnect();
    document.getElementById('screen-wrapper').style.display = 'none';
    document.getElementById('form-wrapper').style.display = 'block';
  });

  document.getElementById('login-btn').addEventListener('click', function () {
    var canvas = document.getElementById('screen');
    var screen = new Screen(canvas);
    client = new Client(screen);
    client.connect2({
      host: document.getElementById('host').value,
      port: parseInt(document.getElementById('port').value, 10),
      password: document.getElementById('password').value
    }).then(function () {
      document.getElementById('form-wrapper').style.display = 'none';
      document.getElementById('screen-wrapper').style.display = 'block';
    });
  }, false);

}());


text:
require 'spec_helper'

describe Rmeter::Server do
  describe "/" do
    it "should glob all the JMeter data files" do
      Dir.should_receive(:[]).with( File.join(app.data, '*') ).and_return([])
      get '/'
    end

    it "should parse each of the data files" do
      files = [ '/foo/file_1.jml', '/foo/file_2.jml' ]
      Dir.stub!(:[]).and_return( files )

      parser_mocks = files.collect do |f|
        mock_parser = mock(Rmeter::Parser)
        mock_parser.should_receive(:parse).and_return({})
        Rmeter::Parser.should_receive(:new).with(f).and_return( mock_parser )
      end

      get '/'
    end
  end
end


text:
import json
import sqlite3 as lite
from . import sqlcommon as sqlc
from . import common as co

class MakeArtistSoup():
	def __init__(self):
		SQLC = sqlc.SqlCommon()
		self.SQLC = SQLC

	def _get_albums(self, artlist, dbpath):
		artistalbumlist = []
		for aa in artlist:
			z = {}
			alblist = self.SQLC._get_albums_for_artist(dbpath, aa)
			albums = list(set(alblist))
			count = 0
			formatedlist = []
			for alb in albums:
				count += 1
				c = "album" + str(count)
				z[alb] = ''
				formatted = "<legend>
%s
</legend>" %alb
				formatedlist.append(formatted)
			z['formatedalb'] = formatedlist
			z['artist'] = aa
			z['albums'] = albums
			z['albcount'] = len(albums)
			artistalbumlist.append(z)
		return artistalbumlist

	def _format_songs(self, a_alb, a_songslist):
		one = "
"
		two = "
%s
" %a_alb
		bb = one + two
		songs = bb
		for sl in a_songslist:
			c = str(sl[0])
			one = "
" %c
			two = "
%s
" %sl[1]
			four = "
"
			dd = one + two + three + four
			songs = songs + dd
		songs = songs + "
"
		return songs

	def _get_album_songs(self, artlist, dbpath, an_path, alpha):
		albs = self._get_albums(artlist, dbpath)
		crash = []
		for a in albs:
			k = {}
			albums = a['albums']
			albu = ""
			for alb in albums:
				songslist = self.SQLC._get_song_songid_for_album(dbpath, alb)
				con = lite.connect(dbpath['ampyche'])
				cur = con.cursor()
				cur.execute("SELECT fileid, song FROM ampyche WHERE album=?", [alb])
				songslist = cur.fetchall()
				con.close()
				s = self._format_songs(alb, songslist)
				a[alb] = s
				albu = albu + a[alb]
			albu = albu + "
"
			artist = a['artist']
			k['artist'] = artist
			k['albums'] = albums
			k['songs'] = albu
			crash.append(k)
		artjsonpath = an_path + "/artistSoup" + alpha + ".json"
		with open(artjsonpath, 'w') as artist:
			artist.write(json.dumps(crash, sort_keys=True, indent=4))


text:
function get_genome()
{
	source `find $gitDir -name paths.sh`
	local organism=$1
	local ref=unknown
	if [ "$organim" == "9606" -o "$organism" == "human" ]; then
		#human genome
		ref=$humanRef
	fi
	echo $ref
}

function get_gtf()
{
	source `find $gitDir -name paths.sh`
	local organism=$1
	local ref=unknown
	if [ "$organism" == "9606" -o "$organism" == "human" ]; then
		#human genome
		ref=$humanGtf
	fi
	echo $ref
}

function get_gio()
{
	local organism=$1
	local ref=`get_genome $organism`
	local fn_gio=`dirname $ref`/genome.config
	if [ ! -f $fn_gio ]; then
		echo $make_gio $ref `dirname $ref` 1>&2
		$make_gio $ref `dirname $ref` 1>&2
	fi
	if [ ! -f $fn_gio ]; then
		echo Error: failed to compute the genome information object in $fn_gio
		exit 1;
	fi
	echo $fn_gio
}


text:
package com.zhigu.mapper;

import org.apache.ibatis.annotations.Param;

import com.zhigu.model.UserAuth;
import com.zhigu.model.UserInfo;

/**
 * 会员数据访问
 *
 * @author ZhouQiBing
 * @date 2014年7月20日
 * @Description:
 */
public interface UserMapper {
	/**
	 * ip注册数统计
	 *
	 * @param ip
	 * @param startTime
	 * @return
	 */
	public int countUserAuthByIp(@Param("ip") String ip, @Param("startTime") String startTime);

	/**
	 * 电话查询认证信息
	 *
	 * @param phone
	 * @return
	 */
	public UserAuth queryUserAuthByPhone(String phone);

	/**
	 * Email查询认证信息
	 *
	 * @param email
	 * @return
	 */
	public UserAuth queryUserAuthByEmail(String email);

	/**
	 * 用户名查询认证信息
	 *
	 * @param username
	 * @return
	 */
	public UserAuth queryUserAuthByUsername(String username);

	/**
	 * 保存用户的认证信息
	 *
	 * @param auth
	 * @return
	 */
	public int saveUserAuth(UserAuth auth);

	/**
	 * 保存用户信息
	 *
	 * @param info
	 */
	public void saveUserInfo(UserInfo info);

	/**
	 * 查询用户认证信息
	 *
	 * @param userID
	 * @return
	 */
	public UserAuth queryUserAuthByUserID(int userID);

	/**
	 * 查询用户基本信息
	 *
	 * @param userID
	 * @return
	 */
	public UserInfo queryUserInfoById(int userID);

	/**
	 * 修改手机号
	 *
	 * @param userID
	 * @param phone
	 */
	public void updateUserInfoPhone(@Param("userID") int userID, @Param("phone") String phone);

	/**
	 * 修改手机号
	 *
	 * @param userID
	 * @param phone
	 */
	public void updateUserAuthPhone(@Param("userID") int userID, @Param("phone") String phone);

	/**
	 * 修改用户认证邮箱
	 *
	 * @param userID
	 * @param email
	 */
	public void updateUserAuthEmail(@Param("userID") int userID, @Param("email") String email);

	/**
	 * 修改用户信息邮箱
	 *
	 * @param userID
	 * @param email
	 */
	public void updateUserInfoEmail(@Param("userID") int userID, @Param("email") String email);

	/**
	 * 修改userInfo的实名认证Flg
	 *
	 * @param userID
	 * @param realUserFlg
	 * @return
	 */
	public int updateUserInfoRealUserFlg(@Param("userID") int userID, @Param("realUserFlg") int realUserFlg);

	/**
	 * 修改用户名
	 *
	 * @param userID
	 * @param username
	 */
	public void updateUsername(@Param("userID") int userID, @Param("username") String username);

	/**
	 * 修改登录密码
	 *
	 * @param userID
	 * @param pwd
	 */
	public int updateLoginPwd(@Param("userID") int userID, @Param("pwd") String pwd, @Param("salt") String salt);

	/**
	 * 修改用户基本信息
	 *
	 * @param info
	 */
	public void updateUserInfo(UserInfo info);

	/**
	 * 修改头像
	 *
	 * @param path
	 * @param userID
	 */
	public void updateAvatar(@Param("path") String path, @Param("userID") int userID);

	/**
	 * 修改用户类型
	 *
	 * @param userID
	 * @param userType
	 */
	public int updateUserType(@Param("userID") int userID, @Param("userType") int userType);

	/**
	 * 更新userauth的用户登录记录(最后登录时间,登录count)
	 *
	 * @param userID
	 */
	public void updateUserauthInfoLoginData(int userID);

}


text:
package com.example.powerincode.popularmovies.common.views;

import android.content.Context;
import android.graphics.Matrix;
import android.util.AttributeSet;

public class ImageViewPoster extends android.support.v7.widget.AppCompatImageView {
    public void setOffsetX(int offsetX) {
        this.offsetX = offsetX;
    }

    public void setOffsetY(int offsetY) {
        this.offsetY = offsetY;
    }

    private int offsetX;
    private int offsetY;

    public ImageViewPoster(Context context) {
        super(context);
    }

    public ImageViewPoster(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageViewPoster(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected boolean setFrame(int l, int t, int r, int b) {
        setMatrix();
        return super.setFrame(l, t, r, b);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        setMatrix();
    }

    private void setup() {
        setScaleType(ScaleType.MATRIX);
    }

    private void setMatrix() {
        if (getDrawable() == null) {
            return;
        }

        if (getScaleType() == ScaleType.MATRIX) {
            Matrix matrix = getImageMatrix();
            float scaleFactor = getWidth() / (float) getDrawable().getIntrinsicWidth();
            matrix.setScale(scaleFactor, scaleFactor, offsetX, offsetY);
            setImageMatrix(matrix);
        }
    }
}


text:
package org.trifort.rootbeer.testcases.rootbeertest.exception;

public class NullPointer2Object {

  public int m_Value;
}


text:
package kodkod.test.unit;

import static kodkod.ast.IntExpression.compose;
import static kodkod.ast.operator.IntOperator.DIVIDE;
import static kodkod.ast.operator.IntOperator.MINUS;
import static kodkod.ast.operator.IntOperator.MODULO;
import static kodkod.ast.operator.IntOperator.MULTIPLY;
import static kodkod.ast.operator.IntOperator.PLUS;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.junit.Test;

import junit.framework.TestCase;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IntConstant;
import kodkod.ast.IntExpression;
import kodkod.ast.Relation;
import kodkod.ast.operator.IntOperator;
import kodkod.engine.Evaluator;
import kodkod.engine.Solution;
import kodkod.engine.Solver;
import kodkod.engine.config.Options;
import kodkod.engine.satlab.SATFactory;
import kodkod.instance.Bounds;
import kodkod.instance.Instance;
import kodkod.instance.TupleFactory;
import kodkod.instance.Universe;

public class OverflowNumTest extends TestCase {

    protected final TupleFactory factory;
    protected final Relation     ret;
    protected Bounds             bounds;
    protected Options            options;

    private static final int     DEF_VAL = -1;

    @SuppressWarnings("serial" )
    public class NoSol extends RuntimeException {}

    public abstract class Tester {

        public abstract void doTest(int i, int j);
    }

    public abstract class GenericTester extends Tester {

        public void doTmpTest() {
            int bw = 5, l = -(1 << (bw - 1)), h = (1 << (bw - 1));
            IntOperator[] ops = new IntOperator[] {
                                                   PLUS, MINUS, MULTIPLY, DIVIDE, MODULO
            };
            for (IntOperator op : ops)
                for (int i = l; i < h; i++)
                    for (int j = l; j < h; j++) {
                        Formula f = ret.eq(compose(op, IntConstant.constant(i), IntConstant.constant(j)).toExpression());
                        int javaResult = -1;
                        try {
                            javaResult = exeJava(op, i, j);
                        } catch (ArithmeticException e) {
                            continue;
                        }
                        if (javaResult >= h || javaResult < l) {
                            try {
                                int kkResult = exeKodkod(f);
                                fail(String.format("Overflow not detected: (%s) %s (%s) != %s", i, op, j, kkResult));
                            } catch (NoSol e) {}
                        } else {
                            try {
                                int kkResult = exeKodkod(f);
                                assertEquals(String.format("Wrong result: (%s) %s (%s) != %s", i, op, j, kkResult), javaResult, kkResult);
                            } catch (NoSol e) {
                                fail(String.format("No solution for (%s) %s (%s); expected: %s", i, op, j, javaResult));
                            }
                        }
                    }
        }

        private int exeKodkod(Formula f) {
            Solution sol = solve(f);
            return eval(sol.instance());
        }

        private int exeJava(IntOperator op, int i, int j) {
            switch (op) {
                case PLUS :
                    return i + j;
                case MINUS :
                    return i - j;
                case MULTIPLY :
                    return i * j;
                case DIVIDE :
                    return i / j;
                case MODULO :
                    return i % j;
                default :
                    throw new RuntimeException("unknown op: " + op);
            }
        }

        // ===================================

        @Override
        public void doTest(int i, int j) {
            doTestNoDef(i, j);
            doTestDef(i, j);
        }

        protected void doTestDef(int i, int j) {
            int min = min();
            int max = max();
            String op = getOp();
            int res;
            boolean of = false;
            try {
                res = exeJava(i, j);
                if (res > max || res < min) {
                    of = true;
                    res = DEF_VAL;
                }
            } catch (Exception e) {
                of = true;
                res = DEF_VAL;
            }
            try {
                int x = exeKodkodDef(i, j);
                String msg = of ? String.format("Expected the default value (%d) due to overflow ((%d) %s (%d)) but got %d", DEF_VAL, i, op, j, x) : String.format("Wrong result: %s %s %s != %s", i, op, j, x);
                assertEquals(msg, res, x);
            } catch (NoSol e) {
                String msg = String.format("Expected the default value (%d) due to overflow (%d %s %d) but got exception: %s", DEF_VAL, i, op, j, e.getClass().getSimpleName() + ": " + e.getMessage());
                fail(msg);
            }
        }

        protected void doTestNoDef(int i, int j) {
            if (skip(i, j))
                return;
            int min = min();
            int max = max();
            String op = getOp();
            int res = exeJava(i, j);
            if (res > max || res < min) {
                try {
                    int x = exeKodkod(i, j);
                    fail(String.format("Overflow not detected: (%s) %s (%s) != %s", i, op, j, x));
                } catch (NoSol e) {}
            } else {
                try {
                    int x = exeKodkod(i, j);
                    assertEquals(String.format("Wrong result: (%s) %s (%s) != %s", i, op, j, x), res, x);
                } catch (NoSol e) {
                    fail(String.format("No solution for (%s) %s (%s); expected: %s", i, op, j, res));
                }
            }
        }

        protected int eval(Instance instance) {
            if (instance == null)
                throw new NoSol();
            Evaluator ev = new Evaluator(instance);
            return Integer.parseInt(ev.evaluate(ret).iterator().next().atom(0).toString());
        }

        protected int exeKodkod(int i, int j) {
            Formula f = ret.eq(kodkodOpExpr(IntConstant.constant(i), IntConstant.constant(j)).toExpression());
            Solution sol = solve(f);
            return eval(sol.instance());
        }

        protected int exeKodkodDef(int i, int j) {
            IntExpression kkIntExpr = kodkodOpExpr(IntConstant.constant(i), IntConstant.constant(j));
            Expression kkExpr = kkIntExpr.toExpression();
            Formula f = ret.eq(kkExpr.some().thenElse(kkIntExpr.toExpression(), IntConstant.constant(DEF_VAL).toExpression()));
            Solution sol = solve(f);
            return eval(sol.instance());
        }

        protected abstract int exeJava(int i, int j);

        protected abstract IntExpression kodkodOpExpr(IntExpression i, IntExpression j);

        protected abstract String getOp();

        protected boolean skip(int i, int j) {
            return false;
        }
    }

    public OverflowNumTest() {
        this.ret = Relation.unary("ret");
        int min = min();
        int max = max();
        List<String> atoms = new ArrayList<String>(max - min + 1);
        for (int i = min; i <= max; i++) {
            atoms.add(String.valueOf(i));
        }
        final Universe universe = new Universe(atoms);
        this.factory = universe.factory();
        this.bounds = new Bounds(factory.universe());
        for (int i = min; i <= max; i++) {
            bounds.boundExactly(i, factory.setOf(String.valueOf(i)));
        }
        bounds.bound(ret, factory.noneOf(1), factory.allOf(1));
    }

    protected int bw() {
        return 5;
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        setupOptions();
    }

    protected void setupOptions() {
        options = new Options();
        options.setNoOverflow(true);
        options.setBitwidth(bw());
        options.setSolver(SATFactory.MiniSat);
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
    }

    protected Solution solve(Formula formula) {
        return new Solver(options).solve(formula, bounds);
    }

    protected Iterator<Solution> solveAll(Formula formula) {
        return new Solver(options).solveAll(formula, bounds);
    }

    @Test
    public void testPlus() {
        runTestForAll(new GenericTester() {

            @Override
            protected int exeJava(int i, int j) {
                return i + j;
            }

            @Override
            protected IntExpression kodkodOpExpr(IntExpression i, IntExpression j) {
                return i.plus(j);
            }

            @Override
            protected String getOp() {
                return "+";
            }
        });
    }

    @Test
    public void testMinus() {
        runTestForAll(new GenericTester() {

            @Override
            protected int exeJava(int i, int j) {
                return i - j;
            }

            @Override
            protected IntExpression kodkodOpExpr(IntExpression i, IntExpression j) {
                return i.minus(j);
            }

            @Override
            protected String getOp() {
                return "-";
            }
        });
    }

    @Test
    public void testTimes() {
        runTestForAll(new GenericTester() {

            @Override
            protected int exeJava(int i, int j) {
                return i * j;
            }

            @Override
            protected IntExpression kodkodOpExpr(IntExpression i, IntExpression j) {
                return i.multiply(j);
            }

            @Override
            protected String getOp() {
                return "*";
            }
        });
    }

    @Test
    public void testDiv() {
        runTestForAll(new GenericTester() {

            @Override
            protected int exeJava(int i, int j) {
                return i / j;
            }

            @Override
            protected IntExpression kodkodOpExpr(IntExpression i, IntExpression j) {
                return i.divide(j);
            }

            @Override
            protected String getOp() {
                return "/";
            }

            @Override
            protected boolean skip(int i, int j) {
                return j == 0;
            }
        });
    }

    @Test
    public void testMod() {
        runTestForAll(new GenericTester() {

            @Override
            protected int exeJava(int i, int j) {
                return i % j;
            }

            @Override
            protected IntExpression kodkodOpExpr(IntExpression i, IntExpression j) {
                return i.modulo(j);
            }

            @Override
            protected String getOp() {
                return "%";
            }

            @Override
            protected boolean skip(int i, int j) {
                return j == 0;
            }
        });
    }

    @Test
    public void testTmp() {
        new GenericTester() {

            @Override
            protected IntExpression kodkodOpExpr(IntExpression i, IntExpression j) {
                return null;
            }

            @Override
            protected String getOp() {
                return null;
            }

            @Override
            protected int exeJava(int i, int j) {
                return 0;
            }
        }.doTmpTest();
    }

    protected void runTestForAll(Tester t) {
        int min = min();
        int max = max();
        for (int i = min; i <= max; i++) {
            for (int j = min; j <= max; j++) {
                t.doTest(i, j);
            }
        }
    }

    protected int min() {
        return -(1 << (bw() - 1));
    }

    protected int max() {
        return (1 << (bw() - 1)) - 1;
    }

}


text:
namespace browser_sync {

namespace {

// Maximum number of sessions we're going to display on the NTP
const size_t kMaxSessionsToShow = 10;

// Converts the DeviceType enum value to a string. This is used
// in the NTP handler for foreign sessions for matching session
// types to an icon style.
std::string DeviceTypeToString(sync_pb::SyncEnums::DeviceType device_type) {
  switch (device_type) {
    case sync_pb::SyncEnums::TYPE_UNSET:
      break;
    case sync_pb::SyncEnums::TYPE_WIN:
      return "win";
    case sync_pb::SyncEnums::TYPE_MAC:
      return "macosx";
    case sync_pb::SyncEnums::TYPE_LINUX:
      return "linux";
    case sync_pb::SyncEnums::TYPE_CROS:
      return "chromeos";
    case sync_pb::SyncEnums::TYPE_OTHER:
      return "other";
    case sync_pb::SyncEnums::TYPE_PHONE:
      return "phone";
    case sync_pb::SyncEnums::TYPE_TABLET:
      return "tablet";
  }
  return std::string();
}

// Helper method to create JSON compatible objects from Session objects.
base::Value SessionTabToValue(const ::sessions::SessionTab& tab) {
  if (tab.navigations.empty())
    return base::Value();

  int selected_index = std::min(tab.current_navigation_index,
                                static_cast<int>(tab.navigations.size() - 1));
  const ::sessions::SerializedNavigationEntry& current_navigation =
      tab.navigations.at(selected_index);
  GURL tab_url = current_navigation.virtual_url();
  if (!tab_url.is_valid() || tab_url.spec() == chrome::kChromeUINewTabURL)
    return base::Value();

  base::Value dictionary(base::Value::Type::DICTIONARY);
  NewTabUI::SetUrlTitleAndDirection(&dictionary, current_navigation.title(),
                                    tab_url);
  dictionary.SetStringKey("remoteIconUrlForUma",
                          current_navigation.favicon_url().spec());
  dictionary.SetStringKey("type", "tab");
  dictionary.SetDoubleKey("timestamp",
                          static_cast<double>(tab.timestamp.ToInternalValue()));
  // TODO(jeremycho): This should probably be renamed to tabId to avoid
  // confusion with the ID corresponding to a session.  Investigate all the
  // places (C++ and JS) where this is being used.  (http://crbug.com/154865).
  dictionary.SetIntKey("sessionId", tab.tab_id.id());
  return dictionary;
}

// Helper for initializing a boilerplate SessionWindow JSON compatible object.
base::Value BuildWindowData(base::Time modification_time, SessionID window_id) {
  base::Value dictionary(base::Value::Type::DICTIONARY);
  // The items which are to be written into |dictionary| are also described in
  // chrome/browser/resources/ntp4/other_sessions.js in @typedef for WindowData.
  // Please update it whenever you add or remove any keys here.
  dictionary.SetStringKey("type", "window");
  dictionary.SetDoubleKey("timestamp", modification_time.ToInternalValue());

  dictionary.SetIntKey("sessionId", window_id.id());
  return dictionary;
}

// Helper method to create JSON compatible objects from SessionWindow objects.
base::Value SessionWindowToValue(const ::sessions::SessionWindow& window) {
  if (window.tabs.empty())
    return base::Value();

  base::Value tab_values(base::Value::Type::LIST);
  // Calculate the last |modification_time| for all entries within a window.
  base::Time modification_time = window.timestamp;
  for (const std::unique_ptr<sessions::SessionTab>& tab : window.tabs) {
    base::Value tab_value = SessionTabToValue(*tab.get());
    if (!tab_value.is_none()) {
      modification_time = std::max(modification_time, tab->timestamp);
      tab_values.Append(std::move(tab_value));
    }
  }
  if (tab_values.GetList().empty())
    return base::Value();

  base::Value dictionary = BuildWindowData(window.timestamp, window.window_id);
  dictionary.SetKey("tabs", std::move(tab_values));
  return dictionary;
}

}  // namespace

ForeignSessionHandler::ForeignSessionHandler() = default;

ForeignSessionHandler::~ForeignSessionHandler() = default;

// static
void ForeignSessionHandler::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterDictionaryPref(prefs::kNtpCollapsedForeignSessions);
}

// static
void ForeignSessionHandler::OpenForeignSessionTab(
    content::WebUI* web_ui,
    const std::string& session_string_value,
    int window_num,
    SessionID tab_id,
    const WindowOpenDisposition& disposition) {
  sync_sessions::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(web_ui);
  if (!open_tabs)
    return;

  // We don't actually care about |window_num|, this is just a sanity check.
  DCHECK_LE(0, window_num);
  const ::sessions::SessionTab* tab;
  if (!open_tabs->GetForeignTab(session_string_value, tab_id, &tab)) {
    LOG(ERROR) << "Failed to load foreign tab.";
    return;
  }
  if (tab->navigations.empty()) {
    LOG(ERROR) << "Foreign tab no longer has valid navigations.";
    return;
  }
  SessionRestore::RestoreForeignSessionTab(web_ui->GetWebContents(), *tab,
                                           disposition);
}

// static
void ForeignSessionHandler::OpenForeignSessionWindows(
    content::WebUI* web_ui,
    const std::string& session_string_value,
    int window_num) {
  sync_sessions::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(web_ui);
  if (!open_tabs)
    return;

  std::vector<const ::sessions::SessionWindow*> windows;
  // Note: we don't own the ForeignSessions themselves.
  if (!open_tabs->GetForeignSession(session_string_value, &windows)) {
    LOG(ERROR) << "ForeignSessionHandler failed to get session data from"
                  "OpenTabsUIDelegate.";
    return;
  }
  std::vector<const ::sessions::SessionWindow*>::const_iterator iter_begin =
      windows.begin() + (window_num < 0 ? 0 : window_num);
  auto iter_end =
      window_num < 0
          ? std::vector<const ::sessions::SessionWindow*>::const_iterator(
                windows.end())
          : iter_begin + 1;

  SessionRestore::RestoreForeignSessionWindows(Profile::FromWebUI(web_ui),
                                               iter_begin, iter_end);

  size_t total_tabs_opened = 0;
  for (const ::sessions::SessionWindow* window : windows) {
    UMA_HISTOGRAM_COUNTS_1000(
        "HistoryPage.OtherDevicesMenu.OpenAll.TabsPerWindow",
        window->tabs.size());
    total_tabs_opened += window->tabs.size();
  }
  UMA_HISTOGRAM_COUNTS_1000("HistoryPage.OtherDevicesMenu.OpenAll.TotalTabs",
                            total_tabs_opened);
  UMA_HISTOGRAM_COUNTS_100("HistoryPage.OtherDevicesMenu.OpenAll.TotalWindows",
                           windows.size());
}

// static
sync_sessions::OpenTabsUIDelegate* ForeignSessionHandler::GetOpenTabsUIDelegate(
    content::WebUI* web_ui) {
  Profile* profile = Profile::FromWebUI(web_ui);
  sync_sessions::SessionSyncService* service =
      SessionSyncServiceFactory::GetInstance()->GetForProfile(profile);
  return service ? service->GetOpenTabsUIDelegate() : nullptr;
}

void ForeignSessionHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "deleteForeignSession",
      base::BindRepeating(&ForeignSessionHandler::HandleDeleteForeignSession,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "getForeignSessions",
      base::BindRepeating(&ForeignSessionHandler::HandleGetForeignSessions,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "openForeignSession",
      base::BindRepeating(&ForeignSessionHandler::HandleOpenForeignSession,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "setForeignSessionCollapsed",
      base::BindRepeating(
          &ForeignSessionHandler::HandleSetForeignSessionCollapsed,
          base::Unretained(this)));
}

void ForeignSessionHandler::OnJavascriptAllowed() {
  // This can happen if the page is refreshed.
  if (initial_session_list_.is_none())
    initial_session_list_ = GetForeignSessions();

  Profile* profile = Profile::FromWebUI(web_ui());

  sync_sessions::SessionSyncService* service =
      SessionSyncServiceFactory::GetInstance()->GetForProfile(profile);

  // NOTE: The SessionSyncService can be null in tests.
  if (service) {
    // base::Unretained() is safe below because the subscription itself is a
    // class member field and handles destruction well.
    foreign_session_updated_subscription_ =
        service->SubscribeToForeignSessionsChanged(
            base::BindRepeating(&ForeignSessionHandler::OnForeignSessionUpdated,
                                base::Unretained(this)));
  }
}

void ForeignSessionHandler::OnForeignSessionUpdated() {
  FireWebUIListener("foreign-sessions-changed",
                    std::move(GetForeignSessions()));
}

void ForeignSessionHandler::InitializeForeignSessions() {
  initial_session_list_ = GetForeignSessions();
}

base::string16 ForeignSessionHandler::FormatSessionTime(
    const base::Time& time) {
  // Return a time like "1 hour ago", "2 days ago", etc.
  base::Time now = base::Time::Now();
  // TimeFormat does not support negative TimeDelta values, so then we use 0.
  return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
                                ui::TimeFormat::LENGTH_SHORT,
                                now < time ? base::TimeDelta() : now - time);
}

void ForeignSessionHandler::HandleGetForeignSessions(
    const base::ListValue* args) {
  AllowJavascript();
  CHECK(!initial_session_list_.is_none());
  const base::Value& callback_id = args->GetList()[0];
  ResolveJavascriptCallback(callback_id, std::move(initial_session_list_));

  // Clear the initial list so that it will be reset in AllowJavascript if the
  // page is refreshed.
  initial_session_list_ = base::Value(base::Value::Type::NONE);
}

base::Value ForeignSessionHandler::GetForeignSessions() {
  sync_sessions::OpenTabsUIDelegate* open_tabs =
      GetOpenTabsUIDelegate(web_ui());
  std::vector<const sync_sessions::SyncedSession*> sessions;

  base::Value session_list(base::Value::Type::LIST);
  if (open_tabs && open_tabs->GetAllForeignSessions(&sessions)) {
    // Use a pref to keep track of sessions that were collapsed by the user.
    // To prevent the pref from accumulating stale sessions, clear it each time
    // and only add back sessions that are still current.
    DictionaryPrefUpdate pref_update(Profile::FromWebUI(web_ui())->GetPrefs(),
                                     prefs::kNtpCollapsedForeignSessions);
    base::DictionaryValue* current_collapsed_sessions = pref_update.Get();
    std::unique_ptr<base::DictionaryValue> collapsed_sessions(
        current_collapsed_sessions->DeepCopy());
    current_collapsed_sessions->Clear();

    // Note: we don't own the SyncedSessions themselves.
    for (size_t i = 0; i < sessions.size() && i < kMaxSessionsToShow; ++i) {
      const sync_sessions::SyncedSession* session = sessions[i];
      const std::string& session_tag = session->session_tag;
      base::Value session_data(base::Value::Type::DICTIONARY);
      // The items which are to be written into |session_data| are also
      // described in chrome/browser/resources/history/externs.js
      // @typedef for ForeignSession. Please update it whenever you add or
      // remove any keys here.
      session_data.SetStringKey("tag", session_tag);
      session_data.SetStringKey("name", session->session_name);
      session_data.SetStringKey("deviceType",
                                DeviceTypeToString(session->device_type));
      session_data.SetStringKey("modifiedTime",
                                FormatSessionTime(session->modified_time));
      session_data.SetDoubleKey("timestamp", session->modified_time.ToJsTime());

      bool is_collapsed = collapsed_sessions->HasKey(session_tag);
      session_data.SetBoolKey("collapsed", is_collapsed);
      if (is_collapsed)
        current_collapsed_sessions->SetBoolean(session_tag, true);

      base::Value window_list(base::Value::Type::LIST);

      // Order tabs by visual order within window.
      for (const auto& window_pair : session->windows) {
        base::Value window_data =
            SessionWindowToValue(window_pair.second->wrapped_window);
        if (!window_data.is_none()) {
          window_list.Append(std::move(window_data));
        }
      }

      session_data.SetKey("windows", std::move(window_list));
      session_list.Append(std::move(session_data));
    }
  }
  return session_list;
}

void ForeignSessionHandler::HandleOpenForeignSession(
    const base::ListValue* args) {
  size_t num_args = args->GetSize();
  // Expect either 1 or 8 args. For restoring an entire session, only
  // one argument is required -- the session tag. To restore a tab,
  // the additional args required are the window id, the tab id,
  // and 4 properties of the event object (button, altKey, ctrlKey,
  // metaKey, shiftKey) for determining how to open the tab.
  if (num_args != 8U && num_args != 1U) {
    LOG(ERROR) << "openForeignSession called with " << args->GetSize()
               << " arguments.";
    return;
  }

  // Extract the session tag (always provided).
  std::string session_string_value;
  if (!args->GetString(0, &session_string_value)) {
    LOG(ERROR) << "Failed to extract session tag.";
    return;
  }

  // Extract window number.
  std::string window_num_str;
  int window_num = -1;
  if (num_args >= 2 && (!args->GetString(1, &window_num_str) ||
                        !base::StringToInt(window_num_str, &window_num))) {
    LOG(ERROR) << "Failed to extract window number.";
    return;
  }

  // Extract tab id.
  std::string tab_id_str;
  SessionID::id_type tab_id_value = 0;
  if (num_args >= 3 && (!args->GetString(2, &tab_id_str) ||
                        !base::StringToInt(tab_id_str, &tab_id_value))) {
    LOG(ERROR) << "Failed to extract tab SessionID.";
    return;
  }

  SessionID tab_id = SessionID::FromSerializedValue(tab_id_value);
  if (tab_id.is_valid()) {
    WindowOpenDisposition disposition = webui::GetDispositionFromClick(args, 3);
    OpenForeignSessionTab(web_ui(), session_string_value, window_num, tab_id,
                          disposition);
  } else {
    OpenForeignSessionWindows(web_ui(), session_string_value, window_num);
  }
}

void ForeignSessionHandler::HandleDeleteForeignSession(
    const base::ListValue* args) {
  if (args->GetSize() != 1U) {
    LOG(ERROR) << "Wrong number of args to deleteForeignSession";
    return;
  }

  // Get the session tag argument (required).
  std::string session_tag;
  if (!args->GetString(0, &session_tag)) {
    LOG(ERROR) << "Unable to extract session tag";
    return;
  }

  sync_sessions::OpenTabsUIDelegate* open_tabs =
      GetOpenTabsUIDelegate(web_ui());
  if (open_tabs)
    open_tabs->DeleteForeignSession(session_tag);
}

void ForeignSessionHandler::HandleSetForeignSessionCollapsed(
    const base::ListValue* args) {
  if (args->GetSize() != 2U) {
    LOG(ERROR) << "Wrong number of args to setForeignSessionCollapsed";
    return;
  }

  // Get the session tag argument (required).
  std::string session_tag;
  if (!args->GetString(0, &session_tag)) {
    LOG(ERROR) << "Unable to extract session tag";
    return;
  }

  bool is_collapsed;
  if (!args->GetBoolean(1, &is_collapsed)) {
    LOG(ERROR) << "Unable to extract boolean argument";
    return;
  }

  // Store session tags for collapsed sessions in a preference so that the
  // collapsed state persists.
  PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
  DictionaryPrefUpdate update(prefs, prefs::kNtpCollapsedForeignSessions);
  if (is_collapsed)
    update.Get()->SetBoolean(session_tag, true);
  else
    update.Get()->Remove(session_tag, nullptr);
}

}  // namespace browser_sync


text:
import fcntl
import os
import shutil
import tempfile
import threading

import eventlet
from eventlet import greenpool
from eventlet import greenthread
from eventlet import semaphore
from oslo.config import cfg

from openstack.common.fixture import config
from openstack.common import lockutils
from openstack.common import test

class TestFileLocks(test.BaseTestCase):

    def test_concurrent_green_lock_succeeds(self):
        """Verify spawn_n greenthreads with two locks run concurrently."""
        tmpdir = tempfile.mkdtemp()
        try:
            self.completed = False

            def locka(wait):
                a = lockutils.InterProcessLock(os.path.join(tmpdir, 'a'))
                with a:
                    wait.wait()
                self.completed = True

            def lockb(wait):
                b = lockutils.InterProcessLock(os.path.join(tmpdir, 'b'))
                with b:
                    wait.wait()

            wait1 = eventlet.event.Event()
            wait2 = eventlet.event.Event()
            pool = greenpool.GreenPool()
            pool.spawn_n(locka, wait1)
            pool.spawn_n(lockb, wait2)
            wait2.send()
            eventlet.sleep(0)
            wait1.send()
            pool.waitall()

            self.assertTrue(self.completed)

        finally:
            if os.path.exists(tmpdir):
                shutil.rmtree(tmpdir)

class LockTestCase(test.BaseTestCase):

    def setUp(self):
        super(LockTestCase, self).setUp()
        self.config = self.useFixture(config.Config()).config

    def test_synchronized_wrapped_function_metadata(self):
        @lockutils.synchronized('whatever', 'test-')
        def foo():
            """Bar"""
            pass

        self.assertEqual(foo.__doc__, 'Bar', "Wrapped function's docstring "
                                             "got lost")
        self.assertEqual(foo.__name__, 'foo', "Wrapped function's name "
                                              "got mangled")

    def test_lock_internally(self):
        """We can lock across multiple green threads."""
        saved_sem_num = len(lockutils._semaphores)
        seen_threads = list()

        def f(_id):
            with lockutils.lock('testlock2', 'test-', external=False):
                for x in range(10):
                    seen_threads.append(_id)
                    greenthread.sleep(0)

        threads = []
        pool = greenpool.GreenPool(10)
        for i in range(10):
            threads.append(pool.spawn(f, i))

        for thread in threads:
            thread.wait()

        self.assertEqual(len(seen_threads), 100)
        # Looking at the seen threads, split it into chunks of 10, and verify
        # that the last 9 match the first in each chunk.
        for i in range(10):
            for j in range(9):
                self.assertEqual(seen_threads[i * 10],
                                 seen_threads[i * 10 + 1 + j])

        self.assertEqual(saved_sem_num, len(lockutils._semaphores),
                         "Semaphore leak detected")

    def test_nested_synchronized_external_works(self):
        """We can nest external syncs."""
        tempdir = tempfile.mkdtemp()
        try:
            self.config(lock_path=tempdir)
            sentinel = object()

            @lockutils.synchronized('testlock1', 'test-', external=True)
            def outer_lock():

                @lockutils.synchronized('testlock2', 'test-', external=True)
                def inner_lock():
                    return sentinel
                return inner_lock()

            self.assertEqual(sentinel, outer_lock())

        finally:
            if os.path.exists(tempdir):
                shutil.rmtree(tempdir)

    def _do_test_lock_externally(self):
        """We can lock across multiple processes."""

        def lock_files(handles_dir):

            with lockutils.lock('external', 'test-', external=True):
                # Open some files we can use for locking
                handles = []
                for n in range(50):
                    path = os.path.join(handles_dir, ('file-%s' % n))
                    handles.append(open(path, 'w'))

                # Loop over all the handles and try locking the file
                # without blocking, keep a count of how many files we
                # were able to lock and then unlock. If the lock fails
                # we get an IOError and bail out with bad exit code
                count = 0
                for handle in handles:
                    try:
                        fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
                        count += 1
                        fcntl.flock(handle, fcntl.LOCK_UN)
                    except IOError:
                        os._exit(2)
                    finally:
                        handle.close()

                # Check if we were able to open all files
                self.assertEqual(50, count)

        handles_dir = tempfile.mkdtemp()
        try:
            children = []
            for n in range(50):
                pid = os.fork()
                if pid:
                    children.append(pid)
                else:
                    try:
                        lock_files(handles_dir)
                    finally:
                        os._exit(0)

            for i, child in enumerate(children):
                (pid, status) = os.waitpid(child, 0)
                if pid:
                    self.assertEqual(0, status)
        finally:
            if os.path.exists(handles_dir):
                shutil.rmtree(handles_dir, ignore_errors=True)

    def test_lock_externally(self):
        lock_dir = tempfile.mkdtemp()
        self.config(lock_path=lock_dir)

        try:
            self._do_test_lock_externally()
        finally:
            if os.path.exists(lock_dir):
                shutil.rmtree(lock_dir, ignore_errors=True)

    def test_lock_externally_lock_dir_not_exist(self):
        lock_dir = tempfile.mkdtemp()
        os.rmdir(lock_dir)
        self.config(lock_path=lock_dir)

        try:
            self._do_test_lock_externally()
        finally:
            if os.path.exists(lock_dir):
                shutil.rmtree(lock_dir, ignore_errors=True)

    def test_synchronized_with_prefix(self):
        lock_name = 'mylock'
        lock_pfix = 'mypfix-'

        foo = lockutils.synchronized_with_prefix(lock_pfix)

        @foo(lock_name, external=True)
        def bar(dirpath, pfix, name):
            filepath = os.path.join(dirpath, '%s%s' % (pfix, name))
            return os.path.isfile(filepath)

        lock_dir = tempfile.mkdtemp()
        self.config(lock_path=lock_dir)

        self.assertTrue(bar(lock_dir, lock_pfix, lock_name))

    def test_synchronized_without_prefix(self):
        lock_dir = tempfile.mkdtemp()

        @lockutils.synchronized('lock', external=True, lock_path=lock_dir)
        def test_without_prefix():
            path = os.path.join(lock_dir, "lock")
            self.assertTrue(os.path.exists(path))

        try:
            test_without_prefix()
        finally:
            if os.path.exists(lock_dir):
                shutil.rmtree(lock_dir, ignore_errors=True)

    def test_synchronized_prefix_without_hypen(self):
        lock_dir = tempfile.mkdtemp()

        @lockutils.synchronized('lock', 'hypen', True, lock_dir)
        def test_without_hypen():
            path = os.path.join(lock_dir, "hypen-lock")
            self.assertTrue(os.path.exists(path))

        try:
            test_without_hypen()
        finally:
            if os.path.exists(lock_dir):
                shutil.rmtree(lock_dir, ignore_errors=True)

    def test_contextlock(self):
        lock_dir = tempfile.mkdtemp()

        try:
            # Note(flaper87): Lock is not external, which means
            # a semaphore will be yielded
            with lockutils.lock("test") as sem:
                semaphores = (semaphore.Semaphore, threading._Semaphore)
                self.assertTrue(isinstance(sem, semaphores))

                # NOTE(flaper87): Lock is external so an InterProcessLock
                # will be yielded.
                with lockutils.lock("test2", external=True,
                                    lock_path=lock_dir):
                    path = os.path.join(lock_dir, "test2")
                    self.assertTrue(os.path.exists(path))

                with lockutils.lock("test1",
                                    external=True,
                                    lock_path=lock_dir) as lock1:
                    self.assertTrue(isinstance(lock1,
                                               lockutils.InterProcessLock))
        finally:
            if os.path.exists(lock_dir):
                shutil.rmtree(lock_dir, ignore_errors=True)

    def test_contextlock_unlocks(self):
        lock_dir = tempfile.mkdtemp()

        sem = None

        try:
            with lockutils.lock("test") as sem:
                semaphores = (semaphore.Semaphore, threading._Semaphore)
                self.assertTrue(isinstance(sem, semaphores))

                with lockutils.lock("test2", external=True,
                                    lock_path=lock_dir):
                    path = os.path.join(lock_dir, "test2")
                    self.assertTrue(os.path.exists(path))

                # NOTE(flaper87): Lock should be free
                with lockutils.lock("test2", external=True,
                                    lock_path=lock_dir):
                    path = os.path.join(lock_dir, "test2")
                    self.assertTrue(os.path.exists(path))

            # NOTE(flaper87): Lock should be free
            # but semaphore should already exist.
            with lockutils.lock("test") as sem2:
                self.assertEqual(sem, sem2)
        finally:
            if os.path.exists(lock_dir):
                shutil.rmtree(lock_dir, ignore_errors=True)

    def test_synchronized_externally_without_lock_path(self):
        self.config(lock_path=None)

        @lockutils.synchronized('external', 'test-', external=True)
        def foo():
            pass

        self.assertRaises(cfg.RequiredOptError, foo)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Dragablz;
using Slamby.TAU.View;

namespace Slamby.TAU.Helper
{
    public class InterTabClient : IInterTabClient
    {
        public INewTabHost<Window> GetNewHost(IInterTabClient interTabClient, object partition, TabablzControl source)
        {
            var view = new EmptyTabClient();
            return new NewTabHost<Window>(view, view.InitialTabablzControl);
        }

        public TabEmptiedResponse TabEmptiedHandler(TabablzControl tabControl, Window window)
        {
            return TabEmptiedResponse.CloseWindowOrLayoutBranch;
        }
    }
}


text:
package org.takes.rs;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.cactoos.Bytes;
import org.cactoos.Text;
import org.cactoos.io.BytesOf;
import org.cactoos.text.Joined;
import org.cactoos.text.TextOf;
import org.takes.Response;

/**
 * Response decorator that can print an entire response in HTTP format.
 *
 * <p>The class is immutable and thread-safe.
 *
 * @since 0.1
 * @todo #1054:30min Continue replacing guava in tests.
 *  Create new todos until guava is removed and Takes is much more Cactoos
 *  oriented as started with #804.
 */
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public final class RsPrint extends RsWrap implements Text, Bytes {

    /**
     * Head print representation.
     */
    private final HeadPrint head;

    /**
     * Body print representation.
     */
    private final BodyPrint body;

    /**
     * Ctor.
     * @param res Original response
     */
    public RsPrint(final Response res) {
        super(res);
        this.head = new HeadPrint(res);
        this.body = new BodyPrint(res);
    }

    @Override
    public String asString() throws IOException {
        return new Joined(
            new TextOf(""),
            this.head,
            this.body
        ).asString();
    }

    @Override
    public byte[] asBytes() throws Exception {
        return new BytesOf(
            this.asString(),
            StandardCharsets.UTF_8
        ).asBytes();
    }
}


text:
import _ from 'underscore';
import s from 'underscore.string';

RocketChat.checkUsernameAvailability = function(username) {
	return RocketChat.settings.get('Accounts_BlockedUsernameList', function(key, value) {
		const usernameBlackList = _.map(value.split(','), function(username) {
			return username.trim();
		});
		if (usernameBlackList.length !== 0) {
			if (usernameBlackList.every(restrictedUsername => {
				const regex = new RegExp(`^${ s.escapeRegExp(restrictedUsername) }$`, 'i');
				return !regex.test(s.trim(s.escapeRegExp(username)));
			})) {
				return !Meteor.users.findOne({
					username: {
						$regex: new RegExp(`^${ s.trim(s.escapeRegExp(username)) }$`, 'i')
					}
				});
			}
			return false;
		}
	});
};


text:
sub print_copyright
{
    *FILE   = $_[0];
    $prefix = $_[1];
    @copyright = (
        "",
        "",
        "Copyright 2010, 2020 IBM Corp. All rights reserved.",
        "",
        "Redistribution and use in source and binary forms, with or without",
        " modification, are permitted provided that the following conditions",
        "are met:",
        "1. Redistributions of source code must retain the above copyright",
        "   notice, this list of conditions and the following disclaimer.",
        "2. Redistributions in binary form must reproduce the above copyright",
        "   notice, this list of conditions and the following disclaimer in the",
        "documentation and/or other materials provided with the distribution.",
        "3. Neither the name of the copyright holder nor the names of its",
        "   contributors may be used to endorse or promote products derived from",
        "   this software without specific prior written permission.",
        "",
        "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''",
        "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
        "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
        "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE",
        "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR",
        "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF",
        "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS",
        "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN",
        "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)",
        "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
        "POSSIBILITY OF SUCH DAMAGE.",
        "",
        "",
        );

    foreach $line ( @copyright ) {
        $p = "$prefix$line";
        $p =~ s/\s+$//;
        print FILE "$p\n";
    }
}

if ($ARGV[0] =~ /replace_copyright.pl/) {
    exit 0
}

$org_file_name = "$ARGV[0].org";
$in_copyright = 0;

rename($ARGV[0], $org_file_name) || die "Cannot rename $ARGV[0]";

open(ORG, "<$org_file_name") || die "Cannot open $org_file_name";
open(NEW, ">$ARGV[0]") || die "Cannot open $ARGV[0]";

while (<ORG>) {
    if ($in_copyright == 0) {
        if ($_ =~ /^(\s*\S+\s*)OO_Copyright_BEGIN/) {
            $in_copyright = 1;
            $prefix = $1;
            print "Start copyright section: $ARGV[0]\n";
            print "Prefix = \"$prefix\"\n";
            print NEW $_;
            print_copyright(*NEW, $prefix);
        } elsif ($_ =~ /^OO_Copyright_BEGIN/) {
            $in_copyright = 1;
            print "Start copyright section: $ARGV[0]\n";
            print NEW $_;
            print_copyright(*NEW, "");
        }
    } else {
        if ($_ =~ /^(\s*\S+\s*)OO_Copyright_END/ || $_ =~ /^OO_Copyright_END/) {
            $in_copyright = 0;
            print "End copyright section: $ARGV[0]\n";
        }
    }

    if ($in_copyright == 0) {
        $_ =~ s/([Ll])ong ([Tt])erm ([Ff])ile ([Ss])ystem/$1inear $2ape $3ile $4ystem/g;
        print NEW $_;
    }
}

close(ORG);
close(NEW);

unlink($org_file_name);


text:
set +x

#TRIGGER_PIPELINES=(docker-node docker-ruby docker-fluentd docker-geoip docker-nginx docker-openjdk docker-prometheus docker-php)
RELEASE_NAME=$(buildkite-agent meta-data get release-name || echo "n/a")

# Define release hint for Github release
read -r -d '' release_hint << EOF
It's common practice to prefix your version names with the letter v. Some good tag names might be v1.0 or v2.3.4.
If the tag isn't meant for production use, add a pre-release version after the version name. Some good pre-release versions might be v0.2-alpha or v5.9-beta.3.
EOF

set -e

# Master banch before Github release
if [ "$RELEASE_NAME" == "n/a"  -a "$BUILDKITE_BRANCH" == 'master' ]; then
cat <<EOF
steps:
  - label: ':hammer: Run tests'
    command: bin/alpine tests --build
  - wait
  - block: ':github: Release'
    prompt: "Fill out the details for release"
    fields:
      - text: "Release name"
        key: "release-name"
        required: true
        hint: "$release_hint"
      - text: "Describe this release"
        key: "release-notes"
        required: false
        hint: "List of what's changed in this release"
      - select: "Release type"
        key: "release-type"
        default: "draft"
        options:
        - label: "Draft"
          value: "draft"
        - label: "Pre-release"
          value: "pre-release"
        - label: "Release"
          value: "release"
  - command: .buildkite/pipeline.sh | buildkite-agent pipeline upload
    label: ":pipeline: Setup pipeline"
EOF
exit 0
fi

# Master branch after Github release
if [ "$RELEASE_NAME" != "n/a" -a "$BUILDKITE_BRANCH" == 'master' ]; then
cat <<EOF
steps:
  - label: ':github: Release'
    command: .buildkite/release.sh
  - wait
  - label: ':docker: Release on Dockerhub'
    command: bin/alpine release
  - wait
EOF
#for TRIGGER_PIPELINE in ${TRIGGER_PIPELINES[@]}; do
#cat <<EOF
#  - trigger: "$TRIGGER_PIPELINE"
#    label: "Trigger pipeline $TRIGGER_PIPELINE"
#    async: true
#    build:
#      message: "Build triggered after releasing 'bandsintown/alpine' images ($RELEASE_NAME)"
#EOF
#done
exit 0
fi

# Pull Requests
cat <<EOF
steps:
  - label: ':hammer: Run tests'
    command: bin/alpine tests --build
EOF


text:
#ifndef __ARCH_I386_ATOMIC__
#define __ARCH_I386_ATOMIC__

#include <sys/cdefs.h>
__BEGIN_DECLS

/*
 * Make sure gcc doesn't try to be clever and move things around
 * on us. We need to use _exactly_ the address the user gave us,
 * not some alias that contains the same information.
 */
typedef volatile int atomic_t;

#define ATOMIC_INIT(i)	{ (i) }

/**
 * atomic_read - read atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically reads the value of @v.
 */
#define atomic_read(v)		(*(v))

/**
 * atomic_set - set atomic variable
 * @v: pointer of type atomic_t
 * @i: required value
 *
 * Atomically sets the value of @v to @i.
 */
#define atomic_set(v,i)		(*(v) = (i))

static __inline__ int atomic_clear(atomic_t *v)
{
	return __sync_fetch_and_and(v, 0);
}

/**
 * atomic_add - add integer to atomic variable
 * @i: integer value to add
 * @v: pointer of type atomic_t
 *
 * Atomically adds @i to @v.
 */
static __inline__ int atomic_add(int i, atomic_t *v)
{
	return __sync_fetch_and_add(v, i);
}

/**
 * atomic_sub - subtract the atomic variable
 * @i: integer value to subtract
 * @v: pointer of type atomic_t
 *
 * Atomically subtracts @i from @v.
 */
static __inline__ int atomic_sub(int i, atomic_t *v)
{
	return __sync_fetch_and_sub(v, i);
}

/**
 * atomic_sub_and_test - subtract value from variable and test result
 * @i: integer value to subtract
 * @v: pointer of type atomic_t
 *
 * Atomically subtracts @i from @v and returns
 * true if the result is zero, or false for all
 * other cases.
 */
static __inline__ int atomic_sub_and_test(int i, atomic_t *v)
{
	return __sync_sub_and_fetch(v, i) == 0;
}

/**
 * atomic_inc - increment atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically increments @v by 1.
 */
static __inline__ int atomic_inc(atomic_t *v)
{
	return __sync_fetch_and_add(v, 1);
}

/**
 * atomic_dec - decrement atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically decrements @v by 1.
 */
static __inline__ int atomic_dec(atomic_t *v)
{
	return __sync_fetch_and_sub(v, 1);
}

/**
 * atomic_dec_and_test - decrement and test
 * @v: pointer of type atomic_t
 *
 * Atomically decrements @v by 1 and
 * returns true if the result is 0, or false for all other
 * cases.
 */
static __inline__ int atomic_dec_and_test(atomic_t *v)
{
	return __sync_sub_and_fetch(v, 1) == 0;
}

/**
 * atomic_inc_and_test - increment and test
 * @v: pointer of type atomic_t
 *
 * Atomically increments @v by 1
 * and returns true if the result is zero, or false for all
 * other cases.
 */
static __inline__ int atomic_inc_and_test(atomic_t *v)
{
	return __sync_add_and_fetch(v, 1) == 0;
}

/**
 * atomic_add_negative - add and test if negative
 * @v: pointer of type atomic_t
 * @i: integer value to add
 *
 * Atomically adds @i to @v and returns true
 * if the result is negative, or false when
 * result is greater than or equal to zero.
 */
static __inline__ int atomic_add_negative(int i, atomic_t *v)
{
	return __sync_add_and_fetch(v, i) < 0;
}

/**
 * atomic_add_return - add and return
 * @v: pointer of type atomic_t
 * @i: integer value to add
 *
 * Atomically adds @i to @v and returns @i + @v
 */
static __inline__ int atomic_add_return(int i, atomic_t *v)
{
	return __sync_add_and_fetch(v, i);
}

static __inline__ int atomic_sub_return(int i, atomic_t *v)
{
	return __sync_sub_and_fetch(v, i);
}

#define atomic_inc_return(v)  (atomic_add_return(1,v))
#define atomic_dec_return(v)  (atomic_sub_return(1,v))

__END_DECLS
#endif


text:
def getgkmsvmAccuracy(gkmsvmPredictionsFileName, numPos):
	# Get the accuracy of gkmsvm
	gkmsvmPredictionsFile = open(gkmsvmPredictionsFileName)
	numPosCorrect = 0
	numNegCorrect = 0
	count = 0
	atNeg = False
	for line in gkmsvmPredictionsFile:
		# Iterate through the predictions and determine if they are positive or negative
		count = count + 1
		if count == numPos + 1:
			# At the first negative example
			atNeg = True
		lineElements = line.split("\t")
		prediction = float(lineElements[1])
		if prediction > 0:
			# Prediction is positive
			if atNeg == False:
				# The prediction is a true positive
				numPosCorrect = numPosCorrect + 1
		else:
			# Prediction is a negative
			if atNeg == True:
				# The prediction is a true negative
				numNegCorrect = numNegCorrect + 1
	sensitivity = float(numPosCorrect)/float(numPos)
	print "Sensitivity: " + str(sensitivity)
	specificity = float(numNegCorrect)/float(count - numPos)
	print "Specificity: " + str(specificity)
	accuracy = float(numPosCorrect + numNegCorrect)/float(count)
	print "Accuracy: " + str(accuracy)
	gkmsvmPredictionsFile.close()

if __name__=="__main__":
	import sys
	gkmsvmPredictionsFileName = sys.argv[1]
	numPos = int(sys.argv[2])
	getgkmsvmAccuracy(gkmsvmPredictionsFileName, numPos)


text:
section: exercises
description: Auth0 digital identity Lab 4: Single Page App
topics:
  - digital identity
  - OIDC
  - OpenId Connect
  - OAuth2
contentType:
  - index
  - concept
---
# Lab 4: Single Page App

## Prerequisites

- Read the introduction on the [main Identity Labs page](/identity-labs)
- Watch the [Single Page Apps video](/videos/learn-identity/06-single-page-apps)

## What You'll Need

<%= include('../_includes/_what-you-need') %>

---

**For Windows users** - We recommend that you use the Windows PowerShell terminal (instead of the Windows command line) so that the terminal commands provided in the lab instructions work as they are. This is because the syntax of the commands used in the labs is the same for the Mac and PowerShell terminals.

Start →