text:
namespace mate {

namespace internal {

template <typename T>
class RefCountedGlobal;

// Manages the V8 function with RAII.
class SafeV8Function {
 public:
  SafeV8Function(v8::Isolate* isolate, v8::Local<v8::Value> value);
  SafeV8Function(const SafeV8Function& other);
  ~SafeV8Function();

  bool IsAlive() const;
  v8::Local<v8::Function> NewHandle(v8::Isolate* isolate) const;

 private:
  scoped_refptr<RefCountedGlobal<v8::Function>> v8_function_;
};

// Helper to invoke a V8 function with C++ parameters.
template <typename Sig>
struct V8FunctionInvoker {};

template <typename... ArgTypes>
struct V8FunctionInvoker<v8::Local<v8::Value>(ArgTypes...)> {
  static v8::Local<v8::Value> Go(v8::Isolate* isolate,
                                 const SafeV8Function& function,
                                 ArgTypes... raw) {
    Locker locker(isolate);
    v8::EscapableHandleScope handle_scope(isolate);
    if (!function.IsAlive())
      return v8::Null(isolate);
    v8::MicrotasksScope script_scope(isolate,
                                     v8::MicrotasksScope::kRunMicrotasks);
    v8::Local<v8::Function> holder = function.NewHandle(isolate);
    v8::Local<v8::Context> context = holder->CreationContext();
    v8::Context::Scope context_scope(context);
    std::vector<v8::Local<v8::Value>> args{
        ConvertToV8(isolate, std::forward<ArgTypes>(raw))...};
    v8::MaybeLocal<v8::Value> ret = holder->Call(
        context, holder, args.size(), args.empty() ? nullptr : &args.front());
    if (ret.IsEmpty())
      return v8::Undefined(isolate);
    else
      return handle_scope.Escape(ret.ToLocalChecked());
  }
};

template <typename... ArgTypes>
struct V8FunctionInvoker<void(ArgTypes...)> {
  static void Go(v8::Isolate* isolate,
                 const SafeV8Function& function,
                 ArgTypes... raw) {
    Locker locker(isolate);
    v8::HandleScope handle_scope(isolate);
    if (!function.IsAlive())
      return;
    v8::MicrotasksScope script_scope(isolate,
                                     v8::MicrotasksScope::kRunMicrotasks);
    v8::Local<v8::Function> holder = function.NewHandle(isolate);
    v8::Local<v8::Context> context = holder->CreationContext();
    v8::Context::Scope context_scope(context);
    std::vector<v8::Local<v8::Value>> args{
        ConvertToV8(isolate, std::forward<ArgTypes>(raw))...};
    holder
        ->Call(context, holder, args.size(),
               args.empty() ? nullptr : &args.front())
        .IsEmpty();
  }
};

template <typename ReturnType, typename... ArgTypes>
struct V8FunctionInvoker<ReturnType(ArgTypes...)> {
  static ReturnType Go(v8::Isolate* isolate,
                       const SafeV8Function& function,
                       ArgTypes... raw) {
    Locker locker(isolate);
    v8::HandleScope handle_scope(isolate);
    ReturnType ret = ReturnType();
    if (!function.IsAlive())
      return ret;
    v8::MicrotasksScope script_scope(isolate,
                                     v8::MicrotasksScope::kRunMicrotasks);
    v8::Local<v8::Function> holder = function.NewHandle(isolate);
    v8::Local<v8::Context> context = holder->CreationContext();
    v8::Context::Scope context_scope(context);
    std::vector<v8::Local<v8::Value>> args{
        ConvertToV8(isolate, std::forward<ArgTypes>(raw))...};
    v8::Local<v8::Value> result;
    auto maybe_result = holder->Call(context, holder, args.size(),
                                     args.empty() ? nullptr : &args.front());
    if (maybe_result.ToLocal(&result))
      Converter<ReturnType>::FromV8(isolate, result, &ret);
    return ret;
  }
};

// Helper to pass a C++ funtion to JavaScript.
using Translater = base::Callback<void(Arguments* args)>;
v8::Local<v8::Value> CreateFunctionFromTranslater(v8::Isolate* isolate,
                                                  const Translater& translater,
                                                  bool one_time);
v8::Local<v8::Value> BindFunctionWith(v8::Isolate* isolate,
                                      v8::Local<v8::Context> context,
                                      v8::Local<v8::Function> func,
                                      v8::Local<v8::Value> arg1,
                                      v8::Local<v8::Value> arg2);

// Calls callback with Arguments.
template <typename Sig>
struct NativeFunctionInvoker {};

template <typename ReturnType, typename... ArgTypes>
struct NativeFunctionInvoker<ReturnType(ArgTypes...)> {
  static void Go(base::Callback<ReturnType(ArgTypes...)> val, Arguments* args) {
    using Indices = typename IndicesGenerator<sizeof...(ArgTypes)>::type;
    Invoker<Indices, ArgTypes...> invoker(args, 0);
    if (invoker.IsOK())
      invoker.DispatchToCallback(val);
  }
};

}  // namespace internal

template <typename Sig>
struct Converter<base::RepeatingCallback<Sig>> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
                                   const base::RepeatingCallback<Sig>& val) {
    // We don't use CreateFunctionTemplate here because it creates a new
    // FunctionTemplate everytime, which is cached by V8 and causes leaks.
    internal::Translater translater =
        base::Bind(&internal::NativeFunctionInvoker<Sig>::Go, val);
    // To avoid memory leak, we ensure that the callback can only be called
    // for once.
    return internal::CreateFunctionFromTranslater(isolate, translater, true);
  }
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     base::RepeatingCallback<Sig>* out) {
    if (!val->IsFunction())
      return false;

    *out = base::BindRepeating(&internal::V8FunctionInvoker<Sig>::Go, isolate,
                               internal::SafeV8Function(isolate, val));
    return true;
  }
};

// Convert a callback to V8 without the call number limitation, this can easily
// cause memory leaks so use it with caution.
template <typename Sig>
v8::Local<v8::Value> CallbackToV8(v8::Isolate* isolate,
                                  const base::Callback<Sig>& val) {
  internal::Translater translater =
      base::Bind(&internal::NativeFunctionInvoker<Sig>::Go, val);
  return internal::CreateFunctionFromTranslater(isolate, translater, false);
}

}  // namespace mate

#endif  // SHELL_COMMON_NATIVE_MATE_CONVERTERS_CALLBACK_H_

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="ExDoc v0.19.2">
    <title>Core.Rpc.Error —  v9.1.0</title>
    <link rel="stylesheet" href="dist/html-c1666276880c0f8e3769.css" />

<button class="sidebar-button sidebar-toggle">

  Toggle Sidebar
</button>
<button class="sidebar-button night-mode-toggle">

  Toggle Theme
</button>

        v9.1.0

  <form class="sidebar-search" action="search.html">
    <button type="submit" class="search-button">

    </button>
    <input name="q" type="text" id="search-list" class="search-input" placeholder="Search" aria-label="Search" autocomplete="off" />
  </form>

Pages

Modules

Exceptions

         v9.1.0
Core.Rpc.Error exception

            Built using
            ExDoc (v0.19.2),

            designed by
            Friedel Ziegelmayer.


text:
namespace autofill_assistant {

// Allow the selection of one or more suggestions.
class PromptAction : public Action {
 public:
  explicit PromptAction(ActionDelegate* delegate, const ActionProto& proto);

  PromptAction(const PromptAction&) = delete;
  PromptAction& operator=(const PromptAction&) = delete;

  ~PromptAction() override;

 private:
  // Overrides Action:
  void InternalProcessAction(ProcessActionCallback callback) override;

  void RegisterChecks(
      BatchElementChecker* checker,
      base::OnceCallback<void(const ClientStatus&)> wait_for_dom_callback);
  void SetupConditions();
  bool HasNonemptyPreconditions();
  void OnPreconditionResult(
      size_t choice_index,
      const ClientStatus& status,
      const std::vector<std::string>& ignored_payloads,
      const std::vector<std::string>& ignored_tags,
      const base::flat_map<std::string, DomObjectFrameStack>& ignored_elements);
  void UpdateUserActions();
  void OnAutoSelectCondition(
      const ClientStatus& status,
      const std::vector<std::string>& payloads,
      const std::vector<std::string>& tags,
      const base::flat_map<std::string, DomObjectFrameStack>& ignored_elements);
  void OnElementChecksDone(
      base::OnceCallback<void(const ClientStatus&)> wait_for_dom_callback);
  void OnDoneWaitForDom(const ClientStatus& status);
  void OnSuggestionChosen(int choice_index);
  void OnNavigationEnded();
  void EndAction(const ClientStatus& status);
  void UpdateTimings();

  ProcessActionCallback callback_;

  // preconditions_[i] contains the element preconditions for
  // proto.prompt.choice[i].
  std::vector<ElementConditionProto> preconditions_;

  // precondition_results_[i] contains the last result reported by
  // preconditions_[i].
  std::vector<bool> precondition_results_;
  // positive_precondition_changes_[i] contains true only when the corresponding
  // preconditions_[i] changed from false to true in the last periodic checks.
  std::vector<bool> positive_precondition_changes_;
  // precondition_stopwatches_[i] contains a stopwatch with the active time for
  // preconditions_[i]. This will be 0 as long as preconditions_[i] is false
  // and will contain the sum of the time that the precondition checks required
  // to complete plus half the duration of the retry period.
  std::vector<Stopwatch> precondition_stopwatches_;

  // true if something in precondition_results_ has changed, which means that
  // the set of user actions must be updated.
  bool precondition_changed_ = false;

  // The action ends once this precondition matches. The payload points
  // to the specific choice that matched.
  absl::optional<ElementConditionProto> auto_select_;

  // If >= 0, contains the index of the Choice to auto-select. Set based or the
  // payload reported by |auto_select_|.
  int auto_select_choice_index_ = -1;

  // Batch element checker for preconditions and auto-selection.
  std::unique_ptr<BatchElementChecker> element_checker_;

  // This stopwatch contains the total wait time, needed all exit criteria
  // except the autoselect one.
  Stopwatch wait_time_stopwatch_;
  // Contains the duration of the last retry period.
  Stopwatch last_period_stopwatch_;
  // Contains the duration of the last precondition checks.
  Stopwatch last_checks_stopwatch_;

  base::WeakPtrFactory<PromptAction> weak_ptr_factory_{this};
};

}  // namespace autofill_assistant
#endif  // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_ACTIONS_PROMPT_ACTION_H_


text:
package org.apache.dubbo.registry.client;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.DefaultPage;
import org.apache.dubbo.common.utils.Page;
import org.apache.dubbo.event.EventDispatcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static java.util.Collections.emptyList;

/**
 * In-Memory {@link ServiceDiscovery} implementation
 *
 * @since 2.7.5
 */
public class InMemoryServiceDiscovery extends AbstractServiceDiscovery {

    private final EventDispatcher dispatcher = EventDispatcher.getDefaultExtension();

    private Map<String, List<ServiceInstance>> repository = new HashMap<>();

    private URL registryURL;

    @Override
    public Set<String> getServices() {
        return repository.keySet();
    }

    @Override
    public Page<ServiceInstance> getInstances(String serviceName, int offset, int pageSize, boolean healthyOnly) {
        List<ServiceInstance> instances = new ArrayList<>(repository.computeIfAbsent(serviceName, s -> new LinkedList<>()));
        int totalSize = instances.size();
        List<ServiceInstance> data = emptyList();
        if (offset < totalSize) {
            int toIndex = offset + pageSize > totalSize - 1 ? totalSize : offset + pageSize;
            data = instances.subList(offset, toIndex);
        }
        if (healthyOnly) {
            Iterator<ServiceInstance> iterator = data.iterator();
            while (iterator.hasNext()) {
                ServiceInstance instance = iterator.next();
                if (!instance.isHealthy()) {
                    iterator.remove();
                }
            }
        }
        return new DefaultPage<>(offset, pageSize, data, totalSize);
    }

    @Override
    public URL getUrl() {
        return registryURL;
    }

    public String toString() {
        return "InMemoryServiceDiscovery";
    }

    @Override
    public void doRegister(ServiceInstance serviceInstance) {
        String serviceName = serviceInstance.getServiceName();
        List<ServiceInstance> serviceInstances = repository.computeIfAbsent(serviceName, s -> new LinkedList<>());
        if (!serviceInstances.contains(serviceInstance)) {
            serviceInstances.add(serviceInstance);
        }
    }

    @Override
    public void doUpdate(ServiceInstance serviceInstance) {
        unregister(serviceInstance);
        register(serviceInstance);
    }

    @Override
    public void unregister(ServiceInstance serviceInstance) throws RuntimeException {
        String serviceName = serviceInstance.getServiceName();
        List<ServiceInstance> serviceInstances = repository.computeIfAbsent(serviceName, s -> new LinkedList<>());
        serviceInstances.remove(serviceInstance);
    }

    @Override
    public void initialize(URL registryURL) throws Exception {
        this.registryURL = registryURL;
    }

    @Override
    public void destroy() {
    }
}


text:
help(
[[
Quantum Espresso is an integrated suite of Open-Source computer codes for electronic-structure calculations and materials modeling at the nanoscale. It is based on density-functional theory, plane waves, and pseudopotentials.
]])

local version = "5.2"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/espresso/"..version
whatis("Quantum Espresso is an integrated suite of Open-Source computer codes for electronic-structure calculations")
prepend_path("PATH", base)
prepend_path("PATH", pathJoin(base, "bin"))
family('espresso')


text:
import { Document } from './Document'
import { TextElement } from './TextElement'

export class TSpanElement extends TextElement {
  override type = 'tspan'
  protected readonly text: string

  constructor(
    document: Document,
    node: HTMLElement,
    captureTextNodes?: boolean
  ) {
    super(
      document,
      node,
      new.target === TSpanElement
        ? true
        : captureTextNodes
    )

    // if this node has children, then they own the text
    this.text = this.children.length > 0
      ? ''
      : this.getTextFromNode()
  }

  override getText() {
    return this.text
  }
}


text:
"""
Working function with integer parameters and explicit maximization.
"""
# Future
from __future__ import absolute_import, division, print_function, \
    unicode_literals, with_statement

# First Party
from metaopt.core.paramspec.util import param
from metaopt.core.returnspec.util.decorator import maximize

@maximize("y")
@param.int("x", interval=[0, 10])
def f(x):
    return x


text:
'use strict';

var helper = require('../helpers/helper');
var express = require('express');
var router = express.Router();

var contractArtifact = require('../build/contracts/DebtManager.json');
var Web3 = require('web3');
var provider = new Web3.providers.HttpProvider("http://localhost:8545");
var web3 = new Web3(provider);

var account = '0x8a0643dfe5a35c75e75bfe241ec6e63f2170e201';

var contract = require("truffle-contract");
var DebtManager = contract(contractArtifact);
DebtManager.providers

/**
 * Get debts
 */
router.get('/', function (req, res) {

    //console.log(DebtManager);

    DebtManager.setProvider(provider);

    var meta;
    DebtManager.deployed().then(function(instance) {
    meta = instance;
    return meta.createOrder('test', account, {from: account});
    }).then(function(result) {
    // If this callback is called, the transaction was successfully processed.
    alert("Transaction successful!")
    }).catch(function(e) {
    // There was an error! Handle it.
    })

    res.json([]);
});

module.exports = router;


text:
title: Divide One Number by Another with JavaScript
localeTitle: قسمة رقم واحد على آخر باستخدام JavaScript
---
# قسمة رقم واحد على آخر باستخدام JavaScript

تستخدم جافا سكريبت الرمز `/` للقسمة.

 `var quotient = 6 / 3; //quotient will get value 2
`


text:
package ar.uba.fi.lfd.opencvcameratest;

import android.hardware.Camera;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.SurfaceView;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Size;

import java.util.List;
import java.util.ListIterator;

public class MainActivity extends ActionBarActivity {
    static {
        System.loadLibrary("opencv_java3");
    }

    private static final String TAG = MainActivity.class.getName();
    private ScreenNotifier notifier;
    private CameraViewListener cameraViewListener;

    private ToggleButton grayModeButton;
    private CustomCameraView cameraView;

    private BaseLoaderCallback openCVCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            if (status == LoaderCallbackInterface.SUCCESS) {
                Log.i(TAG, "OpenCV loaded successfully");
                cameraView.enableView();
            } else {
                Log.e(TAG, "Error on OpenCV loading");
                super.onManagerConnected(status);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "Application started.");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.notifier = new ScreenNotifier(this);
        this.cameraViewListener = new CameraViewListener(this.notifier);

        this.cameraView = (CustomCameraView)this.findViewById(R.id.camera_view);
        this.grayModeButton = (ToggleButton)this.findViewById(R.id.gray_mode);

        this.cameraView.setVisibility(SurfaceView.VISIBLE);
        this.cameraView.setCvCameraViewListener(this.cameraViewListener);
        this.grayModeButton.setOnCheckedChangeListener(this.grayModeListener);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, openCVCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            openCVCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }

    private List<Camera.Size> mResolutionList;
    private MenuItem[] mResolutionMenuItems;
    private SubMenu mResolutionMenu;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        mResolutionMenu = menu.addSubMenu("Resolution");
        mResolutionList = cameraView.getResolutionList();
        mResolutionMenuItems = new MenuItem[mResolutionList.size()];

        ListIterator<Camera.Size> resolutionItr = mResolutionList.listIterator();
        int idx = 0;
        while(resolutionItr.hasNext()) {
            Camera.Size element = resolutionItr.next();
            mResolutionMenuItems[idx] = mResolutionMenu.add(2, idx, Menu.NONE,
                    Integer.valueOf(element.width).toString() + "x" + Integer.valueOf(element.height).toString());
            idx++;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        if (item.getGroupId() == 2)
        {
            Camera.Size resolution = mResolutionList.get(id);
            cameraView.setResolution(resolution);
            resolution = cameraView.getResolution();
            String caption = Integer.valueOf(resolution.width).toString() + "x" + Integer.valueOf(resolution.height).toString();
            notifier.showDialog(caption);
            return true;
        }
        else
            return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        if (cameraView != null)
            cameraView.disableView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (cameraView != null)
            cameraView.disableView();
    }

    private CompoundButton.OnCheckedChangeListener grayModeListener = new CompoundButton.OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(CompoundButton v, boolean isChecked){
            try {
                if (isChecked) {
                    cameraViewListener.toGrayMode();
                } else {
                    cameraViewListener.toColorMode();
                }
            } catch (Exception e) {
                notifier.showError(e);
            }
        }
    };
}


text:
using System;

namespace ArmorGamesDownloader.Extensions
{
    public static class EnumExtension
    {
        // TODO Метод использует рефлексию, что медленно, но допустимо для редких обращений
        public static String GetStringValue(this Enum value)
        {
            string output = null;
            var attrs = value
                .GetType()
                .GetField(value.ToString())
                .GetCustomAttributes(typeof(StringValue), false) as StringValue[];

            if (attrs != null && attrs.Length > 0)
            {
                output = attrs[0].Value;
            }

            return output;
        }

        public class StringValue : Attribute
        {
            private string _value;

            public StringValue(string value)
            {
                _value = value;
            }

            public string Value
            {
                get { return _value; }
            }
        }
    }
}


text:
<?php
/**
 * Alert view helper styled for Bootstrap 3
 *
 * @author     Leandro Silva <leandro@leandrosilva.info>
 * @category   LosUi
 * @license    https://github.com/Lansoweb/LosUi/blob/master/LICENSE BSD-3 License
 * @link       http://github.com/LansoWeb/LosUi
 * @link       http://getbootstrap.com/components/#alerts
 */
namespace LosUi\View\Helper;

use Zend\Form\View\Helper\AbstractHelper;

/**
 * Alert view helper styled for Bootstrap 3
 *
 * @author     Leandro Silva <leandro@leandrosilva.info>
 * @category   LosUi
 * @license    https://github.com/Lansoweb/LosUi/blob/master/LICENSE BSD-3 License
 * @link       http://github.com/LansoWeb/LosUi
 * @link       http://getbootstrap.com/components/#alerts
 */
class Alert extends AbstractHelper
{
    protected $format = '
%s
';

    protected $formatDismissible = '
<button type="button" class="close" data-dismiss="alert">×Close</button>%s
';

    protected $isDismissible = false;

    public function info($alert)
    {
        return $this->render($alert, 'alert-info');
    }

    public function danger($alert)
    {
        return $this->render($alert, 'alert-danger');
    }

    public function error($alert)
    {
        return $this->danger($alert);
    }

    public function success($alert)
    {
        return $this->render($alert, 'alert-success');
    }

    public function warning($alert)
    {
        return $this->render($alert, 'alert-warning');
    }

    public function render($alert, $class = 'alert-warning')
    {
        $class = trim($class);

        if ($this->isDismissible) {
            return sprintf($this->formatDismissible, $class, $alert);
        } else {
            return sprintf($this->format, $class, $alert);
        }
    }

    public function setDismissible($dismissible)
    {
        if (! is_bool($dismissible)) {
            throw new \InvalidArgumentException("Argument must be a bool value.");
        }

        $this->isDismissible = $dismissible;

        return $this;
    }

    public function __invoke($alert = null, $class = 'alert-warning')
    {
        if ($alert) {
            return $this->render($alert, $class);
        }

        return $this;
    }
}


text:
:mod:`oasis.stratification`.stratify_by_scores
===========================================================

.. currentmodule:: oasis.stratification

.. autofunction:: stratify_by_scores

.. Not needed since there is no "Examples" section in the docstrings
.. .. include:: oasis.stratification.stratify_by_scores.examples

.. raw:: html


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>MediaPrintableArea (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.print.attribute.standard.MediaPrintableArea class">
<meta name="keywords" content="INCH">
<meta name="keywords" content="MM">
<meta name="keywords" content="getPrintableArea()">
<meta name="keywords" content="getX()">
<meta name="keywords" content="getY()">
<meta name="keywords" content="getWidth()">
<meta name="keywords" content="getHeight()">
<meta name="keywords" content="equals()">
<meta name="keywords" content="getCategory()">
<meta name="keywords" content="getName()">
<meta name="keywords" content="toString()">
<meta name="keywords" content="hashCode()">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.print.attribute.standard

Class MediaPrintableArea

java.lang.Object

javax.print.attribute.standard.MediaPrintableArea

All Implemented Interfaces:

Serializable, Attribute, DocAttribute, PrintJobAttribute, PrintRequestAttribute

public final class MediaPrintableArea
extends Object
implements DocAttribute, PrintRequestAttribute, PrintJobAttribute

Class MediaPrintableArea is a printing attribute used to distinguish
 the printable and non-printable areas of media.

 The printable area is specified to be a rectangle, within the overall
 dimensions of a media.

 Most printers cannot print on the entire surface of the media, due
 to printer hardware limitations. This class can be used to query
 the acceptable values for a supposed print job, and to request an area
 within the constraints of the printable area to be used in a print job.

 To query for the printable area, a client must supply a suitable context.
 Without specifying at the very least the size of the media being used
 no meaningful value for printable area can be obtained.

 The attribute is not described in terms of the distance from the edge
 of the paper, in part to emphasise that this attribute is not independent
 of a particular media, but must be described within the context of a
 choice of other attributes. Additionally it is usually more convenient
 for a client to use the printable area.

 The hardware's minimum margins is not just a property of the printer,
 but may be a function of the media size, orientation, media type, and
 any specified finishings.
 PrintService provides the method to query the supported
 values of an attribute in a suitable context :
 See  PrintService.getSupportedAttributeValues()

 The rectangular printable area is defined thus:
 The (x,y) origin is positioned at the top-left of the paper in portrait
 mode regardless of the orientation specified in the requesting context.
 For example a printable area for A4 paper in portrait or landscape
 orientation will have height > width.

 A printable area attribute's values are stored
 internally as integers in units of micrometers (µm), where 1 micrometer
 = 10-6 meter = 1/1000 millimeter = 1/25400 inch. This permits
 dimensions to be represented exactly to a precision of 1/1000 mm (= 1
 µm) or 1/100 inch (= 254 µm). If fractional inches are expressed in

 negative powers of two, this permits dimensions to be represented exactly to
 a precision of 1/8 inch (= 3175 µm) but not 1/16 inch (because 1/16 inch

 does not equal an integral number of µm).

 IPP Compatibility: MediaPrintableArea is not an IPP attribute.

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

static int
INCH

Value to indicate units of inches (in).

static int
MM

Value to indicate units of millimeters (mm).

Constructor Summary

Constructors

Constructor and Description

MediaPrintableArea(float x,
                  float y,
                  float w,
                  float h,
                  int units)

Constructs a MediaPrintableArea object from floating point values.

MediaPrintableArea(int x,
                  int y,
                  int w,
                  int h,
                  int units)

Constructs a MediaPrintableArea object from integer values.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
equals(Object object)

Returns whether this media margins attribute is equivalent to the passed
 in object.

Class<? extends Attribute>
getCategory()

Get the printing attribute class which is to be used as the "category"
 for this printing attribute value.

float
getHeight(int units)

Get the height of the printable area in the specified units.

String
getName()

Get the name of the category of which this attribute value is an
 instance.

float[]
getPrintableArea(int units)

Get the printable area as an array of 4 values in the order
 x, y, w, h.

float
getWidth(int units)

Get the width of the printable area in the specified units.

float
getX(int units)

Get the x location of the origin of the printable area in the
 specified units.

float
getY(int units)

Get the y location of the origin of the printable area in the
 specified units.

int
hashCode()

Returns a hash code value for this attribute.

String
toString()

Returns a string version of this rectangular size attribute in mm.

String
toString(int units,
        String unitsName)

Returns a string version of this rectangular size attribute in the
 given units.

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

INCH

public static final int INCH

Value to indicate units of inches (in). It is actually the conversion
 factor by which to multiply inches to yield µm (25400).

See Also:

Constant Field Values

MM

public static final int MM

Value to indicate units of millimeters (mm). It is actually the
 conversion factor by which to multiply mm to yield µm (1000).

See Also:

Constant Field Values

Constructor Detail

MediaPrintableArea

public MediaPrintableArea(float x,
                          float y,
                          float w,
                          float h,
                          int units)

Constructs a MediaPrintableArea object from floating point values.

Parameters:

x - printable x

y - printable y

w - printable width

h - printable height

units - in which the values are expressed.

Throws:

IllegalArgumentException - Thrown if x < 0 or y < 0
     or w <= 0 or h <= 0 or
     units < 1.

MediaPrintableArea

public MediaPrintableArea(int x,
                          int y,
                          int w,
                          int h,
                          int units)

Constructs a MediaPrintableArea object from integer values.

Parameters:

x - printable x

y - printable y

w - printable width

h - printable height

units - in which the values are expressed.

Throws:

IllegalArgumentException - Thrown if x < 0 or y < 0
     or w <= 0 or h <= 0 or
     units < 1.

Method Detail

getPrintableArea

public float[] getPrintableArea(int units)

Get the printable area as an array of 4 values in the order
 x, y, w, h. The values returned are in the given units.

Parameters:

units - Unit conversion factor, e.g. INCH or
     MM.

Returns:

printable area as array of x, y, w, h in the specified units.

Throws:

IllegalArgumentException - (unchecked exception) Thrown if units < 1.

getX

public float getX(int units)

Get the x location of the origin of the printable area in the
 specified units.

Parameters:

units - Unit conversion factor, e.g. INCH or
     MM.

Returns:

x location of the origin of the printable area in the
 specified units.

Throws:

IllegalArgumentException - (unchecked exception) Thrown if units < 1.

getY

public float getY(int units)

Get the y location of the origin of the printable area in the
 specified units.

Parameters:

units - Unit conversion factor, e.g. INCH or
     MM.

Returns:

y location of the origin of the printable area in the
 specified units.

Throws:

IllegalArgumentException - (unchecked exception) Thrown if units < 1.

getWidth

public float getWidth(int units)

Get the width of the printable area in the specified units.

Parameters:

units - Unit conversion factor, e.g. INCH or
     MM.

Returns:

width of the printable area in the specified units.

Throws:

IllegalArgumentException - (unchecked exception) Thrown if units < 1.

getHeight

public float getHeight(int units)

Get the height of the printable area in the specified units.

Parameters:

units - Unit conversion factor, e.g. INCH or
     MM.

Returns:

height of the printable area in the specified units.

Throws:

IllegalArgumentException - (unchecked exception) Thrown if units < 1.

equals

public boolean equals(Object object)

Returns whether this media margins attribute is equivalent to the passed
 in object.
 To be equivalent, all of the following conditions must be true:

 object is not null.

 object is an instance of class MediaPrintableArea.

 The origin and dimensions are the same.

Overrides:

equals in class Object

Parameters:

object - Object to compare to.

Returns:

True if object is equivalent to this media margins
          attribute, false otherwise.

See Also:

Object.hashCode(),
HashMap

getCategory

public final Class<? extends Attribute> getCategory()

Get the printing attribute class which is to be used as the "category"
 for this printing attribute value.

 For class MediaPrintableArea, the category is
 class MediaPrintableArea itself.

Specified by:

getCategory in interface Attribute

Returns:

Printing attribute class (category), an instance of class
          java.lang.Class.

getName

public final String getName()

Get the name of the category of which this attribute value is an
 instance.

 For class MediaPrintableArea,
 the category name is "media-printable-area".

This is not an IPP V1.1 attribute.

Specified by:

getName in interface Attribute

Returns:

Attribute category name.

toString

public String toString(int units,
                       String unitsName)

Returns a string version of this rectangular size attribute in the
 given units.

Parameters:

units - Unit conversion factor, e.g. INCH or
     MM.

unitsName - Units name string, e.g. "in" or "mm". If
     null, no units name is appended to the result.

Returns:

String version of this two-dimensional size attribute.

Throws:

IllegalArgumentException - (unchecked exception) Thrown if units < 1.

toString

public String toString()

Returns a string version of this rectangular size attribute in mm.

Overrides:

toString in class Object

Returns:

a string representation of the object.

hashCode

public int hashCode()

Returns a hash code value for this attribute.

Overrides:

hashCode in class Object

Returns:

a hash code value for this object.

See Also:

Object.equals(java.lang.Object),
System.identityHashCode(java.lang.Object)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
KEYSTORE=$CUSTOMER-$CAGE.keystore
artifactory_tomcat_home=/usr/share/artifactory-3.4.2/tomcat
# run as sudo
echo Copy $KEYSTORE to $artifactory_tomcat_home/conf/ssl
cp $KEYSTORE $artifactory_tomcat_home/conf/ssl

echo Copy cacerts to /etc/pki/java/cacerts
cp cacerts /etc/pki/java/cacerts

echo Restarting Artifactory
service artifactory restart


text:
  <form name="_form" class="form-horizontal" ng-submit="submit(_form)">

      <button type="button" class="close" ng-click="dismiss()" aria-hidden="true">×</button>

Widget Settings

        Name

          <input name="name" type="text" ng-model="form.name" class="form-control" />

            Width

              <input name="sizeX" ng-model="form.sizeX" class="form-control" />

            Height

              <input name="sizeY" ng-model="form.sizeY" class="form-control" />

            Column

              <input name="col" ng-model="form.col" class="form-control" />

            Row

              <input name="row" ng-model="form.row" class="form-control" />

      Delete
      Cancel
      <button type="submit" class="btn btn-primary btn-lg">Save</button>

  </form>


text:
package morebridgemethods;

import static com.google.j2cl.integration.testing.Asserts.assertTrue;

public class TestCase9226 {
  static class B<B1> {
    @SuppressWarnings("unused")
    public String get(String value) {
      return "B get String";
    }
  }

  static class C extends B<String> {}

  @SuppressWarnings({"unchecked", "rawtypes"})
  public static void test() {
    C c = new C();
    assertTrue(((B) c).get("").equals("B get String"));
    assertTrue(c.get("").equals("B get String"));
  }
}


text:
function Swimlane() {
}

Swimlane.prototype.getStorageKey = function() {
    return "hidden_swimlanes_" + $("#board").data("project-id");
};

Swimlane.prototype.expand = function(swimlaneId) {
    var swimlaneIds = this.getAllCollapsed();
    var index = swimlaneIds.indexOf(swimlaneId);

    if (index > -1) {
        swimlaneIds.splice(index, 1);
    }

    localStorage.setItem(this.getStorageKey(), JSON.stringify(swimlaneIds));

    $('.board-swimlane-columns-' + swimlaneId).css('display', 'table-row');
    $('.board-swimlane-tasks-' + swimlaneId).css('display', 'table-row');
    $('.hide-icon-swimlane-' + swimlaneId).css('display', 'inline');
    $('.show-icon-swimlane-' + swimlaneId).css('display', 'none');
};

Swimlane.prototype.collapse = function(swimlaneId) {
    var swimlaneIds = this.getAllCollapsed();

    if (swimlaneIds.indexOf(swimlaneId) < 0) {
        swimlaneIds.push(swimlaneId);
        localStorage.setItem(this.getStorageKey(), JSON.stringify(swimlaneIds));
    }

    $('.board-swimlane-columns-' + swimlaneId + ':not(:first-child)').css('display', 'none');
    $('.board-swimlane-tasks-' + swimlaneId).css('display', 'none');
    $('.hide-icon-swimlane-' + swimlaneId).css('display', 'none');
    $('.show-icon-swimlane-' + swimlaneId).css('display', 'inline');
};

Swimlane.prototype.isCollapsed = function(swimlaneId) {
    return this.getAllCollapsed().indexOf(swimlaneId) > -1;
};

Swimlane.prototype.getAllCollapsed = function() {
    return JSON.parse(localStorage.getItem(this.getStorageKey())) || [];
};

Swimlane.prototype.refresh = function() {
    var swimlaneIds = this.getAllCollapsed();

    for (var i = 0; i < swimlaneIds.length; i++) {
        this.collapse(swimlaneIds[i]);
    }
};

Swimlane.prototype.listen = function() {
    var self = this;

    $(document).on('click', ".board-swimlane-toggle", function(e) {
        e.preventDefault();

        var swimlaneId = $(this).data('swimlane-id');

        if (self.isCollapsed(swimlaneId)) {
            self.expand(swimlaneId);
        }
        else {
            self.collapse(swimlaneId);
        }
    });
};


text:
<?php
require_once 'tutorial_autoload.php';

// create an ezcUrlConfiguration object
$urlCfg = new ezcUrlConfiguration();

$urlCfg->basedir = '/mydir/shop';
$urlCfg->script = 'index.php';
$urlCfg->addOrderedParameter( 'module' );

$url = new ezcUrl( 'http://www.example.com/mydir/shop/index.php/order/Software/PHP/Version/5.2/Extension/XDebug/Extension/openssl', $urlCfg );

// get the unordered parameters as a flat array
var_dump( $url->getParams() ); // will output array( 'Software', 'PHP', 'Version', '5.2', 'Extension', 'XDebug', 'Extension', 'openssl' )
?>


text:
'use strict';

const React = require('react');
const ReactRelayContext = require('../ReactRelayContext');
const ReactRelayFragmentContainer = require('../ReactRelayFragmentContainer');
const ReactTestRenderer = require('react-test-renderer');

const {
  createReaderSelector,
  createOperationDescriptor,
  graphql,
} = require('relay-runtime');
const {createMockEnvironment} = require('relay-test-utils-internal');

describe('ReactRelayFragmentContainer with fragment ownerhsip', () => {
  let TestComponent;
  let TestContainer;
  let UserFragment;
  let UserQuery;
  let UserQueryWithCond;

  let environment;
  let ownerUser1;
  let ownerUser1WithCondVar;
  let ownerUser2;
  let render;
  let spec;
  let variables;

  class ContextSetter extends React.Component {
    constructor(props) {
      super();
      this.__relayContext = {
        environment: props.environment,
        variables: props.variables,
      };
      this.state = {props: null};
    }
    UNSAFE_componentWillReceiveProps(nextProps) {
      // eslint-disable-next-line no-shadow
      const {environment} = nextProps;
      if (environment !== this.__relayContext.environment) {
        this.__relayContext = {environment};
      }
    }
    setProps(props) {
      this.setState({props});
    }
    setContext(env, vars) {
      this.__relayContext = {
        environment: env,
      };
      this.setProps({});
    }
    render() {
      let child = React.Children.only(this.props.children);
      if (this.state.props) {
        child = React.cloneElement(child, this.state.props);
      }
      return (
        <ReactRelayContext.Provider value={this.__relayContext}>
          {child}
        </ReactRelayContext.Provider>
      );
    }
  }

  beforeEach(() => {
    jest.resetModules();

    environment = createMockEnvironment();
    UserQuery = graphql`
      query ReactRelayFragmentContainerWithFragmentOwnershipTestUserQuery(
        $id: ID!
      ) {
        node(id: $id) {
          ...ReactRelayFragmentContainerWithFragmentOwnershipTestUserFragment
        }
      }
    `;
    UserQueryWithCond = graphql`
      query ReactRelayFragmentContainerWithFragmentOwnershipTestWithCondUserQuery(
        $id: ID!
        $condGlobal: Boolean!
      ) {
        node(id: $id) {
          ...ReactRelayFragmentContainerWithFragmentOwnershipTestUserFragment
            @arguments(cond: $condGlobal)
        }
      }
    `;
    UserFragment = graphql`
      fragment ReactRelayFragmentContainerWithFragmentOwnershipTestUserFragment on User
        @argumentDefinitions(cond: {type: "Boolean!", defaultValue: true}) {
        id
        name @include(if: $cond)
        ...ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment
      }
    `;
    graphql`
      fragment ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment on User {
        username
      }
    `;

    render = jest.fn(() => <div />);
    spec = {
      user: UserFragment,
    };
    variables = {rootVariable: 'root'};
    TestComponent = render;
    TestComponent.displayName = 'TestComponent';
    TestContainer = ReactRelayFragmentContainer.createContainer(
      TestComponent,
      spec,
    );

    // Pre-populate the store with data
    ownerUser1 = createOperationDescriptor(UserQuery, {id: '4'});
    environment.commitPayload(ownerUser1, {
      node: {
        id: '4',
        __typename: 'User',
        name: 'Zuck',
        username: 'zuck',
      },
    });
    ownerUser1WithCondVar = createOperationDescriptor(UserQueryWithCond, {
      id: '4',
      condGlobal: false,
    });
    environment.commitPayload(ownerUser1, {
      node: {
        id: '4',
        __typename: 'User',
        username: 'zuck',
      },
    });
    ownerUser2 = createOperationDescriptor(UserQuery, {id: '842472'});
    environment.commitPayload(ownerUser2, {
      node: {
        id: '842472',
        __typename: 'User',
        name: 'Joe',
        username: 'joe',
      },
    });
  });

  it('resolves & subscribes fragment props', () => {
    const userPointer = environment.lookup(ownerUser1.fragment, ownerUser1).data
      .node;

    ReactTestRenderer.create(
      <ContextSetter environment={environment} variables={variables}>
        <TestContainer user={userPointer} />
      </ContextSetter>,
    );
    // Data & Variables are passed to component
    expect(render.mock.calls.length).toBe(1);
    expect(render.mock.calls[0][0]).toEqual({
      relay: {
        environment: environment,
      },
      user: {
        id: '4',
        name: 'Zuck',
        __id: '4',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser1.request,
      },
    });
    // Subscribes for updates
    expect(environment.subscribe.mock.calls.length).toBe(1);
    expect(environment.subscribe.mock.calls[0][0]).toEqual({
      data: {
        id: '4',
        name: 'Zuck',
        __id: '4',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser1.request,
      },
      missingRequiredFields: null,
      isMissingData: false,
      seenRecords: expect.any(Object),
      selector: createReaderSelector(
        UserFragment,
        '4',
        {cond: true},
        ownerUser1.request,
      ),
    });
  });

  it('re-renders on subscription callback', () => {
    const userPointer = environment.lookup(ownerUser1.fragment, ownerUser1).data
      .node;

    ReactTestRenderer.create(
      <ContextSetter environment={environment} variables={variables}>
        <TestContainer user={userPointer} />
      </ContextSetter>,
    );
    const callback = environment.subscribe.mock.calls[0][1];
    render.mockClear();
    environment.lookup.mockClear();
    environment.subscribe.mockClear();

    callback({
      dataID: '4',
      node: UserFragment,
      variables: {cond: true},
      data: {
        id: '4',
        // !== 'Zuck'
        name: 'Mark',
        __id: '4',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser1.request,
      },
      seenRecords: {},
      isMissingData: false,
    });

    // No need to resolve props or resubscribe
    expect(environment.lookup).not.toBeCalled();
    expect(environment.subscribe).not.toBeCalled();
    // Data & Variables are passed to component
    expect(render.mock.calls.length).toBe(1);
    expect(render.mock.calls[0][0]).toEqual({
      relay: {
        environment: environment,
      },
      user: {
        id: '4',
        name: 'Mark',
        __id: '4',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser1.request,
      },
    });
  });

  it('resolves new props', () => {
    let userPointer = environment.lookup(ownerUser1.fragment, ownerUser1).data
      .node;
    const instance = ReactTestRenderer.create(
      <ContextSetter environment={environment} variables={variables}>
        <TestContainer user={userPointer} />
      </ContextSetter>,
    );
    render.mockClear();
    environment.lookup.mockClear();
    environment.subscribe.mockClear();

    userPointer = environment.lookup(ownerUser2.fragment, ownerUser2).data.node;
    instance.getInstance().setProps({
      user: userPointer,
    });

    // New data & variables are passed to component
    expect(render.mock.calls.length).toBe(1);
    expect(render.mock.calls[0][0]).toEqual({
      relay: {
        environment: environment,
      },
      user: {
        id: '842472',
        name: 'Joe',
        __id: '842472',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser2.request,
      },
    });

    // Container subscribes for updates on new props
    expect(environment.subscribe.mock.calls.length).toBe(1);
    expect(environment.subscribe.mock.calls[0][0]).toEqual({
      data: {
        id: '842472',
        name: 'Joe',
        __id: '842472',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser2.request,
      },
      missingRequiredFields: null,
      isMissingData: false,
      seenRecords: expect.any(Object),
      selector: createReaderSelector(
        UserFragment,
        '842472',
        {cond: true},
        ownerUser2.request,
      ),
    });
  });

  it('resolves new props when ids dont change', () => {
    let userPointer = environment.lookup(ownerUser1.fragment, ownerUser1).data
      .node;
    const instance = ReactTestRenderer.create(
      <ContextSetter environment={environment}>
        <TestContainer user={userPointer} />
      </ContextSetter>,
    );
    render.mockClear();
    environment.lookup.mockClear();
    environment.subscribe.mockClear();

    userPointer = environment.lookup(
      ownerUser1WithCondVar.fragment,
      ownerUser1WithCondVar,
    ).data.node;
    instance.getInstance().setProps({
      user: userPointer,
    });

    // New data & variables are passed to component
    expect(render.mock.calls.length).toBe(1);
    expect(render.mock.calls[0][0]).toEqual({
      relay: {
        environment: environment,
      },
      user: {
        id: '4',
        // Name is excluded since value of cond is now false
        __id: '4',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser1WithCondVar.request,
      },
    });
    // Container subscribes for updates on new props
    expect(environment.subscribe.mock.calls.length).toBe(1);
    expect(environment.subscribe.mock.calls[0][0]).toEqual({
      data: {
        id: '4',
        // Name is excluded since value of cond is now false
        __id: '4',
        __fragments: {
          ReactRelayFragmentContainerWithFragmentOwnershipTestNestedUserFragment: {},
        },
        __fragmentOwner: ownerUser1WithCondVar.request,
      },
      missingRequiredFields: null,
      isMissingData: false,
      seenRecords: expect.any(Object),
      selector: createReaderSelector(
        UserFragment,
        '4',
        {cond: false},
        ownerUser1WithCondVar.request,
      ),
    });
  });
});


text:
using UnityEngine;
using System.Collections;

public class Levitation : MonoBehaviour {

	public float levitationForce;
	public string[] tagToAvoide;

	void OnTriggerEnter(Collider other)
	{
		if(tagToAvoide.Length > 0)
		{
			for(int i=0; i< tagToAvoide.Length; i++)
			{
				if(other.tag != tagToAvoide[i])
				{
					other.rigidbody.velocity = Vector3.zero;
				}
			}
		}
		else
		{
			other.rigidbody.velocity = Vector3.zero;
		}
	}

	void OnTriggerStay(Collider other)
	{
		if(tagToAvoide.Length > 0)
		{
			for(int i=0; i< tagToAvoide.Length; i++)
			{
				if(other.tag != tagToAvoide[i])
				{
					other.rigidbody.AddForce(Vector3.up * levitationForce, ForceMode.Acceleration);
				}
			}
		}
		else
		{
			other.rigidbody.AddForce(Vector3.up * levitationForce, ForceMode.Acceleration);
		}
	}

	void OnTriggerExit(Collider other)
	{
		if(tagToAvoide.Length > 0)
		{
			for(int i=0; i< tagToAvoide.Length; i++)
			{
				if(other.tag != tagToAvoide[i])
				{
					//other.rigidbody.velocity = Vector3.zero;
				}
			}
		}
		else
		{
			//other.rigidbody.velocity = Vector3.zero;
		}
	}
}


text:
using UnityEngine;
using System.Collections;

public class CreditText : MonoBehaviour {

	private float dir = -1f;
	public bool enabled = true;
	public float speed = 5f;
	public bool isDying = false;
	private bool exploded = false;
	private Transform text;
	private Transform emitter;
	public GameObject textExplosion;

	private float deathTime = 0.5f;
	private bool shifting = false;
	private bool shifted = false;
	private Vector3 initialPos;

	// Use this for initialization
	void Start () {
		text = transform.FindChild("Text");
		emitter = transform.FindChild ("Emitter");
		Checkpoint();
	}

	public void Checkpoint() {
		initialPos = transform.position;
	}

	public void Restart() {
		transform.position = initialPos;
		shifting = false;
		shifted = false;
		exploded = false;
		enabled = true;
		isDying = false;
		deathTime = 0.5f;
		emitter.gameObject.GetComponent<ParticleSystem>().Stop();
		text.localEulerAngles = new Vector3(0, 180, 0);
		text.gameObject.GetComponent<MeshRenderer>().enabled = true;
		gameObject.GetComponent<BoxCollider>().enabled = true;
    }

	// Update is called once per frame
	void FixedUpdate () {
		if (enabled) {
			float s = isDying ? speed / 10 : speed;
			if (!shifting) {
				transform.Translate(Vector3.up * dir * s * Time.deltaTime);
				if (!shifted && transform.localPosition.y < -19f) {
					shifting = true;
                }
			} else {
				transform.Translate(Vector3.forward * dir * s * Time.deltaTime);
				if (transform.localPosition.z < -4f){
					shifting = false;
					shifted = true;
				}
			}
		}

		if (isDying && !exploded) {
			text.localEulerAngles = new Vector3(0, 180, Random.Range(-2, 2));
			deathTime -= 0.01f;
			if (deathTime < 0 && !exploded) {
				exploded = true;
				emitter.gameObject.GetComponent<ParticleSystem>().Stop();
				GameObject explode = Instantiate(textExplosion, gameObject.transform.position, Quaternion.identity) as GameObject;
				explode.GetComponent<AudioSource>().Play();
				// Destroy(text.gameObject);
				text.gameObject.GetComponent<MeshRenderer>().enabled = false;
				gameObject.GetComponent<BoxCollider>().enabled = false;

			}
		}
	}

	public void Die(){
		isDying = true;
		emitter.gameObject.GetComponent<ParticleSystem>().Play();
	}

	public void Enable() {
		enabled = true;
	}

}


text:
namespace cc {

class CC_EXPORT ResourceUtil {
 public:
  // Returns true if the width is valid and fits in bytes, false otherwise.
  template <typename T>
  static bool VerifyWidthInBytes(int width, ResourceFormat format);
  // Returns true if the size is valid and fits in bytes, false otherwise.
  template <typename T>
  static bool VerifySizeInBytes(const gfx::Size& size, ResourceFormat format);

  // Dies with a CRASH() if the width can not be represented as a positive
  // number of bytes.
  template <typename T>
  static T CheckedWidthInBytes(int width, ResourceFormat format);
  // Dies with a CRASH() if the size can not be represented as a positive
  // number of bytes.
  template <typename T>
  static T CheckedSizeInBytes(const gfx::Size& size, ResourceFormat format);

  // Returns the width in bytes but may overflow or return 0. Only do this for
  // computing widths for sizes that have already been checked.
  template <typename T>
  static T UncheckedWidthInBytes(int width, ResourceFormat format);
  // Returns the size in bytes but may overflow or return 0. Only do this for
  // sizes that have already been checked.
  template <typename T>
  static T UncheckedSizeInBytes(const gfx::Size& size, ResourceFormat format);
  // Returns the width in bytes aligned but may overflow or return 0. Only do
  // this for computing widths for sizes that have already been checked.
  template <typename T>
  static T UncheckedWidthInBytesAligned(int width, ResourceFormat format);
  // Returns the size in bytes aligned but may overflow or return 0. Only do
  // this for sizes that have already been checked.
  template <typename T>
  static T UncheckedSizeInBytesAligned(const gfx::Size& size,
                                       ResourceFormat format);

 private:
  // TODO(prashant.n): Replace IsSameType with std::is_same once C++11 is used
  // on all platforms.
  template <typename T, typename U>
  struct IsSameType {
    static const bool value = false;
  };

  template <typename T>
  struct IsSameType<T, T> {
    static const bool value = true;
  };

  template <typename T>
  static inline void VerifyType();

  template <typename T>
  static bool VerifyFitsInBytesInternal(int width,
                                        int height,
                                        ResourceFormat format,
                                        bool verify_size,
                                        bool aligned);

  template <typename T>
  static T BytesInternal(int width,
                         int height,
                         ResourceFormat format,
                         bool verify_size,
                         bool aligned);

  DISALLOW_COPY_AND_ASSIGN(ResourceUtil);
};

template <typename T>
bool ResourceUtil::VerifyWidthInBytes(int width, ResourceFormat format) {
  VerifyType<T>();
  return VerifyFitsInBytesInternal<T>(width, 0, format, false, false);
}

template <typename T>
bool ResourceUtil::VerifySizeInBytes(const gfx::Size& size,
                                     ResourceFormat format) {
  VerifyType<T>();
  return VerifyFitsInBytesInternal<T>(size.width(), size.height(), format, true,
                                      false);
}

template <typename T>
T ResourceUtil::CheckedWidthInBytes(int width, ResourceFormat format) {
  VerifyType<T>();
  DCHECK(VerifyFitsInBytesInternal<T>(width, 0, format, false, false));
  base::CheckedNumeric<T> checked_value = BitsPerPixel(format);
  checked_value *= width;
  checked_value = MathUtil::CheckedRoundUp<T>(checked_value.ValueOrDie(), 8);
  checked_value /= 8;
  return checked_value.ValueOrDie();
}

template <typename T>
T ResourceUtil::CheckedSizeInBytes(const gfx::Size& size,
                                   ResourceFormat format) {
  VerifyType<T>();
  DCHECK(VerifyFitsInBytesInternal<T>(size.width(), size.height(), format, true,
                                      false));
  base::CheckedNumeric<T> checked_value = BitsPerPixel(format);
  checked_value *= size.width();
  checked_value = MathUtil::CheckedRoundUp<T>(checked_value.ValueOrDie(), 8);
  checked_value /= 8;
  checked_value *= size.height();
  return checked_value.ValueOrDie();
}

template <typename T>
T ResourceUtil::UncheckedWidthInBytes(int width, ResourceFormat format) {
  VerifyType<T>();
  DCHECK(VerifyFitsInBytesInternal<T>(width, 0, format, false, false));
  return BytesInternal<T>(width, 0, format, false, false);
}

template <typename T>
T ResourceUtil::UncheckedSizeInBytes(const gfx::Size& size,
                                     ResourceFormat format) {
  VerifyType<T>();
  DCHECK(VerifyFitsInBytesInternal<T>(size.width(), size.height(), format, true,
                                      false));
  return BytesInternal<T>(size.width(), size.height(), format, true, false);
}

template <typename T>
T ResourceUtil::UncheckedWidthInBytesAligned(int width, ResourceFormat format) {
  VerifyType<T>();
  DCHECK(VerifyFitsInBytesInternal<T>(width, 0, format, false, true));
  return BytesInternal<T>(width, 0, format, false, true);
}

template <typename T>
T ResourceUtil::UncheckedSizeInBytesAligned(const gfx::Size& size,
                                            ResourceFormat format) {
  VerifyType<T>();
  DCHECK(VerifyFitsInBytesInternal<T>(size.width(), size.height(), format, true,
                                      true));
  return BytesInternal<T>(size.width(), size.height(), format, true, true);
}

template <typename T>
void ResourceUtil::VerifyType() {
  static_assert(
      std::numeric_limits<T>::is_integer && !IsSameType<T, bool>::value,
      "T must be non-bool integer type. Preferred type is size_t.");
}

template <typename T>
bool ResourceUtil::VerifyFitsInBytesInternal(int width,
                                             int height,
                                             ResourceFormat format,
                                             bool verify_size,
                                             bool aligned) {
  base::CheckedNumeric<T> checked_value = BitsPerPixel(format);
  checked_value *= width;
  if (!checked_value.IsValid())
    return false;

  // Roundup bits to byte (8 bits) boundary. If width is 3 and BitsPerPixel is
  // 4, then it should return 16, so that row pixels do not get truncated.
  checked_value = MathUtil::UncheckedRoundUp<T>(checked_value.ValueOrDie(), 8);

  // If aligned is true, bytes are aligned on 4-bytes boundaries for upload
  // performance, assuming that GL_PACK_ALIGNMENT or GL_UNPACK_ALIGNMENT have
  // not changed from default.
  if (aligned) {
    checked_value /= 8;
    if (!checked_value.IsValid())
      return false;
    checked_value =
        MathUtil::UncheckedRoundUp<T>(checked_value.ValueOrDie(), 4);
    checked_value *= 8;
  }

  if (verify_size)
    checked_value *= height;
  if (!checked_value.IsValid())
    return false;
  T value = checked_value.ValueOrDie();
  if ((value % 8) != 0)
    return false;
  return true;
}

template <typename T>
T ResourceUtil::BytesInternal(int width,
                              int height,
                              ResourceFormat format,
                              bool verify_size,
                              bool aligned) {
  T bytes = BitsPerPixel(format);
  bytes *= width;
  bytes = MathUtil::UncheckedRoundUp<T>(bytes, 8);
  bytes /= 8;
  if (aligned)
    bytes = MathUtil::UncheckedRoundUp<T>(bytes, 4);
  if (verify_size)
    bytes *= height;

  return bytes;
}

}  // namespace cc

#endif  // CC_RESOURCES_RESOURCE_UTIL_H_


text:
package org.bds.lang.nativeMethods;

import org.bds.lang.Parameters;
import org.bds.lang.Type;
import org.bds.run.BdsThread;

/**
 * Method for testing
 *
 * @author pcingola
 */
public class MethodNativeZzz extends MethodNative {

	public MethodNativeZzz() {
		super();
	}

	@Override
	protected void initMethod() {
		functionName = "zzz";
		classType = Type.STRING;
		returnType = Type.STRING;

		String argNames[] = { "this", "ext" };
		Type argTypes[] = { classType, Type.STRING };
		parameters = Parameters.get(argTypes, argNames);
		addNativeMethodToClassScope();
	}

	@Override
	protected Object runMethodNative(BdsThread csThread, Object objThis) {
		return objThis.toString();
	}
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Documentation Index</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

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

        </button>

				Classes

AuthAPI

FindAPI

Fmrest

Global

GlobalAPI

Portal

RecordAPI

Request

Sort

                <form class="navbar-form" role="search">

                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">

                            <button class="btn btn-default" id="search-submit"></button>

                </form>

FMREST

A javascript wrapper for Filemaker's Data API (REST API)

Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

Prerequisites

You will need to install Filemaker Server 16 and enable the Data API.  To do my testing I disabled the https protocol on Filemaker's IIS server.  I have also supplied my testing file - db.fmp12.

Running the tests

Run all tasks including tests:

npm i gulp-cli -g
gulp

Run only tests:

jasmine

Note: fmrestSpec.js is commented out, uncomment when you have a filemaker server 16 environment setup.

API Code Samples

Almost every function returns a Promise except createRequest, createGlobal and createSort.

Configuration

npm install fmrest

const Fmrest = require('fmrest');

// Set configuration
const filemaker = new Fmrest({
    user: "admin",
    password: "admin",
    host: "http://localhost",
    solution: "db",
    layout: "db"
});

Authentication

// Login
filemaker
    .login()
    .then(token => {
        console.log(token);
    });

// Logout
filemaker
    .logout()
    .then(isLoggedOut => {
        console.log(isLoggedOut);
    });

Records

// Create Record
const values = {
    "name": "Bill",
    "address": "102 park ave",
    "date": "6/21/2017"
}

filemaker
    .createRecord(values) // if empty, creates record w/ default values
    .then(id => {
        console.log(id);
    });

// Delete Record
filemaker
    .deleteRecord(2) // supply with Filemaker's unique interal recordID
    .then(isDeleted => {
        console.log(isDeleted);
    })

// Edit Record
const values2 = {
    "name": "James",
    "address": "105 lake dr",
    "date": "6/22/2017"
}

filemaker
    .editRecord(2, values2)
    .then(isEdited => {
        console.log(isEdited);
    })

// Get Record
filemaker
    .getRecord(3)
    .then(record => {
        console.log(record);
    })

// Get Record w/ Portal Data
let portal1 = filemaker
    .createPortal('portal1', 1, 2); // (portal name, offset, range)
                                    // offset and range are optional
let portal2 = filemaker
    .createPortal('portal2', 1, 2);

filemaker
    .getRecord(3, [portal1, portal2])
    .then(record => {
        console.log(record);
    });

// Get All Records
filemaker
    .getAllRecords()
    .then(records => {
        console.log(records);
    })

// Get All Records w/ Portal Data, sorting, offset and range
let portal1 = filemaker
    .createPortal('portal1');

let sort1 = filemaker
    .createSort('name', 'ascend');

filemaker
    .getAllRecords({
        offset: 1,
        range: 10,
        sorts: [sort1],
        portals: [portal1]
    })
    .then(records => {
        console.log(records);
    });

Finds

// Find Records
let request = filemaker
    .createRequest()
    .where('name').is('=bill');

filemaker
    .find({requests: [request]})
    .then(records => {
        console.log(records);
    })

// Find w/ multiple requests
let request = filemaker
    .createRequest()
    .where('name').is('=bill')
    .where('address').is('102*');

let request2 = filemaker
    .createRequest()
    .where('name').is('=james');

filemaker               // Append .omit() to make the request omit records
    .find({requests: [request.omit(), request2]})
    .then(records => {
        console.log(records);
    })

// Find w/ multiple requests and sorting
let request = filemaker
    .createRequest()
    .where('name').is('*');

let request2 = filemaker
    .createRequest()
    .where('address')
    .is('102*');

let sort = filemaker
    .createSort('name', 'ascend');

let sort2 = filemaker
    .createSort('address', 'descend');

filemaker
    .find({
        requests: [request, request2],
        sorts: [sort, sort2]
    })
    .then(records => {
        console.log(records);
    })

// Find w/ all optional parameters
let request = filemaker.createRequest().where('name').is('*');

let sort = filemaker.createSort('name', 'ascend');

let portal1 = filemaker.createPortal('portal1', 1, 1);

filemaker
    .find({
        requests: [request],
        sorts: [sort],      // optional
        offset: 2,          // optional
        range: 10,          // optional
        portals: [portal1]  // optional
    })
    .then(records => {
        console.log(records);
    })

Set Global Fields

// Set Global Fields
let global1 = filemaker
    .createGlobal('global1', 'aValue');

let global2 = filemaker
    .createGlobal('global2', 'anotherValue');

filemaker
    .setGlobals([global1, global2])
    .then(isSet => {
        console.log(isSet);
    })

TODO

[x] Add ability to get portal data with getRecord

[x] Add ability to get portal data with getAllRecords

[ ] Global fields were not actually "setting" for me

[x] Add offset and range parameters for portals under Find (eg. offset.Portal1)

Resources

Filemaker Data API Guide

Better API Guide here if you have Filemaker Server 16 installed

Contributing / Code of Conduct

Please read CONTRIBUTING.md and CODE_OF_CONDUCT.md for details on our code of conduct, and the process for submitting pull requests to us.

License

This project is licensed under the MIT License - see the LICENSE file for details

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Search results

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

	Documentation generated by JSDoc 3.4.3

		on June 27th 2017, 11:41:08 am

	using the DocStrap template.


text:
/* eslint-disable jsdoc/require-jsdoc */
import { useRef, useEffect, useCallback, createRef } from 'react'
import PropTypes from 'prop-types'
import { debounce, Box, LinearProgress } from '@mui/material'

import { useList, useNearScreen } from 'client/hooks'

const ListInfiniteScroll = ({ list, renderResult }) => {
  const gridRef = createRef()
  const { loading, shortList, finish, reset, setLength } = useList({
    list,
    initLength: 50,
  })

  const loaderRef = useRef()
  const { isNearScreen } = useNearScreen({
    distance: '100px',
    externalRef: loading ? null : loaderRef,
    once: false,
  })

  useEffect(() => {
    reset(list)
    gridRef.current.scrollIntoView({ block: 'start' })
  }, [list])

  const debounceHandleNextPage = useCallback(
    debounce(() => setLength((prevLength) => prevLength + 20), 200),
    [setLength]
  )

  useEffect(() => {
    if (isNearScreen && !finish) debounceHandleNextPage()
  }, [isNearScreen, finish, debounceHandleNextPage])

  return (
    <Box sx={{ overflowY: 'auto' }}>
      <Box
        ref={gridRef}
        sx={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
          gridGap: 4,
        }}
      >
        {shortList?.map(renderResult)}
      </Box>
      {!finish && (
        <LinearProgress
          ref={loaderRef}
          color="secondary"
          sx={{ width: '100%', marginTop: 10 }}
        />
      )}
    </Box>
  )
}

ListInfiniteScroll.propTypes = {
  list: PropTypes.arrayOf(PropTypes.any),
  renderResult: PropTypes.func,
}

ListInfiniteScroll.defaultProps = {
  list: [],
  renderResult: () => null,
}

export default ListInfiniteScroll


text:
using System;

namespace NMaier.SimpleDlna.Utilities
{
  internal sealed class StringSortPart
  : BaseSortPart, IComparable<StringSortPart>
  {
    private readonly StringComparer comparer;

    private readonly string str;

    internal StringSortPart(string str, StringComparer comparer)
    {
      this.str = str;
      this.comparer = comparer;
    }

    public int CompareTo(StringSortPart other)
    {
      if (other == null) {
        throw new ArgumentNullException("other");
      }
      return comparer.Compare(str, other.str);
    }
  }
}


text:
package net.sourceforge.mayfly.acceptance;

import java.sql.ResultSet;
import java.sql.SQLException;

public class OrderByTest extends SqlTestCase {

    public void testOrderByDoesNotCountAsWhat() throws Exception {
        execute("create table vehicles (name varchar(255), wheels integer)");
        execute("insert into vehicles (name, wheels) values ('bicycle', 2)");
        ResultSet results = query("select name from vehicles order by wheels");
        assertTrue(results.next());
        assertEquals("bicycle", results.getString(1));
        if (!dialect.orderByCountsAsWhat()) {
            try {
                results.getInt(2);
                fail();
            } catch (SQLException e) {
                assertMessage("no column 2", e);
            }
        } else {
            // Is this just a hypersonic quirk or do other databases do this?
            assertEquals(2, results.getInt(2));
        }

        results.close();
    }

    public void testOrderBy() throws Exception {
        execute("create table vehicles (name varchar(255), wheels integer, speed integer)");
        execute("insert into vehicles (name, wheels, speed) values ('bicycle', 2, 15)");
        execute("insert into vehicles (name, wheels, speed) values ('car', 4, 100)");
        execute("insert into vehicles (name, wheels, speed) values ('tricycle', 3, 5)");
        assertResultList(new String[] { "'bicycle'", "'tricycle'", "'car'" },
            query("select name from vehicles order by wheels asc")
        );
        assertResultList(new String[] { "'car'", "'tricycle'", "'bicycle'" },
            query("select name from vehicles order by wheels desc")
        );
        assertResultList(new String[] { "'tricycle'", "'bicycle'", "'car'" },
            query("select name from vehicles order by speed")
        );
    }

    public void testNullSortOrder() throws Exception {
        execute("create table foo (a varchar(255))");
        execute("insert into foo (a) values ('one')");
        execute("insert into foo (a) values (null)");
        execute("insert into foo (a) values ('')");
        if (dialect.nullSortsLower()) {
            assertTrue(connection.getMetaData().nullsAreSortedLow());
            assertFalse(connection.getMetaData().nullsAreSortedHigh());
            assertFalse(connection.getMetaData().nullsAreSortedAtStart());
            assertFalse(connection.getMetaData().nullsAreSortedAtEnd());
            assertResultList(
                new String[] { " null ", " '' ", " 'one' " },
                query("select a from foo order by a")
            );
            assertResultList(
                new String[] { " 'one' ", " '' ", " null " },
                query("select a from foo order by a desc")
            );
        }
        else {
            assertFalse(connection.getMetaData().nullsAreSortedLow());
            assertTrue(connection.getMetaData().nullsAreSortedHigh());
            assertFalse(connection.getMetaData().nullsAreSortedAtStart());
            assertFalse(connection.getMetaData().nullsAreSortedAtEnd());
            assertResultList(
                new String[] { " '' ", " 'one' ", " null " },
                query("select a from foo order by a")
            );
            assertResultList(
                new String[] { " null ", " 'one' ", " '' " },
                query("select a from foo order by a desc")
            );

        }
    }

    public void testOrderByExpression() throws Exception {
        execute("create table foo (a integer, b integer)");
        execute("insert into foo(a, b) values (5, 30)");
        execute("insert into foo(a, b) values (8, 40)");
        execute("insert into foo(a, b) values (3, 50)");
        execute("insert into foo(a, b) values (4, 60)");
        execute("insert into foo(a, b) values (2, 70)");

        /* So here's the evil part: an integer is not an expression, it is a
           reference (special case) */
        assertResultList(new String[] { "2", "3", "4", "5", "8" },
            query("select a from foo order by 1, b"));
        assertResultList(new String[] { "8", "5", "4", "3", "2" },
            query("select a from foo order by 1 desc, b"));
        assertResultList(new String[] { "35", "48", "53", "64", "72" },
            query("select a + b from foo order by 1 asc, b desc"));

        String expression = "select a from foo order by a + b";
        // But "1 + 0" is an expression, not a reference
        String constantExpression = "select a from foo order by 1 + 0, b";
        if (dialect.canOrderByExpression(false)) {
            // Derby returns false, although it actually supports the feature.
//            assertTrue(connection.getMetaData().supportsExpressionsInOrderBy());
            assertResultList(new String[] { "5", "8", "3", "4", "2" }, query(expression));
            // Evil!  We can at the very least give an error on a constant expression, I hope
            assertResultList(new String[] { "5", "8", "3", "4", "2" }, query(constantExpression));
        }
        else {
            assertFalse(connection.getMetaData().supportsExpressionsInOrderBy());
            expectQueryFailure(expression,
                "expected column reference in ORDER BY but got expression");
            expectQueryFailure(constantExpression,
                "expected end of file but got '+'");
        }
    }

    public void testOrderByExpressionWithColumnAlias() throws Exception {
        execute("create table foo (a integer, b integer)");
        execute("insert into foo(a, b) values (5, 30)");
        execute("insert into foo(a, b) values (8, 40)");
        execute("insert into foo(a, b) values (3, 50)");

        assertResultList(new String[] { "35", "48", "53", },
            query("select a + b as total from foo order by total"));
    }

    public void testOrderByNumericReference() throws Exception {
        execute("create table foo (a integer, b integer)");
        execute("insert into foo(a, b) values (5, 30)");
        execute("insert into foo(a, b) values (8, 40)");
        execute("insert into foo(a, b) values (3, 50)");
        execute("insert into foo(a, b) values (4, 60)");
        execute("insert into foo(a, b) values (2, 70)");

        assertResultList(new String[] { "2", "3", "4", "5", "8" }, query("select a from foo order by 1"));
        assertResultList(new String[] { "8", "5", "4", "3", "2" }, query("select a from foo order by 1 desc"));
        expectQueryFailure("select a from foo order by 0",
            "ORDER BY 0 must be in range 1 to 1");

        // Does negative mean something?
        // In hypersonic, I got 2,4,3,8,5 (reverse order of insertion, apparently).
        // In Derby, an ArrayOutOfBoundsException
        //        expectQueryFailure("select a from foo order by -1", "ORDER BY -1 must be in range 1 to 1");
        //expectQueryFailure("select a from foo order by -1", "expected identifier but got '-'");

        expectQueryFailure("select a from foo order by 2",
            "ORDER BY 2 must be in range 1 to 1");
    }

    public void testOrderByNumericReferenceWithAsterisks() throws Exception {
        execute("create table foo (a integer, b integer)");
        execute("insert into foo(a, b) values (5, 30)");
        execute("insert into foo(a, b) values (8, 40)");
        execute("insert into foo(a, b) values (3, 50)");
        execute("insert into foo(a, b) values (4, 60)");
        execute("insert into foo(a, b) values (2, 70)");

        String orderByB = "select foo.*, a from foo order by 2";
        String orderBySecondA = "select foo.*, a from foo order by 3";

        assertResultList(new String[] { "2", "3", "4", "5", "8" },
            query("select a, foo.* from foo order by 1"));
        String orderBySecondA2 = "select a, foo.* from foo order by 2";

        if (dialect.expectMayflyBehavior()) {
            // Currently, mayfly is written so the numbers refer to the position
            // in the select clause before foo.* is expanded.  That seems questionable,
            // in that mayfly seems to be the only database tested which does that.
            //
            // On the other hand, it seems a bit questionable to add a column and
            // thus cause the ORDER BY to refer to something different.
            assertResultList(new String[] { "2", "3", "4", "5", "8" }, query(orderByB));
            expectQueryFailure(orderBySecondA, "ORDER BY 3 must be in range 1 to 2");
            expectQueryFailure(orderBySecondA2, "ORDER BY 2 refers to foo.* not an expression");
        }
        else {
            assertResultList(new String[] { "5", "8", "3", "4", "2" }, query(orderByB));
            assertResultList(new String[] { "2", "3", "4", "5", "8" }, query(orderBySecondA));
            assertResultList(new String[] { "2", "3", "4", "5", "8" }, query(orderBySecondA2));
        }
    }

    public void testOrderByWithSelectAll() throws Exception {
        execute("create table foo (a integer, b integer)");
        execute("insert into foo(a, b) values (5, 30)");
        execute("insert into foo(a, b) values (8, 40)");
        execute("insert into foo(a, b) values (3, 50)");
        execute("insert into foo(a, b) values (4, 60)");
        execute("insert into foo(a, b) values (2, 70)");

        String orderByOne = "select * from foo order by 1";

        if (dialect.expectMayflyBehavior()) {
            expectQueryFailure(orderByOne, "ORDER BY 1 refers to * not an expression");
        }
        else {
            assertResultList(new String[] { "2", "3", "4", "5", "8" }, query(orderByOne));
        }
    }

    public void testOrderByWithTableAlias() throws Exception {
        execute("create table places (id integer, parent integer, name varchar(255))");
        execute("insert into places(id, parent, name) values(10, 1, 'B')");
        execute("insert into places(id, parent, name) values(1, 20, 'A')");
        execute("insert into places(id, parent, name) values(20, 0, 'C')");
        String baseQuery = "select child.name from " +
                "places child LEFT OUTER JOIN places parent " +
                "on child.parent = parent.id";
        assertResultList(new String[] { "'A'", "'B'", "'C'" },
            query(baseQuery + " order by child.id")
        );

        assertResultList(new String[] { "'C'", "'B'", "'A'" },
            query(baseQuery + " order by child.parent")
        );

        assertResultList(
            dialect.nullSortsLower() ?
                new String[] { "'C'", "'B'", "'A'" } :
                new String[] { "'B'", "'A'", "'C'" },
            query(baseQuery + " order by parent.id")
        );

    }

    public void testOrderBySeveralColumns() throws Exception {
        execute("create table foo (name varchar(255), major integer, minor integer)");
        execute("insert into foo (name, major, minor) values ('E', 8, 2)");
        execute("insert into foo (name, major, minor) values ('C', 6, 6)");
        execute("insert into foo (name, major, minor) values ('A', 4, 99)");
        execute("insert into foo (name, major, minor) values ('B', 6, 3)");
        execute("insert into foo (name, major, minor) values ('D', 6, 9)");

        assertResultList(new String[] { "'A'", "'B'", "'C'", "'D'", "'E'" },
            query("select name from foo order by major, minor")
        );
    }

    public void testOrderByAmbiguous() throws Exception {
        execute("CREATE TABLE foo (A INTEGER)");
        execute("CREATE TABLE bar (A INTEGER)");
        String sql = "select foo.a, bar.a from foo, bar order by a";
        if (dialect.detectsAmbiguousColumnsInOrderBy()) {
            expectQueryFailure(sql, "ambiguous column a");
        } else {
            assertResultSet(new String[] { }, query(sql));
        }
    }

    public void testMixAggregateAndScalar() throws Exception {
        execute("create table foo(a integer)");
        execute("insert into foo(a) values(50)");
        execute("insert into foo(a) values(50)");
        execute("insert into foo(a) values(51)");
        execute("insert into foo(a) values(52)");
        execute("insert into foo(a) values(52)");
        execute("insert into foo(a) values(53)");

        String orderByWhenSelectingAggregate = "select count(a) from foo order by a";
        if (dialect.errorIfNotAggregateOrGrouped(true)) {
            expectQueryFailure(orderByWhenSelectingAggregate,
                "a is not aggregate or mentioned in GROUP BY");
        }
        else {
            query(orderByWhenSelectingAggregate);
        }
    }

    public void testCompletelyUnheardOfName() throws Exception {
        execute("create table foo(a integer)");
        expectQueryFailure("select a as b from foo order by c", "no column c");
    }

    // TODO: order by a   -- where a is in several columns, only one of which survives after the joins
    // TODO: what other cases involving resolving column names?

}


text:
#ifndef TENSORFLOW_CORE_GRAPH_DEFAULT_DEVICE_H_
#define TENSORFLOW_CORE_GRAPH_DEFAULT_DEVICE_H_

#include <string>

#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"

namespace tensorflow {
namespace graph {

// Sets the default device for all nodes in graph_def to "device",
// only if not already set.
inline void SetDefaultDevice(const string& device, GraphDef* graph_def) {
  for (int i = 0; i < graph_def->node_size(); ++i) {
    auto node = graph_def->mutable_node(i);
    if (node->device().empty()) {
      node->set_device(device);
    }
  }
}

}  // namespace graph
}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_GRAPH_DEFAULT_DEVICE_H_


text:
from __future__ import division

import multiprocessing as mp
import IPython.lib.backgroundjobs as bgjobs

########################################################################################################################

class SimulationManager(object):

    def __init__(self):

        self.simulations = bgjobs.BackgroundJobManager()

    ##

    def new(self, data, model, niters=10000, bg=True, nthreads=None):

        ## multi-processing
        nthreads = mp.cpu_count() if nthreads is None or nthreads <= 0 else nthreads
        pool = None if nthreads == 1 else mp.Pool(nthreads)

        ## reformat data
        counts_norm = [data.counts_norm[samples].values for samples in data.groups.values()]
        nreplicas = data.nreplicas.values()
        data = counts_norm, nreplicas

        ## start new job
        if bg is True:
            self.simulations.new(_run, data, model, niters, pool)
        else:
            _run(data, model, niters, pool)

########################################################################################################################

def _run(data, model, niters, pool):

    ##
    if model.iter == 0:
        model.save()

    ## loop
    for t in range(model.iter, model.iter+niters):
        model.update(data, pool)                # update model state
        model.save()                            # save state