text:
package akha.yakhont.demo.gui;

import akha.yakhont.demo.MainFragment;
import akha.yakhont.demo.R;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * not directly related to the Yakhont Demo - just some GUI stuff
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class SlideShow {

    private static final int                SLIDE_SHOW_DELAY        = 2000;

    private ViewGroup                       mContainer;
    private View                            mSwipeRefreshView;
    private ImageSwitcher                   mImageView;

    private View                            mControlPanel;
    private View                            mControlPanelBtn;

    private Timer                           mTimer;
    private LayoutInflater                  mLayoutInflater;
    private int                             mImageCounter;

    private WeakReference<MainFragment>     mFragment               = new WeakReference<>(null);

    public void init(View view) {
        mContainer          = (ViewGroup) view.findViewById(R.id.container);
        mSwipeRefreshView   = view.findViewById(R.id.swipeContainer);
        mImageView          = (ImageSwitcher) view.findViewById(R.id.image_slide);

        mControlPanel       = view.findViewById(R.id.control_panel);
        mControlPanelBtn    = view.findViewById(R.id.btn_load);

        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);

        ((AbsListView) view.findViewById(R.id.grid)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startSlideShow((String) view.findViewById(R.id.image).getTag());
            }
        });

        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cleanUpSlideShow();
            }
        });
    }

    public void init(MainFragment fragment) {
        mFragment       = new WeakReference<>(fragment);
        mLayoutInflater = LayoutInflater.from(fragment.getActivity());

        mImageView.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imageView = (ImageView) mLayoutInflater.inflate(R.layout.slide, mImageView, false);
                imageView.setScaleX(-1);    // 'cause of 3D rotation side effect
                return imageView;
            }
        });

        mImageView.setInAnimation (AnimationUtils.loadAnimation(fragment.getActivity(), android.R.anim.fade_in ));
        mImageView.setOutAnimation(AnimationUtils.loadAnimation(fragment.getActivity(), android.R.anim.fade_out));

        mImageView.setAnimateFirstView(false);
    }

    private void startSlideShow(final String idx) {
        cleanUpTimer();
        mTimer = new Timer("slide show timer");

        mTimer.scheduleAtFixedRate(new TimerTask() {

            private String              mPackage;
            private Resources           mResources;

            private int getResourceId(String name) {
                return mResources.getIdentifier(name, "drawable", mPackage);
            }

            @Override
            public void run() {
                Activity activity = getActivity();
                if (activity == null) return;

                mPackage   = activity.getPackageName();
                mResources = activity.getResources  ();

                if (getResourceId(getImageName(idx, ++mImageCounter)) == 0) mImageCounter = 1;

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        MainFragment fragment = mFragment.get();
                        if (fragment == null) return;

                        Rect rect = fragment.getSlideRect();
                        mImageView.setImageDrawable(new BitmapDrawable(mResources, Utils.decodeBitmap(
                                mResources, getResourceId(getImageName(idx, mImageCounter)),
                                rect.height(), rect.width())));
                    }
                });
            }
        }, 0, SLIDE_SHOW_DELAY);

        applyRotation(true);
    }

    private void cleanUpSlideShow() {
        cleanUpTimer();
        applyRotation(false);
    }

    private void cleanUpImage() {
        mImageView.reset();
    }

    public void cleanUp() {
        mFragment = new WeakReference<>(null);
        cleanUpTimer();
    }

    private void cleanUpTimer() {
        if (mTimer == null) return;

        mTimer.cancel();
        mTimer = null;

        mImageCounter = 0;
    }

    private String getImageName(String idx, int counter) {
        return String.format(Locale.getDefault(), "img_%s_%02d", idx, counter);
    }

    private Activity getActivity() {
        MainFragment fragment = mFragment.get();
        return fragment == null ? null: fragment.getActivity();
    }

    private void enableControlPanel(boolean enable) {
        mControlPanelBtn.setEnabled(enable);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////

    private final static int                DURATION                = 1000;
    private final static float              DEPTH_Z                 =  310;

    private float                           mDeltaY;

    private void applyRotation(final boolean showSlides) {
        MainFragment fragment = mFragment.get();
        if (fragment == null) return;

        fragment.onSlideShow(showSlides);

        float centerX = mContainer.getWidth()  / 2;
        float centerY = mContainer.getHeight() / 2;

        Rotate3dAnimation rotation = new Rotate3dAnimation(showSlides ? 0: 180, 90, centerX, centerY, DEPTH_Z, true);
        rotation.setDuration(DURATION / 2);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());

        rotation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                mContainer.post(new SwapViews(showSlides));
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        mContainer.startAnimation(rotation);

        View view = fragment.getView();

        if (showSlides) {
            mDeltaY = mControlPanel.getHeight() -
                    ((ViewGroup.MarginLayoutParams) mControlPanel.getLayoutParams()).bottomMargin;

            mControlPanel.animate().setDuration((int) (DURATION * 0.75f)).alpha(0);
            //noinspection ConstantConditions
            view.animate().setDuration(DURATION).yBy(-mDeltaY).scaleY(1 + mDeltaY / view.getHeight());

            enableControlPanel(false);
        }
        else {
            mControlPanel.animate().setDuration((int) (DURATION / 0.75f)).alpha(1);
            //noinspection ConstantConditions
            view.animate().setDuration(DURATION).yBy(mDeltaY).scaleY(1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    enableControlPanel(true);
                }
            });
        }
    }

    private final class SwapViews implements Runnable {

        private final boolean               mShowSlides;

        public SwapViews(boolean showSlides) {
            mShowSlides = showSlides;
        }

        public void run() {
            float centerX = mContainer.getWidth()  / 2;
            float centerY = mContainer.getHeight() / 2;

            if (mShowSlides) {
                mSwipeRefreshView.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                mImageView.requestFocus();
            }
            else {
                mImageView.setVisibility(View.GONE);
                mSwipeRefreshView.setVisibility(View.VISIBLE);
                mSwipeRefreshView.requestFocus();

                cleanUpImage();
            }

            Rotate3dAnimation rotation = new Rotate3dAnimation(90, mShowSlides ? 180: 0, centerX, centerY, DEPTH_Z, false);
            rotation.setDuration(DURATION / 2);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }
}


text:
package org.toobs.framework.pres.sec;

import org.toobs.framework.pres.util.ComponentRequestManager;

public interface IComponentSecurity {

  public abstract boolean hasAccess(String layoutId);

  public abstract ComponentRequestManager getRequestManager();

  public abstract void setRequestManager(ComponentRequestManager requestManager);

}

redpajama_set_name: RedPajamaGithub


text:
import { connect } from  'react-redux';
import SnapshotList from '../../components/snapshots/list';

import {
  fetchSnapshotsIfNeeded,
  loadNext,
  searchSnapshots,
  fetchSnapshot,
  deleteSnapshot,
} from '../../actions/snapshots'

export default connect(
  (state) => ({
    snapshots: state.snapshots
  }),
  dispatch => ({
    loadSnapshotsOnce: () => dispatch(fetchSnapshotsIfNeeded()),
    loadNext: () => dispatch(loadNext()),
    search: (term) => dispatch(searchSnapshots(term)),
    reloadSnapshot: (id) => dispatch(fetchSnapshot(id)),
    deleteSnapshot: (id) => dispatch(deleteSnapshot(id))
  })
)(SnapshotList);


text:
package com.atlassian.plugins.codegen.modules.common;

import com.atlassian.plugins.codegen.AbstractCodegenTestCase;
import com.atlassian.plugins.codegen.modules.PluginModuleLocation;

import org.dom4j.Document;
import org.dom4j.Node;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertNotNull;

/**
 * @since 3.6
 */
public class TemplateContextItemTest extends AbstractCodegenTestCase<TemplateContextItemProperties>
{

    public static final String MODULE_NAME = "My Template Context Item";
    public static final String COMPONENT_REF = "i18nResolver";
    public static final String CLASSNAME = "com.atlassian.component.SomeSingleton";
    public static final String CONTEXT_KEY = "i18n";

    @Before
    public void runGenerator() throws Exception
    {
        setCreator(new TemplateContextItemModuleCreator());
        setModuleLocation(new PluginModuleLocation.Builder(srcDir)
                .resourcesDirectory(resourcesDir)
                .testDirectory(testDir)
                .templateDirectory(templateDir)
                .build());

        setProps(new TemplateContextItemProperties(MODULE_NAME, CONTEXT_KEY));

        props.setIncludeExamples(false);

    }

    @Test
    public void componentRefModuleIsValid() throws Exception
    {
        props.setComponentRef(COMPONENT_REF);
        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        String xpath = "/atlassian-plugin/template-context-item[@name='My Template Context Item' and @key='my-template-context-item' and @i18n-name-key='my-template-context-item.name' and @component-ref='" + COMPONENT_REF + "' and @global='false' and @context-key='" + CONTEXT_KEY + "']";
        Node itemNode = pluginDoc.selectSingleNode(xpath);

        assertNotNull("component ref context item not found", itemNode);
    }

    @Test
    public void classModuleIsValid() throws Exception
    {
        props.setFullyQualifiedClassname(CLASSNAME);
        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        String xpath = "/atlassian-plugin/template-context-item[@name='My Template Context Item' and @key='my-template-context-item' and @i18n-name-key='my-template-context-item.name' and @class='" + CLASSNAME + "' and @global='false' and @context-key='" + CONTEXT_KEY + "']";
        Node itemNode = pluginDoc.selectSingleNode(xpath);

        assertNotNull("class context item not found", itemNode);
    }

    @Test
    public void globalModuleIsValid() throws Exception
    {
        props.setComponentRef(COMPONENT_REF);
        props.setGlobal(true);
        creator.createModule(moduleLocation, props);

        Document pluginDoc = getXmlDocument(pluginXml);
        String xpath = "/atlassian-plugin/template-context-item[@name='My Template Context Item' and @key='my-template-context-item' and @i18n-name-key='my-template-context-item.name' and @component-ref='" + COMPONENT_REF + "' and @global='true' and @context-key='" + CONTEXT_KEY + "']";
        Node itemNode = pluginDoc.selectSingleNode(xpath);

        assertNotNull("component ref context item not found", itemNode);
    }
}


text:
    Text Area

foobar


text:
FROM gcr.io/isdal-vmprod/jetty9-compat-stacktrace-1gcore:1.9.50
#FROM gcr.io/isdal-vmprod/jetty9-compat-20170817-memcache-conn-close
ADD . /app


text:
const Button = () => {
	return <button />;
};
export { Button as default };


text:
define([
  'core',
  './entity',
  'resource'
], function (EVT, Entity, Resource) {
  'use strict';

  // Setup Multimedia inheritance from Entity.
  var Multimedia = function () {
    Entity.apply(this, arguments);
  };

  Multimedia.prototype = Object.create(Entity.prototype);
  Multimedia.prototype.constructor = Multimedia;

  // Attach class to EVT module.
  EVT.Multimedia = Multimedia;

  return {
    resourceConstructor: Resource.constructorFactory('/contents/multimedia', EVT.Multimedia)
  };
});


text:
id: hn_premii
layout: spotlight
collection: spotlight
type: spotlight
published: true

date: 2015-04-01
article:
  written_on: 2015-04-01
  updated_on: 2015-04-01

authors:
  - paulkinlan

tags:
- reader
scores:
  pagespeed:
      speed: 70
      ux: 100
  webpagetest:
      value: 3565
      result: http://www.webpagetest.org/result/150401_3F_JSY/

title: "Hacker News Reader"
link: http://hn.premii.com/
developer: Dharmesh Patel

description: "An amazing optimized reader for Hacker News."
pros: |
  A beautiful and highly optimized reading experience for Hacker News. Works well and looks great across mobile, tablet and desktop. It's fast and testing it on mobile you will see some silky smooth transitions. It has a really nice use of theme-color for integration into Android and it is installable as it uses the [Web App Manifest](/web/fundamentals/device-access/stickyness/web-app-manifest.html) and once installed it looks and feels like a native HN news reader app.
cons: |
  The app does a huge number of things very well, it loads quickly and is fast and smooth to use. If there was one thing the app could do it would be that adding support for offline experiences, this could be a simple error page or a more complex view of cached content.

interview:
  - question: Why the web?
    answer: |
      I prefer to use technology that I am most comfortable in. I created my first webpage long before I wrote "hello world" in c++.

      Open web is the only platform that allows me to reach all kinds of users. I can easily develop and deploy new features and fixes for my app without depending on third party. It allows me to push new features and bug fixes anytime.

      User can try my app without downloading, and can use same app on different platforms. As of today, my app works on latest HTML5 capable browsers including but not limited to Firefox OS, Windows Phone, blackberry, iOS and Android; and its available to download on different app stores. This app is also available on the Chrome web store. I am a sole developer and I work on this few hours per week. I don't think that any other technology would have allowed me to support different platform.
  - question: What worked really well during development?
    answer: |
      I was surprised how well all latest browsers support major HTML5 features. I started my webapp as a prototype to see what I can build using Open Web (HTML5, CSS, Javascript). I only tested my app on iOS Safari and Android browser during development, and it worked on Firefox and with little changes, I was able to support IE mobile.

      Like everyone else, I thought 60FPS was not possible on mobile webapp, specially gestures. I was able to implement pull to refresh, and swipe to go back with little learning; and was able to make it work on all major browsers. With that knowledge, I was able to implement Flipboard webapp style story navigation in few hours.
  - question: If you could have any API to improve your app, what would it be?
    answer: |
      **Intent**: Should be able to launch Android native share intent or iOS share from my webapp. This will allow user to choose the service of their choice instead of my app's limited options.

      **Persistent local storage**: Like to see better support for localstorage. 5MB/2.5MB is not enough. Not only that, there is no way to figure out how much space is available. My app can manage storage properly if I knew how much space is left.

      **Native/standalone webapp**: Better option to deploy/install my webapp on iOS, Android and WP as a standalone app. I use Cordova but its painful to update to the latest version. Chrome on Android is moving in right direction, but iOS and Windows Phone is not providing enough support for standalone app.

related:
-
    title: "Web App Manifest"
    href: fundamentals/device-access/stickyness/web-app-manifest.html
    section:
      id: stickyness
      title: "Add To Home Screen"
      href: fundamentals/device-access/stickyness/
---


text:
"use strict";

/**
 * A tool for for running and testing example scenes.
 * @module Demo
 */

const Demo = module.exports = {};

const Gui = require('Gui');
const Inspector = require('Inspector');
const ToolsCommon = require('./Common');

const Matter = require('matter-js');
const Common = Matter.Common;

Demo._isIOS = window.navigator && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
Demo._matterLink = 'https://brm.io/matter-js/';

/**
 * Creates a new demo instance.
 * See example for options and usage.
 * @function Demo.create
 * @param {} options
 */
Demo.create = function(options) {
  let demo = Object.assign({
    example: {
      instance: null
    },
    examples: [],
    resetOnOrientation: false,
    preventZoom: false,
    fullPage: false,
    startExample: true,
    appendTo: document.body,
    toolbar: {
      title: null,
      url: null,
      reset: true,
      source: false,
      inspector: false,
      tools: false,
      fullscreen: true,
      exampleSelect: false
    },
    tools: {
      inspector: null,
      gui: null
    },
    dom: {}
  }, options || {});

  if (!options.toolbar
    || (demo.examples.length > 1 && options.toolbar && options.toolbar.exampleSelect !== false)) {
    demo.toolbar.exampleSelect = true;
  }

  if (Demo._isIOS) {
    demo.toolbar.fullscreen = false;
  }

  if (!Gui) {
    demo.toolbar.tools = false;
    demo.tools.gui = false;
  }

  if (!Inspector) {
    demo.toolbar.inspector = false;
    demo.tools.inspector = false;
  }

  demo.dom = Demo._createDom(demo);
  Demo._bindDom(demo);

  if (!demo.fullPage && demo.inline !== false) {
    demo.dom.root.classList.add('matter-demo-inline');
  }

  if (demo.appendTo) {
    demo.appendTo.appendChild(demo.dom.root);
  }

  if (demo.startExample) {
    Demo.start(demo, demo.startExample);
  }

  return demo;
};

/**
 * Starts a new demo instance by running the first or given example.
 * See example for options and usage.
 * @function Demo.start
 * @param {demo} demo
 * @param {string} [initalExampleId] example to start (defaults to first)
 */
Demo.start = function(demo, initalExampleId) {
  initalExampleId = typeof initalExampleId === 'string' ? initalExampleId : demo.examples[0].id;

  if (window.location.hash.length > 0) {
    initalExampleId = window.location.hash.slice(1);
  }

  Demo.setExampleById(demo, initalExampleId);
};

/**
 * Stops the currently running example in the demo.
 * This requires that the `example.init` function returned
 * an object specifiying a `stop` function.
 * @function Demo.stop
 * @param {demo} demo
 */
Demo.stop = function(demo) {
  if (demo.example && demo.example.instance) {
    demo.example.instance.stop();
  }
};

/**
 * Stops and restarts the currently running example.
 * @function Demo.reset
 * @param {demo} demo
 */
Demo.reset = function(demo) {
  Common._nextId = 0;
  Common._seed = 0;

  Demo.setExample(demo, demo.example);
};

/**
 * Starts the given example by its id.
 * Any running example will be stopped.
 * @function Demo.setExampleById
 * @param {demo} demo
 * @param {string} exampleId
 */
Demo.setExampleById = function(demo, exampleId) {
  let example = demo.examples.filter((example) => {
    return example.id === exampleId;
  })[0];

  Demo.setExample(demo, example);
};

/**
 * Starts the given example.
 * Any running example will be stopped.
 * @function Demo.setExample
 * @param {demo} demo
 * @param {example} example
 */
Demo.setExample = function(demo, example) {
  if (example) {
    let instance = demo.example.instance;

    if (instance) {
      instance.stop();

      if (instance.canvas) {
        instance.canvas.parentElement.removeChild(instance.canvas);
      }
    }

    window.location.hash = example.id;

    demo.example.instance = null;
    demo.example = example;

    demo.example.instance = instance = example.init(demo);

    if (!instance.canvas && instance.render) {
      instance.canvas = instance.render.canvas;
    }

    if (instance.canvas) {
      demo.dom.root.appendChild(instance.canvas);
    }

    demo.dom.exampleSelect.value = example.id;
    demo.dom.buttonSource.href = example.sourceLink || demo.url || '#';

    setTimeout(function() {
      if (demo.tools.inspector) {
        Demo.setInspector(demo, true);
      }

      if (demo.tools.gui) {
        Demo.setGui(demo, true);
      }
    }, 500);
  } else {
    Demo.setExample(demo, demo.examples[0]);
  }
};

/**
 * Enables or disables the inspector tool.
 * If `enabled` a new `Inspector` instance will be created and the old one destroyed.
 * @function Demo.setInspector
 * @param {demo} demo
 * @param {bool} enabled
 */
Demo.setInspector = function(demo, enabled) {
  if (!enabled) {
    Demo._destroyTools(demo, true, false);
    demo.dom.root.classList.toggle('matter-inspect-active', false);
    return;
  }

  let instance = demo.example.instance;

  Demo._destroyTools(demo, true, false);
  demo.dom.root.classList.toggle('matter-inspect-active', true);

  demo.tools.inspector = Inspector.create(
    instance.engine,
    instance.render
  );
};

/**
 * Enables or disables the Gui tool.
 * If `enabled` a new `Gui` instance will be created and the old one destroyed.
 * @function Demo.setGui
 * @param {demo} demo
 * @param {bool} enabled
 */
Demo.setGui = function(demo, enabled) {
  if (!enabled) {
    Demo._destroyTools(demo, false, true);
    demo.dom.root.classList.toggle('matter-gui-active', false);
    return;
  }

  let instance = demo.example.instance;

  Demo._destroyTools(demo, false, true);
  demo.dom.root.classList.toggle('matter-gui-active', true);

  demo.tools.gui = Gui.create(
    instance.engine,
    instance.runner,
    instance.render
  );
};

Demo._destroyTools = function(demo, destroyInspector, destroyGui) {
  let inspector = demo.tools.inspector,
    gui = demo.tools.gui;

  if (destroyInspector && inspector && inspector !== true) {
    Inspector.destroy(inspector);
    demo.tools.inspector = null;
  }

  if (destroyGui && gui && gui !== true) {
    Gui.destroy(gui);
    demo.tools.gui = null;
  }
};

Demo._toggleFullscreen = function(demo) {
  let fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;

  if (!fullscreenElement) {
    fullscreenElement = demo.dom.root;

    if (fullscreenElement.requestFullscreen) {
      fullscreenElement.requestFullscreen();
    } else if (fullscreenElement.mozRequestFullScreen) {
      fullscreenElement.mozRequestFullScreen();
    } else if (fullscreenElement.webkitRequestFullscreen) {
      fullscreenElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
};

Demo._bindDom = function(demo) {
  var dom = demo.dom;

  window.addEventListener('orientationchange', function() {
    setTimeout(() => {
      if (demo.resetOnOrientation) {
        Demo.reset(demo);
      }
    }, 300);
  });

  if (demo.preventZoom) {
    document.body.addEventListener('gesturestart', function(event) {
      event.preventDefault();
    });

    var allowTap = true,
      tapTimeout;

    document.body.addEventListener('touchstart', function(event) {
      if (!allowTap) {
        event.preventDefault();
      }

      allowTap = false;

      clearTimeout(tapTimeout);
      tapTimeout = setTimeout(function() {
        allowTap = true;
      }, 500);
    });
  }

  if (dom.exampleSelect) {
    dom.exampleSelect.addEventListener('change', function() {
      let exampleId = this.options[this.selectedIndex].value;
      Demo.setExampleById(demo, exampleId);
    });
  }

  if (dom.buttonReset) {
    dom.buttonReset.addEventListener('click', function() {
      Demo.reset(demo);
    });
  }

  if (dom.buttonInspect) {
    dom.buttonInspect.addEventListener('click', function() {
      var showInspector = !demo.tools.inspector;
      Demo.setInspector(demo, showInspector);
    });
  }

  if (dom.buttonTools) {
    dom.buttonTools.addEventListener('click', function() {
      var showGui = !demo.tools.gui;
      Demo.setGui(demo, showGui);
    });
  }

  if (dom.buttonFullscreen) {
    dom.buttonFullscreen.addEventListener('click', function() {
      Demo._toggleFullscreen(demo);
    });

    var fullscreenChange = function() {
      var isFullscreen = document.fullscreen || document.webkitIsFullScreen || document.mozFullScreen;
      document.body.classList.toggle('matter-is-fullscreen', isFullscreen);
    };

    document.addEventListener('webkitfullscreenchange', fullscreenChange);
    document.addEventListener('mozfullscreenchange', fullscreenChange);
    document.addEventListener('fullscreenchange', fullscreenChange);
  }
};

Demo._createDom = function(options) {
  let styles = require('../styles/demo.css');
  ToolsCommon.injectStyles(styles, 'matter-demo-style');

  let root = document.createElement('div');

  let exampleOptions = options.examples.map((example) => {
    return `<option value="${example.id}">${example.name}</option>`;
  }).join(' ');

  var preventZoomClass = options.preventZoom && Demo._isIOS ? 'prevent-zoom-ios' : '';

  root.innerHTML = `

              ${options.toolbar.title}
                <svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
                  <path d="M0 0h24v24H0z" fill="none"/>
                  <path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z"/>
                </svg>

                <select aria-label="Select example" title="Select example" class="matter-example-select matter-select">
                  ${exampleOptions}
                </select>
                <svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
                  <path d="M7 10l5 5 5-5z"/>
                  <path d="M0 0h24v24H0z" fill="none"/>
                </svg>

              <button class="matter-btn matter-btn-reset" title="Reset">
                <svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
                  <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
                  <path d="M0 0h24v24H0z" fill="none"/>
                </svg>
              </button>
              { }
              <button class="matter-btn matter-btn-tools" title="Tools">
                <svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
                  <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
                  <path d="M0 0h24v24H0z" fill="none"/>
                </svg>
              </button>
              <button class="matter-btn matter-btn-inspect" title="Inspect">
              <svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
                <path d="M0 0h24v24H0z" fill="none"/>
                <path d="M11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zm7.32.19C16.84 3.05 15.01 2.25 13 2.05v2.02c1.46.18 2.79.76 3.9 1.62l1.42-1.43zM19.93 11h2.02c-.2-2.01-1-3.84-2.21-5.32L18.31 7.1c.86 1.11 1.44 2.44 1.62 3.9zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zM15 12c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.31 4.9l1.43 1.43c1.21-1.48 2.01-3.32 2.21-5.32h-2.02c-.18 1.45-.76 2.78-1.62 3.89zM13 19.93v2.02c2.01-.2 3.84-1 5.32-2.21l-1.43-1.43c-1.1.86-2.43 1.44-3.89 1.62zm-7.32-.19C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43z"/>
              </svg>
              </button>
              <button class="matter-btn matter-btn-fullscreen" title="Fullscreen">
                <svg fill="#000000" height="22" viewBox="0 0 22 22" width="22" xmlns="http://www.w3.org/2000/svg">
                  <path d="M0 0h24v24H0z" fill="none"/>
                  <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>
                </svg>
              </button>

              <svg class="matter-logo" height="100" viewBox="0 952.04859 330 100" width="268" xmlns="http://www.w3.org/2000/svg">
                <path id="m-triangle" style="fill:#76f09b;" d="m 115.83215,1052.3622 -57.916072,0 -57.916078053812107,0 L 28.958038,1002.2054 57.916077,952.04859 86.874114,1002.2054 Z" />
                <path id="m-square" style="fill:#f55f5f" d="m 168.03172,952.36218 0,100.00002 100,0 0,-100.00002 -100,0 z" />
                <circle id="m-circle" style="fill:#f5b862" r="12.947398" cy="1039.4148" cx="140.28374" />
              </svg>

  `;

  let dom = {
    root: root.firstElementChild,
    title: root.querySelector('.matter-demo-title'),
    header: root.querySelector('.matter-header'),
    exampleSelect: root.querySelector('.matter-example-select'),
    buttonReset: root.querySelector('.matter-btn-reset'),
    buttonSource: root.querySelector('.matter-btn-source'),
    buttonTools: root.querySelector('.matter-btn-tools'),
    buttonInspect: root.querySelector('.matter-btn-inspect'),
    buttonFullscreen: root.querySelector('.matter-btn-fullscreen')
  };

  if (!options.toolbar.title) {
    ToolsCommon.domRemove(dom.title);
  }

  if (!options.toolbar.exampleSelect) {
    ToolsCommon.domRemove(dom.exampleSelect.parentElement);
  }

  if (!options.toolbar.reset) {
    ToolsCommon.domRemove(dom.buttonReset);
  }

  if (!options.toolbar.source) {
    ToolsCommon.domRemove(dom.buttonSource);
  }

  if (!options.toolbar.inspector) {
    ToolsCommon.domRemove(dom.buttonInspect);
  }

  if (!options.toolbar.tools) {
    ToolsCommon.domRemove(dom.buttonTools);
  }

  if (!options.toolbar.fullscreen) {
    ToolsCommon.domRemove(dom.buttonFullscreen);
  }

  return dom;
};


text:
import toCamelCase = require('to-camel-case');

// $ExpectType string
toCamelCase('to-camel-case'); // => 'toCamelCase'


text:
<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>

	<parent>
		<groupId>com.puresoltechnologies.ductiledb</groupId>
		<artifactId>ductiledb-parent</artifactId>
		<version>0.2.0-SNAPSHOT</version>
	</parent>

	<artifactId>tinkerpop</artifactId>
	<name>DuctileDB: ${project.artifactId}</name>

	<dependencies>
		<dependency>
			<groupId>com.puresoltechnologies.ductiledb</groupId>
			<artifactId>core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.tinkerpop</groupId>
			<artifactId>gremlin-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.tinkerpop</groupId>
			<artifactId>tinkergraph-gremlin</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.tinkerpop</groupId>
			<artifactId>gremlin-groovy</artifactId>
		</dependency>
	</dependencies>
</project>


text:
A sync prompt for node. very simple. no C++ bindings and no bash scripts.

Works on Linux, OS X and Windows.

# BASIC MODE
```js

var prompt = require('prompt-sync')();
//
// get input from the user.
//
var n = prompt('How many more times? ');
```
# WITH HISTORY

History is an optional extra, to use simply install the history plugin.

```sh
npm install --save prompt-sync-history
```

```js
var prompt = require('prompt-sync')({
  history: require('prompt-sync-history')() //open history file
});
//get some user input
var input = prompt()
prompt.history.save() //save history back to file
```

See the [prompt-sync-history](http://npm.im/prompt-sync-history) module
for options, or fork it for customized behaviour.

# API

## `require('prompt-sync')(config) => prompt`

Returns an instance of the `prompt` function.
Takes `config` option with the following possible properties

`sigint`: Default is `false`. A ^C may be pressed during the input process to abort the text entry. If sigint it `false`, prompt returns `null`. If sigint is `true` the ^C will be handled in the traditional way: as a SIGINT signal causing process to exit with code 130.

`autocomplete`: A completer function that will be called when user enters TAB to allow for autocomplete. It takes a string as an argument an returns an array of strings that are possible matches for completion. An empty array is returned if there are no matches.

`history`: Takes an object that supplies a "history interface", see [prompt-sync-history](http://npm.im/prompt-sync-history) for an example.

## `prompt(ask, value, opts)`

`ask` is the label of the prompt, `value` is the default value
in absence of a response.

The `opts` argument can also be in the first or second parameter position.

Opts can have the following properties

`echo`: Default is `'*'`. If set the password will be masked with the specified character. For hidden input, set echo to `''` (or use `prompt.hide`).

`autocomplete`: Overrides the instance `autocomplete` function to allow for custom
autocompletion of a particular prompt.

`value`: Same as the `value` parameter, the default value for the prompt. If `opts`
is in the third position, this property will *not* overwrite the `value` parameter.

`ask`: Sames as the `value` parameter. The prompt label. If `opts` is not in the first position, the `ask` parameter will *not* be overridden by this property.

## `prompt.hide(ask)`

Convenience method for creating a standard hidden password prompt,
this is the same as `prompt(ask, {echo: ''})`

# LINE EDITING
Line editing is enabled in the non-hidden mode. (use up/down arrows for history and backspace and left/right arrows for editing)

History is not set when using hidden mode.

# EXAMPLES

```js
  //basic:
  console.log(require('prompt-sync')()('tell me something about yourself: '))

  var prompt = require('prompt-sync')({
    history: require('prompt-sync-history')(),
    autocomplete: complete(['hello1234', 'he', 'hello', 'hello12', 'hello123456']),
    sigint: false
  });

  var value = 'frank';
  var name = prompt('enter name: ', value);
  console.log('enter echo * password');
  var pw = prompt({echo: '*'});
  var pwb = prompt('enter hidden password (or don\'t): ', {echo: '', value: '*pwb default*'})
  var pwc = prompt.hide('enter another hidden password: ')
  var autocompleteTest = prompt('custom autocomplete: ', {
    autocomplete: complete(['bye1234', 'by', 'bye12', 'bye123456'])
  });

  prompt.history.save();

  console.log('\nName: %s\nPassword *: %s\nHidden password: %s\nAnother Hidden password: %s', name, pw, pwb, pwc);
  console.log('autocomplete2: ', autocompleteTest);

  function complete(commands) {
    return function (str) {
      var i;
      var ret = [];
      for (i=0; i< commands.length; i++) {
        if (commands[i].indexOf(str) == 0)
          ret.push(commands[i]);
      }
      return ret;
    };
  };
```


text:
import datetime
from django.contrib.auth.models import User
from django.contrib.comments.managers import CommentManager
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db import models
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH',3000)

class BaseCommentAbstractModel(models.Model):
    """
    An abstract base class that any custom comment models probably should
    subclass.
    """

    # Content-object field
    content_type   = models.ForeignKey(ContentType,
            related_name="content_type_set_for_%(class)s")
    object_pk      = models.TextField(_('object ID'))
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")

    # Metadata about the comment
    site        = models.ForeignKey(Site)

    class Meta:
        abstract = True

    def get_content_object_url(self):
        """
        Get a URL suitable for redirecting to the content object.
        """
        return urlresolvers.reverse(
            "comments-url-redirect",
            args=(self.content_type_id, self.object_pk)
        )

class Comment(BaseCommentAbstractModel):
    """
    A user comment about some object.
    """

    # Who posted this comment? If ``user`` is set then it was an authenticated
    # user; otherwise at least user_name should have been set and the comment
    # was posted by a non-authenticated user.
    user        = models.ForeignKey(User, blank=True, null=True, related_name="%(class)s_comments")
    user_name   = models.CharField(_("user's name"), max_length=50, blank=True)
    user_email  = models.EmailField(_("user's email address"), blank=True)
    user_url    = models.URLField(_("user's URL"), blank=True)

    comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH)

    # Metadata about the comment
    submit_date = models.DateTimeField(_('date/time submitted'), default=None)
    ip_address  = models.IPAddressField(_('IP address'), blank=True, null=True)
    is_public   = models.BooleanField(_('is public'), default=True,
                    help_text=_('Uncheck this box to make the comment effectively ' \
                                'disappear from the site.'))
    is_removed  = models.BooleanField(_('is removed'), default=False,
                    help_text=_('Check this box if the comment is inappropriate. ' \
                                'A "This comment has been removed" message will ' \
                                'be displayed instead.'))

    # Manager
    objects = CommentManager()

    class Meta:
        db_table = "django_comments"
        ordering = ('submit_date',)
        permissions = [("can_moderate", "Can moderate comments")]

    def __unicode__(self):
        return "%s: %s..." % (self.name, self.comment[:50])

    def save(self, force_insert=False, force_update=False):
        if self.submit_date is None:
            self.submit_date = datetime.datetime.now()
        super(Comment, self).save(force_insert, force_update)

    def _get_userinfo(self):
        """
        Get a dictionary that pulls together information about the poster
        safely for both authenticated and non-authenticated comments.

        This dict will have ``name``, ``email``, and ``url`` fields.
        """
        if not hasattr(self, "_userinfo"):
            self._userinfo = {
                "name"  : self.user_name,
                "email" : self.user_email,
                "url"   : self.user_url
            }
            if self.user_id:
                u = self.user
                if u.email:
                    self._userinfo["email"] = u.email

                # If the user has a full name, use that for the user name.
                # However, a given user_name overrides the raw user.username,
                # so only use that if this comment has no associated name.
                if u.get_full_name():
                    self._userinfo["name"] = self.user.get_full_name()
                elif not self.user_name:
                    self._userinfo["name"] = u.username
        return self._userinfo
    userinfo = property(_get_userinfo, doc=_get_userinfo.__doc__)

    def _get_name(self):
        return self.userinfo["name"]
    def _set_name(self, val):
        if self.user_id:
            raise AttributeError(_("This comment was posted by an authenticated "\
                                   "user and thus the name is read-only."))
        self.user_name = val
    name = property(_get_name, _set_name, doc="The name of the user who posted this comment")

    def _get_email(self):
        return self.userinfo["email"]
    def _set_email(self, val):
        if self.user_id:
            raise AttributeError(_("This comment was posted by an authenticated "\
                                   "user and thus the email is read-only."))
        self.user_email = val
    email = property(_get_email, _set_email, doc="The email of the user who posted this comment")

    def _get_url(self):
        return self.userinfo["url"]
    def _set_url(self, val):
        self.user_url = val
    url = property(_get_url, _set_url, doc="The URL given by the user who posted this comment")

    def get_absolute_url(self, anchor_pattern="#c%(id)s"):
        return self.get_content_object_url() + (anchor_pattern % self.__dict__)

    def get_as_text(self):
        """
        Return this comment as plain text.  Useful for emails.
        """
        d = {
            'user': self.user,
            'date': self.submit_date,
            'comment': self.comment,
            'domain': self.site.domain,
            'url': self.get_absolute_url()
        }
        return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d

class CommentFlag(models.Model):
    """
    Records a flag on a comment. This is intentionally flexible; right now, a
    flag could be:

        * A "removal suggestion" -- where a user suggests a comment for (potential) removal.

        * A "moderator deletion" -- used when a moderator deletes a comment.

    You can (ab)use this model to add other flags, if needed. However, by
    design users are only allowed to flag a comment with a given flag once;
    if you want rating look elsewhere.
    """
    user      = models.ForeignKey(User, related_name="comment_flags")
    comment   = models.ForeignKey(Comment, related_name="flags")
    flag      = models.CharField(max_length=30, db_index=True)
    flag_date = models.DateTimeField(default=None)

    # Constants for flag types
    SUGGEST_REMOVAL = "removal suggestion"
    MODERATOR_DELETION = "moderator deletion"
    MODERATOR_APPROVAL = "moderator approval"

    class Meta:
        db_table = 'django_comment_flags'
        unique_together = [('user', 'comment', 'flag')]

    def __unicode__(self):
        return "%s flag of comment ID %s by %s" % \
            (self.flag, self.comment_id, self.user.username)

    def save(self, force_insert=False, force_update=False):
        if self.flag_date is None:
            self.flag_date = datetime.datetime.now()
        super(CommentFlag, self).save(force_insert, force_update)


text:
namespace chrome_browser_net {

// Creates a mock DNS client with a single rule for the known-good query
// (currently google.com) that returns |result| for A queries.
std::unique_ptr<net::DnsClient> CreateMockDnsClientForProbes(
    net::MockDnsClientRule::ResultType result);

}  // namespace chrome_browser_net

#endif  // CHROME_BROWSER_NET_DNS_PROBE_TEST_UTIL_H_


text:
package org.jeewx.api.wxstore.product.model;

public class AttrExt {
	// 是否包邮
	private Integer isPostFree;
	// 是否提供发票
	private Integer isHasReceipt;
	// 是否保修
	private Integer isUnderGuaranty;
	// 是否支持退换货
	private Integer isSupportReplace;
	// 商品所在地地址
	private AttrExtLocation location;
	public Integer getIsPostFree() {
		return isPostFree;
	}
	public void setIsPostFree(Integer isPostFree) {
		this.isPostFree = isPostFree;
	}
	public Integer getIsHasReceipt() {
		return isHasReceipt;
	}
	public void setIsHasReceipt(Integer isHasReceipt) {
		this.isHasReceipt = isHasReceipt;
	}
	public Integer getIsUnderGuaranty() {
		return isUnderGuaranty;
	}
	public void setIsUnderGuaranty(Integer isUnderGuaranty) {
		this.isUnderGuaranty = isUnderGuaranty;
	}
	public Integer getIsSupportReplace() {
		return isSupportReplace;
	}
	public void setIsSupportReplace(Integer isSupportReplace) {
		this.isSupportReplace = isSupportReplace;
	}
	public AttrExtLocation getLocation() {
		return location;
	}
	public void setLocation(AttrExtLocation location) {
		this.location = location;
	}
}


text:
package com.pdfjet;

class FeatureRecord {
    byte[] featureTag;  // 4-byte feature identification tag
    int featureOffset;  // Offset to Feature table-from beginning of FeatureList
}


text:
package org.drip.product.params;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2017 Lakshmi Krishnamurthy
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * Copyright (C) 2015 Lakshmi Krishnamurthy
 * Copyright (C) 2014 Lakshmi Krishnamurthy
 * Copyright (C) 2013 Lakshmi Krishnamurthy
 * Copyright (C) 2012 Lakshmi Krishnamurthy
 * Copyright (C) 2011 Lakshmi Krishnamurthy
 *
 *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
 *  	libraries targeting analysts and developers
 *  	https://lakshmidrip.github.io/DRIP/
 *
 *  DRIP is composed of four main libraries:
 *
 *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
 *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
 *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
 *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
 *
 *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
 *  	Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
 *  	Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
 *  	Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
 *  	Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
 *
 *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
 *  	Incorporator, Holdings Constraint, and Transaction Costs.
 *
 *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
 *
 *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   	you may not use this file except in compliance with the License.
 *
 *  You may obtain a copy of the License at
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  	distributed under the License is distributed on an "AS IS" BASIS,
 *  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *  	limitations under the License.
 */

/**
 * TerminationSetting class contains the current "liveness" state of the component, and, if inactive, how it
 *  entered that state. It exports serialization into and de-serialization out of byte arrays.
 *
 * @author Lakshmi Krishnamurthy
 */

public class TerminationSetting implements org.drip.product.params.Validatable {
	private boolean _bIsDefaulted = false;
	private boolean _bIsPerpetual = false;
	private boolean _bHasBeenExercised = false;

	/**
	 * Construct the TerminationSetting object from the perpetual flag, defaulted flag, and the has
	 * 	been exercised flag.
	 *
	 * @param bIsPerpetual True (component is perpetual)
	 * @param bIsDefaulted True (component has defaulted)
	 * @param bHasBeenExercised True (component has been exercised)
	 */

	public TerminationSetting (
		final boolean bIsPerpetual,
		final boolean bIsDefaulted,
		final boolean bHasBeenExercised)
	{
		_bIsPerpetual = bIsPerpetual;
		_bIsDefaulted = bIsDefaulted;
		_bHasBeenExercised = bHasBeenExercised;
	}

	@Override public boolean validate()
	{
		return true;
	}

	/**
	 * Indicate if the contract has defaulted
	 *
	 * @return TRUE - The Contract has defaulted
	 */

	public boolean defaulted()
	{
		return _bIsDefaulted;
	}

	/**
	 * Indicate if the contract is perpetual
	 *
	 * @return TRUE - The Contract is Perpetual
	 */

	public boolean perpetual()
	{
		return _bIsPerpetual;
	}

	/**
	 * Indicate if the contract has been exercised
	 *
	 * @return TRUE - The Contract has been exercised
	 */

	public boolean exercised()
	{
		return _bHasBeenExercised;
	}
}


text:
<?php

    define('MYSQL_HOST','localhost');
    define('MYSQL_USER','root');
    define('MYSQL_PASSWORD','');
    define('DB_NAME','project');

    function connection() {
        try {
            $con = new PDO('mysql:host='.MYSQL_HOST.';dbname='.DB_NAME,MYSQL_USER,MYSQL_PASSWORD);
            $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (Exception $ex) {
            echo 'Erro ao conectar ao MYSQL: ' . $ex->getMessage();
        }
        return $con;
    }
?>


text:
<?php

namespace ONGR\ElasticsearchBundle\DSL\Query;

use ONGR\ElasticsearchBundle\DSL\BuilderInterface;
use ONGR\ElasticsearchBundle\DSL\ParametersTrait;

/**
 * Elasticsearch query_string query class.
 */
class QueryStringQuery implements BuilderInterface
{
    use ParametersTrait;

    /**
     * @var string The actual query to be parsed.
     */
    private $query;

    /**
     * @param string $query
     * @param array  $parameters
     */
    public function __construct($query, array $parameters = [])
    {
        $this->query = $query;
        $this->setParameters($parameters);
    }

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return 'query_string';
    }

    /**
     * {@inheritdoc}
     */
    public function toArray()
    {
        $query = [
            'query' => $this->query,
        ];

        $output = $this->processArray($query);

        return $output;
    }
}


text:
package com.vladkel.eFindMe.xml.parsing.demo;

import com.vladkel.eFindMe.xml.parsing.demo.DemoSimpleXMLParsing;

public class SimpleXMLParsingIT {

	public static void main(String[] args){

		DemoSimpleXMLParsing dsxp = new DemoSimpleXMLParsing();

		dsxp.demo();

	}
}


text:
<?php
/**
 * Common upgrade script for disabling allow_tags_in_post System Setting
 *
 * See issue #9080.
 *
 * @var modX $modx
 * @package setup
 */
if ($object = $modx->getObject('modSystemSetting', array('key' => 'allow_tags_in_post', 'value' => '1'), false)) {
    $object->set('value', '0');
    $object->save();
}


text:
package com.google.gerrit.reviewdb.server;

import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gwtorm.server.Access;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.PrimaryKey;
import com.google.gwtorm.server.Query;
import com.google.gwtorm.server.ResultSet;

public interface AccountGroupAccess extends
    Access<AccountGroup, AccountGroup.Id> {
  @Override
  @PrimaryKey("groupId")
  AccountGroup get(AccountGroup.Id id) throws OrmException;

  @Query("WHERE groupUUID = ?")
  ResultSet<AccountGroup> byUUID(AccountGroup.UUID uuid) throws OrmException;

  @Query
  ResultSet<AccountGroup> all() throws OrmException;
}


text:
package com.suscipio_solutions.consecro_mud.Abilities.Common;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.Directions;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings("rawtypes")
public class Speculate extends CommonSkill
{
	@Override public String ID() { return "Speculate"; }
	private final static String localizedName = CMLib.lang().L("Speculating");
	@Override public String name() { return localizedName; }
	private static final String[] triggerStrings =I(new String[] {"SPECULATE","SPECULATING"});
	@Override public String[] triggerStrings(){return triggerStrings;}
	@Override public int classificationCode() {   return Ability.ACODE_COMMON_SKILL|Ability.DOMAIN_NATURELORE; }

	protected boolean success=false;
	public Speculate()
	{
		super();
		displayText=L("You are speculating...");
		verb=L("speculating");
	}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if((affected!=null)&&(affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
		{
			final MOB mob=(MOB)affected;
			if(tickUp==6)
			{
				if(success==false)
				{
					final StringBuffer str=new StringBuffer(L("Your speculate attempt failed.\n\r"));
					commonTell(mob,str.toString());
					unInvoke();
				}

			}
		}
		return super.tick(ticking,tickID);
	}

	@Override
	public void unInvoke()
	{
		if(canBeUninvoked())
		{
			if((affected!=null)&&(affected instanceof MOB))
			{
				final MOB mob=(MOB)affected;
				final Room room=mob.location();
				if((success)&&(!aborted)&&(room!=null))
				{
					int resource=room.myResource()&RawMaterial.RESOURCE_MASK;
					if(RawMaterial.CODES.IS_VALID(resource))
					{
						final StringBuffer str=new StringBuffer("");
						String resourceStr=RawMaterial.CODES.NAME(resource);
						str.append(L("You think this spot would be good for @x1.\n\r",resourceStr.toLowerCase()));
						for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
						{
							final Room room2=room.getRoomInDir(d);
							if((room2!=null)
							&&(room.getExitInDir(d)!=null)
							&&(room.getExitInDir(d).isOpen()))
							{
								resource=room2.myResource()&RawMaterial.RESOURCE_MASK;
								if(RawMaterial.CODES.IS_VALID(resource))
								{
									resourceStr=RawMaterial.CODES.NAME(resource);
									str.append(L("There looks like @x1 @x2.\n\r",resourceStr.toLowerCase(),Directions.getInDirectionName(d)));
								}
							}
						}
						commonTell(mob,str.toString());
					}
					else
						commonTell(mob,L("You don't find any good resources around here."));
				}
			}
		}
		super.unInvoke();
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if(super.checkStop(mob, commands))
			return true;
		verb=L("speculating");
		success=false;
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;
		if(proficiencyCheck(mob,0,auto))
			success=true;
		final int duration=getDuration(45,mob,1,10);
		final CMMsg msg=CMClass.getMsg(mob,null,this,getActivityMessageType(),L("<S-NAME> start(s) speculating on this area."));
		if(mob.location().okMessage(mob,msg))
		{
			mob.location().send(mob,msg);
			beneficialAffect(mob,mob,asLevel,duration);
		}
		return true;
	}
}


text:
/**
 * Apply a search and pagination to Mongoose query
 */

var mongoose = require('mongoose'),
    Query = mongoose.Query;

var computedFilters = {};

/**
 * Apply the pagination on the current query.
 * @param req, the current request containing the pagin and search objects
 * @return {Query}
 */
Query.prototype.paginatedSearch = function (req) {
    var pagin = {};
    // add pagination
    if (req.query.pagin) {
        pagin = JSON.parse(req.query.pagin);
    } else {
        pagin = {
            limit: 0,
            skip: 0
        };
    }

    return this.skip(pagin.skip).limit(pagin.limit)
};

/**
 * Return an object containing all the filters
 * @param filters, an object {property: value}
 */
exports.getFilters = function (filters) {

    computedFilters = {};

    for (var property in filters) {

        if (!Array.isArray(filters[property])) {
            filters[property] = [filters[property]];
        }

        for (var key in filters[property]) {

            var params = filters[property][key];

            var op = params.op || '=';
            var source = params.source || null;
            var condition = params.hasOwnProperty('condition') ? params.condition : true;

            if (source) {
                var key = typeof params === 'object' ? params.value : params;
                var value = source[key];
            } else {
                var value = typeof params === 'object' ? params.value : params;
            }

            if (value) {
                switch (op) {
                    case '=':
                        _addFilter(property, value, condition);
                        break;
                    case 'like':
                        _addFilter(property, new RegExp('^(.)*' + value + '(.)*$', "i"), condition);
                        break;
                    case 'in':
                        if (!Array.isArray(value)) {
                            value = [value];
                        }
                        _addFilter(property, {$in: value}, condition);
                        break;
                    case 'nin':
                        if (!Array.isArray(value)) {
                            value = [value];
                        }
                        _addFilter(property, {$nin: value}, condition);
                        break;
                }
            } else {
                delete computedFilters[property];
            }
        }
    }

    return computedFilters;
};

/**
 * Add a new filter if the condition returns true
 * @param property
 * @param value
 * @param condition
 * @private
 */
var _addFilter = function (property, value, condition) {

    if (condition === true) {
        computedFilters[property] = value;
    }
};


text:
import { Map } from 'immutable';

import fireAction from '../../test-utils/fire-action';
import commentReducer from '../reducers/comment';

import {
  GET_COMMENT_LIST_ERROR,
  GET_COMMENT_LIST_PENDING,
  GET_COMMENT_LIST_SUCCESS,

  POST_COMMENT_ERROR,
  POST_COMMENT_PENDING,
  POST_COMMENT_SUCCESS
} from '../../src/constants/comment.action.types';

let state = commentReducer();

describe('Comment Reducer', () => {

  describe('on POST_COMMENT_PENDING', () => {
    it('should set loading to true', () => {
      state = fireAction(commentReducer, state, POST_COMMENT_PENDING);
      expect(state.get('isLoading')).toBe(true);
      expect(state.get('hasError')).toBe(false)
    });
  });

  describe('on POST_COMMENT_SUCCESS', () => {
    it('should have one comment', () => {
      const res = mockResponse()
      state = fireAction(
        commentReducer,
        state,
        POST_COMMENT_SUCCESS,
        res
      );

      expect(state.get('isLoading')).toBe(false);
      expect(state.get('hasError')).toBe(false);
      expect(state.get('comments').get(res.postId.toString())).toBeTruthy(state)
      expect(state.get('comments').get(
        res.postId.toString()).size
      ).toBe(1, state);
    });
  });

  describe('on POST_COMMENT_ERROR', () => {
    it('should has error', () => {
      state = fireAction(commentReducer, state, POST_COMMENT_ERROR);

      expect(state.get('isLoading')).toBe(false);
      expect(state.get('hasError')).toBe(true);
    });
  });

  describe('on GET_COMMENT_LIST_PENDING', () => {
    it('should be pending', () => {
      state = fireAction(commentReducer, state, GET_COMMENT_LIST_PENDING);
      expect(state.get('isLoading')).toBe(true);
      expect(state.get('hasError')).toBe(false)
    });
  });

  describe('on GET_COMMENT_LIST_SUCCESS', () => {
    it('should save one comment', () => {
      const res = [mockResponse()]
      state = fireAction(
        commentReducer,
        state,
        GET_COMMENT_LIST_SUCCESS,
        res
      );

      expect(state.get('isLoading')).toBe(false);
      expect(state.get('hasError')).toBe(false);
      expect(state.get('comments').get(
        res[0].postId.toString())
      ).toBeTruthy(state)

      expect(
        state.get('comments').get(res[0].postId.toString()).size
      ).toBe(2, state.get(res[0].postId.toString()));
    });
  });

  describe('on GET_COMMENT_LIST_ERROR', () => {
    it('should has error', () => {
      state = fireAction(commentReducer, state, GET_COMMENT_LIST_ERROR);

      expect(state.get('isLoading')).toBe(false);
      expect(state.get('hasError')).toBe(true);
    });
  });

});

function mockResponse() {
  return {
    comment: {
      entityMap: {},
      blocks: [
        {
          key: 'bk1gc',
          text: 'asdasd',
          type: 'unstyled',
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: {}
        }]
    },
    id: 255,
    postId: 201,
    author: {
      'avatar': 'http://images.yibencezi.com/FqSfRyyFKt0f5E7YyeLcxi1VkEMk',
      'first': 'Super',
      'last': 'Dave',
      'id': '3dddazz'
    }
  }
}


text:
class CreateLanguages < ActiveRecord::Migration[5.0]
  def change
    create_table :languages do |t|
      t.string :iso
      t.string :name

      t.timestamps
    end
  end
end


text:
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "PathCairo.h"
#include <math.h>
#include "DrawTargetCairo.h"
#include "Logging.h"
#include "PathHelpers.h"
#include "HelpersCairo.h"

namespace mozilla {
namespace gfx {

CairoPathContext::CairoPathContext(cairo_t* aCtx, DrawTargetCairo* aDrawTarget)
 : mContext(aCtx)
 , mDrawTarget(aDrawTarget)
{
  cairo_reference(mContext);

  // A new path in the DrawTarget's context.
  aDrawTarget->SetPathObserver(this);
  cairo_new_path(mContext);
}

CairoPathContext::CairoPathContext(CairoPathContext& aPathContext)
 : mContext(aPathContext.mContext)
 , mDrawTarget(nullptr)
{
  cairo_reference(mContext);
  DuplicateContextAndPath();
}

CairoPathContext::~CairoPathContext()
{
  if (mDrawTarget) {
    DrawTargetCairo* drawTarget = mDrawTarget;
    ForgetDrawTarget();

    // We need to set mDrawTarget to nullptr before we tell DrawTarget otherwise
    // we will think we need to make a defensive copy of the path.
    drawTarget->SetPathObserver(nullptr);
  }
  cairo_destroy(mContext);
}

void
CairoPathContext::DuplicateContextAndPath()
{
  // Duplicate the path.
  cairo_path_t* path = cairo_copy_path(mContext);

  // Duplicate the context.
  cairo_surface_t* surf = cairo_get_target(mContext);
  cairo_matrix_t matrix;
  cairo_get_matrix(mContext, &matrix);
  cairo_destroy(mContext);

  mContext = cairo_create(surf);

  // Set the matrix to match the source context so that the path is copied in
  // device space. After this point it doesn't matter what the transform is
  // set to because it's always swapped out before use.
  cairo_set_matrix(mContext, &matrix);

  // Add the path, and throw away our duplicate.
  cairo_append_path(mContext, path);
  cairo_path_destroy(path);
}

void
CairoPathContext::ForgetDrawTarget()
{
  // We don't need to set the path observer back to nullptr in this case
  // because ForgetDrawTarget() is trigged when the target has been
  // grabbed by another path observer.
  mDrawTarget = nullptr;
}

void
CairoPathContext::PathWillChange()
{
  // Once we've copied out the context's path, there's no use to holding on to
  // the draw target. Thus, there's nothing for us to do if we're independent
  // of the draw target, since we'll have already copied out the context's
  // path.
  if (mDrawTarget) {
    // The context we point to is going to change from under us. To continue
    // using this path, we need to copy it to a new context.
    DuplicateContextAndPath();
    ForgetDrawTarget();
  }
}

void
CairoPathContext::CopyPathTo(cairo_t* aToContext, Matrix& aTransform)
{
  if (aToContext != mContext) {
    CairoTempMatrix tempMatrix(mContext, aTransform);
    cairo_path_t* path = cairo_copy_path(mContext);
    cairo_new_path(aToContext);
    cairo_append_path(aToContext, path);
    cairo_path_destroy(path);
  }
}

bool
CairoPathContext::ContainsPath(const Path* aPath)
{
  if (aPath->GetBackendType() != BACKEND_CAIRO) {
    return false;
  }

  const PathCairo* path = static_cast<const PathCairo*>(aPath);
  RefPtr<CairoPathContext> ctx = const_cast<PathCairo*>(path)->GetPathContext();
  return ctx == this;
}

PathBuilderCairo::PathBuilderCairo(CairoPathContext* aPathContext,
                                   FillRule aFillRule,
                                   const Matrix& aTransform /* = Matrix() */)
 : mPathContext(aPathContext)
 , mTransform(aTransform)
 , mFillRule(aFillRule)
{}

PathBuilderCairo::PathBuilderCairo(cairo_t* aCtx, DrawTargetCairo* aDrawTarget, FillRule aFillRule)
 : mPathContext(new CairoPathContext(aCtx, aDrawTarget))
 , mTransform(aDrawTarget->GetTransform())
 , mFillRule(aFillRule)
{}

void
PathBuilderCairo::MoveTo(const Point &aPoint)
{
  PrepareForWrite();
  CairoTempMatrix tempMatrix(*mPathContext, mTransform);
  cairo_move_to(*mPathContext, aPoint.x, aPoint.y);
}

void
PathBuilderCairo::LineTo(const Point &aPoint)
{
  PrepareForWrite();
  CairoTempMatrix tempMatrix(*mPathContext, mTransform);
  cairo_line_to(*mPathContext, aPoint.x, aPoint.y);
}

void
PathBuilderCairo::BezierTo(const Point &aCP1,
                           const Point &aCP2,
                           const Point &aCP3)
{
  PrepareForWrite();
  CairoTempMatrix tempMatrix(*mPathContext, mTransform);
  cairo_curve_to(*mPathContext, aCP1.x, aCP1.y, aCP2.x, aCP2.y, aCP3.x, aCP3.y);
}

void
PathBuilderCairo::QuadraticBezierTo(const Point &aCP1,
                                    const Point &aCP2)
{
  PrepareForWrite();
  CairoTempMatrix tempMatrix(*mPathContext, mTransform);

  // We need to elevate the degree of this quadratic Bézier to cubic, so we're
  // going to add an intermediate control point, and recompute control point 1.
  // The first and last control points remain the same.
  // This formula can be found on http://fontforge.sourceforge.net/bezier.html
  Point CP0 = CurrentPoint();
  Point CP1 = (CP0 + aCP1 * 2.0) / 3.0;
  Point CP2 = (aCP2 + aCP1 * 2.0) / 3.0;
  Point CP3 = aCP2;

  cairo_curve_to(*mPathContext, CP1.x, CP1.y, CP2.x, CP2.y, CP3.x, CP3.y);
}

void
PathBuilderCairo::Close()
{
  PrepareForWrite();
  cairo_close_path(*mPathContext);
}

void
PathBuilderCairo::Arc(const Point &aOrigin, float aRadius, float aStartAngle,
                     float aEndAngle, bool aAntiClockwise)
{
  ArcToBezier(this, aOrigin, aRadius, aStartAngle, aEndAngle, aAntiClockwise);
}

Point
PathBuilderCairo::CurrentPoint() const
{
  CairoTempMatrix tempMatrix(*mPathContext, mTransform);
  double x, y;
  cairo_get_current_point(*mPathContext, &x, &y);
  return Point((Float)x, (Float)y);
}

TemporaryRef<Path>
PathBuilderCairo::Finish()
{
  return new PathCairo(mPathContext, mTransform, mFillRule);
}

TemporaryRef<CairoPathContext>
PathBuilderCairo::GetPathContext()
{
  return mPathContext;
}

void
PathBuilderCairo::PrepareForWrite()
{
  // Only PathBuilder and PathCairo maintain references to CairoPathContext.
  // DrawTarget does not. If we're sharing a reference to the context then we
  // need to create a copy that we can modify. This provides copy on write
  // behaviour.
  if (mPathContext->refCount() != 1) {
    mPathContext = new CairoPathContext(*mPathContext);
  }
}

PathCairo::PathCairo(CairoPathContext* aPathContext, Matrix& aTransform,
                     FillRule aFillRule)
 : mPathContext(aPathContext)
 , mTransform(aTransform)
 , mFillRule(aFillRule)
{}

TemporaryRef<PathBuilder>
PathCairo::CopyToBuilder(FillRule aFillRule) const
{
  return new PathBuilderCairo(mPathContext, aFillRule, mTransform);
}

TemporaryRef<PathBuilder>
PathCairo::TransformedCopyToBuilder(const Matrix &aTransform, FillRule aFillRule) const
{
  // We are given the transform we would apply from device space to user space.
  // However in cairo our path is in device space so we view the transform as
  // being the other way round. We therefore need to apply the inverse transform
  // to our current cairo transform.
  Matrix inverse = aTransform;
  inverse.Invert();

  return new PathBuilderCairo(mPathContext, aFillRule, mTransform * inverse);
}

bool
PathCairo::ContainsPoint(const Point &aPoint, const Matrix &aTransform) const
{
  CairoTempMatrix(*mPathContext, mTransform);

  Matrix inverse = aTransform;
  inverse.Invert();
  Point transformed = inverse * aPoint;

  // Needs the correct fill rule set.
  cairo_set_fill_rule(*mPathContext, GfxFillRuleToCairoFillRule(mFillRule));
  return cairo_in_fill(*mPathContext, transformed.x, transformed.y);
}

Rect
PathCairo::GetBounds(const Matrix &aTransform) const
{
  CairoTempMatrix(*mPathContext, mTransform);

  double x1, y1, x2, y2;

  cairo_path_extents(*mPathContext, &x1, &y1, &x2, &y2);
  Rect bounds(Float(x1), Float(y1), Float(x2 - x1), Float(y2 - y1));
  return aTransform.TransformBounds(bounds);
}

Rect
PathCairo::GetStrokedBounds(const StrokeOptions &aStrokeOptions,
                            const Matrix &aTransform) const
{
  CairoTempMatrix(*mPathContext, mTransform);

  double x1, y1, x2, y2;

  SetCairoStrokeOptions(*mPathContext, aStrokeOptions);

  cairo_stroke_extents(*mPathContext, &x1, &y1, &x2, &y2);
  Rect bounds((Float)x1, (Float)y1, (Float)(x2 - x1), (Float)(y2 - y1));
  return aTransform.TransformBounds(bounds);
}

TemporaryRef<CairoPathContext>
PathCairo::GetPathContext()
{
  return mPathContext;
}

void
PathCairo::CopyPathTo(cairo_t* aContext, DrawTargetCairo* aDrawTarget)
{
  mPathContext->CopyPathTo(aContext, mTransform);
  cairo_set_fill_rule(aContext, GfxFillRuleToCairoFillRule(mFillRule));
}

}
}


text:
/*	Public domain	*/
/*
 * This demo tests the various canned dialogs provided by AG_Text(3).
 */

#include "agartest.h"

char someString[256];
double v = 10.0;

static void
TestPrompts(AG_Event *event)
{
	/* Edit an existing floating-point variable. */
	AG_TextEditFloat(&v, 0.0, 100.0, "cm", "Edit a float value: ");

	/* Edit a fixed-size string buffer. */
	AG_Strlcpy(someString, "Test string", sizeof(someString));
	AG_TextEditString(someString, sizeof(someString), "Edit a string: ");
}

static void
TestCanned(AG_Event *event)
{
	AG_TextWarning("my-warning-key", "This is a warning");
	AG_TextError("This is an error message");
	AG_TextTmsg(AG_MSG_INFO, 3000, "This is a timed message");
	AG_TextMsg(AG_MSG_INFO, "This is an informational message");
	AG_TextInfo("infomsg",
	    "This is an informational message with \n"
	    "multiple lines");
}

static int
TestGUI(void *obj, AG_Window *win)
{
	AG_ButtonNewFn(win, 0, "Test prompts", TestPrompts, "%p", win);
	AG_ButtonNewFn(win, 0, "Test canned dialogs", TestCanned, "%p", win);
	return (0);
}

const AG_TestCase textDlgTest = {
	"textDlg",
	N_("Test canned dialogs in AG_Text(3)"),
	"1.4.2",
	0,
	sizeof(AG_TestInstance),
	NULL,		/* init */
	NULL,		/* destroy */
	NULL,		/* test */
	TestGUI,
	NULL		/* bench */
};


text:
PWGJE::EMCALJetTasks::AliAnalysisTaskChargedParticlesRefMC *AddTaskChargedParticlesRefMCSystematics(const char *dummy, const char *suffix){
  return PWGJE::EMCALJetTasks::AliAnalysisTaskChargedParticlesRefMC::AddTaskChargedParticlesRefMC(suffix);
}


text:
require 'resque'

module Peek
  module Views
    class Resque < View
      def initialize(options = {})
        @queues = options.fetch(:queues, ['*'])
      end

      def job_count
        lookup = @queues == ['*'] ? ::Resque.queues : @queues
        lookup.collect { |queue| ::Resque.size(queue) }.inject(&:+)
      end

      def context
        {
          :jobs => {
            :failures => ::Resque::Failure.count
          }
        }
      end

      def results
        { :jobs => job_count, :workers => ::Resque.workers.size }
      end
    end
  end
end


text:
module VagrantZFS
  module Action
    module Box
      class Destroy
        def initialize(app, env)
          @app = app
          @env = env
        end

        def call(env)
          # Delete the existing box
          env[:ui].info I18n.t("vagrant.actions.box.destroy.destroying", :name => env[:box_name])
          VagrantZFS::ZFS.destroy_at env['box_directory'].to_s

          # Reload the box collection
          env[:box_collection].reload!

          @app.call(env)
        end
      end
    end
  end
end


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace Mobile_App_Xamarin_Native.iOS
{
    [Register ("DgfipResourceViewController")]
    partial class DgfipResourceViewController
    {
        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        UIKit.UILabel NbPacLabel { get; set; }

        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        UIKit.UILabel NbPartLabel { get; set; }

        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        UIKit.UILabel RfrLabel { get; set; }

        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        UIKit.UILabel SitFamLabel { get; set; }

        void ReleaseDesignerOutlets ()
        {
            if (NbPacLabel != null) {
                NbPacLabel.Dispose ();
                NbPacLabel = null;
            }

            if (NbPartLabel != null) {
                NbPartLabel.Dispose ();
                NbPartLabel = null;
            }

            if (RfrLabel != null) {
                RfrLabel.Dispose ();
                RfrLabel = null;
            }

            if (SitFamLabel != null) {
                SitFamLabel.Dispose ();
                SitFamLabel = null;
            }
        }
    }
}


text:
@interface NFRRenderTarget : NSObject

typedef NS_ENUM(NSUInteger, NFR_TARGET_BUFFER_TYPE) {
    kTextureBuffer,
    kCubeMapBuffer,
    kRenderBuffer
};

typedef NS_ENUM(NSUInteger, NFR_ATTACHMENT_TYPE) {
    kColorAttachment,
    kDepthAttachment,
    kStencilAttachment,
    kDepthStencilAttachment
};

//
// TODO: use this struct for attachment handles (could also use a better name
//
typedef struct NFRRenderTargetAttachment_t {
    NSUInteger handle;
    NFR_TARGET_BUFFER_TYPE type;
} NFRRenderTargetAttachment_t;

// for a framebuffer to be complete it needs at least
// - one attached buffer (color, depth, or stencil buffer)
// - there should be at least one color attachment
// - all attachments need to be complete (reserved memory)
// - each buffer should have the same number of samples

//
// TODO: consider changing width and height to type GLsizei
//
@property (nonatomic, assign) uint32_t width;
@property (nonatomic, assign) uint32_t height;

- (instancetype) initWithWidth:(uint32_t)width withHeight:(uint32_t)height NS_DESIGNATED_INITIALIZER;

- (void) resizeWithWidth:(uint32_t)width withHeight:(uint32_t)height;

- (void) addAttachment:(NFR_ATTACHMENT_TYPE)attachmentType withBackingBuffer:(NFR_TARGET_BUFFER_TYPE)bufferType;

//
// TODO: should try to avoid having an externally facing enable/disable methods
//
- (void) enable;
- (void) disable;

@property (nonatomic, assign, readonly) NFRRenderTargetAttachment_t colorAttachment;
@property (nonatomic, assign, readonly) NFRRenderTargetAttachment_t depthAttachment;
@property (nonatomic, assign, readonly) NFRRenderTargetAttachment_t stencilAttachment;
@property (nonatomic, assign, readonly) NFRRenderTargetAttachment_t depthStencilAttachment;

@end


text:
<script type="text/javascript">
    $(document).ready(function(){
        $("div.answer > button").click(function(){

            $(this).addClass('teal lighten-2');
            $(this).siblings().removeClass('teal lighten-2');
        });
    });
</script>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.poprosturonin.cameraapp">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_camera_alt_black_24dp"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
<?php

namespace phpManufaktur\Contact\Data\Contact;

use Silex\Application;

class Form
{

    protected $app = null;
    protected static $table_name = null;

    /**
     * Constructor
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
        self::$table_name = FRAMEWORK_TABLE_PREFIX.'contact_form';
    }

    /**
     * Create the FORM table
     *
     * @throws \Exception
     */
    public function createTable()
    {
        $table = self::$table_name;

        $SQL = <<<EOD
    CREATE TABLE IF NOT EXISTS `$table` (
        `form_id` INT(11) NOT NULL AUTO_INCREMENT,
        `contact_id` INT(11) NOT NULL DEFAULT '-1',
        `contact_data` TEXT NOT NULL,
        `form_name` VARCHAR(255) NOT NULL DEFAULT '',
        `form_config` TEXT NOT NULL,
        `form_data` TEXT NOT NULL,
        `form_submitted_when` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
        `form_submitter_ip` VARCHAR(64) NOT NULL DEFAULT '0.0.0.0',
        `form_timestamp` TIMESTAMP,
        PRIMARY KEY (`form_id`),
        INDEX (`contact_id`)
        )
    COMMENT='The contact form table'
    ENGINE=InnoDB
    AUTO_INCREMENT=1
    DEFAULT CHARSET=utf8
    COLLATE='utf8_general_ci'
EOD;
        try {
            $this->app['db']->query($SQL);
            $this->app['monolog']->addInfo("Created table 'contact_form'", array(__METHOD__, __LINE__));
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Delete table - switching check for foreign keys off before executing
     *
     * @throws \Exception
     */
    public function dropTable()
    {
        $this->app['db.utils']->dropTable(self::$table_name);
    }

/**
     * Insert a new record in the FORM table
     *
     * @param array $data
     * @param reference integer $form_id
     * @throws \Exception
     */
    public function insert($data, &$form_id=null)
    {
        try {
            $insert = array();
            foreach ($data as $key => $value) {
                if (($key == 'form_id') || ($key == 'form_timestamp')) continue;
                $insert[$key] = is_string($value) ? $this->app['utils']->sanitizeText($value) : $value;
            }
            if (!isset($insert['form_submitted_when'])) {
                // add the 'form_submitted_when' field with the actual date/time
                $insert['form_submitted_when'] = date('Y-m-d H:i:s');
            }
            $this->app['db']->insert(self::$table_name, $insert);
            $contact_id = $this->app['db']->lastInsertId();
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }
}


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

<TITLE>
G-Index
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

C D G M W

G

getInternalAddressFromExternalUrl(String, String) -
Method in class com.ibm.xsp.webdav.repository.DAVRepositoryDominoDocuments

getResource(String) -
Method in class com.ibm.xsp.webdav.repository.DAVRepositoryDominoDocuments

getResource(String, boolean) -
Method in class com.ibm.xsp.webdav.repository.DAVRepositoryDominoDocuments

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

C D G M W


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>MAGMA: Sparse-Iter</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

MAGMA
    1.6.1

Matrix Algebra for GPU and Multicore Architectures

Main Page

Related Pages

Modules

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

 All Classes Files Functions Friends Groups Pages

Sparse-Iter

The MAGMA Sparse-Iter Package

The sparse-iter package recently added to the MAGMA software stack contains sparse BLAS routines as well as functions to handle the complete iterative solution process of a sparse linear system of equations.

A typical application includes:

an interface passing the linear system to MAGMA

choosing the desired data structures for the respective sparse BLAS functions

sending the data structures to the device

choosing solver, eigensolver, and preconditioner

solving the respective system on the device

passing back the results

For each of these steps, multiple options are offered by the MAGMA software stack.

Sparse Data Structures

For a more generic programming approach, the sparse data structures (matrices and vectors) are stored in data structures containing all information necessary to access the sparse-BLAS via wrappers:

struct magma_z_sparse_matrix{
    magma_storage_t    storage_type;            // matrix format - CSR, ELL, SELL-P
    magma_location_t   memory_location;         // CPU or DEV
    magma_symmetry_t   sym;                     // opt: indicate symmetry
    magma_diagorder_t  diagorder_type;          // opt: only needed for factorization matrices
    magma_fillmode_t   fill_mode;               // fill mode full/lower/upper
    magma_int_t        num_rows;                // number of rows
    magma_int_t        num_cols;                // number of columns
    magma_int_t        nnz;                     // opt: number of nonzeros
    magma_int_t        max_nnz_row;             // opt: max number of nonzeros in one row
    magma_int_t        diameter;                // opt: max distance of entry from main diagonal
    union {
        magmaDoubleComplex      *val;           // array containing values in CPU case
        magmaDoubleComplex_ptr  dval;           // array containing values in DEV case
    };
    union {
        magmaDoubleComplex      *diag;          // opt: diagonal entries in CPU case
        magmaDoubleComplex_ptr  ddiag;          // opt: diagonal entries in DEV case
    };
    union {
        magma_index_t           *row;           // row pointer CPU case
        magmaIndex_ptr          drow;           // row pointer DEV case
    };
    union {
        magma_index_t           *rowidx;        // opt: array containing row indices CPU case
        magmaIndex_ptr          drowidx;        // opt: array containing row indices DEV case
    };
    union {
        magma_index_t           *col;           // array containing col indices CPU case
        magmaIndex_ptr          dcol;           // array containing col indices  DEV case
    };
    magma_index_t      *blockinfo;              // opt: for BCSR format CPU case
    magma_int_t        blocksize;               // opt: info for SELL-P/BCSR
    magma_int_t        numblocks;               // opt: info for SELL-P/BCSR
    magma_int_t        alignment;               // opt: info for SELL-P/BCSR
}magma_z_sparse_matrix;

struct magma_z_vector{
    magma_location_t   memory_location;         // CPU or DEV
    magma_int_t        num_rows;                // number of rows
    magma_int_t        num_cols;                // number of columns (in case of a block of vectors)
    magma_int_t        nnz;                     // opt: number of nonzeros
    union {
        magmaDoubleComplex      *val;           // array containing values in CPU case
        magmaDoubleComplex_ptr  dval;           // array containing values in DEV case
    };
    magma_order_t      major;                   // storage type:Row/Column-Major
}magma_z_vector;

The purpose of the unions (e.g. for the val array) is to support different hardware platforms, where the magmaXXX_ptr is adapted to the respective device characteristics.

For sparse matrices, the main formats are CSR, ELL and the MAGMA-specific SELL-P. Generally, the sparse-BLAS routines provide for these the best performance.

Without specifying the storage type, the memory location or the dimension of the matrix, the sparse matrix vector product can then be used via the wrapper:

magma_z_spmv(
        magmaDoubleComplex alpha,
        magma_z_sparse_matrix A,
        magma_z_vector x,
        magmaDoubleComplex beta,
        magma_z_vector y,
        magma_queue_t queue );

Sparse I/O

A sparse matrix stored in mtx format can be read from disk via the function:

magma_z_csr_mtx(
        magma_z_sparse_matrix *A,
        const char *filename,
        magma_queue_t queue );

A sparse linear system of dimension mxn present in main memory can be passed to MAGMA via the function:

magma_zcsrset(
        magma_int_t m,
        magma_int_t n,
        magma_index_t *row,
        magma_index_t *col,
        magmaDoubleComplex *val,
        magma_z_sparse_matrix *A,
        magma_queue_t queue );

where row, col, val contain the matrix in CSR format.

If the matrix is already present in DEV memory, the corresponding function is

magma_zcsrset_gpu(
    magma_int_t m,
    magma_int_t n,
    magmaIndex_ptr row,
    magmaIndex_ptr col,
    magmaDoubleComplex_ptr val,
    magma_z_sparse_matrix *A,
    magma_queue_t queue );

Similarly, matrices handled in MAGMA can be returned via the functions

magma_zcsrget(
    magma_z_sparse_matrix A,
    magma_int_t *m,
    magma_int_t *n,
    magma_index_t **row,
    magma_index_t **col,
    magmaDoubleComplex **val,
    magma_queue_t queue );

magma_zcsrget_gpu(
    magma_z_sparse_matrix A,
    magma_int_t *m,
    magma_int_t *n,
    magmaIndex_ptr *row,
    magmaIndex_ptr *col,
    magmaDoubleComplex_ptr *val,
    magma_queue_t queue );

respectively

write_z_csrtomtx(
    magma_z_sparse_matrix A,
    const char *filename,
    magma_queue_t queue );

Additionally, MAGMA contains routines to generate stencil discretizations of different kind.

Vectors can be initiated inside MAGMA via

magma_z_vinit(
    magma_z_vector *x,
    magma_location_t memory_location,
    magma_int_t num_rows,
    magmaDoubleComplex values,
    magma_queue_t queue );

where ''memory_location'' sets the location (Magma_CPU or Magma_DEV). Also, vectors can be read from file via

magma_z_vread(
    magma_z_vector *x,
    magma_int_t length,
    char * filename,
    magma_queue_t queue );

or - in case of a block of sparse vectors stored as CSR matrix - via

magma_z_vspread(
    magma_z_vector *x,
    const char * filename,
    magma_queue_t queue );

or passed from/to main memory:

magma_zvset(
    magma_int_t m,
    magma_int_t n,
    magmaDoubleComplex *val,
    magma_z_vector *b,
    magma_queue_t queue );

magma_zvget(
    magma_z_vector b
    magma_int_t *m,
    magma_int_t *n,
    magmaDoubleComplex **val,
    magma_queue_t queue );

Matrix Formats

To convert a matrix from one into another format, the CPU-based routine

magma_z_mconvert(
    magma_z_sparse_matrix A,
    magma_z_sparse_matrix *B,
    magma_storage_t old_format,
    magma_storage_t new_format,
    magma_queue_t queue );

can be used where old_format and new_format determine the specific conversion.

Memory Handling

All iterative solvers and eigensolvers included in the sparse-iter package work on the device. Hence, it is required to send the respective data structures to the device for solving, and back to access the solution. The functions

magma_z_mtransfer(
    magma_z_sparse_matrix A,
    magma_z_sparse_matrix *B,
    magma_location_t src,
    magma_location_t dst,
    magma_queue_t queue );

magma_z_vtransfer(
    magma_z_vector x,
    magma_z_vector *y,
    magma_location_t src,
    magma_location_t dst,
    magma_queue_t queue );

allow any data copy operation - from host to device, device to device, device to host or host to host.

Linear algebra objects can be deallocated via

magma_z_mfree(
    magma_z_sparse_matrix *A,
    magma_queue_t queue );

magma_z_vfree(
    magma_z_vector *x,
    magma_queue_t queue );

Iterative Solvers

The sparse-iter package contains a variety of linear solvers, eigensolvers, and preconditioners. The standard procedure to call a solver is to pass the linear algebra objects (located on the device) and a structure called magma_z_solver_par (respectively and magma_z_precond_par) controlling the iterative solver and collecting information during the execution:

struct magma_z_solver_par{
    magma_solver_type  solver;                  // solver type
    magma_int_t        version;                 // sometimes there are different versions
    double             epsilon;                 // relative residual stopping criterion
    magma_int_t        maxiter;                 // upper iteration limit
    magma_int_t        restart;                 // for GMRES
    magma_ortho_t      ortho;                   // for GMRES
    magma_int_t        numiter;                 // feedback: number of needed iterations
    double             init_res;                // feedback: initial residual
    double             final_res;               // feedback: final residual
    double             iter_res;                // feedback: iteratively computed residual
    real_Double_t      runtime;                 // feedback: runtime needed
    real_Double_t      *res_vec;                // feedback: array containing residuals
    real_Double_t      *timing;                 // feedback: detailed timing
    magma_int_t        verbose;                 // print residual ever 'verbose' iterations
    magma_int_t        num_eigenvalues;         // number of EV for eigensolvers
    magma_int_t        ev_length;               // needed for framework
    double             *eigenvalues;            // feedback: array containing eigenvalues
    magmaDoubleComplex *eigenvectors;           // feedback: array containing eigenvectors
    magma_int_t        info;                    // feedback: did the solver converge etc
}magma_z_solver_par;

These entities can either be initialized manually, or via the function

magma_zsolverinfo_init(
    magma_z_solver_par *solver_par,
    magma_z_preconditioner *precond,
    magma_queue_t queue );

setting them to some default values. For eigensolvers, the workspace needed for the eigenvectors has to be allocated consistent with the matrix dimension, which requires additionally calling

magma_zeigensolverinfo_init(
    magma_z_solver_par *solver_par,
    magma_queue_t queue );

after setting solver_par.ev_length and solver_par.num_eigenvalues to the correct numbers.

An easy way to access the data collected during a solver execution is given by the function

magma_zsolverinfo(
    magma_z_solver_par *solver_par,
    magma_z_preconditioner *precond_par,
    magma_queue_t queue );

After completion,

magma_zsolverinfo_free(
    magma_z_solver_par *solver_par,
    magma_z_preconditioner *precond,
    magma_queue_t queue );

deallocates all memory used within the solver and preconditioner structure.

A solver can then be called via

magma_z*solvername*(
    magma_z_sparse_matrix A,
    magma_z_vector b,
    magma_z_vector *x,
    magma_z_solver_par *solver_par,
    magma_queue_t queue );

respectively

magma_z*solvername*(
    magma_z_sparse_matrix A,
    magma_z_vector b,
    magma_z_vector *x,
    magma_z_solver_par *solver_par,
    magma_z_preconditioner *precond_par,
    magma_queue_t queue );

More conveniant is the use the wrapper

magma_z_solver(
    magma_z_sparse_matrix A, magma_z_vector b,
    magma_z_vector *x, magma_zopts *zopts,
    magma_queue_t queue );

where zopts is a structure containing both, the solver and the preconditioner information: struct magma_zopts{ magma_z_solver_par solver_par; magma_z_preconditioner precond_par; magma_storage_t input_format; int blocksize; int alignment; magma_storage_t output_format; magma_location_t input_location; magma_location_t output_location; magma_scale_t scaling; }magma_zopts;

All entities of this structure can be initialized from command line by calling

magma_zparse_opts(
    int argc,
    char** argv,
    magma_zopts *opts,
    int *matrices,
    magma_queue_t queue );

Example

Especially when using sparse-iter for the first time, the easiest way to get familiar with the package is to use and modify one of the predefined testers.

In the following example we assume to have an application coded in C and running in double precision that at some instance requires solving a linear system of the form Ax=b, where A and b are generated within the application. Furthermore, we assume that the matrix A is in CSR format together with a RHS vector b in present in main memory. We do not know which solver and preconditioner combination works best for this problem, and which data format gives the best sparse-BLAS performance. For this purpose we extract parts of the testing_dsolver.cpp located in the sparse-iter/testing folder.

First, we copy the includes, initialization and finalization into our application program. Then we focus on the linear system we want to solve. We extract line 34-54 and copy it into the right location. This includes the setup of the solver parameters via command line. As we do not want to read the linear system from file, but solve the system present in memory, we use

    magma_dcsrset( m, n, row, col, val, &A, queue );

to pass the matrix (present in row, col val) and

    magma_dvset( m, n, valb, &b, queue );

to pass the RHS vector b (entries in valb) to MAGMA. For the solution vector, we allocate an initial guess on the device via:

    magma_d_vector x_d;
    magma_d_vinit( &x_d, Magma_DEV, A.num_cols, one, queue );

We then copy line 74-78 into the application to convert the matrix into the preferred format and copy it to the device. The RHS is transferred via

    magma_d_vector b_d;
    magma_d_vtransfer( b, &b_d, Magma_CPU, Magma_DEV, queue );

We solve with

    magma_d_solver( B_d, b_d, &x_d, &zopts, queue );

and return the solution vector to the application via

    magma_int_t m, n;
    double * valx;
    magma_dvget( x_d, &m, &n, &valx, queue );

Finally, we clean up the used memory via

    magma_z_mfree(&B_d, queue );
    magma_z_mfree(&B, queue );
    magma_z_vfree(&x_d, queue );
    magma_z_vfree(&b_d, queue );

and magma_zsolverinfo_free( &zopts.solver_par, &zopts.precond_par, queue );

Finally, we clean up the used memory via

    magma_z_mfree(&B_d, queue );
    magma_z_mfree(&B, queue );
    magma_z_vfree(&x_d, queue );
    magma_z_vfree(&b_d, queue );

and

    magma_dsolverinfo_free( &dopts.solver_par, &dopts.precond_par, queue );

Generated on Fri Jan 30 2015 19:00:45 for MAGMA by

     1.8.7