text:
S V U I   By: Munglunch
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--

local _G = _G;
--LUA
local unpack        = _G.unpack;
local select        = _G.select;
local assert        = _G.assert;
local type          = _G.type;
local error         = _G.error;
local pcall         = _G.pcall;
local print         = _G.print;
local ipairs        = _G.ipairs;
local pairs         = _G.pairs;
local next          = _G.next;
local rawset        = _G.rawset;
local rawget        = _G.rawget;
local tostring      = _G.tostring;
local tonumber      = _G.tonumber;
local getmetatable  = _G.getmetatable;
local setmetatable  = _G.setmetatable;
local tinsert       = _G.tinsert;
local tremove       = _G.tremove;
local twipe         = _G.wipe;
--STRING
local string        = _G.string;
local format        = string.format;
local find          = string.find;
local match         = string.match;
--MATH
local math          = _G.math;
local min, random   = math.min, math.random;
--TABLE
local table         = _G.table;
local bit 					= _G.bit;
local band, bor 		= bit.band, bit.bor
--[[ LOCALIZED BLIZZ FUNCTIONS ]]--
local NewHook = hooksecurefunc;
--[[
##########################################################
GET ADDON DATA AND TEST FOR oUF
##########################################################
]]--
local SV = _G['SVUI']
local L = SV.L;
local LSM = _G.LibStub("LibSharedMedia-3.0")
local MOD = SV.UnitFrames

if(not MOD) then return end

local oUF_SVUI = MOD.oUF
assert(oUF_SVUI, "SVUI UnitFrames: unable to locate oUF.")
--[[
##########################################################
LOCALS
##########################################################
]]--
local BodyGuard = {
  CurrentName = false,
  CurrentHealth = 1,
  CurrentMaxHealth = 1,
  CurrentStatus = 0,
  Initialized = false,
};
BodyGuard.UF = CreateFrame("Button", "SVUI_BodyGuard", UIParent, "SecureActionButtonTemplate")
local EventListener = CreateFrame("Frame");
local CONTINENT_DRAENOR = 7;
local BODYGUARD_IDS, BODYGUARD_NAMES, BARRACKS_LIST, BODYGUARD_BANNED_ZONES = {}, {}, {[27]=true,[28]=true}, {[978]=true,[1009]=true,[1011]=true};
local FLAGMASK = bor(COMBATLOG_OBJECT_TYPE_GUARDIAN, COMBATLOG_OBJECT_CONTROL_PLAYER, COMBATLOG_OBJECT_REACTION_FRIENDLY, COMBATLOG_OBJECT_AFFILIATION_MINE);

do
  local AURA_SEARCH = {
    [173663]=true,[173662]=true,[173664]=true,[173977]=true,[173665]=true,[173656]=true,[173666]=true,
    [173660]=true,[173657]=true,[173658]=true,[173976]=true,[173659]=true,[173649]=true,[173661]=true
  };
  for id, _ in pairs(AURA_SEARCH) do
    local spellName = GetSpellInfo(id)
    local name = spellName:match("^([%w%s]+) %w+")
    if name then
      BODYGUARD_NAMES[name] = true
      BODYGUARD_IDS[id] = name
    end
  end
end

local function ZoneTest()
  SetMapToCurrentZone()
  if(GetCurrentMapContinent() ~= 7) then return false; end
  local zone = GetCurrentMapAreaID()
  if(BODYGUARD_BANNED_ZONES[zone]) then return false; end
  return true
end

function BodyGuard:RefreshData()
  self.CurrentName = false
  self.CurrentHealth = 1
  self.CurrentMaxHealth = 1
  self.CurrentStatus = 0
  self.Initialized = true

  local buildings = C_Garrison.GetBuildings()

  for i = 1, #buildings do
    local building = buildings[i]
    local building_id = building.buildingID
    if(building_id and BARRACKS_LIST[building_id]) then
      local name, level, quality, displayID, followerID, garrFollowerID, status, portraitIconID = C_Garrison.GetFollowerInfoForBuilding(building.plotID)
      if(not name) then
        self.CurrentStatus = 0;
        self:StatusUpdate()
        return
      end
      self.CurrentName = name
      self.CurrentStatus = 2
      self:NameUpdate()
      break
    end
  end
end

function BodyGuard:GARRISON_BUILDINGS_SWAPPED()
  self:RefreshData()
end

function BodyGuard:GARRISON_BUILDING_ACTIVATED()
  self:RefreshData()
end

function BodyGuard:GARRISON_BUILDING_UPDATE(buildingID)
  if BARRACKS_LIST[buildingID] then self:RefreshData() end
end

function BodyGuard:GARRISON_FOLLOWER_REMOVED()
  self:RefreshData()
end

function BodyGuard:GARRISON_FOLLOWER_ADDED()
  self:RefreshData()
end

function BodyGuard:GARRISON_UPDATE()
  self:RefreshData()
end

function BodyGuard:PLAYER_TARGET_CHANGED(arg)
  if(not self.CurrentName) then return end
  if((arg ~= "LeftButton") and (arg ~= "up")) then return end
  local unit = "target"
  if(self.CurrentName ~= UnitName(unit)) then return end
  self.CurrentHealth = UnitHealth(unit)
  self.CurrentMaxHealth = UnitHealthMax(unit)
  self:HealthUpdate()
end

function BodyGuard:UPDATE_MOUSEOVER_UNIT()
  if(not self.CurrentName) then return end
  local unit = "mouseover"
  local mouseover_name = UnitName(unit)
  if(self.CurrentName == mouseover_name) then
    local tip = _G["GameTooltipTextLeft2"]
    if tip and tip.GetText then
      local text = tip:GetText()
      if(text:find("Bodyguard")) then
        if(self.CurrentStatus == 2) then self.CurrentStatus = 1 end
      else
        self.CurrentStatus = 0
      end
    end
    if(self.CurrentStatus == 1) then
      self.CurrentHealth = UnitHealth(unit)
      self.CurrentMaxHealth = UnitHealthMax(unit)
    end
    self:StatusUpdate()
  end
end

function BodyGuard:UNIT_HEALTH(unit)
  if(not self.CurrentName) then return end
  if(self.CurrentName ~= UnitName(unit)) then return end
  self.CurrentHealth = UnitHealth(unit)
  self.CurrentMaxHealth = UnitHealthMax(unit)
  self:HealthUpdate()
end

function BodyGuard:COMBAT_LOG_EVENT_UNFILTERED(timestamp, event, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...)
  if(not self.CurrentName) then return end
  if(sourceName and (sourceName == self.CurrentName)) then
    if(not band(sourceFlags, FLAGMASK) == FLAGMASK) then return end
    self.CurrentStatus = 1
    self:StatusUpdate()
  elseif(destName and (destName == self.CurrentName)) then
    if(not band(destFlags, FLAGMASK) == FLAGMASK) then return end
    local prefix, suffix = event:match("^([A-Z_]+)_([A-Z]+)$")
    local value, updated = 0;

    if prefix:match("^SPELL") then
      value = select(4, ...);
    elseif prefix == "ENVIRONMENTAL" then
      value = select(2, ...);
    else
      value = select(1, ...);
    end

    if suffix == "DAMAGE" then
      self.CurrentHealth = self.CurrentHealth - value
      updated = true
    elseif suffix == "HEAL" then
      self.CurrentHealth = self.CurrentHealth + value
      if self.CurrentMaxHealth <= self.CurrentHealth then
        self.CurrentHealth = self.CurrentMaxHealth
      end
      updated = true
    elseif suffix == "INSTAKILL" then
      self.CurrentHealth = 0
      updated = true
    end

    if(updated) then
      if self.CurrentHealth <= 0 then
        self.CurrentHealth = 0
        self.CurrentStatus = 2
      else
        self.CurrentStatus = 1
      end
      self:HealthUpdate()
    end

    self:StatusUpdate()
  end
end

function BodyGuard:PLAYER_REGEN_ENABLED()
  if(self.CurrentHealth <= 0) then return end
  self.CurrentHealth = self.CurrentMaxHealth
  self:HealthUpdate()
end

function BodyGuard:UNIT_AURA()
  for i = 1, 40 do
    local _, _, _, _, _, duration, expireTime, _, _, _, id = UnitDebuff("player", i)
    if not BODYGUARD_IDS[id] then return end
    local name = BODYGUARD_IDS[id]
    if name == self.CurrentName then
      self.CurrentStatus = 0
      self.CurrentHealth = 0
      self:HealthUpdate()
      self:StatusUpdate()
      return
    end
  end
end

function BodyGuard:PLAYER_ENTERING_WORLD()
  local showing = self:IsShowing()

  if(not self.Initialized) then
    self:RefreshData()
  end

  if((not self.CurrentName) or (self.CurrentStatus == 0)) then
    self:ToggleVisibility("Hide")
    return
  end
  if(not ZoneTest()) then
    self:ToggleVisibility("Hide")
  elseif showing then
    self:UpdateSettings()
  elseif self.CurrentStatus == 1 then
    self:ToggleVisibility("Show")
  end
end

function BodyGuard:ZONE_CHANGED_NEW_AREA()
  if(not ZoneTest()) then
    if not self:IsShowing() then return end
    self:ToggleVisibility("Hide")
  elseif self.CurrentStatus == 1 then
    self:ToggleVisibility("Show")
  end
end

function BodyGuard:IsShowing()
  if(self.UF and (self.UF:IsShown() or self.UF.VisualState == "Show")) then
    return true
  else
    return false
  end
end

function BodyGuard:ToggleVisibility(state)
  if(InCombatLockdown()) then
    self.UF:RegisterEvent("PLAYER_REGEN_ENABLED")
    self.UF.VisualState = state
    return
  elseif(self.UF:IsEventRegistered("PLAYER_REGEN_ENABLED")) then
    self.UF:UnregisterEvent("PLAYER_REGEN_ENABLED")
  end
  if(state == "Hide") then self.UF:Hide() else self.UF:Show() end
end

function BodyGuard:UpdateSettings()
  if(not self.UF) then return end
  if(SV.db.UnitFrames.bodyguard.enable) then
    self.UF:SetParent(SV.Screen)
  else
    self.UF:SetParent(SV.Hidden)
  end

  self:HealthUpdate()
  self.UF:SetWidth(SV.db.UnitFrames.bodyguard.width)
  self.UF:SetHeight(SV.db.UnitFrames.bodyguard.height)
end

function BodyGuard:StatusUpdate()
  if self.CurrentStatus == 1 then
    self:NameUpdate()
    self:HealthUpdate()
    self:ToggleVisibility("Show")
  else
    self:ToggleVisibility("Hide")
  end
end

function BodyGuard:NameUpdate()
  if(not InCombatLockdown() and self.CurrentName) then
    self.UF:SetAttribute("macrotext1", "/targetexact " .. self.CurrentName)
  end
  if(not self.UF.Name) then return end
  self.UF.Name:SetText(self.CurrentName)
end

function BodyGuard:HealthUpdate()
  if(not self.UF) then return end
  local health = self.CurrentHealth;
  local maxHealth = self.CurrentMaxHealth;

  self.UF.Health:SetMinMaxValues(0, maxHealth)
  self.UF.Health:SetValue(health)

  local r, g, b = unpack(oUF_SVUI.colors.health)
  r, g, b = oUF_SVUI.ColorGradient(health, maxHealth, 1, 0, 0, 1, 1, 0, r, g, b)

  self.UF.Health:SetStatusBarColor(r, g, b)
  self.UF.Health.bg:SetVertexColor(r * 0.25, g * 0.25, b * 0.25)
end

-- LOAD

local EventListener_OnEvent = function(self, event, ...)
    local fn = BodyGuard[event]
    if(fn and type(fn) == "function") then
        local _, catch = pcall(fn, BodyGuard, ...)
        if(catch) then
            SV:HandleError("UnitFrames [BodyGuard]", event, catch)
        end
    end
end

local _hook_GOSSIP_CONFIRM = function(...)
  if(not BodyGuard:IsShowing()) then return end
  BodyGuard.CurrentStatus = 0
  BodyGuard.CurrentHealth = BodyGuard.CurrentMaxHealth
  BodyGuard:StatusUpdate()
  BodyGuard:HealthUpdate()
end

function MOD:InitializeBodyGuard()
  BodyGuard.UF.VisualState = "Hide"
  BodyGuard.UF:SetPoint("BOTTOMRIGHT", SV.Dock.BottomLeft, "TOPRIGHT", 0, 10)
  BodyGuard.UF:SetWidth(SV.db.UnitFrames.bodyguard.width)
  BodyGuard.UF:SetHeight(SV.db.UnitFrames.bodyguard.height)
  BodyGuard.UF:SetScript("OnEvent", function(self, event)
    if(event == "PLAYER_REGEN_ENABLED") then
      BodyGuard:ToggleVisibility(self.VisualState)
    elseif(event == "PLAYER_TARGET_CHANGED") then
      if(UnitExists("target") and UnitName("target") == BodyGuard.CurrentName) then
        self.TargetGlow:Show()
      else
        self.TargetGlow:Hide()
      end
    end
  end)
  BodyGuard.UF:SetStyle("Frame", "Icon")

  BodyGuard.UF.TargetGlow = BodyGuard.UF.Panel.Shadow
  BodyGuard.UF.TargetGlow:SetBackdropBorderColor(0, 1, 0, 0.5)
  BodyGuard.UF.TargetGlow:Hide()

  BodyGuard.UF:RegisterEvent("PLAYER_TARGET_CHANGED")
  BodyGuard.UF.Health = CreateFrame("StatusBar", nil, BodyGuard.UF)
  BodyGuard.UF.Health:InsetPoints(BodyGuard.UF)
  BodyGuard.UF.Health:SetMinMaxValues(0, 1)
  BodyGuard.UF.Health:SetValue(1)
  BodyGuard.UF.Health:SetStatusBarTexture(LSM:Fetch("statusbar", SV.db.UnitFrames.statusbar))

  BodyGuard.UF.Health.bg = BodyGuard.UF.Health:CreateTexture(nil, "BORDER")
  BodyGuard.UF.Health.bg:SetAllPoints()
  BodyGuard.UF.Health.bg:SetTexture(SV.media.statusbar.gradient)
  BodyGuard.UF.Health.bg:SetVertexColor(0.1, 0.1, 0.1)

  BodyGuard.UF.Name = BodyGuard.UF.Health:CreateFontString(nil, 'OVERLAY')
  SV:FontManager(BodyGuard.UF.Name, "unitsecondary")
  BodyGuard.UF.Name:SetPoint("CENTER", BodyGuard.UF, "CENTER")
  BodyGuard.UF.Name:SetTextColor(unpack(oUF_SVUI.colors.reaction[5]))

  SV:NewAnchor(BodyGuard.UF, L["BodyGuard Frame"])

  BodyGuard.UF:SetAttribute("type1", "macro")
  if BodyGuard.CurrentName then
    BodyGuard.UF:SetAttribute("macrotext1", "/targetexact " .. BodyGuard.CurrentName)
  end
  BodyGuard:RefreshData()
  BodyGuard:HealthUpdate()
  BodyGuard.UF:Hide()

  EventListener:SetScript("OnEvent", EventListener_OnEvent)

  EventListener:RegisterEvent("GARRISON_BUILDINGS_SWAPPED")
  EventListener:RegisterEvent("GARRISON_BUILDING_ACTIVATED")
  EventListener:RegisterEvent("GARRISON_BUILDING_UPDATE")
  EventListener:RegisterEvent("GARRISON_FOLLOWER_REMOVED")
  EventListener:RegisterEvent("GARRISON_FOLLOWER_ADDED")
  EventListener:RegisterEvent("GARRISON_UPDATE")
  EventListener:RegisterEvent("PLAYER_TARGET_CHANGED")
  EventListener:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
  EventListener:RegisterEvent("UNIT_HEALTH")
  EventListener:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
  EventListener:RegisterEvent("PLAYER_REGEN_ENABLED")
  EventListener:RegisterEvent("PLAYER_ENTERING_WORLD")
  EventListener:RegisterEvent("ZONE_CHANGED_NEW_AREA")
  EventListener:RegisterUnitEvent("UNIT_AURA", "player")

  hooksecurefunc(StaticPopupDialogs.GOSSIP_CONFIRM, "OnAccept", _hook_GOSSIP_CONFIRM)
end

BodyGuard:RefreshData()


text:
node-red-node-sensortag
=======================

This node adds support to Node-RED to read from the Texas Instruments SensorTag.

The SensorTag is a Bluetooth LE device hosting the following sensors:

* Humidity and Temperature
* Ambient & IR Temperatures
* Barometric Pressure
* 3 axis Accelerometer
* 3 axis Gyroscope
* 3 axis Magnetometer
* 2 push Buttons
* 1 Luxometer (CC2650 version only)

The config node allows the user to enable/disable any of the sensors listed above. The readings from
these sensors will be sent as a JSON object payload with the sensor name appended to the topic provided:

* Humidity - { topic: [topic_prefix]/humidity , payload: { temp: 21.2, humidity: 88} }
* Temperature - { topic: [topic_prefix]/temperature, payload: { ambient: 21.2, object: 33.0 } }
* Barometric Pressure - { topic: [topic_prefix]/pressure, payload: { pres: 1000 } }
* Accelerometer - { topic: [topic_prefix]/accelerometer , payload: { x:0.0, y:9.8, z:0.0 } }
* Magnetometer - { topic: [topic_prefix]/magnetometer , payload: { x:0.0, y:0.0, z:0.0 } }
* Gyroscope - { topic: [topic_prefix]/gyroscope , payload: { x:0.0, y:0.0, z:0.0 } }
* Luxometer - { topic: [topic_prefix]/luxometer , payload: { lux: 212 } }
* Buttons - { topic: [topic_prefix]/keys , payload: { left: true, right: false} }

The sensorTag library used by this node only supports using 1 SensorTag at a time.

**NOTE:** On Linux Node-RED needs to be run as root in order or access the Linux Bluetooth 4.0 system calls

redpajama_set_name: RedPajamaGithub


text:
class UsersController < ApplicationController
  before_action :authenticate_user!
  after_action :verify_authorized

  def show
    authorize :user, :show?
    @count_user_movies = current_user.movies.count
    @total_search_count = current_user.total_search_count
  end

  def my_movies
    authorize :user, :my_movies?
    @user_movies = current_user.movies.order('created_at DESC').page(params[:page]).per(5)
  end
end


text:
**_THIS REPOSITORY IS DEPRECATED. ALL OF ITS CONTENT AND HISTORY HAS BEEN MOVED TO [GOOGLE-CLOUD-NODE](https://github.com/googleapis/google-cloud-node/tree/main/packages/google-analytics-admin)_**

[//]: # "This README.md file is auto-generated, all changes to this file will be lost."
[//]: # "To regenerate it, use `python -m synthtool`."
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>

# [Google Analytics Admin: Node.js Client](https://github.com/googleapis/nodejs-analytics-admin)

[![release level](https://img.shields.io/badge/release%20level-preview-yellow.svg?style=flat)](https://cloud.google.com/terms/launch-stages)
[![npm version](https://img.shields.io/npm/v/@google-analytics/admin.svg)](https://www.npmjs.org/package/@google-analytics/admin)

Admin client for Node.js

A comprehensive list of changes in each version may be found in
[the CHANGELOG](https://github.com/googleapis/nodejs-analytics-admin/blob/main/CHANGELOG.md).

* [Google Analytics Admin Node.js Client API Reference][client-docs]
* [Google Analytics Admin Documentation][product-docs]
* [github.com/googleapis/nodejs-analytics-admin](https://github.com/googleapis/nodejs-analytics-admin)

Read more about the client libraries for Cloud APIs, including the older
Google APIs Client Libraries, in [Client Libraries Explained][explained].

[explained]: https://cloud.google.com/apis/docs/client-libraries-explained

**Table of contents:**

* [Quickstart](#quickstart)
  * [Before you begin](#before-you-begin)
  * [Installing the client library](#installing-the-client-library)
  * [Using the client library](#using-the-client-library)
* [Samples](#samples)
* [Versioning](#versioning)
* [Contributing](#contributing)
* [License](#license)

## Quickstart

### Before you begin

1.  [Select or create a Cloud Platform project][projects].
1.  [Enable the Google Analytics Admin API][enable_api].
1.  [Set up authentication with a service account][auth] so you can access the
    API from your local workstation.

### Installing the client library

```bash
npm install @google-analytics/admin
```

### Using the client library

```javascript
// Imports the Google Analytics Admin API client library
const analyticsAdmin = require('@google-analytics/admin');

async function main() {
  // Instantiates a client using default credentials.
  // TODO(developer): uncomment and use the following line in order to
  //  manually set the path to the service account JSON file instead of
  //  using the value from the GOOGLE_APPLICATION_CREDENTIALS environment
  //  variable.
  // const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(
  //     {keyFilename: "your_key_json_file_path"});
  const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient();

  // Calls listAccounts() method of the Google Analytics Admin API and prints
  // the response for each account.
  const [accounts] = await analyticsAdminClient.listAccounts();

  console.log('Accounts:');
  accounts.forEach(account => {
    console.log(account);
  });
}

main(...process.argv.slice(2)).catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});
process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

```

## Samples

Samples are in the [`samples/`](https://github.com/googleapis/nodejs-analytics-admin/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample.

| Sample                      | Source Code                       | Try it |
| --------------------------- | --------------------------------- | ------ |
| Quickstart | [source code](https://github.com/googleapis/nodejs-analytics-admin/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-analytics-admin&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) |
| Quickstart_installed_oauth2 | [source code](https://github.com/googleapis/nodejs-analytics-admin/blob/main/samples/quickstart_installed_oauth2.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-analytics-admin&page=editor&open_in_editor=samples/quickstart_installed_oauth2.js,samples/README.md) |

The [Google Analytics Admin Node.js Client API Reference][client-docs] documentation
also contains samples.

## Supported Node.js Versions

Our client libraries follow the [Node.js release schedule](https://nodejs.org/en/about/releases/).
Libraries are compatible with all current _active_ and _maintenance_ versions of
Node.js.
If you are using an end-of-life version of Node.js, we recommend that you update
as soon as possible to an actively supported LTS version.

Google's client libraries support legacy versions of Node.js runtimes on a
best-efforts basis with the following warnings:

* Legacy versions are not tested in continuous integration.
* Some security patches and features cannot be backported.
* Dependencies cannot be kept up-to-date.

Client libraries targeting some end-of-life versions of Node.js are available, and
can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag).
The dist-tags follow the naming convention `legacy-(version)`.
For example, `npm install @google-analytics/admin@legacy-8` installs client libraries
for versions compatible with Node.js 8.

## Versioning

This library follows [Semantic Versioning](http://semver.org/).

This library is considered to be in **preview**. This means it is still a
work-in-progress and under active development. Any release is subject to
backwards-incompatible changes at any time.

More Information: [Google Cloud Platform Launch Stages][launch_stages]

[launch_stages]: https://cloud.google.com/terms/launch-stages

## Contributing

Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-analytics-admin/blob/main/CONTRIBUTING.md).

Please note that this `README.md`, the `samples/README.md`,
and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`)
are generated from a central template. To edit one of these files, make an edit
to its templates in
[directory](https://github.com/googleapis/synthtool).

## License

Apache Version 2.0

See [LICENSE](https://github.com/googleapis/nodejs-analytics-admin/blob/main/LICENSE)

[client-docs]: https://googleapis.dev/nodejs/analytics-admin/latest/index.html
[product-docs]: https://developers.google.com/analytics
[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png
[projects]: https://console.cloud.google.com/project
[billing]: https://support.google.com/cloud/answer/6293499#enable-billing
[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=analyticsadmin.googleapis.com
[auth]: https://cloud.google.com/docs/authentication/getting-started


text:
enyo.depends(
	// Primary settings file
	"settings.main.js"
);


text:
require 'concurrent/utility/native_extension_loader'
require 'concurrent/utility/engine'
require 'concurrent/atomic_reference/concurrent_update_error'
require 'concurrent/atomic_reference/mutex_atomic'

begin
  # force fallback impl with FORCE_ATOMIC_FALLBACK=1
  if /[^0fF]/ =~ ENV['FORCE_ATOMIC_FALLBACK']
    ruby_engine = 'mutex_atomic'
  else
    ruby_engine = Concurrent.ruby_engine
  end

  require "concurrent/atomic_reference/#{ruby_engine}"
rescue LoadError
  #warn 'Compiled extensions not installed, pure Ruby Atomic will be used.'
end

if defined? Concurrent::JavaAtomicReference

  # @!macro atomic_reference
  class Concurrent::AtomicReference < Concurrent::JavaAtomicReference
  end

elsif defined? Concurrent::RbxAtomicReference

  # @!macro atomic_reference
  class Concurrent::AtomicReference < Concurrent::RbxAtomicReference
  end

elsif defined? Concurrent::CAtomicReference

  # @!macro atomic_reference
  class Concurrent::AtomicReference < Concurrent::CAtomicReference
  end

else

  # @!macro atomic_reference
  class Concurrent::AtomicReference < Concurrent::MutexAtomicReference
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Reporting.Rdl.Utility
{
    public sealed class Conversion
    {
        static internal bool ToBoolean(string tf, ReportLog rl)
        {
            string low_tf = tf.ToLower();
            if (low_tf.CompareTo("true") == 0)
                return true;
            if (low_tf.CompareTo("false") == 0)
                return false;
            rl.LogError(4, "Unknown True/False value '" + tf + "'.  False assumed.");
            return false;
        }

        static internal int ToInteger(string i)
        {
            return Convert.ToInt32(i);
        }

    }
}


text:
require 'cliver'

# make sure we have all of our cli dependencies
Cliver.detect!('sox')


text:
/**
 */
package isostdisois_13584_32ed_1techxmlschemaontomlSimplified;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'LEVEL'.
 *
 *
 *
 * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getLEVEL()
 * @model
 * @generated
 */
public interface LEVEL extends EObject {
} // LEVEL


text:
/*
 * @(#)Subscription.java        1.0 09/12/14
 *
 * This file has been auto-generated by JNC, the
 * Java output format plug-in of pyang.
 * Origin: module "hcta-epc", revision: "2014-09-18".
 */

package hctaEpc.mmeSgsn.subscriber;

import Element;

import ElementChildrenIterator;

import Epc;

import Imsi;

import JNCException;

import com.tailf.jnc.YangElement;

/**
 * This class represents an element from
 * the namespace http://hitachi-cta.com/ns/epc
 * generated to "src/hctaEpc/mmeSgsn/subscriber/subscription"
 * <p>
 * See line 1432 in
 * scCli.yang
 *
 * @version 1.0 2014-12-09
 * @author Auto Generated
 */
public class Subscription extends YangElement {

    private static final long serialVersionUID = 1L;

    /**
     * Constructor for an empty Subscription object.
     */
    public Subscription() {
        super(Epc.NAMESPACE, "subscription");
    }

    /**
     * Clones this object, returning an exact copy.
     * @return A clone of the object.
     */
    public Subscription clone() {
        return (Subscription)cloneContent(new Subscription());
    }

    /**
     * Clones this object, returning a shallow copy.
     * @return A clone of the object. Children are not included.
     */
    public Subscription cloneShallow() {
        return (Subscription)cloneShallowContent(new Subscription());
    }

    /**
     * @return An array with the identifiers of any key children
     */
    public String[] keyNames() {
        return null;
    }

    /**
     * @return An array with the identifiers of any children, in order.
     */
    public String[] childrenNames() {
        return new String[] {
            "imsi",
        };
    }

    /* Access methods for list child: "imsi". */

    /**
     * Gets list entry "imsi", with specified keys.
     */
    public Imsi getImsi() throws JNCException {
        String path = "imsi";
        return (Imsi)searchOne(path);
    }

    /**
     * Iterator method for the list "imsi".
     * @return An iterator for the list.
     */
    public ElementChildrenIterator imsiIterator() {
        return new ElementChildrenIterator(children, "imsi");
    }

    /**
     * Adds list entry "imsi", using an existing object.
     * @param imsi The object to add.
     * @return The added child.
     */
    public Imsi addImsi(Imsi imsi) throws JNCException {
        insertChild(imsi, childrenNames());
        return imsi;
    }

    /**
     * Adds list entry "imsi".
     * This method is used for creating subtree filters.
     * @return The added child.
     */
    public Imsi addImsi() throws JNCException {
        Imsi imsi = new Imsi();
        insertChild(imsi, childrenNames());
        return imsi;
    }

    /**
     * Deletes list entry "imsi", with specified keys.
     */
    public void deleteImsi() throws JNCException {
        String path = "imsi";
        delete(path);
    }

    /**
     * Support method for addChild.
     * Adds a child to this object.
     *
     * @param child The child to add
     */
    public void addChild(Element child) {
        super.addChild(child);
    }

}


text:
<?php
namespace Czim\PxlCms\Test;

use Czim\PxlCms\Generator\Generator;
use Czim\PxlCms\Models\Checkbox;
use Czim\PxlCms\Models\Image;
use Generated\Models\News;
use Generated\Models\Page;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Database\Eloquent\Collection;

class PxlCmsAdapterTest extends TestCase
{

    /**
     * @test
     */
    function it_can_be_instantiated()
    {
        new Generator();
    }

    /**
     * @test
     */
    function it_generates_models()
    {
        $pxlcms = new Generator();
        $pxlcms->generate();

        $models = [
            'Page',
            'PageTranslation',
            'Slug',
            'News',
            'NewsTranslation',
        ];

        /** @var Filesystem $files */
        $files = $this->app['files'];

        // check if files were created and whether the content matches
        // what was pre-generated since we cannot actually load the run-time
        // generated models, this is as far as the test can go. We can
        // separately test the actual pre-generated models later, since they
        // were tested to be the same.

        foreach ($models as $model) {

            $file = $this->generatedPath
                  . DIRECTORY_SEPARATOR . 'Models'
                  . DIRECTORY_SEPARATOR . $model . '.php';

            $this->assertTrue($files->exists($file), "model file should exist");

            $pregeneratedFile = $this->getGeneratedContentPath()
                              . DIRECTORY_SEPARATOR . 'Models'
                              . DIRECTORY_SEPARATOR . $model . '.php';

            $this->assertEquals(
                $files->get($pregeneratedFile),
                $files->get($file),
                "The generated content for model '{$model}' does not match the pregenerated file."
            );
        }
    }

    /**
     * @test
     */
    function it_generates_models_that_can_retrieve_data()
    {
        $this->seedDatabaseCmsContent();

        $records = Page::all();

        // 2 active, 3 with inactive
        $this->assertCount(2, $records);
        $this->assertEquals(3, Page::withInactive()->count());

        // check the order, by position, 3 should be first
        $this->assertEquals(3, $records->first()->id, "Position 1 page is not first");
        $this->assertEquals(1, $records->last()->id, "Position 3 page is not first");

        // before eager loading, the news attribute should return the foreign key
        $this->assertEquals(3, $records->first()->news, "Unloaded news attribute should return foreign key");

        // magic property after loading should get related record
        $records->first()->load('news');
        $related = $records->first()->news;
        $this->assertInstanceOf('Generated\\Models\\News', $related, "Loaded news attribute should return a news model");
        $this->assertEquals(3, $related->id);

        // lookup through relation
        $related = $records->first()->news()->first();
        $this->assertInstanceOf('Generated\\Models\\News', $related, "Relation acces after eager loading should return a news model");
        $this->assertEquals(3, $related->id);
    }

    /**
     * @test
     */
    function it_generates_models_that_can_save_data()
    {
        $page = new Page();

        $this->assertEquals(0, Page::count(), "Should be no models before creating");

        // basic attributes
        $page->e_user_id = 0;

        // translated attributes
        $page->name            = "test";
        $page->title           = "testing title";
        $page->content         = "created testing content";
        $page->seo_title       = "seo test en";
        $page->seo_description = "seo description en";

        $page->save();

        unset($page);

        // check if database has the right content
        $this->seeInDatabase('cms_m22_pages', [
            'id'       => 1,
            'e_active' => 1,
        ]);

        $this->seeInDatabase('cms_m22_pages_ml', [
            'entry_id'        => 1,
            'language_id'     => 38,
            'name'            => 'test',
            'title'           => 'testing title',
            'content'         => 'created testing content',
            'seo_title'       => 'seo test en',
            'seo_description' => 'seo description en',
        ]);

        // check if newly created model is returned correctly
        $this->assertEquals(1, Page::count(), "Should be one new model after creating");

        /** @var Page $page */
        $page =Page::find(1);

        $this->assertInstanceOf('Generated\\Models\\Page', $page);

        // test translations
        $this->assertEquals('testing title', $page->title, 'translated value incorrect');
        $this->assertInstanceOf('Generated\\Models\\PageTranslation', $page->getTranslation('en'));

        app()->setLocale('nl');
        $this->assertEmpty($page->title, 'translation for different language should be empty');
        $this->assertEmpty($page->getTranslation('nl'), 'translation for different language should be empty');
    }

    /**
     * @test
     */
    function it_generates_models_that_can_save_data_through_belongs_to_and_has_many_relations()
    {
        $this->seedDatabaseCmsContent();

        /** @varPage $page */
        $page = Page::withInactive()->with('news')->find(2);

        $this->assertInstanceOf('Generated\\Models\\Page', $page, "setup model not found");
        $this->assertEmpty($page->news, "should not have news relation yet");

        // create and associate belongsto item
        $news = new News();

        $news->content   = "new news test";
        $news->author    = "test author";
        $news->e_user_id = 0;

        $news->save();

        $page->news()->associate($news);
        $page->save();

        $this->assertInstanceOf('Generated\\Models\\News', $page->news, "BelongsTo save() didn't work");

        $newsId = 5;

        $this->seeInDatabase('cms_m22_pages', [
            'id'   => 2,
            'news' => $newsId,
        ]);

        $this->seeInDatabase('cms_m40_news', [
            'id'     => $newsId,
            'author' => 'test author',
        ]);

        $this->seeInDatabase('cms_m40_news_ml', [
            'entry_id'    => $newsId,
            'content'     => 'new news test',
            'language_id' => 38,
        ]);
    }

    /**
     * @test
     */
    function it_generates_models_that_can_save_data_through_belongs_to_many_relations()
    {
        $this->seedDatabaseCmsContent();

        /** @var News $news */
        $news = News::find(2);

        $this->assertInstanceOf('Generated\\Models\\News', $news, "setup model not found");
        $this->assertEmpty($news->relevantNews);

        // attach two new relevant news items
        $relatedNewsA = new News();
        $relatedNewsA->content   = "content A";
        $relatedNewsA->author    = "author A";
        $relatedNewsA->e_user_id = 0;

        $relatedNewsB = new News();
        $relatedNewsB->content   = "content B";
        $relatedNewsB->author    = "author B";
        $relatedNewsB->e_user_id = 0;

        $news->relevantNews()->saveMany([
            $relatedNewsA,
            $relatedNewsB,
        ]);

        // see if we can load them through eloquent
        $news->load('relevantNews');
        $related = $news->relevantNews;

        $this->assertInstanceOf('Illuminate\\Database\\Eloquent\\Collection', $related, "eloquent related data incorrect");
        $this->assertCount(2, $related, "eloquent related data incorrect");
        $this->assertInstanceOf('Generated\\Models\\News', $related->first(), "eloquent related data incorrect");

        // and the reverse relations
        /** @var Collection $relatedReverse */
        $relatedReverse = $related->first()->relevantNewsReverse()->get();

        $this->assertInstanceOf('Illuminate\\Database\\Eloquent\\Collection', $relatedReverse, "eloquent reversed related data incorrect");
        $this->assertCount(1, $relatedReverse, "eloquent reversed related data incorrect");
        $this->assertInstanceOf('Generated\\Models\\News', $relatedReverse->first(), "eloquent reversed related data incorrect");

        // check if database was updated
        $this->seeInDatabase('cms_m40_news', [
            'id'     => 5,
            'author' => 'author A',
        ]);
        $this->seeInDatabase('cms_m40_news', [
            'id'     => 6,
            'author' => 'author B',
        ]);

        $this->seeInDatabase('cms_m40_news_ml', [
            'entry_id'    => 5,
            'content'     => 'content A',
            'language_id' => 38,
        ]);
        $this->seeInDatabase('cms_m40_news_ml', [
            'entry_id'    => 6,
            'content'     => 'content B',
        ]);

        $this->seeInDatabase('cms_m_references', [
            'from_field_id' => 185,
            'from_entry_id' => 2,
            'to_entry_id'   => 5,
        ]);
        $this->seeInDatabase('cms_m_references', [
            'from_field_id' => 185,
            'from_entry_id' => 2,
            'to_entry_id'   => 6,
        ]);
    }

    /**
     * @test
     */
    function it_generates_models_that_can_save_related_images()
    {
        $this->seedDatabaseCmsContent();

        // note that this does not take care of the upload itself, just the database record

        /** @var News $news */
        $news = News::find(1);

        $this->assertEmpty($news->image()->get(), "setup situation should not have any images");

        $image = new Image();

        $image->file        = "test_file_name.png";
        $image->extension   = ".png";
        $image->caption     = "caption test";
        $image->language_id = 0;
        $image->uploaded    = \Carbon\Carbon::now();

        $news->image()->save($image);

        unset($image);

        /** @var Image $image */
        $image = $news->image()->first();

        $this->assertInstanceOf('Czim\\PxlCms\\Models\\Image', $image, "image not retrievable through eloquent");

        $this->seeInDatabase('cms_m_images', [
            'entry_id'    => 1,
            'field_id'    => 182,
            'language_id' => 0,
            'file'        => 'test_file_name.png',
            'extension'   => '.png',
            'caption'     => 'caption test',
        ]);

        $this->assertEquals('http://localhost/cms_img/test_file_name.png', $image->url);

        // uploaded date should be set correctly
        $this->assertEquals(date('Y-m-d'), $image->uploaded->format('Y-m-d'), "uploaded date not set correctly");
    }

    /**
     * @test
     */
    function it_generates_models_that_can_save_related_checkboxes()
    {
        $this->seedDatabaseCmsContent();

        /** @var Page $page */
        $page = Page::find(1);

        $checkbox = new Checkbox();
        $checkbox->choice = "checkbox test";

        $page->showInMenu()->save($checkbox);

        unset($checkbox);

        /** @var Checkbox $checkbox */
        $checkbox = $page->showInMenu()->first();

        $this->assertInstanceOf('Czim\\PxlCms\\Models\\Checkbox', $checkbox, "checkbox not retrievable through eloquent");

        $this->seeInDatabase('cms_m_checkboxes', [
            'entry_id' => 1,
            'field_id' => 102,
            'choice'   => 'checkbox test',
        ]);
    }

    // ------------------------------------------------------------------------------
    //      Set up and helpers
    // ------------------------------------------------------------------------------

    /**
     * Make sure that any previously generated files in the testbench fixture are removed
     *
     * @before
     */
    protected function clearGenerated()
    {
        $this->app['files']->deleteDirectory($this->generatedPath);
    }

    /**
     * Returns path to generated content
     *
     * @return string
     */
    protected function getGeneratedContentPath()
    {
        return __DIR__ . DIRECTORY_SEPARATOR . 'Generated';
    }

}


text:
typedef hcx_value_t
hcx_ternary_t[HCX_VALUE_COUNT][HCX_VALUE_COUNT][HCX_VALUE_COUNT];

void hcx_ternary_generate(hcx_ternary_t *destination, hcx_ternary_t *source_1,
    hcx_ternary_t *source_2);
hcx_value_t hcx_ternary_pull(hcx_ternary_t ternary);
void hcx_ternary_push(hcx_ternary_t ternary, hcx_value_t value);
void hcx_ternary_randomize(hcx_ternary_t ternary);
void hcx_ternary_shuffle(hcx_ternary_t ternary);
void hcx_ternary_swap_values(hcx_ternary_t ternary, hcx_value_t position_a_x,
    hcx_value_t position_a_y, hcx_value_t position_a_z,
    hcx_value_t position_b_x, hcx_value_t position_b_y,
    hcx_value_t position_b_z);
void hcx_ternary_zero(hcx_ternary_t ternary);

#endif


text:
<!DOCTYPE html>

  <meta http-equiv="origin-trial"
    content="AsKJ0YJfrprDHN9cO+Arkwlyt0SqGVbRekp6Ho6B0zL8/aWcEEa7mYjLrXVRY4E3+ZPTupaMmCxJOtl4ava9CgAAAABteyJvcmlnaW4iOiJodHRwczovL3lvdXR1YmUuY29tOjQ0MyIsImZlYXR1cmUiOiJQcml2YWN5U2FuZGJveEFkc0FQSXMiLCJleHBpcnkiOjE2Njk3NjYzOTksImlzU3ViZG9tYWluIjp0cnVlfQ==">
  <link rel="shortcut icon" href="https://www.youtube.com/s/desktop/70ea5db2/img/favicon.ico" type="image/x-icon">
  <link rel="icon" href="https://www.youtube.com/s/desktop/70ea5db2/img/favicon_32x32.png" sizes="32x32">
  <link rel="icon" href="https://www.youtube.com/s/desktop/70ea5db2/img/favicon_48x48.png" sizes="48x48">
  <link rel="icon" href="https://www.youtube.com/s/desktop/70ea5db2/img/favicon_96x96.png" sizes="96x96">
  <link rel="icon" href="https://www.youtube.com/s/desktop/70ea5db2/img/favicon_144x144.png" sizes="144x144">
  <meta name="theme-color" content="rgba(33, 33, 33, 0.98)">
  <link rel="search" type="application/opensearchdescription+xml" href="https://www.youtube.com/opensearch?locale=en_US"
    title="YouTube">
  <link rel="manifest" href="/manifest.webmanifest" crossorigin="use-credentials">
  <link rel="canonical" href="https://www.youtube.com/watch?v=S49CN57Y58o">
  <link rel="alternate" media="handheld" href="https://m.youtube.com/watch?v=S49CN57Y58o">
  <link rel="alternate" media="only screen and (max-width: 640px)" href="https://m.youtube.com/watch?v=S49CN57Y58o">
  <title>Full Length Freight Trains! 1 Hour of Trains! - YouTube</title>
  <meta name="title" content="Full Length Freight Trains! 1 Hour of Trains!">
  <meta name="description"
    content="All aboard! In this video, we will watch several freight trains pass by in their entirety! From the locomotives to the last car, you'll see the entire trains...">
  <meta name="keywords"
    content="freight trains, railroads, full length train pass bys, BNSF, Union Pacific, CSX, Norfolk Southern, relaxing, background noise">
  <link rel="shortlinkUrl" href="https://youtu.be/S49CN57Y58o">
  <link rel="alternate" href="android-app://com.google.android.youtube/http/www.youtube.com/watch?v=S49CN57Y58o">
  <link rel="alternate" href="ios-app://544007664/vnd.youtube/www.youtube.com/watch?v=S49CN57Y58o">
  <link rel="alternate" type="application/json+oembed"
    href="https://www.youtube.com/oembed?format=json&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS49CN57Y58o"
    title="Full Length Freight Trains! 1 Hour of Trains!">
  <link rel="alternate" type="text/xml+oembed"
    href="https://www.youtube.com/oembed?format=xml&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS49CN57Y58o"
    title="Full Length Freight Trains! 1 Hour of Trains!">
  <link rel="image_src" href="https://i.ytimg.com/vi/S49CN57Y58o/maxresdefault.jpg">
  <meta property="og:site_name" content="YouTube">
  <meta property="og:url" content="https://www.youtube.com/watch?v=S49CN57Y58o">
  <meta property="og:title" content="Full Length Freight Trains! 1 Hour of Trains!">
  <meta property="og:image" content="https://i.ytimg.com/vi/S49CN57Y58o/maxresdefault.jpg">
  <meta property="og:image:width" content="1280">
  <meta property="og:image:height" content="720">
  <meta property="og:description"
    content="All aboard! In this video, we will watch several freight trains pass by in their entirety! From the locomotives to the last car, you'll see the entire trains...">
  <meta property="al:ios:app_store_id" content="544007664">
  <meta property="al:ios:app_name" content="YouTube">
  <meta property="al:ios:url" content="vnd.youtube://www.youtube.com/watch?v=S49CN57Y58o&feature=applinks">
  <meta property="al:android:url" content="vnd.youtube://www.youtube.com/watch?v=S49CN57Y58o&feature=applinks">
  <meta property="al:web:url" content="http://www.youtube.com/watch?v=S49CN57Y58o&feature=applinks">
  <meta property="og:type" content="video.other">
  <meta property="og:video:url" content="https://www.youtube.com/embed/S49CN57Y58o">
  <meta property="og:video:secure_url" content="https://www.youtube.com/embed/S49CN57Y58o">
  <meta property="og:video:type" content="text/html">
  <meta property="og:video:width" content="1280">
  <meta property="og:video:height" content="720">
  <meta property="al:android:app_name" content="YouTube">
  <meta property="al:android:package" content="com.google.android.youtube">
  <meta property="og:video:tag" content="freight trains">
  <meta property="og:video:tag" content="railroads">
  <meta property="og:video:tag" content="full length train pass bys">
  <meta property="og:video:tag" content="BNSF">
  <meta property="og:video:tag" content="Union Pacific">
  <meta property="og:video:tag" content="CSX">
  <meta property="og:video:tag" content="Norfolk Southern">
  <meta property="og:video:tag" content="relaxing">
  <meta property="og:video:tag" content="background noise">
  <meta property="fb:app_id" content="87741124305">
  <meta name="twitter:card" content="player">
  <meta name="twitter:site" content="@youtube">
  <meta name="twitter:url" content="https://www.youtube.com/watch?v=S49CN57Y58o">
  <meta name="twitter:title" content="Full Length Freight Trains! 1 Hour of Trains!">
  <meta name="twitter:description"
    content="All aboard! In this video, we will watch several freight trains pass by in their entirety! From the locomotives to the last car, you'll see the entire trains...">
  <meta name="twitter:image" content="https://i.ytimg.com/vi/S49CN57Y58o/maxresdefault.jpg">
  <meta name="twitter:app:name:iphone" content="YouTube">
  <meta name="twitter:app:id:iphone" content="544007664">
  <meta name="twitter:app:name:ipad" content="YouTube">
  <meta name="twitter:app:id:ipad" content="544007664">
  <meta name="twitter:app:url:iphone" content="vnd.youtube://www.youtube.com/watch?v=S49CN57Y58o&feature=applinks">
  <meta name="twitter:app:url:ipad" content="vnd.youtube://www.youtube.com/watch?v=S49CN57Y58o&feature=applinks">
  <meta name="twitter:app:name:googleplay" content="YouTube">
  <meta name="twitter:app:id:googleplay" content="com.google.android.youtube">
  <meta name="twitter:app:url:googleplay" content="https://www.youtube.com/watch?v=S49CN57Y58o">
  <meta name="twitter:player" content="https://www.youtube.com/embed/S49CN57Y58o">
  <meta name="twitter:player:width" content="1280">
  <meta name="twitter:player:height" content="720">
  <meta name="referrer" content="origin-when-cross-origin">

    <link itemprop="url" href="https://www.youtube.com/watch?v=S49CN57Y58o">
    <meta itemprop="name" content="Full Length Freight Trains! 1 Hour of Trains!">
    <meta itemprop="description"
      content="All aboard! In this video, we will watch several freight trains pass by in their entirety! From the locomotives to the last car, you'll see the entire trains...">
    <meta itemprop="paid" content="False">
    <meta itemprop="channelId" content="UCXOPfBqPphU15a6mpW7hwVw">
    <meta itemprop="videoId" content="S49CN57Y58o">
    <meta itemprop="duration" content="PT71M51S">
    <meta itemprop="unlisted" content="False">
      <link itemprop="url" href="http://www.youtube.com/user/CoasterFan2105">
      <link itemprop="name" content="CoasterFan2105">

    <link itemprop="thumbnailUrl" href="https://i.ytimg.com/vi/S49CN57Y58o/maxresdefault.jpg">
      <link itemprop="url" href="https://i.ytimg.com/vi/S49CN57Y58o/maxresdefault.jpg">
      <meta itemprop="width" content="1280">
      <meta itemprop="height" content="720">

    <link itemprop="embedUrl" href="https://www.youtube.com/embed/S49CN57Y58o">
    <meta itemprop="playerType" content="HTML5 Flash">
    <meta itemprop="width" content="1280">
    <meta itemprop="height" content="720">
    <meta itemprop="isFamilyFriendly" content="true">
    <meta itemprop="regionsAllowed"
      content="AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW">
    <meta itemprop="interactionCount" content="2925789">
    <meta itemprop="datePublished" content="2019-02-15">
    <meta itemprop="uploadDate" content="2019-02-15">
    <meta itemprop="genre" content="Autos & Vehicles">


text:
package com.erakk.lnreader.helper.db;

import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.erakk.lnreader.dao.NovelsDao;
import com.erakk.lnreader.helper.DBHelper;
import com.erakk.lnreader.model.UpdateInfoModel;
import com.erakk.lnreader.model.UpdateType;

public class UpdateInfoModelHelper {
	private static final String TAG = UpdateInfoModelHelper.class.toString();
	private static DBHelper helper = NovelsDao.getInstance().getDBHelper();

	// New column should be appended as the last column
	public static final String DATABASE_CREATE_UPDATE_HISTORY = "create table if not exists "
			  + DBHelper.TABLE_UPDATE_HISTORY + "(" + DBHelper.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "	// 0
			  						+ DBHelper.COLUMN_PAGE + " text not null, "							// 1
			  						+ DBHelper.COLUMN_UPDATE_TITLE + " text not null, "					// 2
			  						+ DBHelper.COLUMN_UPDATE_TYPE + " integer not null, "				// 3
			  						+ DBHelper.COLUMN_LAST_UPDATE + " integer);";						// 4

	public static UpdateInfoModel cursorToUpdateInfoModel(Cursor cursor) {
		UpdateInfoModel update = new UpdateInfoModel();
		update.setId(cursor.getInt(0));
		update.setUpdatePage(cursor.getString(1));
		update.setUpdateTitle(cursor.getString(2));
		int type = cursor.getInt(3);
		update.setUpdateType(UpdateType.values()[type]);
		update.setUpdateDate(new Date(cursor.getLong(4)*1000));
		return update;
	}

	/*
	 * Query Stuff
	 */

	public static ArrayList<UpdateInfoModel> getAllUpdateHistory(SQLiteDatabase db) {
		ArrayList<UpdateInfoModel> updates = new ArrayList<UpdateInfoModel>();

		Cursor cursor = helper.rawQuery(db, "select * from " + DBHelper.TABLE_UPDATE_HISTORY
					                   + " order by case "
					                   + "   when " + DBHelper.COLUMN_UPDATE_TYPE + " = " + UpdateType.UpdateTos.ordinal() + " then 0 "
					                   + "   when " + DBHelper.COLUMN_UPDATE_TYPE + " = " + UpdateType.NewNovel.ordinal() + " then 1 "
					                   + "   when " + DBHelper.COLUMN_UPDATE_TYPE + " = " + UpdateType.New.ordinal() + " then 2 "
					                   + "   when " + DBHelper.COLUMN_UPDATE_TYPE + " = " + UpdateType.Updated.ordinal() + " then 3 "
					                   + "   else 4 end "
					                   + ", " + DBHelper.COLUMN_LAST_UPDATE + " desc "
					                   + ", " + DBHelper.COLUMN_PAGE, null);
		try {
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				UpdateInfoModel update = cursorToUpdateInfoModel(cursor);
				updates.add(update);
				cursor.moveToNext();
			}
		} finally{
			if(cursor != null) cursor.close();
		}

		return updates;
	}

	public static UpdateInfoModel getUpdateHistory(SQLiteDatabase db, UpdateInfoModel update) {
		UpdateInfoModel result = null;

		Cursor cursor = helper.rawQuery(db, "select * from " + DBHelper.TABLE_UPDATE_HISTORY
										 + " where " + DBHelper.COLUMN_PAGE + " = ? "
				                   , new String[] {update.getUpdatePage()});
		try {
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				result = cursorToUpdateInfoModel(cursor);
				break;
			}
		} finally{
			if(cursor != null) cursor.close();
		}

		return result;
	}

	/*
	 * Insert Stuff
	 */

	public static int insertUpdateHistory(SQLiteDatabase db, UpdateInfoModel update) {
		UpdateInfoModel tempUpdate = getUpdateHistory(db, update);

		ContentValues cv = new ContentValues();
		cv.put(DBHelper.COLUMN_PAGE, update.getUpdatePage());
		cv.put(DBHelper.COLUMN_UPDATE_TITLE, update.getUpdateTitle());
		cv.put(DBHelper.COLUMN_UPDATE_TYPE, update.getUpdateType().ordinal());
		cv.put(DBHelper.COLUMN_LAST_UPDATE, (int) (update.getUpdateDate().getTime() / 1000));

		if(tempUpdate == null) {
			return (int) helper.insertOrThrow(db, DBHelper.TABLE_UPDATE_HISTORY, null, cv);
		}
		else {
			return helper.update(db, DBHelper.TABLE_UPDATE_HISTORY, cv, DBHelper.COLUMN_ID + " = ? ", new String[] {"" + tempUpdate.getId()});
		}
	}

	/*
	 * Delete Stuff
	 */

	public static void deleteAllUpdateHistory(SQLiteDatabase db) {
		db.execSQL("DROP TABLE IF EXISTS " + DBHelper.TABLE_UPDATE_HISTORY);
		db.execSQL(DATABASE_CREATE_UPDATE_HISTORY);
		Log.d(TAG, "Recreate " + DBHelper.TABLE_UPDATE_HISTORY);
	}

	public static int deleteUpdateHistory(SQLiteDatabase db, UpdateInfoModel updateInfo) {
		Log.d(TAG, "Deleting UpdateInfoModel id: " + updateInfo.getId());
		return helper.delete(db, DBHelper.TABLE_UPDATE_HISTORY, DBHelper.COLUMN_ID + " = ? "
				 , new String[] {updateInfo.getId() + ""});
	}
}


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

#include "components/password_manager/core/browser/password_store_proxy_backend.h"
#include <memory>
#include <utility>
#include <vector>

#include "base/barrier_callback.h"
#include "base/barrier_closure.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/functional/identity.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/ranges/algorithm.h"
#include "base/strings/strcat.h"
#include "components/password_manager/core/browser/field_info_table.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/sync/model/proxy_model_type_controller_delegate.h"

namespace password_manager {

namespace {

using MethodName = base::StrongAlias<struct MethodNameTag, std::string>;

bool IsPasswordUniquePtrLess(const std::unique_ptr<PasswordForm>& lhs,
                             const std::unique_ptr<PasswordForm>& rhs) {
  return PasswordFormUniqueKey(*lhs) < PasswordFormUniqueKey(*rhs);
}

bool IsPasswordUniquePtrWithSameKeyInconsistent(
    const std::unique_ptr<PasswordForm>& lhs,
    const std::unique_ptr<PasswordForm>& rhs) {
  return lhs->password_value != rhs->password_value;
}

void InvokeCallbackWithCombinedStatus(base::OnceCallback<void(bool)> completion,
                                      std::vector<bool> statuses) {
  std::move(completion).Run(base::ranges::all_of(statuses, base::identity()));
}

// Records the difference metrics between |main_result| and |backend_result|
// when returned by |method_name|. |main_result| and |backend_result| must be
// vectors of type T. |is_less| can be used to compare two objects of type T.
// |is_inconsistent| can be used to compute if the two objects have inconsistent
// password values.
template <typename T, typename IsLess, typename IsInconsistent>
void RecordMetrics(const MethodName& method_name,
                   const std::vector<T>& main_result,
                   const std::vector<T>& backend_result,
                   IsLess is_less,
                   IsInconsistent is_inconsistent) {
  // Comparison is done by creating two sets that contain pointers to the
  // objects stored in |main_result| and |backend_result|. Using the passed
  // comparison methods, we compute and report metrics regarding the difference
  // between both result vectors.
  auto is_less_ptr = [is_less](const T* lhs, const T* rhs) {
    return is_less(*lhs, *rhs);
  };

  auto address_of = [](const T& object) { return &object; };

  auto main_elements =
      base::MakeFlatSet<const T*>(main_result, is_less_ptr, address_of);
  auto shadow_elements =
      base::MakeFlatSet<const T*>(backend_result, is_less_ptr, address_of);

  auto common_elements = [&] {
    std::vector<const T*> vec;
    vec.reserve(main_elements.size());
    base::ranges::set_intersection(main_elements, shadow_elements,
                                   std::back_inserter(vec), is_less_ptr);
    return base::flat_set<const T*, decltype(is_less_ptr)>(std::move(vec),
                                                           is_less_ptr);
  }();

  // The cardinalities from which we compute the metrics.
  size_t main_minus_shadow = main_elements.size() - common_elements.size();
  size_t shadow_minus_main = shadow_elements.size() - common_elements.size();
  size_t diff = main_minus_shadow + shadow_minus_main;
  size_t total = diff + common_elements.size();
  size_t inconsistent = base::ranges::count_if(common_elements, [&](auto* f) {
    auto lhs = main_elements.find(f);
    auto rhs = shadow_elements.find(f);
    DCHECK(lhs != main_elements.end());
    DCHECK(rhs != shadow_elements.end());
    return (*is_inconsistent)(**lhs, **rhs);
  });

  // Emits a pair of absolute and relative metrics.
  auto Emit = [&method_name](base::StringPiece metric_infix, size_t nominator,
                             size_t denominator) {
    std::string prefix =
        base::StrCat({"PasswordManager.PasswordStoreProxyBackend.",
                      method_name.value(), ".", metric_infix, "."});
    base::UmaHistogramCounts1M(prefix + "Abs", nominator);
    if (denominator != 0) {
      size_t ceiling_of_percentage =
          (nominator * 100 + denominator - 1) / denominator;
      base::UmaHistogramPercentage(prefix + "Rel", ceiling_of_percentage);
    }
  };
  Emit("Diff", diff, total);
  Emit("MainMinusShadow", main_minus_shadow, total);
  Emit("ShadowMinusMain", shadow_minus_main, total);
  Emit("InconsistentPasswords", inconsistent, common_elements.size());
}

// Records the metrics of a pair of MethodName calls to the main and
// the shadow backends once both calls are finished.
//
// The class is ref-counted because it is equally owned by the two parallel
// method calls : it must outlive the first returning one and shall  be
// destroyed after the second one returns.
class ShadowTrafficMetricsRecorder
    : public base::RefCounted<ShadowTrafficMetricsRecorder> {
 public:
  explicit ShadowTrafficMetricsRecorder(MethodName method_name)
      : method_name_(std::move(method_name)) {}

  // Returns the unchanged |result| so it can be passed to the main handler.
  LoginsResultOrError RecordMainLoginsResultOrError(
      LoginsResultOrError logins_or_error) {
    if (absl::holds_alternative<PasswordStoreBackendError>(logins_or_error)) {
      return logins_or_error;
    }

    LoginsResult logins = std::move(absl::get<LoginsResult>(logins_or_error));
    if (!first_result_) {
      first_result_ = absl::make_optional<LoginsResult>();
      first_result_->reserve(logins.size());
      for (const auto& login : logins)
        first_result_->push_back(std::make_unique<PasswordForm>(*login));
    } else {
      RecordMetrics(method_name_, /*main_result=*/logins,
                    /*shadow_result=*/*first_result_, &IsPasswordUniquePtrLess,
                    &IsPasswordUniquePtrWithSameKeyInconsistent);
    }

    return logins;
  }

  void RecordShadowLoginsResultOrError(LoginsResultOrError logins_or_error) {
    if (absl::holds_alternative<PasswordStoreBackendError>(logins_or_error)) {
      return;
    }

    LoginsResult logins = std::move(absl::get<LoginsResult>(logins_or_error));
    if (!first_result_)
      first_result_ = std::move(logins);
    else
      RecordMetrics(method_name_, /*main_result=*/*first_result_,
                    /*shadow_result=*/logins, &IsPasswordUniquePtrLess,
                    &IsPasswordUniquePtrWithSameKeyInconsistent);
  }

 private:
  friend class RefCounted<ShadowTrafficMetricsRecorder>;
  ~ShadowTrafficMetricsRecorder() = default;

  // Stores the result of the backend that returns first.
  absl::optional<LoginsResult> first_result_;
  const MethodName method_name_;
};

}  // namespace

PasswordStoreProxyBackend::PasswordStoreProxyBackend(
    PasswordStoreBackend* main_backend,
    PasswordStoreBackend* shadow_backend,
    base::RepeatingCallback<bool()> is_syncing_passwords_callback)
    : main_backend_(main_backend),
      shadow_backend_(shadow_backend),
      is_syncing_passwords_callback_(std::move(is_syncing_passwords_callback)) {
}

PasswordStoreProxyBackend::~PasswordStoreProxyBackend() = default;

base::WeakPtr<PasswordStoreBackend> PasswordStoreProxyBackend::GetWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

void PasswordStoreProxyBackend::InitBackend(
    RemoteChangesReceived remote_form_changes_received,
    base::RepeatingClosure sync_enabled_or_disabled_cb,
    base::OnceCallback<void(bool)> completion) {
  base::RepeatingCallback<void(bool)> pending_initialization_calls =
      base::BarrierCallback<bool>(
          /*num_callbacks=*/2, base::BindOnce(&InvokeCallbackWithCombinedStatus,
                                              std::move(completion)));

  main_backend_->InitBackend(std::move(remote_form_changes_received),
                             std::move(sync_enabled_or_disabled_cb),
                             base::BindOnce(pending_initialization_calls));
  shadow_backend_->InitBackend(base::DoNothing(), base::DoNothing(),
                               base::BindOnce(pending_initialization_calls));
}

void PasswordStoreProxyBackend::Shutdown(base::OnceClosure shutdown_completed) {
  base::RepeatingClosure pending_shutdown_calls = base::BarrierClosure(
      /*num_closures=*/2, std::move(shutdown_completed));
  main_backend_->Shutdown(pending_shutdown_calls);
  shadow_backend_->Shutdown(pending_shutdown_calls);
}

void PasswordStoreProxyBackend::GetAllLoginsAsync(LoginsOrErrorReply callback) {
  scoped_refptr<ShadowTrafficMetricsRecorder> handler =
      base::MakeRefCounted<ShadowTrafficMetricsRecorder>(
          MethodName("GetAllLoginsAsync"));
  main_backend_->GetAllLoginsAsync(
      base::BindOnce(
          &ShadowTrafficMetricsRecorder::RecordMainLoginsResultOrError, handler)
          .Then(std::move(callback)));

  if (is_syncing_passwords_callback_.Run() &&
      base::FeatureList::IsEnabled(
          features::kUnifiedPasswordManagerShadowAndroid)) {
    shadow_backend_->GetAllLoginsAsync(base::BindOnce(
        &ShadowTrafficMetricsRecorder::RecordShadowLoginsResultOrError,
        handler));
  }
}

void PasswordStoreProxyBackend::GetAutofillableLoginsAsync(
    LoginsOrErrorReply callback) {
  main_backend_->GetAutofillableLoginsAsync(std::move(callback));
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

void PasswordStoreProxyBackend::FillMatchingLoginsAsync(
    LoginsReply callback,
    bool include_psl,
    const std::vector<PasswordFormDigest>& forms) {
  main_backend_->FillMatchingLoginsAsync(std::move(callback), include_psl,
                                         forms);
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

void PasswordStoreProxyBackend::AddLoginAsync(
    const PasswordForm& form,
    PasswordStoreChangeListReply callback) {
  main_backend_->AddLoginAsync(form, std::move(callback));
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

void PasswordStoreProxyBackend::UpdateLoginAsync(
    const PasswordForm& form,
    PasswordStoreChangeListReply callback) {
  main_backend_->UpdateLoginAsync(form, std::move(callback));
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

void PasswordStoreProxyBackend::RemoveLoginAsync(
    const PasswordForm& form,
    PasswordStoreChangeListReply callback) {
  main_backend_->RemoveLoginAsync(form, std::move(callback));
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

void PasswordStoreProxyBackend::RemoveLoginsByURLAndTimeAsync(
    const base::RepeatingCallback<bool(const GURL&)>& url_filter,
    base::Time delete_begin,
    base::Time delete_end,
    base::OnceCallback<void(bool)> sync_completion,
    PasswordStoreChangeListReply callback) {
  main_backend_->RemoveLoginsByURLAndTimeAsync(
      url_filter, std::move(delete_begin), std::move(delete_end),
      std::move(sync_completion), std::move(callback));
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

void PasswordStoreProxyBackend::RemoveLoginsCreatedBetweenAsync(
    base::Time delete_begin,
    base::Time delete_end,
    PasswordStoreChangeListReply callback) {
  main_backend_->RemoveLoginsCreatedBetweenAsync(
      std::move(delete_begin), std::move(delete_end), std::move(callback));
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

void PasswordStoreProxyBackend::DisableAutoSignInForOriginsAsync(
    const base::RepeatingCallback<bool(const GURL&)>& origin_filter,
    base::OnceClosure completion) {
  main_backend_->DisableAutoSignInForOriginsAsync(origin_filter,
                                                  std::move(completion));
  // TODO(crbug.com/1229655): Request shadow_backend_ and compare results.
}

SmartBubbleStatsStore* PasswordStoreProxyBackend::GetSmartBubbleStatsStore() {
  return main_backend_->GetSmartBubbleStatsStore();
}

FieldInfoStore* PasswordStoreProxyBackend::GetFieldInfoStore() {
  return main_backend_->GetFieldInfoStore();
}

std::unique_ptr<syncer::ProxyModelTypeControllerDelegate>
PasswordStoreProxyBackend::CreateSyncControllerDelegate() {
  return main_backend_->CreateSyncControllerDelegate();
}

}  // namespace password_manager


text:
import { FormControl } from '@angular/forms';

export interface JavaSettingsControls {
  majorVersion: FormControl;
  minorVersion: FormControl;
  webContainer: FormControl;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module LigneCommande</title>
<meta charset="utf-8">

<big><big>LigneCommande</big></big> (version 1.0)	index
d:\git\pconc\lignecommande.pyw

<tt>Projet          : Editeur, Compilateur et Micro-Ordinateur pour

                  un langage assembleur.

Nom du fichier  : LigneCommande.py

Identification  : LigneCommande

Titre           : Programme «ligne de commande» du projet

Auteurs         : Francis Emond, Malek Khattech,

                  Mamadou Dia, Marc-André Jean

Date            : 13-04-2017

Description     : Démmarrage de l'application en interpréteur.

Le module ``LigneCommande``

================================

Ce module s'occupe de démarrer l'application en mode «ligne de

commande» et de rassembler tous les modules. Les lignes de code

ci-dessous s'occupent de démarrer l'interface après que tous les

modules soient chargés.</tt>

<big>Modules</big>

<tt>      </tt>

FixTk

importlib

	Modules/05-Enum

Modules/01-01-Ordinateur

	re

sys

	_tkinter

<big>Data</big>

<tt>      </tt>
ACTIVE = 'active'

ALL = 'all'

ANCHOR = 'anchor'

ARC = 'arc'

BASELINE = 'baseline'

BEVEL = 'bevel'

BOTH = 'both'

BOTTOM = 'bottom'

BROWSE = 'browse'

BUTT = 'butt'

CASCADE = 'cascade'

CENTER = 'center'

CHAR = 'char'

CHECKBUTTON = 'checkbutton'

CHORD = 'chord'

COMMAND = 'command'

CURRENT = 'current'

DISABLED = 'disabled'

DOTBOX = 'dotbox'

E = 'e'

END = 'end'

EW = 'ew'

EXCEPTION = 8

EXTENDED = 'extended'

FALSE = 0

FIRST = 'first'

FLAT = 'flat'

GROOVE = 'groove'

HIDDEN = 'hidden'

HORIZONTAL = 'horizontal'

INSERT = 'insert'

INSIDE = 'inside'

LAST = 'last'

LEFT = 'left'

MITER = 'miter'

MOVETO = 'moveto'

MULTIPLE = 'multiple'

N = 'n'

NE = 'ne'

NO = 0

NONE = 'none'

NORMAL = 'normal'

NS = 'ns'

NSEW = 'nsew'

NUMERIC = 'numeric'

NW = 'nw'

OFF = 0

ON = 1

OUTSIDE = 'outside'

PAGES = 'pages'

PIESLICE = 'pieslice'

PROJECTING = 'projecting'

RADIOBUTTON = 'radiobutton'

RAISED = 'raised'

READABLE = 2

RIDGE = 'ridge'

RIGHT = 'right'

ROUND = 'round'

S = 's'

SCROLL = 'scroll'

SE = 'se'

SEL = 'sel'

SEL_FIRST = 'sel.first'

SEL_LAST = 'sel.last'

SEPARATOR = 'separator'

SINGLE = 'single'

SOLID = 'solid'

SUNKEN = 'sunken'

SW = 'sw'

StringTypes = (<type 'str'>, <type 'unicode'>)

TOP = 'top'

TRUE = 1

TclVersion = 8.5

TkVersion = 8.5

UNDERLINE = 'underline'

UNITS = 'units'

VERTICAL = 'vertical'

W = 'w'

WORD = 'word'

WRITABLE = 4

X = 'x'

Y = 'y'

YES = 1

__author__ = 'Francis Emond, Malek Khattech, Mamadou Dia, Marc-Andre Jean'

__status__ = 'Production'

__version__ = '1.0'

wantobjects = 1

<big>Author</big>

<tt>      </tt>
Francis Emond, Malek Khattech, Mamadou Dia, Marc-Andre Jean


text:
package firestore

// A simple mock server.

import (
	"context"
	"fmt"
	"sort"
	"strings"

	"cloud.google.com/go/internal/testutil"
	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes/empty"
	pb "google.golang.org/genproto/googleapis/firestore/v1beta1"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type mockServer struct {
	pb.FirestoreServer

	Addr string

	reqItems []reqItem
	resps    []interface{}
}

type reqItem struct {
	wantReq proto.Message
	adjust  func(gotReq proto.Message)
}

func newMockServer() (*mockServer, error) {
	srv, err := testutil.NewServer()
	if err != nil {
		return nil, err
	}
	mock := &mockServer{Addr: srv.Addr}
	pb.RegisterFirestoreServer(srv.Gsrv, mock)
	srv.Start()
	return mock, nil
}

// addRPC adds a (request, response) pair to the server's list of expected
// interactions. The server will compare the incoming request with wantReq
// using proto.Equal. The response can be a message or an error.
//
// For the Listen RPC, resp should be a []interface{}, where each element
// is either ListenResponse or an error.
//
// Passing nil for wantReq disables the request check.
func (s *mockServer) addRPC(wantReq proto.Message, resp interface{}) {
	s.addRPCAdjust(wantReq, resp, nil)
}

// addRPCAdjust is like addRPC, but accepts a function that can be used
// to tweak the requests before comparison, for example to adjust for
// randomness.
func (s *mockServer) addRPCAdjust(wantReq proto.Message, resp interface{}, adjust func(proto.Message)) {
	s.reqItems = append(s.reqItems, reqItem{wantReq, adjust})
	s.resps = append(s.resps, resp)
}

// popRPC compares the request with the next expected (request, response) pair.
// It returns the response, or an error if the request doesn't match what
// was expected or there are no expected rpcs.
func (s *mockServer) popRPC(gotReq proto.Message) (interface{}, error) {
	if len(s.reqItems) == 0 {
		panic("out of RPCs")
	}
	ri := s.reqItems[0]
	s.reqItems = s.reqItems[1:]
	if ri.wantReq != nil {
		if ri.adjust != nil {
			ri.adjust(gotReq)
		}

		// Sort FieldTransforms by FieldPath, since slice order is undefined and proto.Equal
		// is strict about order.
		switch gotReqTyped := gotReq.(type) {
		case *pb.CommitRequest:
			for _, w := range gotReqTyped.Writes {
				switch opTyped := w.Operation.(type) {
				case *pb.Write_Transform:
					sort.Sort(ByFieldPath(opTyped.Transform.FieldTransforms))
				}
			}
		}

		if !proto.Equal(gotReq, ri.wantReq) {
			return nil, fmt.Errorf("mockServer: bad request\ngot:  %T\n%s\nwant: %T\n%s",
				gotReq, proto.MarshalTextString(gotReq),
				ri.wantReq, proto.MarshalTextString(ri.wantReq))
		}
	}
	resp := s.resps[0]
	s.resps = s.resps[1:]
	if err, ok := resp.(error); ok {
		return nil, err
	}
	return resp, nil
}

func (a ByFieldPath) Len() int           { return len(a) }
func (a ByFieldPath) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByFieldPath) Less(i, j int) bool { return a[i].FieldPath < a[j].FieldPath }

type ByFieldPath []*pb.DocumentTransform_FieldTransform

func (s *mockServer) reset() {
	s.reqItems = nil
	s.resps = nil
}

func (s *mockServer) GetDocument(_ context.Context, req *pb.GetDocumentRequest) (*pb.Document, error) {
	res, err := s.popRPC(req)
	if err != nil {
		return nil, err
	}
	return res.(*pb.Document), nil
}

func (s *mockServer) Commit(_ context.Context, req *pb.CommitRequest) (*pb.CommitResponse, error) {
	res, err := s.popRPC(req)
	if err != nil {
		return nil, err
	}
	return res.(*pb.CommitResponse), nil
}

func (s *mockServer) BatchGetDocuments(req *pb.BatchGetDocumentsRequest, bs pb.Firestore_BatchGetDocumentsServer) error {
	res, err := s.popRPC(req)
	if err != nil {
		return err
	}
	responses := res.([]interface{})
	for _, res := range responses {
		switch res := res.(type) {
		case *pb.BatchGetDocumentsResponse:
			if err := bs.Send(res); err != nil {
				return err
			}
		case error:
			return res
		default:
			panic(fmt.Sprintf("bad response type in BatchGetDocuments: %+v", res))
		}
	}
	return nil
}

func (s *mockServer) RunQuery(req *pb.RunQueryRequest, qs pb.Firestore_RunQueryServer) error {
	res, err := s.popRPC(req)
	if err != nil {
		return err
	}
	responses := res.([]interface{})
	for _, res := range responses {
		switch res := res.(type) {
		case *pb.RunQueryResponse:
			if err := qs.Send(res); err != nil {
				return err
			}
		case error:
			return res
		default:
			panic(fmt.Sprintf("bad response type in RunQuery: %+v", res))
		}
	}
	return nil
}

func (s *mockServer) BeginTransaction(_ context.Context, req *pb.BeginTransactionRequest) (*pb.BeginTransactionResponse, error) {
	res, err := s.popRPC(req)
	if err != nil {
		return nil, err
	}
	return res.(*pb.BeginTransactionResponse), nil
}

func (s *mockServer) Rollback(_ context.Context, req *pb.RollbackRequest) (*empty.Empty, error) {
	res, err := s.popRPC(req)
	if err != nil {
		return nil, err
	}
	return res.(*empty.Empty), nil
}

func (s *mockServer) Listen(stream pb.Firestore_ListenServer) error {
	req, err := stream.Recv()
	if err != nil {
		return err
	}
	responses, err := s.popRPC(req)
	if err != nil {
		if status.Code(err) == codes.Unknown && strings.Contains(err.Error(), "mockServer") {
			// The stream will retry on Unknown, but we don't want that to happen if
			// the error comes from us.
			panic(err)
		}
		return err
	}
	for _, res := range responses.([]interface{}) {
		if err, ok := res.(error); ok {
			return err
		}
		if err := stream.Send(res.(*pb.ListenResponse)); err != nil {
			return err
		}
	}
	return nil
}


text:
package com.jaf.examples.concurrent.part4;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * TODO
 *
 * @author liaozhicheng.cn@163.com
 * @since 1.0
 */
public class AtomicReferenceTest {

	/**
	 * AtomicReference 对任意对象的引用进行多线程下安全更新 {@link AtomicReference#compareAndSet(Object, Object)}
	 * (更新前的值, 期望更新的值)
	 */
	public static void main(String[] args) throws InterruptedException {
		final Person p100 = new Person(100, "zhangsan");
		final AtomicReference<Person> atomicRef = new AtomicReference<Person>(p100);

		// 100个线程对该来同时更新该Person对象,但只会有随机的一个线程能够更新成功,其他的都会失败
		final Random random = new Random();
		final CountDownLatch latch = new CountDownLatch(100);
		for (int i = 0; i < 100; i++) {
			new Thread(new Runnable() {
				public void run() {
					try {
						Thread.sleep(random.nextInt(1000));

						String threadName = Thread.currentThread().getName();
						if (atomicRef.compareAndSet(p100, new Person(Integer.parseInt(threadName), "person"))) {
							System.out.println(Thread.currentThread().getName() + " change value success");
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						latch.countDown();
					}
				}
			}, i+"").start();
		}

		latch.await();
		Person p = atomicRef.get();
		System.out.println(p.getId() + " : " + p.getName());
	}

	private static class Person {

		private final int id;
		private final String name;

		Person(int id, String name) {
			this.id = id;
			this.name = name;
		}

		public int getId() {
			return id;
		}

		public String getName() {
			return name;
		}
	}

}


text:
package leshainc.mechanical.client;

import leshainc.mechanical.CommonProxy;
import leshainc.mechanical.Mechanical;
import leshainc.mechanical.block.BlockConveyor;
import leshainc.mechanical.block.Blocks;
import leshainc.mechanical.client.render.RenderConveyor;
import leshainc.mechanical.tile.TileConveyor;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.obj.OBJLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;

@SuppressWarnings("unused")
public class ClientProxy extends CommonProxy {
    @SuppressWarnings("unused")
    @Mod.EventBusSubscriber(modid = Mechanical.MODID)
    public static class Registration extends CommonProxy {
        @SubscribeEvent
        public static void registerModels(ModelRegistryEvent event) {
            OBJLoader.INSTANCE.addDomain(Mechanical.MODID);

            ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(Blocks.CONCRETE), 0,
                    new ModelResourceLocation(Blocks.CONCRETE.getRegistryName(), "inventory"));

            ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(Blocks.SCAFFOLDING), 0,
                    new ModelResourceLocation(Blocks.SCAFFOLDING.getRegistryName(), "inventory"));

            ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(Blocks.CONVEYOR), 0,
                    new ModelResourceLocation(Blocks.CONVEYOR.getRegistryName(), "inventory"));

            ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(Blocks.LADDER), 0,
                    new ModelResourceLocation(Blocks.LADDER.getRegistryName(), "inventory"));

            ClientRegistry.bindTileEntitySpecialRenderer(TileConveyor.class, new RenderConveyor());
        }

        @SubscribeEvent
        public static void registerTextures(TextureStitchEvent event) {
            event.getMap().registerSprite(new ResourceLocation(Mechanical.MODID, "block/conveyor_belt"));
        }
    }

    public void preInit(FMLPreInitializationEvent event) {
        super.preInit(event);
    }

    public void init(FMLInitializationEvent event) {
        super.init(event);
    }

    public void postInit(FMLPostInitializationEvent event) {
        super.postInit(event);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorAccentDark">#990081</color>
</resources>


text:
title: "3sum"
description: "Some description ..."
authors: ["lek-tin"]
tags: ["leetcode", "two-pointers"]
categories: ["algorithm"]
date: 2018-08-23T23:29:18+08:00
draft: false
archive: false
---
Given an array `nums` of `n` integers, are there elements `a, b, c` in `nums` such that `a + b + c = 0`? Find all unique triplets in the array which gives the sum of zero.

**Note**:
The solution set must not contain duplicate triplets.

### Example
```
Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
```
### Solution
```python
# time: o(n^2)
# space: o(1)
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        results = []

        if not nums:
            return results

        nums.sort()
        # low starts from 0, high starts from listLen - 1, so i needs to iterate between 1~(listLen-3)
        for i in range(0, len(nums)-2):
            num = nums[i]
            # i > 0 to prevent reading nums[0 - 1] when i == 0
            # skip duplicating starting points
            if i > 0 and nums[i] == nums[i-1]:
                continue
            left = i + 1
            right = len(nums) - 1
            while left < right:
                sum = nums[left] + nums[right]
                if sum + num == 0:
                    results.append([nums[left], num, nums[right]])
                    left += 1
                    right -= 1
                    # skip duplicates
                    while left < right and nums[left-1] == nums[left]:
                        left += 1
                    while left < right and nums[right] == nums[right+1]:
                        right -= 1
                elif sum + num < 0:
                    left += 1
                else:
                    right -= 1

        return results
```


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Batch.Blast.Batch;
using Microsoft.Azure.Batch.Blast.Storage;

namespace Microsoft.Azure.Batch.Blast.Configuration
{
    public class BlastConfigurationManager
    {
        public static readonly Dictionary<string, int> VmSizesWithCores = new Dictionary<string, int>
        {
            {"Standard_A1", 1},
            {"Standard_A2", 2},
            {"Standard_A3", 4},
            {"Standard_A4", 8},
            {"Standard_A5", 2},
            {"Standard_A6", 4},
            {"Standard_A7", 8},

            {"Standard_A10", 8},
            {"Standard_A11", 16},

            {"Standard_D1_v2", 1},
            {"Standard_D2_v2", 2},
            {"Standard_D3_v2", 4},
            {"Standard_D4_v2", 8},
            {"Standard_D5_v2", 16},
            {"Standard_D11_v2", 2},
            {"Standard_D12_v2", 4},
            {"Standard_D13_v2", 8},
            {"Standard_D14_v2", 16},
            {"Standard_D15_v2", 20},

            {"Standard_F1", 1},
            {"Standard_F2", 2},
            {"Standard_F4", 4},
            {"Standard_F8", 8},
            {"Standard_F16", 16},

            {"Standard_G1", 2},
            {"Standard_G2", 4},
            {"Standard_G3", 8},
            {"Standard_G4", 16},
            {"Standard_G5", 32},
        };

        private readonly Dictionary<string, string> _defaultConfiguration =
            new Dictionary<string, string>
            {
                {"pool.keepalive", "false"},
                {"vm.sizes", string.Join(",", VmSizesWithCores.Select(kvp => kvp.Key + ":" + kvp.Value))},
                {"vm.image.publisher", "Canonical"},
                {"vm.image.offer", "UbuntuServer"},
                {"vm.image.sku", "16.04.0-LTS"},
                {"vm.image.version", "latest"},
                {"node.agent.sku", "batch.node.ubuntu 16.04"},
                {"import.vm.size", "Standard_A2"},
                {"import.vm.cores", "2"},
                {"import.vm.maxvms", "20"},
                {"import.vm.pool", ""},
            };

        private readonly StorageCredentials _storageCredentials;
        private readonly BatchCredentials _batchCredentials;

        public BlastConfigurationManager(
            StorageCredentials storageCredentials,
            BatchCredentials batchCredentials)
        {
            _storageCredentials = storageCredentials;
            _batchCredentials = batchCredentials;
        }

        public BlastConfiguration GetConfiguration()
        {
            return new BlastConfiguration(_defaultConfiguration, _storageCredentials, _batchCredentials);
        }
    }
}


text:
// NPP plugin platform for .Net v0.94.00 by Kasper B. Graversen etc.
//
// This file should stay in sync with the CPP project file
// "notepad-plus-plus/PowerEditor/src/WinControls/DockingWnd/Docking.h"
// found at
// https://github.com/notepad-plus-plus/notepad-plus-plus/blob/master/PowerEditor/src/WinControls/DockingWnd/Docking.h

using System;
using System.Runtime.InteropServices;

namespace Kbg.NppPluginNET.PluginInfrastructure
{

    [Flags]
    public enum NppTbMsg : uint
    {
        // styles for containers
        //CAPTION_TOP                = 1,
        //CAPTION_BOTTOM            = 0,

        // defines for docking manager
        CONT_LEFT = 0,
        CONT_RIGHT = 1,
        CONT_TOP = 2,
        CONT_BOTTOM = 3,
        DOCKCONT_MAX = 4,

        // mask params for plugins of internal dialogs
        DWS_ICONTAB = 0x00000001,            // Icon for tabs are available
        DWS_ICONBAR = 0x00000002,            // Icon for icon bar are available (currently not supported)
        DWS_ADDINFO = 0x00000004,            // Additional information are in use
        DWS_PARAMSALL = (DWS_ICONTAB | DWS_ICONBAR | DWS_ADDINFO),

        // default docking values for first call of plugin
        DWS_DF_CONT_LEFT = (CONT_LEFT << 28),    // default docking on left
        DWS_DF_CONT_RIGHT = (CONT_RIGHT << 28),    // default docking on right
        DWS_DF_CONT_TOP = (CONT_TOP << 28),        // default docking on top
        DWS_DF_CONT_BOTTOM = (CONT_BOTTOM << 28),    // default docking on bottom
        DWS_DF_FLOATING = 0x80000000            // default state is floating
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct NppTbData
    {
        public IntPtr hClient;            // HWND: client Window Handle
        public string pszName;            // TCHAR*: name of plugin (shown in window)
        public int dlgID;                // int: a funcItem provides the function pointer to start a dialog. Please parse here these ID
                                         // user modifications
        public NppTbMsg uMask;                // UINT: mask params: look to above defines
        public uint hIconTab;            // HICON: icon for tabs
        public string pszAddInfo;        // TCHAR*: for plugin to display additional informations
                                         // internal data, do not use !!!
        public RECT rcFloat;            // RECT: floating position
        public int iPrevCont;           // int: stores the privious container (toggling between float and dock)
        public string pszModuleName;    // const TCHAR*: it's the plugin file name. It's used to identify the plugin
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public RECT(int left, int top, int right, int bottom)
        {
            Left = left; Top = top; Right = right; Bottom = bottom;
        }
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>uk.co.platitech.diet-diary</groupId>
    <artifactId>diet-diary</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.7.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>1.2.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.10.19</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.26</version>
                <configuration>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8080</port>
                            <maxIdleTime>60000</maxIdleTime>
                        </connector>
                    </connectors>
                    <stopKey/>
                    <stopPort/>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
// ========== PREREQUISITES ====================================
// LIBRARY WILL NOT WORK UNTIL THIS IS DONE CORRECTLY
// =============================================================

// * Add debug/YouTubeDownloadLibrary.lib to debug linker
// * Add release/YouTubeDownloadLibrary.lib to release linker
// * Copy YouTubeDownloadLibrary.dll to your .exe folder
// * Copy ssleay32.dll to your .exe folder
// * Copy libeay32.dll to your .exe folder

// ========== REQUIRED INCLUDES =================================
//
// ==============================================================

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "YouTubeDownloadLibrary.h"

// ========== MAIN ==============================================
//
// ==============================================================

int main (int argc, char * argv[])
{
	// ========== STEP 1 ========================================
	// GETTING VIDEO INFORMATION
	// ==========================================================

	// Select video id from YouTube
	// This can be found in the YouTube URL
	// example: https://www.youtube.com/watch?v=-U-hf6go8as
	//		video ID is -U-hf6go8as

	std::string videoID = "-U-hf6go8as";

	// Use API to search for video.

	std::vector<YouTubeDownloadLibrary::Video> videos
		= YouTubeDownloadLibrary::YouTubeDownload::GetLink(videoID);

	if (videos.empty()) {
		std::cout << "Video not found." << std::endl
			<< "Check if you are using a valid video id or if you are connected to the internet";
		return -1; // Failure, exit program.
	}

	// ========== STEP 2 ========================================
	// SEARCH FOR WANTED VIDEO CONTAINER AND RESOLUTION
	// ==========================================================

	// Search the list of videos you got from the API search function in step 1 to select a video
	// you want to download.
	//
	// There are 2 methods...
	//
	// NOTE:
	//		Possible containers: (found in "YouTubeDownloadLibrary.h")
	//			.3pg, .flv, .mp4, .webm
	//
	//		Possible resolutions: (found in "YouTubeDownloadLibrary.h")
	//			144p, 240p, 270/360p, 360p, 480p, 720p, 1080p, 3072p
	//
	// SIDE NOTE: The resolution NA means resolution unknown. (DOES NOT MEAN CHOOSE ANY RESOLUTION).
	//					avoid using the NA option.

	YouTubeDownloadLibrary::Video video;
	int result;

		// ===== METHOD 1 =====
		// Search using exact container and resolution.

	result = YouTubeDownloadLibrary::YouTubeDownload::SearchVideo (
		videos,
		YouTubeDownloadLibrary::YouTubeDownload::Container::MP4,
		YouTubeDownloadLibrary::YouTubeDownload::Resolution::_1080P,
		video
		);

	if (result != 0) {
		std::cout << "The video format and resolution you have searched for is not available." << std::endl;
	}

		// ===== METHOD 2 =====
		// Search for a exact container, with highest or lowest resolution.

	result = YouTubeDownloadLibrary::YouTubeDownload::SearchVideo (
		videos,
		YouTubeDownloadLibrary::YouTubeDownload::Container::MP4,
		true, // Set value as true to get the highest findable resolution for container.
			  // Set false for lowest possible findable resolution.
		video
		);

	if (result < 0) {
		std::cout << "The video container you have searched for is not available" << std::endl;
	}

	// ========== STEP 3 ========================================
	// OPEN A FILE TO SAVE YOUR VIDEO TO
	// ==========================================================

	// Open a file stream.
	std::string filename = "MyDownloadedVideo.mp4";

		// Optional: create a file name based on the video id given at the beginning of program
		// and get the file extention directly from the video file you have searched for.

	switch (video.GetContainer())
		{
		case YouTubeDownloadLibrary::YouTubeDownload::Container::FLV:
			filename = videoID + ".flv";
			break;
		case YouTubeDownloadLibrary::YouTubeDownload::Container::MP4:
			filename = videoID + ".mp4";
			break;
		case YouTubeDownloadLibrary::YouTubeDownload::Container::_3PG:
			filename = videoID + ".3pg";
			break;
		case YouTubeDownloadLibrary::YouTubeDownload::Container::WEBM:
			filename = videoID + ".webm";
			break;
		default:
			return -1; // Extention not found.
			break;
		}

	std::fstream file;
	file.open(filename, std::ios::out | std::ios::binary | std::ios::trunc); // Important: open in binary out mode with trunc.

	// ========== STEP 4 ========================================
	// DOWNLOAD YOUR VIDEO TO FILE
	// ==========================================================

	// Download video to file using API.

	int bytesRemaining = YouTubeDownloadLibrary::YouTubeDownload::DownloadToHDD(
							video.GetURL(),
							file,
							true // Set this to true if you want a GUI progress bar showing download progress in console.
						);

	if (bytesRemaining == 0) {
		std::cout << "Download complete." << std::endl;
	} else if (bytesRemaining > 0) {
		std::cout << "Download incomplete, connection was interupted." << std::endl;
	} else {
		std::cout << "Download could not start, can not connect to host." << std::endl;
	}

	// ========== STEP 5 ========================================
	// CLOSE THE FILE YOU DOWNLOADED THE VIDEO TO
	// ==========================================================

	file.close();

	// Exit demo program.
	std::cin.get();

	return 0;
}


text:
<!doctype html>

    <title>Code coverage report for lib/config/watchable.js</title>
    <meta charset="utf-8">

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

Code coverage report for lib/config/watchable.js

        Statements: 78.38% (29 / 37)

        Branches: 50% (5 / 10)

        Functions: 100% (6 / 6)

        Lines: 79.41% (27 / 34)

All files » lib/config/ » watchable.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68	1
1

1

1
1

1
1

1

1
1

1
1
1

1
1

1

1

1
1

1

1
1

1
1
1
1

1
'use strict';
var utils = require('../utils'),
    path = require('path'),
    crypto = require('crypto'),
    fs = require('fs'),
    watchFileName,
    watchFile;

// Attempts to see if fs.watch will work. On some platforms, it doesn't.
// See: http://nodejs.org/api/fs.html#fs_caveats
// Sends the callback true if fs.watch will work, false if it won't
//
// Caveats:
// If there is no writable tmp directory, it will also return true, although
// a warning message will be displayed.
var changeDetected = false;

function check(cb) {
  var tmpdir;

  watchable.cb = cb;
  changeDetected = false;

  Iif (utils.isWindows) {
    tmpdir = process.env.TEMP;
  } else Eif (process.env.TMPDIR) {
    tmpdir = process.env.TMPDIR;
  } else {
    tmpdir = '/tmp';
  }

  watchFileName = path.join(tmpdir, 'nodemonCheckFsWatch' + crypto.randomBytes(16).toString('hex'));
  watchFile = fs.openSync(watchFileName, 'w');
  Iif (watchFile < 0) {
    utils.log.fail('Unable to write to temp directory. If you experience problems with file reloading, ensure ' + tmpdir + ' is writable.');
    cb(true);
    return;
  }
  fs.watch(watchFileName, function() {
    Eif (changeDetected) { return; }

    changeDetected = true;
    cb(true);
  });
  // This should trigger fs.watch, if it works
  fs.writeSync(watchFile, '1');

  setTimeout(function() { verify(); }, 250);
}

// Verifies that fs.watch was not triggered and sends false to the callback
var verify = function() {
  fs.unlinkSync(watchFileName);

  Iif (changeDetected) { return; }

  changeDetected = true; // prevents the `ready` being called twice
  watchable.cb(false);
};

var watchable = module.exports = function (config, ready) {
  check(function(success) {
    config.system.watchWorks = success;
    ready();
  });
};

watchable.check = check;

Generated by istanbul at Sun Jan 05 2014 01:50:14 GMT+0000 (GMT)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Model;

/**
 *
 * @author hinsenchan
 */
//application model director
public interface SecuritySimModelDirector {
    public SecuritySimModel build(SecuritySimModelBuilder builder);
}