text:
'use strict';

var expect = require('chai').expect,
  f = require('util').format,
  Connection = require('../../../lib/connection/connection'),
  ReplSet = require('../../../lib/topologies/replset');

var restartAndDone = function(configuration, done) {
  configuration.manager.restart(9, { waitMS: 2000 }).then(function() {
    done();
  });
};

describe.skip('A replica set', function() {
  this.timeout(0);

  it('Discover arbiters', {
    metadata: { requires: { topology: 'replicaset' } },

    test: function(done) {
      this.timeout(0);
      var self = this;
      var manager = this.configuration.manager;

      // Get the primary server
      manager.primary().then(function(_manager) {
        // Enable connections accounting
        Connection.enableConnectionAccounting();
        // Attempt to connect
        try {
          var server = new ReplSet(
            [
              {
                host: _manager.host,
                port: _manager.port
              }
            ],
            {
              setName: self.configuration.setName
            }
          );
        } catch (err) {
          console.log(err);
          done();
        }

        server.on('joined', function(_type) {
          if (_type === 'arbiter') {
            server.destroy();

            setTimeout(function() {
              expect(Object.keys(Connection.connections()).length).to.equal(0);
              Connection.disableConnectionAccounting();
              done();
            }, 2000);
          }
        });

        // Start connection
        server.connect();
      });
    }
  });

  it('Discover passives', {
    metadata: { requires: { topology: 'replicaset' } },

    test: function(done) {
      var self = this;
      var manager = this.configuration.manager;

      // Get the primary server
      manager.primary().then(function(_manager) {
        // Enable connections accounting
        Connection.enableConnectionAccounting();
        // Attempt to connect
        var server = new ReplSet(
          [
            {
              host: _manager.host,
              port: _manager.port
            }
          ],
          {
            setName: self.configuration.setName
          }
        );

        server.on('joined', function(_type, _server) {
          if (_type === 'secondary' && _server.lastIsMaster().passive) {
            server.destroy();

            setTimeout(function() {
              expect(Object.keys(Connection.connections()).length).to.equal(0);
              Connection.disableConnectionAccounting();
              done();
            }, 1000);
          }
        });

        // Start connection
        server.connect();
      });
    }
  });

  it('Discover primary', {
    metadata: { requires: { topology: 'replicaset' } },

    test: function(done) {
      var self = this;
      var manager = this.configuration.manager;

      // Get the primary server
      manager.primary().then(function(_manager) {
        // Enable connections accounting
        Connection.enableConnectionAccounting();
        // Attempt to connect
        var server = new ReplSet(
          [
            {
              host: _manager.host,
              port: _manager.port
            }
          ],
          {
            setName: self.configuration.setName
          }
        );

        server.on('joined', function(_type) {
          if (_type === 'primary') {
            server.destroy();

            setTimeout(function() {
              expect(Object.keys(Connection.connections()).length).to.equal(0);
              Connection.disableConnectionAccounting();
              done();
            }, 1000);
          }
        });

        // Start connection
        server.connect();
      });
    }
  });

  it('Discover secondaries', {
    metadata: { requires: { topology: 'replicaset' } },

    test: function(done) {
      var self = this;
      var manager = this.configuration.manager;

      // Get the primary server
      manager.primary().then(function(_manager) {
        // Enable connections accounting
        Connection.enableConnectionAccounting();
        // Attempt to connect
        var server = new ReplSet(
          [
            {
              host: _manager.host,
              port: _manager.port
            }
          ],
          {
            setName: self.configuration.setName
          }
        );

        var count = 0;
        server.on('joined', function(_type) {
          if (_type === 'secondary') count = count + 1;
          if (count === 2) {
            server.destroy();

            setTimeout(function() {
              expect(Object.keys(Connection.connections()).length).to.equal(0);
              Connection.disableConnectionAccounting();
              done();
            }, 1000);
          }
        });

        // Start connection
        server.connect();
      });
    }
  });

  it('Replica set discovery', {
    metadata: { requires: { topology: 'replicaset' } },

    test: function(done) {
      var self = this;
      var manager = this.configuration.manager;

      // State
      var state = { primary: 1, secondary: 2, arbiter: 1, passive: 1 };
      // Get the primary server
      manager.primary().then(function(_manager) {
        // Enable connections accounting
        Connection.enableConnectionAccounting();
        // Attempt to connect
        var server = new ReplSet(
          [
            {
              host: _manager.host,
              port: _manager.port
            }
          ],
          {
            setName: self.configuration.setName
          }
        );

        server.on('joined', function(_type, _server) {
          if (_type === 'secondary' && _server.lastIsMaster().passive) {
            state.passive = state.passive - 1;
          } else {
            state[_type] = state[_type] - 1;
          }

          if (
            state.primary === 0 &&
            state.secondary === 0 &&
            state.arbiter === 0 &&
            state.passive === 0
          ) {
            server.destroy();

            setTimeout(function() {
              expect(Object.keys(Connection.connections()).length).to.equal(0);
              Connection.disableConnectionAccounting();
              done();
            }, 1000);
          }
        });

        // Start connection
        server.connect();
      });
    }
  });

  it('Host list differs from seeds', {
    metadata: {
      requires: {
        topology: 'replicaset'
      }
    },

    test: function(done) {
      var self = this;
      var manager = this.configuration.manager;

      // State
      var state = { primary: 1, secondary: 2, arbiter: 1, passive: 1 };
      // Get the primary server
      manager.primary().then(function(_manager) {
        Connection.enableConnectionAccounting();
        // Attempt to connect
        var server = new ReplSet(
          [
            {
              host: _manager.host,
              port: _manager.port
            },
            {
              host: 'localhost',
              port: 41000
            }
          ],
          {
            setName: self.configuration.setName
          }
        );

        server.on('joined', function(_type, _server) {
          // console.log('======= joined :: ' + _type + ' :: ' + _server.name)
          if (_type === 'secondary' && _server.lastIsMaster().passive) {
            state.passive = state.passive - 1;
          } else {
            state[_type] = state[_type] - 1;
          }

          // console.dir(state)

          if (
            state.primary === 0 &&
            state.secondary === 0 &&
            state.arbiter === 0 &&
            state.passive === 0
          ) {
            server.destroy();

            setTimeout(function() {
              expect(Object.keys(Connection.connections()).length).to.equal(0);
              Connection.disableConnectionAccounting();
              done();
            }, 1000);
          }
        });

        // Start connection
        server.connect();
      });
    }
  });

  it('Ghost discovered/Member brought up as standalone', {
    metadata: {
      requires: {
        topology: 'replicaset'
      }
    },

    test: function(done) {
      var self = this;
      var ServerManager = require('mongodb-topology-manager').Server,
        manager = this.configuration.manager;

      // State
      var state = { primary: 1, secondary: 1, arbiter: 1, passive: 1 };
      // Get the primary server
      manager.primary().then(function(primaryManager) {
        // Get the secondary server
        manager.secondaries().then(function(managers) {
          var serverManager = managers[0];

          // Stop the secondary
          serverManager.stop().then(function() {
            // Start a new server manager
            var nonReplSetMember = new ServerManager('mongod', {
              bind_ip: serverManager.host,
              port: serverManager.port,
              dbpath: serverManager.options.dbpath
            });

            // Start a non replset member
            nonReplSetMember.start().then(function() {
              // console.log('------------------------ 4')
              var config = [
                {
                  host: primaryManager.host,
                  port: primaryManager.port
                }
              ];

              var options = {
                setName: self.configuration.setName
              };

              // Wait for primary
              manager.waitForPrimary().then(function() {
                // Enable connections accounting
                Connection.enableConnectionAccounting();
                // Attempt to connect
                var replset = new ReplSet(config, options);
                replset.on('joined', function(_type, _server) {
                  if (_type === 'secondary' && _server.lastIsMaster().passive) {
                    state.passive = state.passive - 1;
                  } else {
                    state[_type] = state[_type] - 1;
                  }
                  // console.dir(state)

                  if (
                    state.primary === 0 &&
                    state.secondary === 0 &&
                    state.arbiter === 0 &&
                    state.passive === 0
                  ) {
                    replset.destroy();
                    setTimeout(function() {
                      expect(Object.keys(Connection.connections()).length).to.equal(0);
                      Connection.disableConnectionAccounting();

                      // Stop the normal server
                      nonReplSetMember.stop().then(function() {
                        // Restart the secondary server
                        serverManager.start().then(function() {
                          restartAndDone(self.configuration, done);
                        });
                      });
                    }, 1000);
                  }
                });

                // Start connection
                replset.connect();
              });
            });
          });
        });
      });
    }
  });

  // ../spec/server-discovery-and-monitoring/rs/member_reconfig.json
  it('Member removed by reconfig', {
    metadata: {
      requires: {
        topology: 'replicaset'
      }
    },

    test: function(done) {
      var self = this;
      var manager = this.configuration.manager;

      // Get the primary server
      manager.primary().then(function(primaryServerManager) {
        // Get the secondary server
        manager.secondaries().then(function(managers) {
          var secondaryServerManager = managers[0];

          var config = [
            {
              host: primaryServerManager.host,
              port: primaryServerManager.port
            }
          ];

          var options = {
            setName: self.configuration.setName
          };

          // console.log('============================= 3')
          // Enable connections accounting
          Connection.enableConnectionAccounting();
          // console.log('============================= 4')
          // Attempt to connect
          var server = new ReplSet(config, options);
          server.on('fullsetup', function() {
            // console.log('------------------------------------------ 0')
            // Save number of secondaries
            var numberOfSecondaries = server.s.replicaSetState.secondaries.length;

            // Let's listen to changes
            server.on('left', function(_t, _server) {
              if (_server.s.options.port === secondaryServerManager.options.port) {
                expect(server.s.replicaSetState.primary).to.not.be.null;
                expect(server.s.replicaSetState.secondaries.length).to.be.below(
                  numberOfSecondaries
                );
                expect(server.s.replicaSetState.arbiters.length).to.equal(1);
                server.destroy();

                setTimeout(function() {
                  // console.log('=================== 0')
                  // console.dir(Object.keys(Connection.connections()))
                  expect(Object.keys(Connection.connections()).length).to.equal(0);
                  // console.log('=================== 1')
                  Connection.disableConnectionAccounting();
                  restartAndDone(self.configuration, done);
                }, 5000);
              }
            });

            // Remove the secondary server
            manager.removeMember(secondaryServerManager, {
              returnImmediately: false,
              force: false,
              skipWait: true
            });
          });

          // Start connection
          server.connect();
        });
      });
    }
  });

  // ../spec/server-discovery-and-monitoring/rs/discovery.json
  it('Should not leak any connections after hammering the replicaset with a mix of operations', {
    metadata: { requires: { topology: 'replicaset' } },

    test: function(done) {
      var self = this;
      var Server = this.configuration.mongo.Server,
        ReadPreference = this.configuration.require.ReadPreference,
        manager = this.configuration.manager;

      // Get the primary server
      manager.primary().then(function(_manager) {
        // Enable connections accounting
        Connection.enableConnectionAccounting();
        Server.enableServerAccounting();
        // Attempt to connect
        var server = new ReplSet(
          [
            {
              host: _manager.host,
              port: _manager.port
            }
          ],
          {
            setName: self.configuration.setName
          }
        );

        var donecount = 0;

        function onDone() {
          donecount = donecount + 1;

          if (donecount === 2) {
            server.destroy();

            Connection.disableConnectionAccounting();
            Server.disableServerAccounting();

            setTimeout(function() {
              expect(Object.keys(Connection.connections()).length).to.equal(0);
              expect(Object.keys(Server.servers()).length).to.equal(0);
              done();
            }, 5000);
          }
        }

        server.on('connect', function(_server) {
          var insertcount = 10000;
          var querycount = 10000;

          var insertCountDecrement = function() {
            insertcount = insertcount - 1;

            if (insertcount === 0) {
              onDone();
            }
          };

          var queryCountDecrement = function() {
            querycount = querycount - 1;

            if (querycount === 0) {
              onDone();
            }
          };

          for (var i = 0; i < 10000; i++) {
            _server.insert(
              f('%s.inserts', self.configuration.db),
              [{ a: 1 }],
              {
                writeConcern: { w: 1 },
                ordered: true
              },
              insertCountDecrement
            );
          }

          for (var j = 0; j < 10000; j++) {
            // Execute find
            var cursor = _server.cursor(
              f('%s.inserts1', self.configuration.db),
              {
                find: f('%s.inserts1', self.configuration.db),
                query: {}
              },
              { readPreference: ReadPreference.secondary }
            );
            cursor.setCursorLimit(1);
            // Execute next
            cursor.next(queryCountDecrement);
          }
        });

        // Start connection
        server.connect();
      });
    }
  });
});


text:
package org.vaadin.demo.ui.vaadin.login.presenter;

import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.VaadinSession;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.UIScope;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.vaadin.demo.event.LoginSuccessEvent;
import org.vaadin.demo.mapper.UserMapper;
import org.vaadin.demo.model.security.User;
import org.vaadin.demo.transfer.security.UserDto;
import org.vaadin.demo.ui.presenter.login.LoginPresenter;
import org.vaadin.demo.ui.vaadin.login.view.VaadinLoginView;
import org.vaadin.mvp.base.presenter.VaadinNavigatablePresenter;

/**
 * Created by huth on 13.07.2017.
 */
@UIScope
@SpringView(name = LoginPresenter.PRESENTER_NAME)
@CommonsLog
public class VaadinLoginPresenter extends LoginPresenter<VaadinLoginView> implements VaadinNavigatablePresenter<VaadinLoginView> {

    @Autowired
    protected AuthenticationManager authenticationManager;

    @Autowired
    public VaadinLoginPresenter(VaadinLoginView view) {
        super(view);
    }

    @Override
    protected void doLogin(String userName, String password, boolean remember) {

        try {
            final Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
            if (auth.isAuthenticated()) {
                final VaadinSession vaadinSession = VaadinSession.getCurrent();
                if (auth.getPrincipal() instanceof User) {
                    final UserDto userDto = UserMapper.INSTANCE.userToUserDto((User) auth.getPrincipal());
                    getEventBus().publish(this, new LoginSuccessEvent(userDto));
                }
                //    vaadinSession.setAttribute("user", auth.);
            }
        } catch (AuthenticationException ae) {
            log.error("User: " + userName + " login failed", ae );
        }
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        init();
    }
}

redpajama_set_name: RedPajamaGithub


text:
author: michael_keiser
layout: single
title: "Elena receives NSF GFRP Fellowship"
modified:
categories: news
excerpt:
tags:
 - awards
image:
  feature:
date: 2016-03-29T00:00:00-07:00
---

Congratulations to Elena on being selected for a [2016 NSF GRFP fellowship](https://www.nsfgrfp.org/)! Opportunely, we were able to memorialize the occasion today with a double celebration, at Leo's paper lunch.

![Lab lunch]({{ site.url }}/assets/images/posts/2016-03-29-lab-lunch.jpg)


text:
.. image:: https://img.shields.io/travis/dgk/django-business-logic/master.svg
   :target: http://travis-ci.org/dgk/django-business-logic?branch=master
   :alt: travis-ci

.. image:: https://img.shields.io/codecov/c/github/dgk/django-business-logic.svg
   :target: https://codecov.io/gh/dgk/django-business-logic
   :alt: codecov

.. image:: https://img.shields.io/codeclimate/maintainability/dgk/django-business-logic.svg
   :target: https://codeclimate.com/github/dgk/django-business-logic
   :alt: codeclimate

.. image:: https://readthedocs.org/projects/django-business-logic/badge/?version=latest
   :target: https://django-business-logic.readthedocs.org/
   :alt: readthedocs

.. image:: https://img.shields.io/pypi/l/django-business-logic.svg
   :target: https://django-business-logic.readthedocs.io/en/latest/license.html
   :alt: MIT license

.. image:: https://img.shields.io/pypi/pyversions/django-business-logic.svg
   :target: https://pypi.org/project/django-business-logic/
   :alt: python versions

.. image:: https://img.shields.io/pypi/djversions/django-business-logic.svg
   :target: https://pypi.org/project/django-business-logic/
   :alt: django versions

.. image:: https://img.shields.io/pypi/v/django-business-logic.svg
   :target: https://pypi.org/project/django-business-logic/
   :alt: pypi versions

.. image:: https://img.shields.io/pypi/status/django-business-logic.svg
   :target: https://pypi.org/project/django-business-logic/
   :alt: pypi versions status

.. image:: https://img.shields.io/gitter/room/django-business-logic/community.svg
   :target: https://gitter.im/django-business-logic/community
   :alt: gitter

Preface
#######

Processes change more often than technic. Domain Rules are situational and may
differ from customer to customer. With diverse code and frequent changes, the code
becomes complicated, then the probability of errors increases. One of the
optimal strategies to avoid this situation is to isolate client logic at the
data level.
When this is the case, programmers need only to watch the correct interpretation
of the rules, but not each of the rules separately. This reduces the amount of
code base needed and reduces the possibility of introducing errors.  Another
question is the form of the description of these rules takes. A visual graphical
representation is optimal for users – this helps to avoid confusion with a variety
of conditions, and helps users understand what is written without any effort.
Many web applications need to use Domain Specific Languages (DSL) during their
lifecycle.  Any type of project, from hobby-level to enterprise, may have this
requirement. There are many ways to carry out this task, such as doing your own
development using internal resources or contractors (you know the cost in both
cases), buying a turnkey solution, (really?) or an adapted solution. In all
cases, you will also need to be a coach for all DSL users.

Stop now and focus your attention here.
The `Blockly <https://opensource.google.com/projects/blockly>`_ visual
programming library was released in 2012, and since 2014 it has been developed
with the support of Google. `Code.org <https://code.org/>`_, a related project
that uses Blockly in its main subsystems, has had hundreds of millions of users
of different ages in its `Hour of Code <https://hourofcode.com/>`_ project.
These users started as young as elementary school, and very quickly learned how
to program using the amazing Blockly library.
Even top universities teach block-based coding (e.g.,
`Berkeley <http://bjc.berkeley.edu/>`_, `Harvard <https://cs50.harvard.edu/>`_).
But Blockly is not just a trainer or a toy. It is suitable for serious tasks:
form processing, workflows, reporting, email marketing, bots, tests, surveys,
quizzes and many other purposes.

The django-business-logic library tries to utilise the block programming
approach to delegate programming tasks to non-programmers by implementing a
framework for creating and working with Visual Domain Specific Languages.

The library comes with:

* pretty easy integration: minor changes in INSTALLED_APPS and root urlconf
* support of many types of built-in django model fields: all numeric, boolean, string, foreign keys
* logical division into interface/program/version: firstly define an "interface" object which is just a named set of django models and its fields; after you can create one or more named "programs" which implements the given interface and than release any number of the program's "versions"
* easy invocation injecting of visually edited code: a few strings in your code, at any place - a view controller, signal handler, asynchronous task, no matter the monolith or microservice
* dropdown controls with custom model object list; you need only register your custom models in the standard django admin interface
* ability to easily integrate and make accessible to the visual editor two types of python functions: imported (from python built-in, third-party or your own module) and editable through django admin
* easy to understand Blockly-based log viewer with the ability to inspect intermediate values

Do not forget that this library is not designed with professional developers in
mind, so the interface may look ugly and awkward in a professional developer's
eyes. Try to disengage from this feeling. Think like a human who gets panicked
when seeing (our lovely) code with obscure brackets, odd commas, strange
arrows, and so on.
We, the development part of the team, can help our teammates from other
departments to do more.
Let's bring the spirit of our successful sprints and fun development rooms to
colleagues from management, marketing, sales, logistics and many others.

Library home
############
https://github.com/dgk/django-business-logic/

Documentation
#############

https://django-business-logic.readthedocs.io/en/latest/

Support us
##########

Any feedback and github stars would be greatly appreciated.

Please feel free to ask any questions in the `gitter chat <https://gitter.im/django-business-logic/community>`_

If you are familiar with react/mobx and want to help to build django-business-logic library
(`next generation frontend code is here <https://github.com/dgk/business-logic-ui/>`_), please contact me dgk@dgk.su.

License
#######

MIT license


text:
#ifndef Widget_h
#define Widget_h

#include "platform/PlatformExport.h"
#include "platform/geometry/FloatPoint.h"
#include "platform/geometry/IntRect.h"
#include "platform/heap/Handle.h"
#include "public/platform/WebFocusType.h"
#include "wtf/Forward.h"

namespace blink {

class CullRect;
class Event;
class GraphicsContext;
class HostWindow;

// The Widget class serves as a base class for FrameView, Scrollbar, and
// PluginView.
//
// Widgets are connected in a hierarchy, with the restriction that plugins and
// scrollbars are always leaves of the tree. Only FrameView can have children
// (and therefore the Widget class has no concept of children).
class PLATFORM_EXPORT Widget : public GarbageCollectedFinalized<Widget> {
 public:
  Widget();
  virtual ~Widget();

  int x() const { return frameRect().x(); }
  int y() const { return frameRect().y(); }
  int width() const { return frameRect().width(); }
  int height() const { return frameRect().height(); }
  IntSize size() const { return frameRect().size(); }
  IntPoint location() const { return frameRect().location(); }

  virtual void setFrameRect(const IntRect& frameRect) {
    m_frameRect = frameRect;
  }
  const IntRect& frameRect() const { return m_frameRect; }
  IntRect boundsRect() const { return IntRect(0, 0, width(), height()); }

  void resize(int w, int h) { setFrameRect(IntRect(x(), y(), w, h)); }
  void resize(const IntSize& s) { setFrameRect(IntRect(location(), s)); }

  virtual void paint(GraphicsContext&, const CullRect&) const {}
  void invalidate() { invalidateRect(boundsRect()); }
  virtual void invalidateRect(const IntRect&) = 0;

  virtual void setFocused(bool, WebFocusType) {}

  virtual void show() {}
  virtual void hide() {}
  bool isSelfVisible() const {
    return m_selfVisible;
  }  // Whether or not we have been explicitly marked as visible or not.
  bool isParentVisible() const {
    return m_parentVisible;
  }  // Whether or not our parent is visible.
  bool isVisible() const {
    return m_selfVisible && m_parentVisible;
  }  // Whether or not we are actually visible.
  virtual void setParentVisible(bool visible) { m_parentVisible = visible; }
  void setSelfVisible(bool v) { m_selfVisible = v; }

  virtual bool isFrameView() const { return false; }
  virtual bool isRemoteFrameView() const { return false; }
  virtual bool isPluginView() const { return false; }
  virtual bool isPluginContainer() const { return false; }
  virtual bool isScrollbar() const { return false; }

  virtual void setParent(Widget*);
  Widget* parent() const { return m_parent; }
  Widget* root() const;

  virtual void handleEvent(Event*) {}

  IntRect convertToRootFrame(const IntRect&) const;
  IntRect convertFromRootFrame(const IntRect&) const;

  IntPoint convertToRootFrame(const IntPoint&) const;
  IntPoint convertFromRootFrame(const IntPoint&) const;
  FloatPoint convertFromRootFrame(const FloatPoint&) const;

  virtual void frameRectsChanged() {}

  virtual void widgetGeometryMayHaveChanged() {}

  virtual IntRect convertToContainingWidget(const IntRect&) const;
  virtual IntRect convertFromContainingWidget(const IntRect&) const;
  virtual IntPoint convertToContainingWidget(const IntPoint&) const;
  virtual IntPoint convertFromContainingWidget(const IntPoint&) const;

  // Virtual methods to convert points to/from child widgets
  virtual IntPoint convertChildToSelf(const Widget*, const IntPoint&) const;
  virtual IntPoint convertSelfToChild(const Widget*, const IntPoint&) const;

  // Notifies this widget that it will no longer be receiving events.
  virtual void eventListenersRemoved() {}

  DECLARE_VIRTUAL_TRACE();
  virtual void dispose() {}

 private:
  Member<Widget> m_parent;
  IntRect m_frameRect;
  bool m_selfVisible;
  bool m_parentVisible;
};

}  // namespace blink

#endif  // Widget_h


text:
using System.Windows;

namespace Gu.Wpf.Localization.NoResources
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
    }
}


text: An experiment with css `mix-blend-mode` rule


text:
instagramoauth2.0
=================

Appcelerator Instagram oauth 2.0 attempt Javascript.


text:
package xal.extension.fit.lsm;

/**
 *  This is an abstract adapter class for a model function with one independent
 *  variable. It delegates calls of getValue and getDerivative methods of
 *  interface to the abstract methods with the same names and different
 *  signatures. The signatures are different in a very simple way. The array of
 *  independent variables is replaced by a simple double value.
 *
 *@author    shishlo
 */
public abstract class ModelFunction1D implements ModelFunction {

	/**
	 *  Returns the value of the model function for the particular value of the
	 *  independent variable and parameters
	 *
	 *@param  x  The value of independent variable
	 *@param  a  The array with set of parameters that should be found
	 *@return    The value of the function
	 */
	public abstract double getValue(double x, double[] a);

	/**
	 *  Returns the partial derivative of the model function for the particular
	 *  value of independent variable and parameters and the index of parameters
	 *  for which the derivative is calculated
	 *
	 *@param  x        The value of independent variable
	 *@param  a        The array with set of parameters that should be found
	 *@param  a_index  The index of parameters for which the derivative is
	 *      calculated
	 *@return          The value of the function
	 */
	public abstract double getDerivative(double x, double[] a, int a_index);

	/**
	 *  Returns the value of the model function for the particular set of
	 *  independent variables and parameters
	 *
	 *@param  x  The array with the set of independent variables
	 *@param  a  The array with set of parameters that should be found
	 *@return    The value of the function
	 */
	public final double getValue(double[] x, double[] a) {
		return getValue(x[0], a);
	}

	/**
	 *  Returns the partial derivative of the model function for the particular set
	 *  of independent variables and parameters and the index of parameters for
	 *  which the derivative is calculated
	 *
	 *@param  x        The array with the set of independent variables
	 *@param  a        The array with set of parameters that should be found
	 *@param  a_index  The index of parameters for which the derivative is
	 *      calculated
	 *@return          The value of the function
	 */
	public final double getDerivative(double[] x, double[] a, int a_index) {
		return getDerivative(x[0], a, a_index);
	}
}


text:
var app = angular.module('what2eatApp', ['ui.bootstrap']); // include dependency on ui.boostrap

// Define the `foodListController` controller on the `phonecatApp` module
app.controller('foodListController', function foodListController($scope, $http) {

    $scope.progress = 10;

    if (navigator.geolocation) navigator.geolocation.getCurrentPosition(onPosition);
    // Once the browser retrieves the users location it will make the
    // AJAX call to the backend and query the YELP api.
    function onPosition(position) {
        $scope.progress = 50;
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
        // Store geolocation
        $scope.coordinates = {
            lat: lat,
            lng: lng
        };
        // build the url to call
        var url = '/api/v1/restaurant/all?longitude=' + lng + '&latitude=' + lat;
        // Make http call to Node.js with the coordinates of the user
        $http.get(url)
            .then(function successCallBack(response) {
                $scope.progress = 80;
                var data = response.data;
                console.log(data);
                // From the resulting data extract the businesses array
                // if not defined set businesses variable to an empty
                // array.
                var businesses = data.businesses || [];
                // Append the result to the scope variable to make it accessible in other places.
                $scope.restaurants = businesses;
                $scope.numberOfResturants = businesses.length;
                $scope.progress = 100;
                $scope.done = true;

            }, function errorCallback(response) {
                console.log('Error calling api: ' + JSON.stringify(response));
            });

    };

    $scope.range = function(num) {
        num = Math.floor(num);
        return new Array(num);
    };

    $scope.isDecimal = function(num) {
        return num % 1 != 0;
    };

});


text:
@class ChromeIdentity;
@class UIImage;

// This class manages an image cache for resized avatar images.
@interface ResizedAvatarCache : NSObject
// Returns cached resized image, if it exists. If the identity avatar has not
// yet been fetched, this method triggers a fetch and returns the default
// avatar image. The user of this class should be an observer of identity
// updates. When notified of identity updates, this method should be called
// again to obtain an updated resized image.
- (UIImage*)resizedAvatarForIdentity:(ChromeIdentity*)identity;
@end

#endif  // IOS_CHROME_BROWSER_UI_SETTINGS_UTILS_RESIZED_AVATAR_CACHE_H_


text:
static const wchar_t kCustomInfoProcessUptimeName[] = L"ptime";
static const size_t kMaxCustomInfoEntries = 4096;

namespace google_breakpad {

ClientInfo::ClientInfo(CrashGenerationServer* crash_server,
                       DWORD pid,
                       MINIDUMP_TYPE dump_type,
                       DWORD* thread_id,
                       EXCEPTION_POINTERS** ex_info,
                       MDRawAssertionInfo* assert_info,
                       const CustomClientInfo& custom_client_info)
    : crash_server_(crash_server),
      pid_(pid),
      dump_type_(dump_type),
      ex_info_(ex_info),
      assert_info_(assert_info),
      custom_client_info_(custom_client_info),
      thread_id_(thread_id),
      process_handle_(NULL),
      dump_requested_handle_(NULL),
      dump_generated_handle_(NULL),
      dump_request_wait_handle_(NULL),
      process_exit_wait_handle_(NULL),
      crash_id_(NULL) {
  GetSystemTimeAsFileTime(&start_time_);
}

bool ClientInfo::Initialize() {
  process_handle_ = OpenProcess(GENERIC_ALL, FALSE, pid_);
  if (!process_handle_) {
    return false;
  }

  // The crash_id will be the low order word of the process creation time.
  FILETIME creation_time, exit_time, kernel_time, user_time;
  if (GetProcessTimes(process_handle_, &creation_time, &exit_time,
                      &kernel_time, &user_time))
    crash_id_ = creation_time.dwLowDateTime;

  dump_requested_handle_ = CreateEvent(NULL,    // Security attributes.
                                       TRUE,    // Manual reset.
                                       FALSE,   // Initial state.
                                       NULL);   // Name.
  if (!dump_requested_handle_) {
    return false;
  }

  dump_generated_handle_ = CreateEvent(NULL,    // Security attributes.
                                       TRUE,    // Manual reset.
                                       FALSE,   // Initial state.
                                       NULL);   // Name.
  return dump_generated_handle_ != NULL;
}

void ClientInfo::UnregisterDumpRequestWaitAndBlockUntilNoPending() {
  if (dump_request_wait_handle_) {
    // Wait for callbacks that might already be running to finish.
    UnregisterWaitEx(dump_request_wait_handle_, INVALID_HANDLE_VALUE);
    dump_request_wait_handle_ = NULL;
  }
}

void ClientInfo::UnregisterProcessExitWait(bool block_until_no_pending) {
  if (process_exit_wait_handle_) {
    if (block_until_no_pending) {
      // Wait for the callback that might already be running to finish.
      UnregisterWaitEx(process_exit_wait_handle_, INVALID_HANDLE_VALUE);
    } else {
      UnregisterWait(process_exit_wait_handle_);
    }
    process_exit_wait_handle_ = NULL;
  }
}

ClientInfo::~ClientInfo() {
  // Waiting for the callback to finish here is safe because ClientInfo's are
  // never destroyed from the dump request handling callback.
  UnregisterDumpRequestWaitAndBlockUntilNoPending();

  // This is a little tricky because ClientInfo's may be destroyed by the same
  // callback (OnClientEnd) and waiting for it to finish will cause a deadlock.
  // Regardless of this complication, wait for any running callbacks to finish
  // so that the common case is properly handled.  In order to avoid deadlocks,
  // the OnClientEnd callback must call UnregisterProcessExitWait(false)
  // before deleting the ClientInfo.
  UnregisterProcessExitWait(true);

  if (process_handle_) {
    CloseHandle(process_handle_);
  }

  if (dump_requested_handle_) {
    CloseHandle(dump_requested_handle_);
  }

  if (dump_generated_handle_) {
    CloseHandle(dump_generated_handle_);
  }
}

bool ClientInfo::GetClientExceptionInfo(EXCEPTION_POINTERS** ex_info) const {
  SIZE_T bytes_count = 0;
  if (!ReadProcessMemory(process_handle_,
                         ex_info_,
                         ex_info,
                         sizeof(*ex_info),
                         &bytes_count)) {
    return false;
  }

  return bytes_count == sizeof(*ex_info);
}

bool ClientInfo::GetClientThreadId(DWORD* thread_id) const {
  SIZE_T bytes_count = 0;
  if (!ReadProcessMemory(process_handle_,
                         thread_id_,
                         thread_id,
                         sizeof(*thread_id),
                         &bytes_count)) {
    return false;
  }

  return bytes_count == sizeof(*thread_id);
}

void ClientInfo::SetProcessUptime() {
  FILETIME now = {0};
  GetSystemTimeAsFileTime(&now);

  ULARGE_INTEGER time_start;
  time_start.HighPart = start_time_.dwHighDateTime;
  time_start.LowPart = start_time_.dwLowDateTime;

  ULARGE_INTEGER time_now;
  time_now.HighPart = now.dwHighDateTime;
  time_now.LowPart = now.dwLowDateTime;

  // Calculate the delay and convert it from 100-nanoseconds to milliseconds.
  __int64 delay = (time_now.QuadPart - time_start.QuadPart) / 10 / 1000;

  // Convert it to a string.
  wchar_t* value = custom_info_entries_.get()[custom_client_info_.count].value;
  _i64tow_s(delay, value, CustomInfoEntry::kValueMaxLength, 10);
}

bool ClientInfo::PopulateCustomInfo() {
  if (custom_client_info_.count > kMaxCustomInfoEntries)
    return false;

  SIZE_T bytes_count = 0;
  SIZE_T read_count = sizeof(CustomInfoEntry) * custom_client_info_.count;

  // If the scoped array for custom info already has an array, it will be
  // the same size as what we need. This is because the number of custom info
  // entries is always the same. So allocate memory only if scoped array has
  // a NULL pointer.
  if (!custom_info_entries_.get()) {
    // Allocate an extra entry for reporting uptime for the client process.
    custom_info_entries_.reset(
        new CustomInfoEntry[custom_client_info_.count + 1]);
    // Use the last element in the array for uptime.
    custom_info_entries_.get()[custom_client_info_.count].set_name(
        kCustomInfoProcessUptimeName);
  }

  if (!ReadProcessMemory(process_handle_,
                         custom_client_info_.entries,
                         custom_info_entries_.get(),
                         read_count,
                         &bytes_count)) {
    return false;
  }

  SetProcessUptime();
  return (bytes_count != read_count);
}

CustomClientInfo ClientInfo::GetCustomInfo() const {
  CustomClientInfo custom_info;
  custom_info.entries = custom_info_entries_.get();
  // Add 1 to the count from the client process to account for extra entry for
  // process uptime.
  custom_info.count = custom_client_info_.count + 1;
  return custom_info;
}

}  // namespace google_breakpad


text:
package com.tocong.mymobilesafe.chapter02.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.tocong.mymobilesafe.R;

/**
 * Created by tocong on 2016/4/22.
 */
public class SetUpPasswordDialog extends Dialog implements View.OnClickListener {
    //标题
    private TextView mTitleTV;
    //首次输入的密码框
    public EditText mFirstPWDET;

    //确认密码输入框
    public EditText mAffirmET;

    private MyCallBack myCallBack;

    public SetUpPasswordDialog(Context context) {
        super(context, R.style.dialog_custom);

    }

    public void setMyCallBack(MyCallBack myCallBack) {
        this.myCallBack = myCallBack;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.setup_password_dialog);
        super.onCreate(savedInstanceState);
        initView();
    }
/*
* 初始化控件
*
* */

    private void initView() {
        mTitleTV = (TextView) findViewById(R.id.tv_setuppwd_title);
        mFirstPWDET = (EditText) findViewById(R.id.et_firstpwd);
        mAffirmET = (EditText) findViewById(R.id.et_affirm_password);
        findViewById(R.id.btn_ok).setOnClickListener(this);
        findViewById(R.id.btn_cancle).setOnClickListener(this);

    }

    public void setTitle(String title) {

        if (!TextUtils.isEmpty(title)) {
            mTitleTV.setText(title);

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_ok:
                myCallBack.ok();
                break;
            case R.id.btn_cancle:
                myCallBack.cancle();
                break;

        }
    }

    public interface MyCallBack {
        void ok();

        void cancle();

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>pk.colorpicker - Pocketknife UI</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 0.0.1

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

pk

pk.accordian

pk.carousel

pk.chart

pk.checkbox

pk.color

pk.colorpicker

pk.datepicker

pk.drag

pk.modal

pk.notify

pk.rating

pk.scroll

pk.select

pk.slider

pk.svg

pk.switch

pk.toggle

pk.tooltip

pocketknife

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

pk.colorpicker Class

                                    Defined in: src/colorpicker/colorpicker.js:2

                                    Module: pocketknife

Create a new colorpicker control

HTML

<div id='colorpicker'></div>

Javascript:

pk.colorpicker({
                            element: document.getElementById('colorpicker'),
                            value:'#FF0000',
                            listeners:{
                                change:function(oldCol,newCol){
                                    // do something
                                }
                            }
                        });

Constructor

pk.colorpicker

                                            (

                                                        options

)

                                            Object

                                        chainable

                                                Defined in
                                        src/colorpicker/colorpicker.js:2

Parameters:

                                                        options
                                                        Object

                                                                    element
                                                                    Object

DOM element to convert to control

                                                                    [value=#000000]
                                                                    String
                                                                    optional

HEX string of initially selected color, defaults black #000000

                                                                    [listeners]
                                                                    Object
                                                                    optional

Object array of event listeners to bind (nb. only detects change event)

Returns:

                                                        Object:

Object  Consisting of original DOM element (item 0) and class methods (see below)

Index

Methods

Events

Item Index

Methods

                                                        val

Events

                                                        change

Methods

val

                                                        (

                                                                    [value]

)

                                                        String

                                                            Defined in
                                                    src/colorpicker/colorpicker.js:225

Gets or sets control value (HEX color string, e.g. #000000)

Parameters:

                                                                    [value]
                                                                    String
                                                                    optional

Value to set

Returns:

                                                                    String:

Returns current value

Events

change

                                                            Defined in
                                                    src/colorpicker/colorpicker.js:218

Fired on selected color changing (click, drag)

Event Payload:

                                                                    oldColor
                                                                    String

HEX color string of previous color

                                                                    newColor
                                                                    String

HEX color string of new color


text:
@javax.xml.bind.annotation.XmlSchema(namespace = "http://skatteverket.se/spar/komponent/1.0", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package se.sparavisering;


text:
Blink(1) Puppet Module for Boxen
================================================================================

Install [Blink(1) Control](http://thingm.com/products/blink-1.html)

Usage
--------------------------------------------------------------------------------

```puppet
include blink1
```

Required Puppet Modules
--------------------------------------------------------------------------------

* `boxen`

Development
--------------------------------------------------------------------------------

Set `GITHUB_API_TOKEN` in your shell with a [Github oAuth Token](https://help.github.com/articles/creating-an-oauth-token-for-command-line-use) to raise your API rate limit. You can get some work done without it, but you're less likely to encounter errors like `Unable to find module 'boxen/puppet-boxen' on https://github.com`.

Then write some code. Run `script/cibuild` to test it. Check the `script`
directory for other useful tools.


text:
<?xml version='1.0' encoding='UTF-8'?>
<user>
  <fullName>acer915</fullName>
  <properties>
    <hudson.model.PaneStatusProperties>
      <collapsed/>
    </hudson.model.PaneStatusProperties>
    <jenkins.security.ApiTokenProperty>
      <apiToken>bChV4vDsdQYXie9zfSbfoq5dTXq6u2w3lH9RkBk6OyCpaFao1eK4WwXGzbl2Xo8F</apiToken>
    </jenkins.security.ApiTokenProperty>
    <com.cloudbees.plugins.credentials.UserCredentialsProvider_-UserCredentialsProperty plugin="credentials@1.14">
      <domainCredentialsMap class="hudson.util.CopyOnWriteMap$Hash"/>
    </com.cloudbees.plugins.credentials.UserCredentialsProvider_-UserCredentialsProperty>
    <hudson.model.MyViewsProperty>
      <views>
        <hudson.model.AllView>
          <owner class="hudson.model.MyViewsProperty" reference="../../.."/>
          <name>All</name>
          <filterExecutors>false</filterExecutors>
          <filterQueue>false</filterQueue>
          <properties class="hudson.model.View$PropertyList"/>
        </hudson.model.AllView>
      </views>
    </hudson.model.MyViewsProperty>
    <hudson.search.UserSearchProperty>
      <insensitiveSearch>false</insensitiveSearch>
    </hudson.search.UserSearchProperty>
    <hudson.tasks.Mailer_-UserProperty plugin="mailer@1.11">
      <emailAddress>acer915@gmail.com</emailAddress>
    </hudson.tasks.Mailer_-UserProperty>
  </properties>
</user>


text:
module StreamRails

  module SyncPolicy

    module SyncCreate

      def self.included(base)
        if base.respond_to? :after_commit
          base.after_commit :add_to_feed, on: :create
        else
          base.after_create :add_to_feed
        end
      end

      private
      def add_to_feed
        begin
          StreamRails.feed_manager.created_activity(self)
        rescue Exception => e
          StreamRails.logger.error "Something went wrong creating an activity: #{e}"
          raise
        end
      end
    end

    module SyncDestroy

      def self.included(base)
        if base.respond_to? :after_commit
          base.after_commit :remove_from_feed, on: :destroy
        else
          base.after_destroy :remove_from_feed
        end
      end

      private
      def remove_from_feed
        begin
          StreamRails.feed_manager.destroyed_activity(self)
        rescue Exception => e
          StreamRails.logger.error "Something went wrong deleting an activity: #{e}"
          raise
        end
      end
    end

  end
end


text:
O trabalho foi realizado utilizando a linguagem de programação [Python 3.5](https://www.python.org/) e a biblioteca [Pyro 4](https://pythonhosted.org/Pyro4/index.html).

## Biblioteca Pyro4

Esta biblioteca implementa o mecanismo **RMI** (Remote Method Invocation). Com isso, o sistema foi construído utilizando orientação a objeto e possui quatros classes: AbstractStorage, StorageProxy, StoragePrimary e StorageSecundary.

## Instalação

Para rodar o sistema você precisa ter instalado:
* [Python 3.5](https://www.python.org/downloads/) (já vem instalado em sistemas Ubuntu e OSX)
* [Pyro 4](https://pythonhosted.org/Pyro4/install.html#obtaining-and-installing-pyro) (pode ser instalador usando o pip, gerenciador de pacotes do Python)

## Como criar os servidores?

Toda a parte de gerência do sistema é feito através do script **manage.py**. Esse script fornece uma CLI onde você pode:

1. Inicializar o serviço. (Cria o proxy, a máquina primária e o servidor de DNS)
2. Adicionar uma cópia secundária.
3. Simular a falha e a recuperação de uma cópia.

## Como utilizar o cliente?

Através da CLI fornecida pelo script **client.py** você pode:

1. Criar e enviar arquivo no formato txt.
2. Enviar arquivo no formato PDF.
3. Deletar arquivos.
4. Ler arquivos.
5. Listar os arquivos.


text:
struct ll_node {
        void *data;
        struct ll_node *next;
        struct ll_node *last;
};

struct ll {
        struct ll_node *head;
        struct ll_node *tail;
        int size;
};

// initialize empty list
struct ll * ll_init();

// create a node with the given value
struct ll_node* ll_create_node(void *value);

int ll_get_size(struct ll *list);

// check if a node exists
int ll_exists(struct ll *list, void* data, NODE_CMP_FUNC);

// append node to the tail of the list
void ll_append(struct ll *list, struct ll_node *node);

// prepend node to the head of the list
void ll_prepend(struct ll *list, struct ll_node *node);

// return node from the front of the list
struct ll_node* ll_first(struct ll *list);

// return the node from the front of the list without removing it
struct ll_node* ll_first_peek(struct ll *list);

// return the node at the tail of the list
struct ll_node* ll_last(struct ll *list);

// peek at the tail node without removing it
struct ll_node* ll_last_peek(struct ll *list);

void ll_print(struct ll*, NODE_PRINT_FUNC);

// remove a node from the list
// DOES NOT FREE THE NODE
void ll_remove(struct ll *list, struct ll_node *node);

// removes all nodes with given data from the list
// DOES NOT FREE THE NODE
void ll_delete(struct ll *list, void* data, NODE_CMP_FUNC);

// clear everything in the list
void ll_clear(struct ll *list, NODE_FREE_FUNC);

// clear the list and free the given pointer
void ll_free(struct ll *list, NODE_FREE_FUNC);

#endif


text:
node[:deploy].each do |application, deploy|
  rails_env = deploy[:rails_env]
  current_path = deploy[:current_path]

  Chef::Log.info("Precompiling Rails assets with environment #{rails_env}")

  execute 'rake assets:precompile' do
    cwd current_path
    user 'deploy'
    command 'bundle exec rake assets:precompile'
    environment deploy[:environment].to_hash
  end

end


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

namespace Ev3Controller.Model
{
    public class SequenceChangedEventArgs : EventArgs
    {
        #region Constructors and the Finalizer
        public SequenceChangedEventArgs(ConnectionState ConnectState, bool Result = true)
        {
            this.ConnectState = ConnectState;
            this.SequenceChangedResult = Result;
        }
        #endregion

        #region Public Properties
        public ConnectionState ConnectState { get; protected set; }

        public bool SequenceChangedResult { get; protected set; }
        #endregion
    }
}


text:
from google.cloud import vmwareengine_v1

async def sample_get_vmware_engine_network():
    # Create a client
    client = vmwareengine_v1.VmwareEngineAsyncClient()

    # Initialize request argument(s)
    request = vmwareengine_v1.GetVmwareEngineNetworkRequest(
        name="name_value",
    )

    # Make the request
    response = await client.get_vmware_engine_network(request=request)

    # Handle the response
    print(response)

# [END vmwareengine_v1_generated_VmwareEngine_GetVmwareEngineNetwork_async]


text:
;(function($) {

    $.fn.slugify = function(source, options) {

        return this.each(function() {
            var $target = $(this),
                $source = $(source);

            $target.on('keyup change', function() {
                if ($target.val() !== '' && $target.val() !== undefined) {
                    $target.data('locked', true);
                } else {
                    $target.data('locked', false);
                }
            });

            $source.on('keyup change', function() {
                if (true === $target.data('locked')) {
                    return;
                }
                if ($target.is('input') || $target.is('textarea')) {
                    $target.val($.slugify($source.val(), options));
                } else {
                    $target.text($.slugify($source.val(), options));
                }
            });
        });
    };

    // Static method.
    $.slugify = function(sourceString, options) {

        // Override default options with passed-in options.
        options = $.extend({}, $.slugify.options, options);

        // Guess language specifics from html.lang attribute
        // when options.lang is not defined
        options.lang = options.lang || $('html').prop('lang');

        // Apply preSlug function - if exists
        if (typeof options.preSlug === 'function') {
            sourceString = options.preSlug(sourceString);
        }

        sourceString = options.slugFunc(sourceString, options);

        // Apply postSlug function - if exists
        if (typeof options.postSlug === 'function') {
            sourceString = options.postSlug(sourceString);
        }

        return sourceString;
    };

    // Default plugin options
    $.slugify.options = {
        preSlug: null,
        postSlug: null,
        slugFunc: function(input, opts) {
            return window.getSlug(input, opts);
        }
    };

}(jQuery));


text:
This library provides a convenient way to connect with SQL-databases via JDBC, and easily make SQL-requests.

**BacKT SQL** is a part of «**Back-end Kotlin Tool Set**» that consists of:

- [BacKT SQL](https://github.com/Anizoptera/BacKT_SQL) (this one)
- [BacKT WebServer](https://github.com/Anizoptera/BacKT_WebServer) (a Netty-based web-server)

It also uses [KotLog](https://github.com/Anizoptera/Kotlin-Logging-Facade) for logging.

## Installation

```gradle
repositories {
	maven { url "http://dl.bintray.com/azadev/maven" }
}

dependencies {
	compile "azadev.backt:backt_sql:0.7.1"
}
```

And of course you need a JDBC database connector. For example, MySQL Connector/J:

```gradle
dependencies {
	// ...

	compile "mysql:mysql-connector-java:5.1.42"
}
```

## Usage

BacKT SQL consists of 4 main parts:

1. `Database`
2. `ConnectionPool`
3. `QueryBuilder`
4. Small utilities

### Database

The main character of the library is the `Database` class. It holds a connection to the database and allows to perform queries and transactions.

```kotlin
// Must be called once, as your application starts:
Database.loadDriver("com.mysql.jdbc.Driver")

val db = Database.connect("jdbc:mysql://localhost:3306/dbname", "user", "pass")
val resultSet = db.executeQuery("SELECT * FROM t WHERE id = ?", 234)
val count = db.executeUpdate("UPDATE t SET id = ?", 234)
```

`Database` provides methods to perform transactions: `disableAutoCommit`, `enableAutoCommit`, `commit`, `rollback`. Here is an example usage:

```kotlin
db.disableAutoCommit()

val rows = db.executeUpdate("UPDATE t SET id = ?", 234)

if (rows == 0) {
	// log error
	db.rollback()
}
else {
	// do something else
	db.commit()
}
```

Read more about transactions on [JDBC Docs](https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html).

### ConnectionPool

Another must-have tool is the `ConnectionPool`. It caches database connections so they can be reused for future requests:

```kotlin
val pool = ConnectionPool(maxSize = 50) { Database.connect(url, user, pass) }

// Obtain a connection:
val db = pool.obtain()

// ... do some work ...

// Then release:
pool.release(db)
```

There is a couple of convenience methods named `use` and `useAndGet`. `useAndGet` returns the result of its lambda, `use` doesn't:

```kotlin
pool.use { db ->
	db.executeUpdate(...)
}

val res = pool.useAndGet { db ->
	db.executeQuery(...)
}
```

### QueryBuilder

`QueryBuilder` helps to build and execute SQL-statements. For example, the methods listed below are performing exacly the same request:

```kotlin
fun getUser(db: Database, id: Int, email: String): ResultSet {
	return db.executeQuery(
			"SELECT `name`, `surname` FROM `user` WHERE `id`=$id AND `email`=? LIMIT 1",
			email
	)
}

fun getUser(db: Database, id: Int, email: String): ResultSet {
	return QueryBuilder()
			.select("name", "surname")
			.from("user")
			.where("id", id)
			.wherep("email", email)
			.limit(1)
			.executeQuery(db)
}
```

`QueryBuilder` is an extremely useful helper when it comes to build SQL-quesries that depend on some conditions:

```kotlin
fun getUser(db: Database, id: Int? = null, email: String? = null, order: String? = null, desc: Boolean = false): ResultSet {
	val q = QueryBuilder().select().from("user")

	if (id != null)
		q.where("id", id)

	if (email != null)
		q.wherep("email", email)

	if (order != null)
		q.orderBy(order, desc)

	return q.executeQuery(db)
}
```

### Utilities

`count`, `countByte`, `countLong`, `countFloat`, `countDouble`:

```kotlin
val countInt = db.executeUpdate("UPDATE ...").count
val idLong = db.executeQuery("SELECT id FROM ...").countLong
val numFloat = db.executeQuery("SELECT rating FROM ...").countFloat
```

`single`, `toList`:

```kotlin
class User(res: ResultSet) { ... }

val user = db.executeQuery("SELECT * FROM user LIMIT 1").single(::User)
val userList = db.executeQuery("SELECT * FROM user").toList(::User)
```

... and others: `escapeSqlLiteral`, `escapeSqlIdentifier`, `makeValueSet`, `asParameterized`

## License

This software is released under the MIT License.
See [LICENSE.md](LICENSE.md) for details.


text:
function [u, X, FVAL, EXITFLAG, OUTPUT] = lmpc_sparse(problem)
%LMPC_SPARSE Compute the input sequence and predicted output using Linear
%MPC sparse (simultaneous) formulation.
%
%   [U, X, FVAL, EXITFLAG, OUTPUT] = LMPC_SPARSE(PROBLEM). Compute the
%   input sequence using a simultaneous Linear MPC formulation over Nc
%   samples for the linear system pair (A,B) with (Q,R) as weighting
%   matrices, starting from state x0 and constraints on inputs desribed by
%   du and on states by dx. The fields of PROBLEM are described below. Some
%   fields are mandatory, others are optional. The optional fields can be
%   omitted or set to empty array.
%   Mathematical formulation of the problem:
%
%              Nc-1
%              --
%              \
%          min /   (x - xref )'Q(x - xref ) + (u - uref )'R(u - uref )
%           u  --    k      k     k      k      k      k     k      k
%              k=0
%                         s.t.:
%                             x(k+1) = A*x(k) + B*u(k)
%                             ul < u(k) < uu (input bounds)
%                             xl < x(k) < xu (state bounds)
%                             Gu*u(k) <= pu
%                             Gx*x(k) <= px, and
%                             du = [ul'; uu']
%                             dx = [xl'; xu']
%
%   Mandatory fields:
%   - A,B: the state-space matrices describing the system dynamic.
%   - Q,R: the weighting matrices in the cost function.
%   - Nc: the control horizon.
%   - x0: the current( initial) state of the system.
%   - du, dx: the constraint vectors for inputs and states. du is a 2-by-nu
%   matrix containing constraints for inputs. First line is upper bound,
%   second is lower bound for each input. dx is a 2-by-nx matrix with
%   constraints for states. If the input/state has no lower bound, set it's
%   corresponding value to -Inf. Conversely, if the input/state has no
%   upper bound, set to Inf.
%       nu - number of inputs, nx - number of states.
%
%   Optional fields:
%   - xref: the desired( reference) state. Must have nx lines, but can have
%   number of columns in the range [1, Nc].
%   - uref: the reference input (stabilizing input). Must have nu lines,
%   but can have number of columns in the range [1, Nc].
%   - xprev: the previously obtained state prediction. This will be used as
%   a starting point for the algorithm, along with uprev.
%   - uprev: the previously obtained input solution. This will be used to
%   'warm start' the algorithm. This should be the u obtained at a previous
%   step.
%   - Gx, px: constraint matrix and vector for states. Gx is a nrx-by-nx
%   matrix of combinations of constraints on the inputs and pu is a nrx
%   vector.
%       nrx - number of constraints on the combinations of states
%       Gx*x <= px
%   - Gu, pu: constraint matrix and vector for inputs. Gu is a nru-by-nu
%   matrix of combinations of constraints on the inputs and pu is a nru
%   vector.
%       nru - number of constraints on the combinations of inputs
%       Gu*u <= pu
%   - Gpec, ppec: constraint matrix and vector for the Persistent Exciting
%   Condition (PEC). These are constraints for the inputs that apply only
%   for the first prediction in the horizon. This does not guarantee the
%   PEC, but help can be used to implement it by applying the constraints
%   on the first input in the sequence. In all other aspects, is the same
%   as Gu and pu.
%
%   Output arguments:
%   - U: a nu-by-Nc matrix of computed inputs. u(:,1) must be used.
%   - X: a nu-by-Nc matrix of computed inputs, same as u.
%   - FVAL: the object function value given by the numerical solver,
%   quadprog.
%   - EXITFLAG: the exitflag from the solver. See 'help quadprog' for
%   details. EXITFLAG is > 0 if a solution has been found.
%   - OUTPUT: the output from the solver. See 'help quadprog' for details.
%
%   Details for the sparse MPC formulation used can be found in 'Metode de
%   optimizare numerica'(romanian) by prof. I. Necoara, pg 239.

%% Extract parameters from struct
% Required fields
A = problem.A;
B = problem.B;
Q = problem.Q;
R = problem.R;
Nc = problem.Nc;
du = problem.du;
dx = problem.dx;
x0 = problem.x0;
% Optional fields: references and previous solutions
if isfield(problem, 'xref')
    xref = problem.xref;
else
    xref = [];
end
if isfield(problem,'uref')
    uref = problem.uref;
else
    uref = [];
end
if isfield(problem, 'xprev')
    Xprev = problem.xprev;
else
    Xprev = [];
end
if isfield(problem, 'uprev')
    uprev = problem.uprev;
else
    uprev = [];
end
% Optional fields: inputs/states combination constraints
if isfield(problem, 'Gx')
    Gx = problem.Gx;
else
    Gx = [];
end
if isfield(problem, 'px')
    px = problem.px;
else
    px = [];
end
if isfield(problem, 'Gu')
    Gu = problem.Gu;
else
    Gu = [];
end
if isfield(problem, 'pu')
    pu = problem.pu;
else
    pu = [];
end
if isfield(problem, 'Gpec')
    Gpec = problem.Gpec;
else
    Gpec = [];
end
if isfield(problem, 'ppec')
    ppec = problem.ppec;
else
    ppec = [];
end
%% Argument processing
nu = size(B,2); %number of inputs
nx = size(A,1); %number of states
if isempty(xref)
    xref = zeros(nx,1);
end
if isempty(uref)
    uref = zeros(nu,1);
end
difx = Nc - size(xref,2);
difu = Nc - size(uref, 2);
% If xref does not have enough columns, append the last column difx times
if difx > 0
    xref = [xref, repmat(xref(:,end), [1 difx])];
end
% For uref same as for xref above
if difu > 0
    uref = [uref, repmat(uref(:,end), [1 difu])];
end
if isempty(Xprev)
    %if there is no previous solution, use the reference as a start point
    Xprev = xref;
else
    Xprev = [Xprev(:,1:end-1), xref(:,end)]; %shift the previous solution
end
if isempty(uprev)
    %if there is no previous solution, use the reference as a start point
    uprev = uref;
else
    uprev = [uprev(:,1:end-1), uref(:,end)]; %shift the previous solution
end
Zprev = [uprev; Xprev];
%% QP definition
ubx = dx(1,:)';
lbx = dx(2,:)';
ubu = du(1,:)';
lbu = du(2,:)';
lb = [lbu; lbx];
ub = [ubu; ubx];
LB = repmat(lb, Nc, 1);
UB = repmat(ub, Nc, 1);
Qsmall = blkdiag(R,Q);
Asmall = [-B eye(nx)];
bsmall= zeros(nx,1);
Q_hat = Qsmall;
A_hat = [-B eye(nx)];
b_hat = A*x0;
for i = 1:Nc-1
    %Add another element to the block diagonal matrices
    Q_hat = blkdiag(Q_hat, Qsmall);
    A_hat = blkdiag(A_hat, Asmall);
    %Add '-A' to the subdiagonal
    lines_l = i*nx + 1;
    lines_u = (i+1)*nx;
    cols_l = i*nu + (i-1)*nx + 1;
    cols_u = i*nu + i*nx;
    A_hat(lines_l: lines_u, cols_l: cols_u)= -A;
end
b_hat = [b_hat; repmat(bsmall, [Nc-1 1])];
zsmall = [ uref; xref];
zref = zsmall(:);
q = -Q_hat*zref;
z0 = Zprev(:);
%% Gbar, pbar
if isempty(Gu)
    Gu = zeros(1, nu);
    pu = 0;
end
if isempty(Gx)
    Gx = zeros(1, nx);
    px = 0;
end
Gbar = [];
Gbarsmall = blkdiag(Gu, Gx);
for i = 1:Nc
    Gbar = blkdiag(Gbar, Gbarsmall);
end
pbarsmall = [pu; px];
pbar = repmat(pbarsmall, [Nc 1]);
if ~isempty(Gpec)
    % Add the pec constraint
    nru = size(Gu,1);
    Gbarpec = padarray(Gpec,[0 ((Nc-1)*nu+Nc*nx)], 0, 'post'); %zero-pad
    Gbar = [Gbar(1:nru,:); Gbarpec; Gbar(nru+1:end,:)];
    pbar = [pbar(1:nru,:); ppec; pbar(nru+1:end,:)];
end
%% QP solver
rel = version('-release');
rel = rel(1:4); %just the year
relnum = str2double(rel);
switch relnum
    case 2010
        options = optimset(...
            'Display', 'off', 'Diagnostics', 'off', 'LargeScale', 'off');
    case 2011
        options = optimset(...
            'Algorithm', 'interior-point-convex', 'Display', 'off');
    case 2013
        options = optimoptions('quadprog', ...
            'Algorithm', 'interior-point-convex', 'Display', 'off');
    otherwise
        error('Can''t set solver options for this version of Matlab');
end
[Z,FVAL,EXITFLAG, OUTPUT] = quadprog(Q_hat, q, Gbar, pbar, A_hat, b_hat, ...
    LB,UB, z0, options);
%% Return variables
X = reshape(Z, nu+nx,[]);
u = X(1:nu,:);
X = X(nu+1:end,:);


text:
(function (root, $) {
    $('.menu .dropdown').dropdown();
    $('span.popup.exception').popup();
    $('a.popup.exception').popup();
}(window, jQuery));

//var resetPasswordUrl = 'https://peaceful-refuge-8041.herokuapp.com/resetpassword/';
var resetPasswordUrl = 'phantom-password-resetter.herokuapp.com/resetpassword/';

$(document).ready(function() {
    $("img").unveil(50);
    $('.misc-toggle').click(function() {
        $(this).find('i').toggleClass('down up')
        $(this).parent().next('.collapse').find('div').slideToggle(500);
        return false;
    });

    $('#reset-password-button').click(function() {
    	var email = $('#reset-password-input').val();
    	$.get( resetPasswordUrl + email, function( data ) {
			alert(data);
		});
    });

});


text:
/*! \file */
/* ************************************************************************
 * Copyright (C) 2018-2022 Advanced Micro Devices, Inc. All rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * ************************************************************************ */

#pragma once

#include <hip/hip_runtime.h>

// Create identity permutation
template <unsigned int BLOCKSIZE, typename I>
__launch_bounds__(BLOCKSIZE) ROCSPARSE_KERNEL void identity_kernel(I n, I* p)
{
    I gid = hipBlockIdx_x * BLOCKSIZE + hipThreadIdx_x;

    if(gid >= n)
    {
        return;
    }

    p[gid] = gid;
}


text:
namespace Farmhand.UI.Base
{
    using System;

    using Farmhand.UI.Interfaces;

    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;

    using StardewValley;

    /// <summary>
    ///     The base menu component.
    /// </summary>
    public abstract class BaseMenuComponent : IMenuComponent
    {
        /// <summary>
        ///     Zoom level 0.5 (pixelZoom / 2).
        /// </summary>
        protected static readonly int Zoom05 = Game1.pixelZoom / 2;

        /// <summary>
        ///     Zoom level 2 (pixelZoom * 2).
        /// </summary>
        protected static readonly int Zoom2 = 2 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 3 (pixelZoom * 3).
        /// </summary>
        protected static readonly int Zoom3 = 3 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 4 (pixelZoom * 4).
        /// </summary>
        protected static readonly int Zoom4 = 4 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 5 (pixelZoom * 5).
        /// </summary>
        protected static readonly int Zoom5 = 5 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 6 (pixelZoom * 6).
        /// </summary>
        protected static readonly int Zoom6 = 6 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 7 (pixelZoom * 7).
        /// </summary>
        protected static readonly int Zoom7 = 7 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 8 (pixelZoom * 8).
        /// </summary>
        protected static readonly int Zoom8 = 8 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 9 (pixelZoom * 9).
        /// </summary>
        protected static readonly int Zoom9 = 9 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 10 (pixelZoom * 10).
        /// </summary>
        protected static readonly int Zoom10 = 10 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 11 (pixelZoom * 11).
        /// </summary>
        protected static readonly int Zoom11 = 11 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 12 (pixelZoom * 12).
        /// </summary>
        protected static readonly int Zoom12 = 12 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 13 (pixelZoom * 13).
        /// </summary>
        protected static readonly int Zoom13 = 13 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 14 (pixelZoom * 14).
        /// </summary>
        protected static readonly int Zoom14 = 14 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 15 (pixelZoom * 15).
        /// </summary>
        protected static readonly int Zoom15 = 15 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 16 (pixelZoom * 16).
        /// </summary>
        protected static readonly int Zoom16 = 16 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 17 (pixelZoom * 17).
        /// </summary>
        protected static readonly int Zoom17 = 17 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 20 (pixelZoom * 20).
        /// </summary>
        protected static readonly int Zoom20 = 20 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 22 (pixelZoom * 22).
        /// </summary>
        protected static readonly int Zoom22 = 22 * Game1.pixelZoom;

        /// <summary>
        ///     Zoom level 28 (pixelZoom * 28).
        /// </summary>
        protected static readonly int Zoom28 = 28 * Game1.pixelZoom;

        private Rectangle area;

        private IComponentContainer parent;

        /// <summary>
        ///     Initializes a new instance of the <see cref="BaseMenuComponent" /> class.
        /// </summary>
        protected BaseMenuComponent()
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="BaseMenuComponent" /> class.
        /// </summary>
        /// <param name="area">
        ///     The bounding area of the component
        /// </param>
        /// <param name="texture">
        ///     The backing texture of the component
        /// </param>
        /// <param name="crop">
        ///     The cropped area of the component
        /// </param>
        protected BaseMenuComponent(Rectangle area, Texture2D texture, Rectangle? crop = null)
        {
            if (crop == null)
            {
                crop = new Rectangle(0, 0, texture.Width, texture.Height);
            }

            this.Texture = texture;
            this.Crop = (Rectangle)crop;
            this.SetScaledArea(area);
        }

        /// <summary>
        ///     Gets or sets the area of this component.
        /// </summary>
        protected Rectangle Area
        {
            get
            {
                return this.area;
            }

            set
            {
                this.area = value;
            }
        }

        /// <summary>
        ///     Gets the backing texture of this component
        /// </summary>
        protected Texture2D Texture { get; }

        /// <summary>
        ///     Gets the cropped area of this component
        /// </summary>
        protected Rectangle Crop { get; }

        #region IMenuComponent Members

        /// <summary>
        ///     Gets the parent of this component
        /// </summary>
        /// <exception cref="NullReferenceException">
        ///     Triggered when parent is null
        /// </exception>
        public IComponentContainer Parent
        {
            get
            {
                if (this.parent == null)
                {
                    throw new NullReferenceException("Component attempted to reference its parent while not attached");
                }

                return this.parent;
            }
        }

        /// <summary>
        ///     Gets or sets a value indicating whether the component is visible.
        /// </summary>
        public bool Visible { get; set; } = true;

        /// <summary>
        ///     Gets or sets the layer of this component.
        /// </summary>
        public int Layer { get; set; } = 0;

        /// <summary>
        ///     Attaches this component to another
        /// </summary>
        /// <param name="collection">
        ///     The collection to attach to
        /// </param>
        /// <exception cref="Exception">
        ///     Thrown if this component already has a parent
        /// </exception>
        public void Attach(IComponentContainer collection)
        {
            if (this.parent != null)
            {
                throw new Exception(
                    "Component is already attached and must be detached first before it can be attached again");
            }

            this.parent = collection;
        }

        /// <summary>
        ///     Detaches this component from it's parent
        /// </summary>
        /// <param name="collection">
        ///     Unused parameter
        /// </param>
        /// <exception cref="Exception">
        ///     Thrown if this component does not have a parent
        /// </exception>
        public void Detach(IComponentContainer collection)
        {
            if (this.parent == null)
            {
                throw new Exception("Component is not attached and must be attached first before it can be detached");
            }

            this.parent = null;
        }

        /// <summary>
        ///     Gets the position of this component
        /// </summary>
        /// <returns>
        ///     The position of this component as a <see cref="Point" />.
        /// </returns>
        public virtual Point GetPosition()
        {
            return new Point(this.area.X, this.area.Y);
        }

        /// <summary>
        ///     Gets the bounding region of this component
        /// </summary>
        /// <returns>
        ///     The region of this component as a <see cref="Rectangle" />.
        /// </returns>
        public virtual Rectangle GetRegion()
        {
            return this.area;
        }

        /// <summary>
        ///     Called every frame on each component, responsible for updating behavior
        /// </summary>
        /// <param name="t">
        ///     The time elapsed since the previous frame
        /// </param>
        public virtual void Update(GameTime t)
        {
        }

        /// <summary>
        ///     Called each frame on each component, responsible for drawing it and it's children
        /// </summary>
        /// <param name="b">
        ///     The sprite batch to use for drawing
        /// </param>
        /// <param name="o">
        ///     The origin of this component
        /// </param>
        public virtual void Draw(SpriteBatch b, Point o)
        {
            if (this.Visible)
            {
                b.Draw(
                    this.Texture,
                    new Rectangle(this.area.X + o.X, this.area.Y + o.Y, this.area.Width, this.area.Height),
                    this.Crop,
                    Color.White,
                    0,
                    Vector2.Zero,
                    SpriteEffects.None,
                    1f);
            }
        }

        #endregion

        /// <summary>
        ///     Inflates the components bounding area by a specified amount
        /// </summary>
        /// <param name="horizontalAmount">
        ///     The horizontal inflation
        /// </param>
        /// <param name="verticalAmount">
        ///     The vertical inflation
        /// </param>
        /// <returns>
        ///     The inflated region as a <see cref="Rectangle" />.
        /// </returns>
        public virtual Rectangle InflateRegion(int horizontalAmount, int verticalAmount)
        {
            this.area.Inflate(horizontalAmount, verticalAmount);
            return this.area;
        }

        /// <summary>
        ///     Moves the bounding region by a specified amount
        /// </summary>
        /// <param name="x">
        ///     The x translation
        /// </param>
        /// <param name="y">
        ///     The y translation
        /// </param>
        /// <returns>
        ///     The moved region as a <see cref="Rectangle" />.
        /// </returns>
        public virtual Rectangle MoveRegion(int x, int y)
        {
            this.area.X += x;
            this.area.Y += y;
            return this.area;
        }

        /// <summary>
        ///     Set the scaled area.
        /// </summary>
        /// <param name="scaledArea">
        ///     The scaled area
        /// </param>
        protected void SetScaledArea(Rectangle scaledArea)
        {
            this.area = new Rectangle(
                scaledArea.X * Game1.pixelZoom,
                scaledArea.Y * Game1.pixelZoom,
                scaledArea.Width * Game1.pixelZoom,
                scaledArea.Height * Game1.pixelZoom);
        }

        /// <summary>
        ///     Calculates the width of a string
        /// </summary>
        /// <param name="text">
        ///     The string to calculate the width of.
        /// </param>
        /// <param name="font">
        ///     The font used.
        /// </param>
        /// <param name="scale">
        ///     The scaling factor of the text.
        /// </param>
        /// <returns>
        ///     The width of the string.
        /// </returns>
        protected int GetStringWidth(string text, SpriteFont font, float scale = 1f)
        {
            return (int)Math.Ceiling(font.MeasureString(text).X / Game1.pixelZoom * scale);
        }
    }
}


text:
var mongodb = require('./db');

/*
//level级别 上传提升等级
levelnumber  级别数值
levelname    级别名称

*/

function Level(level) {
    this.levelnumber = level.levelnumber;
    this.levelname = level.levelname;
}

module.exports = Level;

Level.getLevelByCount = function (bookcount, callback) {
    var level = {
        levelnumber: this.levelnumber,
        levelname: this.levelname
    };

    mongodb.open(function (err, db) {
        if (err) {
            mongodb.close();
            return callback(err);
        }
        db.collection('levels', function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);
            }
            var query = {};
            if (bookcount) {
                //选择小于等于目标值的数据
                levelnumber: { $lte: bookcount }
            }
            //按照等级从大到小排序
            collection.find(query).sort({
                levelnumber: -1
            }).toArray(function (err, docs) {
                mongodb.close();
                if (err) {
                    return callback(err);
                }
                //返回最大的一个数据
                callback(null, docs[0]);
            });
        });
    });
};

Level.get = function (callback) {
    mongodb.open(function (err, db) {
        if (err) {
            mongodb.close();
            return callback(err);
        }
        db.collection('levels', function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);
            }
            var query = {};
            //按照等级从小到大排序
            collection.find(query).sort({
                levelnumber: 1
            }).toArray(function (err, docs) {
                mongodb.close();
                if (err) {
                    return callback(err);
                }
                callback(null, docs);
            });
        });
    });
}


text:
from rest_framework import serializers

from rational_crowd.api.serializers.utils import DynamicFieldsModelSerializer
from rational_crowd.questionnaire.models import Questionnaire, Question, QuestionOption

class QuestionnaireSerializer(DynamicFieldsModelSerializer):
    questions = serializers.SerializerMethodField()

    class Meta:
        model = Questionnaire
        fields = ('name', 'questions')

    def get_questions(self, obj):
        serializer = QuestionSerializer(obj.questions, many=True)
        return serializer.data

class QuestionSerializer(DynamicFieldsModelSerializer):
    options = serializers.SerializerMethodField()

    class Meta:
        model = Question
        fields = ('id', 'content', 'is_multiple_choice', 'options')

    def get_options(self, obj):
        serializer = QuestionOptionSerializer(obj.options, many=True)
        return serializer.data

class QuestionOptionSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = QuestionOption
        fields = ('id', 'content')


text:
import React from "react";
import Link from "next/link";
import Avatar from '../public/dpham2.jpg'

const Hero = (...props) => {
  return (

David M. Pham

          Front-End Developer. I build useful and beautiful interfaces.

              <Link href="https://twitter.com/davidpham5">

                  Twitter

              </Link>

              <Link href="https://github.com/davidpham5">

                  Github

              </Link>

              <Link href="https://linkedin.com/in/davidmpham">

                  Linkedin

              </Link>

  );
};

export default Hero;


text:
#include "Tiano.h"
#include "EfiDriverLib.h"
#include "Ehci.h"

//
// EFI Component Name Functions
//
EFI_STATUS
EFIAPI
EhciComponentNameGetDriverName (
  IN  EFI_COMPONENT_NAME_PROTOCOL     *This,
  IN  CHAR8                           *Language,
  OUT CHAR16                          **DriverName
  );

EFI_STATUS
EFIAPI
EhciComponentNameGetControllerName (
  IN  EFI_COMPONENT_NAME_PROTOCOL     *This,
  IN  EFI_HANDLE                      ControllerHandle,
  IN  EFI_HANDLE                      ChildHandle, OPTIONAL
  IN  CHAR8                           *Language,
  OUT CHAR16                          **ControllerName
  );

//
// EFI Component Name Protocol
//
EFI_COMPONENT_NAME_PROTOCOL     gEhciComponentName = {
  EhciComponentNameGetDriverName,
  EhciComponentNameGetControllerName,
  "eng"
};

static EFI_UNICODE_STRING_TABLE mEhciDriverNameTable[] = {
  { "eng", L"UEFI Usb Ehci Driver" },
  { NULL , NULL }
};

EFI_STATUS
EFIAPI
EhciComponentNameGetDriverName (
  IN  EFI_COMPONENT_NAME_PROTOCOL     *This,
  IN  CHAR8                           *Language,
  OUT CHAR16                          **DriverName
  )
/*++

  Routine Description:
    Retrieves a Unicode string that is the user readable name of the EFI Driver.

  Arguments:
    This       - A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance.
    Language   - A pointer to a three character ISO 639-2 language identifier.
                 This is the language of the driver name that that the caller
                 is requesting, and it must match one of the languages specified
                 in SupportedLanguages.  The number of languages supported by a
                 driver is up to the driver writer.
    DriverName - A pointer to the Unicode string to return.  This Unicode string
                 is the name of the driver specified by This in the language
                 specified by Language.

  Returns:
    EFI_SUCCESS           - The Unicode string for the Driver specified by This
                            and the language specified by Language was returned
                            in DriverName.
    EFI_INVALID_PARAMETER - Language is NULL.
    EFI_INVALID_PARAMETER - DriverName is NULL.
    EFI_UNSUPPORTED       - The driver specified by This does not support the
                            language specified by Language.

--*/
{
  return EfiLibLookupUnicodeString (
          Language,
          gEhciComponentName.SupportedLanguages,
          mEhciDriverNameTable,
          DriverName
          );
}

EFI_STATUS
EFIAPI
EhciComponentNameGetControllerName (
  IN  EFI_COMPONENT_NAME_PROTOCOL     *This,
  IN  EFI_HANDLE                      ControllerHandle,
  IN  EFI_HANDLE                      ChildHandle, OPTIONAL
  IN  CHAR8                           *Language,
  OUT CHAR16                          **ControllerName
  )
/*++

  Routine Description:
    Retrieves a Unicode string that is the user readable name of the controller
    that is being managed by an EFI Driver.

  Arguments:
    This             - A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance.
    ControllerHandle - The handle of a controller that the driver specified by
                       This is managing.  This handle specifies the controller
                       whose name is to be returned.
    ChildHandle      - The handle of the child controller to retrieve the name
                       of.  This is an optional parameter that may be NULL.  It
                       will be NULL for device drivers.  It will also be NULL
                       for a bus drivers that wish to retrieve the name of the
                       bus controller.  It will not be NULL for a bus driver
                       that wishes to retrieve the name of a child controller.
    Language         - A pointer to a three character ISO 639-2 language
                       identifier.  This is the language of the controller name
                       that that the caller is requesting, and it must match one
                       of the languages specified in SupportedLanguages.  The
                       number of languages supported by a driver is up to the
                       driver writer.
    ControllerName   - A pointer to the Unicode string to return.  This Unicode
                       string is the name of the controller specified by
                       ControllerHandle and ChildHandle in the language
                       specified by Language from the point of view of the
                       driver specified by This.

  Returns:
    EFI_SUCCESS           - The Unicode string for the user readable name in the
                            language specified by Language for the driver
                            specified by This was returned in DriverName.
    EFI_INVALID_PARAMETER - ControllerHandle is not a valid EFI_HANDLE.
    EFI_INVALID_PARAMETER - ChildHandle is not NULL and it is not a valid
                            EFI_HANDLE.
    EFI_INVALID_PARAMETER - Language is NULL.
    EFI_INVALID_PARAMETER - ControllerName is NULL.
    EFI_UNSUPPORTED       - The driver specified by This is not currently
                            managing the controller specified by
                            ControllerHandle and ChildHandle.
    EFI_UNSUPPORTED       - The driver specified by This does not support the
                            language specified by Language.

--*/
{
  EFI_STATUS           Status;
  USB2_HC_DEV          *EhciDev;
  EFI_USB2_HC_PROTOCOL *Usb2Hc;

  //
  // This is a device driver, so ChildHandle must be NULL.
  //
  if (ChildHandle != NULL) {
    return EFI_UNSUPPORTED;
  }
  //
  // Make sure this driver is currently managing ControllerHandle
  //
  Status = EfiLibTestManagedDevice (
             ControllerHandle,
             gEhciDriverBinding.DriverBindingHandle,
             &gEfiPciIoProtocolGuid
             );
  if (EFI_ERROR (Status)) {
    return Status;
  }
  //
  // Get the device context
  //
  Status = gBS->OpenProtocol (
                  ControllerHandle,
                  &gEfiUsb2HcProtocolGuid,
                  (VOID **) &Usb2Hc,
                  gEhciDriverBinding.DriverBindingHandle,
                  ControllerHandle,
                  EFI_OPEN_PROTOCOL_GET_PROTOCOL
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  EhciDev = USB2_HC_DEV_FROM_THIS (Usb2Hc);

  return EfiLibLookupUnicodeString (
          Language,
          gEhciComponentName.SupportedLanguages,
          EhciDev->ControllerNameTable,
          ControllerName
          );

}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta charset="utf-8"/>
    <title>    Phing API Documentation » \IniFileParser
</title>
    <meta name="author" content=""/>
    <meta name="description" content=""/>

            <link href="../css/template.css" rel="stylesheet" media="all"/>

            <link rel="shortcut icon" href="../img/favicon.ico"/>
        <link rel="apple-touch-icon" href="../img/apple-touch-icon.png"/>
        <link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png"/>
        <link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png"/>

                Phing API Documentation

                                API Documentation

                                Charts

                                         Class hierarchy diagram

                                Reports

                                         Errors

                                         Markers

                                         Deprecated

            Back to top

                Javascript is disabled; several features are only available if Javascript is enabled.

        <button class="btn details" title="Show descriptions and method names"></button>
        <button class="btn simple" title="Show only method names"></button>

        <button class="btn public active" title="Show public elements">Public</button>
        <button class="btn protected" title="Show protected elements">Protected</button>
        <button class="btn private" title="Show private elements">Private</button>
        <button class="btn inherited active" title="Show inherited elements">Inherited</button>

             Methods

            Builds an array from the given (ini) file and returns it.
parseFile

» Protected

                                Process values when being read in from properties file.
inVal

» Private

             Constants

IniFileParser

                                                                Implements \FileParserInterface

Implements an IniFileParser. The logic is coming from th Properties.php, but I don't know who's the author.

FIXME

Add support for arrays (separated by ',')

                                        author

Mike Lohmann mike.lohmann@deck36.de

                                        package

phing.system.io

 Methods

Process values when being read in from properties file.

inVal(string $val) : mixed

does things like convert "true" => true

Arguments

$val

                                                string

Trimmed value.

Response

                                        mixed

The new property value (may be boolean, etc.)

Builds an array from the given (ini) file and returns it.

parseFile(\PhingFile $file) : array

Arguments

$file

                                                \PhingFile

Response

                                        array

\\

\IniFileParser

            Template is built using Twitter Bootstrap 2 and icons provided by
            Glyphicons.

            Documentation is powered by phpDocumentor  and

            generated on Thu, 13 Oct 2016 11:15:02 +0200.


text:
import { browser, element, by } from 'protractor';

export class ClaritySeedAppHome {

  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('my-app p')).getText();
  }
}