text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Example Processing Loop</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Getting Started with Replicated Berkeley DB Applications" />
    <link rel="up" href="fwrkmasterreplica.html" title="Chapter 4. Replica versus Master Processes" />
    <link rel="prev" href="processingloop.html" title="Processing Loop" />
    <link rel="next" href="addfeatures.html" title="Chapter 5. Additional Features" />

Library Version 11.2.5.3

          Example Processing Loop

          Prev
          Chapter 4. Replica versus Master Processes
           Next

Example Processing Loop

              Running It

                          In this section we take the example
                          processing loop that we presented in the
                          previous section and we flesh it out to
                          provide a more complete example. We do this
                          by updating the
                          doloop()
                          function that our original transaction
                          application used

                          (see Method: SimpleTxn.doloop())
                          to fully support our replicated application.

                          In the following example code, code that we
                          add to the original example is presented in
                          bold.

            To begin, we must implement a way to track whether our
            application is running as a master or a client.  There are many
            ways to do this, but in this case what we will do is extend
            com.sleepycat.db.Environment to carry
            the information. We do this by creating the
            RepQuoteEnvironment class.

package db.repquote;

import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;

public class RepQuoteEnvironment extends Environment
{
    private boolean isMaster;

    public RepQuoteEnvironment(final java.io.File host,
        EnvironmentConfig config)
        throws DatabaseException, java.io.FileNotFoundException
    {
        super(host, config);
        isMaster = false;
    }

    boolean getIsMaster()
    {
        return isMaster;
    }

    public void setIsMaster(boolean isMaster)
    {
        this.isMaster = isMaster;
    }
}

                  Next, we go to RepQuoteExampleGSG.java and
                  we include the
                  RepQuoteEnvironment class
                  as well as the
                  EventHandler class. We then
                  cause our RepQuoteExampleGSG
                  class to implement
                  EventHandler. We also
                  change our environment handle to be an instance
                  of RepQuoteEnvironment
                  instead of Environment.

                  Note that we also import the
                  com.sleepycat.db.ReplicationHandleDeadException
                  class. We will discuss what that exception is
                  used for a little later in this example.

package db.repquote;

import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.Thread;
import java.lang.InterruptedException;

import com.sleepycat.db.Cursor;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.DatabaseType;
import com.sleepycat.db.EnvironmentConfig;
import com.sleepycat.db.EventHandler;
import com.sleepycat.db.LockMode;
import com.sleepycat.db.OperationStatus;
import com.sleepycat.db.ReplicationHandleDeadException;
import com.sleepycat.db.ReplicationHostAddress;
import com.sleepycat.db.ReplicationManagerSiteConfig;

import db.repquote.RepConfig;
import db.repquote.RepQuoteEnvironment

public class RepQuoteExampleGSG  implements EventHandler
{
    private RepConfig repConfig;
    private RepQuoteEnvironment dbenv;

        That done, we can skip the

        main() method and
                our class constructor, because they do not change.

        Instead, we skip down to our

        init() method
                where we take care of opening our environment and setting
                the event handler.

        To update our init() method, we only need
        to do a couple of things. First, we identify the current class as
        the event handler. Then, when we open our environment, we
        instantiate a RepQuoteEnvironment
        class instead of an Environment
        class.

    public int init(RepConfig config)
        throws DatabaseException
    {
        int ret = 0;
        repConfig = config;
        EnvironmentConfig envConfig = new EnvironmentConfig();
        envConfig.setErrorStream(System.err);
        envConfig.setErrorPrefix(RepConfig.progname);

        envConfig.addReplicationManagerSite(repConfig.getThisHost());
        for (ReplicationHostAddress host =
            repConfig.getFirstOtherHost(); host != null;
            host = repConfig.getNextOtherHost()){

            ReplicationManagerSiteConfig repmgrRemoteSiteConfig =
                new ReplicationManagerSiteConfig(host.host, host.port);
            repmgrRemoteSiteConfig.setBootstrapHelper(true);
            envConfig.addReplicationManagerSite(
                repmgrRemoteSiteConfig);
        }

        envConfig.setReplicationPriority(repConfig.priority);

        envConfig.setReplicationManagerAckPolicy(
            ReplicationManagerAckPolicy.ALL);
        envConfig.setCacheSize(RepConfig.CACHESIZE);
        envConfig.setTxnNoSync(true);

        envConfig.setEventHandler(this);

        envConfig.setAllowCreate(true);
        envConfig.setRunRecovery(true);
        envConfig.setThreaded(true);
        envConfig.setInitializeReplication(true);
        envConfig.setInitializeLocking(true);
        envConfig.setInitializeLogging(true);
        envConfig.setInitializeCache(true);
        envConfig.setTransactional(true);
        envConfig.setVerboseReplication(appConfig.verbose);
        try {
            dbenv = new RepQuoteEnvironment(repConfig.getHome(),
                                                       envConfig);
        } catch(FileNotFoundException e) {
            System.err.println("FileNotFound exception: " + e.toString());
            System.err.println(
                "Ensure that the environment directory is pre-created.");
            ret = 1;
        }

        // start Replication Manager
        dbenv.replicationManagerStart(3, repConfig.startPolicy);
        return ret;
    }

    That done, we need to implement the methods
    required for responding to replication events.
        These methods are required because we are now implementing
        com.sleepycat.db.EventHandler.  While
        we are required to provide an implementation for all of these
        methods, for our simple application we are really only interested
        in these because they allow us to track whether a replication
        instance is a master.

    public void handleRepClientEvent()
    {
        dbenv.setIsMaster(false);
    }

    public void handleRepConnectBrokenEvent()
    {
        // Ignored for now.
    }

    public void handleRepConnectEstablishedEvent()
    {
        // Ignored for now.
    }

    public void handleRepConnectTryFailedEvent()
    {
        // Ignored for now.
    }

    public void handleRepMasterEvent()
    {
        dbenv.setIsMaster(true);
    }

    public void handleRepNewMasterEvent(int envId)
    {
        // Ignored for now.
    }

    public void handleWriteFailedEvent(int errorCode)
    {
        System.err.println("Write to stable storage failed!" +
            "Operating system error code:" + errorCode);
        System.err.println("Continuing....");
    }

    public void handleRepStartupDoneEvent()
    {
        // Ignored for now.
    }

    public void handleRepPermFailedEvent()
    {
    // Ignored for now.
    }

    public void handleRepLocalSiteRemovedEvent()
    {
        // Ignored for now.
    }

    public void handleRepSiteAddedEvent()
    {
        // Ignored for now.
    }

    public void handleRepSiteRemovedEvent()
    {
        // Ignored for now.
    }

    public void handleRepElectedEvent()
    {
        // Safely ignored for Replication Manager applications.
    }

    public void handleRepElectionFailedEvent()
    {
        // Safely ignored for Replication Manager applications that do
        // not manage their own master selection.
    }

    public void handleRepJoinFailureEvent()
    {
        // Safely ignored since this application did not turn off AUTOINIT.
    }

    public void handleRepMasterFailureEvent()
    {
        // Safely ignored for Replication Manager applications that do
        // not manage their own master selection.
    }

    public void handleRepDupmasterEvent()
    {
        // Safely ignored for Replication Manager applications that do
        // not manage their own master selection.
    }

    public void handlePanicEvent()
    {
        System.err.println("Panic encountered!");
        System.err.println("Shutting down.");
        System.err.println("You should restart, running recovery.");
        try {
            terminate();
        } catch (DatabaseException dbe) {
            System.err.println("Caught an exception during " +
                "termination in handlePanicEvent: " + dbe.toString());
        }
        System.exit(-1);
    }

        That done, we need to update our
        doloop()

        method.

            We begin by updating our DatabaseConfig
            instance to determine which options to use, depending on whether the
            application is running as a master.

    public int doloop()
        throws DatabaseException
    {
        Database db = null;

        for (;;)
        {
            if (db == null) {
                DatabaseConfig dbconf = new DatabaseConfig();
                dbconf.setType(DatabaseType.BTREE);
                if (dbenv.getIsMaster()) {
                    dbconf.setAllowCreate(true);
                }
                dbconf.setTransactional(true);

    When we open the database, we modify our error handling to
    account for the case where the database does not yet exist. This can
    happen if our code is running as a replica and the Replication Manager has not
    yet had a chance to create the databases for us. Recall that replicas never
    write to their own databases directly, and so they cannot
    create databases on their own.

        If we detect that the database does not yet exist, we simply
        close the database handle, sleep for a short period of time
        and then continue processing. This gives the Replication Manager a chance to
        create the database so that our replica can continue
        operations.

                try {
                    db = dbenv.openDatabase
                        (null, RepConfig.progname, null, dbconf);
                } catch (java.io.FileNotFoundException e) {
                    System.err.println("no stock database available yet.");
                    if (db != null) {
                        db.close(true);
                        db = null;
                    }
                    try {
                        Thread.sleep(RepConfig.SLEEPTIME);
                    } catch (InterruptedException ie) {}
                    continue;
                }
            }

        Next we modify our prompt, so that if the local process is running
        as a replica, we can tell from the shell that the prompt is for a
        read-only process.

            BufferedReader stdin =
                new BufferedReader(new InputStreamReader(System.in));

            // listen for input, and add it to the database.
            System.out.print("QUOTESERVER");
            if (!dbenv.getIsMaster())
                System.out.print("(read-only)");
            System.out.print("> ");
            System.out.flush();
            String nextline = null;
            try {
                nextline = stdin.readLine();
            } catch (IOException ioe) {
                System.err.println("Unable to get data from stdin");
                break;
            }
            String[] words = nextline.split("\\s");

            When we collect data from the prompt, there is a case that says
            if no data is entered then show the entire stocks database.
            This display is performed by our
            print_stocks()

            method
            (which has not
            required a modification since we first introduced it in

                            Method: SimpleTxn.printStocks()
                    ).

            When we call

               printStocks(),
            we check for a dead replication handle. Dead
            replication handles happen whenever a replication election
            results in a previously committed transaction becoming
            invalid. This is an error scenario caused by a new master having a
            slightly older version of the data than the original
            master and so all replicas must modify their database(s) to
            reflect that of the new master. In this situation, some
            number of previously committed transactions may have to be
            unrolled. From the replica's perspective, the database
            handles should all be closed and then opened again.

            // A blank line causes the DB to be dumped to stdout.
            if (words.length == 0 ||
                (words.length == 1 && words[0].length() == 0)) {
                try {
                    printStocks(db);
                } catch (DeadlockException de) {
                    continue;
                // Dead replication handles are caused by an election
                // resulting in a previously committing read becoming
                // invalid. Close the db handle and reopen.
                } catch (ReplicationHandleDeadException rhde) {
                    db.close(true); // close no sync.
                    db = null;
                    continue;
                } catch (DatabaseException e) {
                    System.err.println("Got db exception reading " +
                        "replication DB: " + e.toString());
                    break;
                }
                continue;
            }

            if (words.length == 1 &&
                (words[0].compareToIgnoreCase("quit") == 0 ||
                words[0].compareToIgnoreCase("exit") == 0)) {
                break;
            } else if (words.length != 2) {
                System.err.println("Format: TICKER VALUE");
                continue;
            }

            That done, we need to add a little error checking to our
            command prompt to make sure the user is not attempting to
            modify the database at a replica. Remember, replicas must never
            modify their local databases on their own. This guards against
            that happening due to user input at the prompt.

            if (!dbenv.getIsMaster()) {
                System.err.println("Can't update client.");
                continue;
            }

            DatabaseEntry key = new DatabaseEntry(words[0].getBytes());
            DatabaseEntry data = new DatabaseEntry(words[1].getBytes());

            db.put(null, key, data);
        }
        if (db != null)
            db.close(true);
        return 0;
    }

        With that completed, we are all done updating our application
        for replication.

        The only remaining

        method, printStocks(),

        is unmodified from when we
        originally introduced it. For details on that function, see

                            Method: SimpleTxn.printStocks()
                    .

Running It

                To run our replicated application, we need to make
                sure each participating environment has its own unique
                home directory. We can do this by running
                each site on a separate networked machine, but that
                is not strictly necessary; multiple instances of this
                code can run on the same machine provided the
                environment home restriction is observed.

                To run a process, make sure the environment home exists and
                then start the process using the -h
                option to specify that directory. You must also use the
                -l or  -L option to
                identify the local host and port that this process will use
                to listen for replication messages (-L means that this is a
                group creator), and the -r option to
                identify the other processes in the replication group.
                Finally, use the -p option to specify a
                priority.  The process that you designate to have the
                highest priority will become the master.

> mkdir env1
> java db.repquote_gsg.RepQuoteExampleGSG -h env1 -L localhost:8080 \
-p 10
No stock database yet available.
No stock database yet available.

        Now, start another process. This time, change the environment
        home to something else, use the -l flag to at
        least change the port number the process is listening on, and
        use the -r option to identify the host and
        port of the other replication process:

> mkdir env2
> java db.repquote_gsg.RepQuoteExampleGSG -h env2 -l localhost:8081 \
-r localhost:8080 -p 20

        After a short pause, the second process should display the master
        prompt:

QUOTESERVER >

        And the first process should
        display the read-only prompt:

QUOTESERVER (read-only)>

        Now go to the master process and give it a couple of stocks and stock
        prices:

QUOTESERVER> FAKECO 9.87
QUOTESERVER> NOINC .23
QUOTESERVER>

    Then, go to the replica and hit return at the prompt to
    see the new values:

QUOTESERVER (read-only)>
        Symbol  Price
        ======  =====
        FAKECO  9.87
        NOINC    .23
QUOTESERVER (read-only)>

        Doing the same at the master results in the same thing:

QUOTESERVER>
        Symbol  Price
        ======  =====
        FAKECO  9.87
        NOINC    .23
QUOTESERVER>

        You can change a stock by simply entering the stock value and
        new price at the master's prompt:

QUOTESERVER> FAKECO 10.01
QUOTESERVER>

        Then, go to either the master or the replica to see the updated
        database. On the master:

QUOTESERVER>
        Symbol  Price
        ======  =====
        FAKECO  10.01
        NOINC    .23
QUOTESERVER>

        And on the replica:

QUOTESERVER (read-only)>
        Symbol  Price
        ======  =====
        FAKECO  10.01
        NOINC    .23
QUOTESERVER (read-only)>

        Finally, to quit the applications, simply type
        quit at both prompts. On the replica:

QUOTESERVER (read-only)> quit
>

        And on the master as well:

QUOTESERVER> quit
>

          Prev

            Up

           Next

          Processing Loop

            Home

           Chapter 5. Additional Features


text:
<?php

  /**
   * Render checkbox field
   *
   * Parameters:
   *
   * - name - Field name
   * - value - Initial value. Value of this field is ignored if checked attribute
   *   is present
   * - array of additional attributes
   *
   * @param array $params
   * @param Smarty $smarty
   * @return string
   */
  function smarty_function_checkbox_field($params, &$smarty) {
    $params['type'] = 'checkbox';

    if(array_key_exists('checked', $params)) {
      if($params['checked']) {
        $params['checked'] = 'checked';
      } else {
        unset($params['checked']);
      } // if
    } // if

    $class = array_var($params, 'class');
    if($class == '') {
      $classes[] = 'inline';
      $classes[] = 'input_checkbox';
    } else {
      $classes = explode(' ', $class);
      if(!in_array('inline', $classes)) {
        $classes[] = 'inline';
      } // if
      $classes[] = 'input_checkbox';
    } // if
    $params['class'] = implode(' ', $classes);

    if(!isset($params['value'])) {
      $params['value'] = '1';
    } // if

    return open_html_tag('input', $params, true);
  } // smarty_function_checkbox_field

?>

redpajama_set_name: RedPajamaGithub


text:
var express = require('express');
var router = express.Router();

let mongoose = require('mongoose')
const User = mongoose.model('User')
// const Token = mongoose.model('Token')
// const Session = mongoose.model('Session')

let passport = require("passport")
let FacebookStrategy = require("passport-facebook").Strategy
let GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
let LocalStrategy = require('passport-local').Strategy

// let bodyParser = require('body-parser')

passport.use(new LocalStrategy(
  function(username, password, done){
    console.log("strategy function starting...");
    User.getUserByEmail(username, function(err, user){
      if (err) throw err;
      if (user.length < 1){
        console.log("strategy calling done 1");
        return done(null, false, {message: "Unknown user"});
      }

      // User.comparePassword(password, user[0].password, function (err, isMatch) {
      //   if (err) throw err;
      //   if (isMatch) {
      //     console.log("strategy calling done 2");
      //     return done(null, user[0]);
      //   } else {
      //     console.log("strategy calling done 3");
      //     return done(null, false, {message: "Invalid password"});
      //   }
      // });
      if(password === 'tu@123'){
        return done(null, user[0]);
      }  else {
        return done(null, false, {message: "Invalid password"});
      }

    });
  }
))

passport.use(new FacebookStrategy({
    clientID:'123093138237586',
    clientSecret:'bfddf6c0cb2bc745914a2b3236f57202',
    // callbackURL:'http://localhost:3000/auth/facebook/callback',
    callbackURL:'http://comhoavang.com/auth/facebook/callback',
    profileFields: ['id', 'displayName', 'emails', 'name']
  }, function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({username: profile.emails[0].value},
      {
        uid: profile.id,
        name: profile.displayName,
        username: profile.emails[0].value,
        provider: 'facebook',
        accessToken: accessToken,
        mustConfirmEmail: false,
        password: '',
      },
      function(err, user){
        // logoutOther(user.username)
        cb(null, user)
      })
  }
))

passport.use(new GoogleStrategy({
    clientID: '181209932345-e5onckmk63rbchst6djlq9tjshbkmr79.apps.googleusercontent.com',
    clientSecret: 'a6Nz9Od7WfL82VdnFwpxLvKq',
    callbackURL: "http://edu.anabim.com/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, cb) {

    User.findOrCreate({username: profile.emails[0].value},
      {
        uid: profile.id,
        name: profile.displayName,
        username: profile.emails[0].value,
        provider: 'google',
        accessToken: accessToken,
        password: '',
        mustConfirmEmail: false,
      },
      function(err, user){
        logoutOther(user.username)
        cb(null, user)
      })
  }
))

passport.serializeUser(function(user, done){
  done(null, user)
})

passport.deserializeUser(function(user,done){
  done(null, user)
})

router.get('/session/:email', (req, res) => {
  var r = new RegExp(req.params.email,'i');
  Session.remove({session: {$regex: r}}, (err, session) => {
    if (err) throw err
    res.send(session)
  })
})

router.post('/signup', (req, res) => {
  User.getUserByEmail(req.body.username, function(err, user) {
    if (err) throw err
    if (user.length > 0)
      res.json({status: false, m: "Email đã được đăng ký"})
    else
      User.createUser(req.body, (err, user) => {
        if (err) throw err
        Token.create({type: 'signup', email: user.username}, (err, token) => {
          Mailer.sendActiveMail(user.username, user.name, 'http://edu.anabim.com/token/active/' + token.token)
          res.json({status: true, m: user.username})
        })
      })
  })
})

router.get('/facebook', passport.authenticate('facebook', {scope: ['email']}))

router.get('/facebook/callback',
  passport.authenticate('facebook', {failureRedirect: '/'}),
  function (req, res) {
    if(req.user.isAdmin){
      return res.redirect('/admin')
    }
    return res.redirect('/')
  })

router.get('/google',
  passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login', 'email'] }))

router.get('/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  function(req, res) {
    res.redirect('/')
  })

router.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

router.post('/login', passport.authenticate('local', { successRedirect: '/auth/login/ok',
  failureRedirect: '/auth/login/false' }))

router.get('/login/ok', function(req, res, next) {
  // Mailer.sendRegister('luanlv2591@gmail.com', 'Luan')
  res.send(true)
});

router.get('/login/false', function(req, res, next) {
  res.send(false)
});

module.exports = router

// var logoutOther = (username) => {
//   var r = new RegExp(username,'i');
//   Session.remove({session: {$regex: r}}, (err, session) => {
//     if (err) throw err
//   })
// }


text:
group: Global Styles
order: 3
title: Font
---

The font system is one of the most foundational parts of any interface design.

Text is a major channel for users to understand application content and complete their work, and a well designed font system will greatly enhance the user's reading experience and work efficiency. The Ant Design typography system is based on the design principle of "dynamic order" combined with the law of natural logarithm and temperament. We strongly recommend it since it has been verified by a large number of Ant products. While defining the font system for a visual system, we propose to start from the following five aspects:

1. Font Family
2. Base Font Size
3. Font Scale & Line Height
4. Font Weight
5. Font Color

---

## Font Family

In order to implement a good font system, the first thing is to choose an appropriate font family. Ant Design prefers the system default font family and then also provides a set of alternative font libraries to maintain readability for screens on different platforms and browsers and to make sure it's always user friendly, stable and professional to end user.

```css
@font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
  'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
  'Noto Color Emoji';
```

> References:https://www.smashingmagazine.com/2015/11/using-system-ui-fonts-practical-guide/ and http://markdotto.com/2018/02/07/github-system-fonts/

In addition, in many applications, numbers often need to be displayed vertically. We set the CSS property `font-variant-numeric` to `tabular-nums;` to use [tabular figures](https://www.fonts.com/content/learning/fontology/level-3/numbers/proportional-vs-tabular-figures).

> References:https://stackoverflow.com/questions/32660748/how-to-use-apples-new-san-francisco-font-on-a-webpage#comment78509178_32660790

## Base Font Size

We have updated Ant Design's base font size from the original 12 to 14 to ensure the best user reading efficiency on most common monitors based on display screen reading distance (50 cm) and optimal reading angle (0.3).

## Font Scale & Line Height

The font scale and line height determine the beauty of the dynamics and order of a font system. Font scale refers to a series of font with different sizes. Line height can be understood as an invisible box wrapped outside the font.

Ant Design was inspired by the pentatonic scale and natural law to define 10 different font sizes and corresponding line heights.

In Ant Design's visual system, our recommended base font size is 14, and its corresponding line height is 22. The choice of the rest of the font scale can be freely defined according to the specific circumstances. It is recommended that in a design system (except for display pages), the choice of font scale should be controlled within 3 to 5 types, and the principle of restraint should be maintained.

## Font Weight

The choice of font weight is also based on the principles of order, stability, and restraint. In most cases, just regular(400) and medium(500) should be enough. In the case of bold English words, semibold(600) could be used.

## Font Color

Text will be difficult to read if it is too close to the background color. To achieve barrier-free design, we follow the WCAG standard, which maintains an AAA level of contrast ratio, i.e. 7:1 or more between body text, title, and background color.

## Advanced Tips

The construction of the font system is the first step to achieve "the beauty of dynamic order". In practical design, we have three more advanced tips:

1. **Establish a systematic design thinking:** In the UI design of the same system, a systematic design thinking should be established first. The primary, secondary, auxiliary, title, display, and other types of fonts are planned in a unified manner. And then make any necessary fine tuning according to the specific situation. The establishment of a systematic design approach helps to increase the consistency of horizontal font landing, improve the cost-effectiveness of font uses, and avoid unnecessary style waste.
1. **Less is more:**Visual design should be achieved with as few styles as possible. Avoid meaningless use of large numbers of font scales, colors, and font weight to emphasize visual or contrast relationships.
1. **Try to make font scale dance like a note** When you need to expand any gap, you can try to choose the different sizes of the font from the font scale table, which will create a subtle rhythm between the word scales.


text:
class Observers
{
public:
    Observers();
};

#endif // OBSERVERS_H


text:
<?php

namespace SURFnet\SslLabs\Dto;

class Info
{
    const CLASS_NAME = 'SURFnet\SslLabs\Dto\Info';

    /**
     * SSL Labs software version as a string (e.g., "1.20.28")
     *
     * @var string
     */
    public $engineVersion;

    /**
     * Rating criteria version as a string (e.g., "2009f")
     *
     * @var string
     */
    public $criteriaVersion;

    /**
     * The maximum number of concurrent assessments
     * the client is allowed to initiate.
     *
     * @var int
     */
    public $maxAssessments;

    /**
     * The number of ongoing assessments submitted by this client.
     *
     * @var int
     */
    public $currentAssessments;

    /**
     * The cool-off period after each new assessment, in milliseconds;
     * you're not allowed to submit a new assessment before
     * the cool-off expires, otherwise you'll get a 429.
     *
     * @var int
     */
    public $newAssessmentCoolOff;

    /**
     * A list of messages (strings).
     *
     * Messages can be public (sent to everyone) and private
     * (sent only to the invoking client).
     * Private messages are prefixed with "[Private]".
     *
     * @var string[]
     */
    public $messages;
}


text:
import Ember from 'ember';

export function weatherIconClass(weatherId) {
  weatherId = weatherId[0];
  var weatherCls = 'weather-icon-';

  if(200 <= weatherId && weatherId <= 299){
    weatherCls += 'thunderstorm';
  }
  else if(300 <= weatherId && weatherId <= 399){
    weatherCls += 'drizzle';
  }
  else if(500 <= weatherId && weatherId <= 599){
    weatherCls += 'rain';
  }
  else if(600 <= weatherId && weatherId <= 699){
    weatherCls += 'snow';
  }
  else if(weatherId === 701){
    weatherCls += 'mist';
  }
  else if(weatherId === 800){
    weatherCls += 'sun';
  }
  else if(801 <= weatherId && weatherId <= 809){
    weatherCls += 'cloudy';
  }
  else if(weatherId === 905 || weatherId === 957){
    weatherCls += 'wind';
  }
  return weatherCls;
}

export default Ember.Helper.helper(weatherIconClass);


text:
package northwind.model;

import java.util.Set;

public class Category {
    private int categoryID;
    private String categoryName;
    private String description;
    private byte[] picture;
    private int rowVersion;

    private Set<Product> products;

	public int getCategoryID() {
		return categoryID;
	}

	public void setCategoryID(int categoryID) {
		this.categoryID = categoryID;
	}

	public String getCategoryName() {
		return categoryName;
	}

	public void setCategoryName(String categoryName) {
		this.categoryName = categoryName;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public byte[] getPicture() {
		return picture;
	}

	public void setPicture(byte[] picture) {
		this.picture = picture;
	}

	public int getRowVersion() {
		return rowVersion;
	}

	public void setRowVersion(int rowVersion) {
		this.rowVersion = rowVersion;
	}

	public Set<Product> getProducts() {
		return products;
	}

	public void setProducts(Set<Product> products) {
		this.products = products;
	}

}


text:
<?php

namespace Playbloom\Satisfy\Controller;

use Playbloom\Satisfy\Form\Type\RepositoryType;
use Playbloom\Satisfy\Form\Type\ComposerLockType;
use Playbloom\Satisfy\Model\Repository;
use Silex\Application;
use Silex\ControllerCollection;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Repository controller provider.
 *
 * @author Ludovic Fleury <ludo.fleury@gmail.com>
 */
class RepositoryController implements ControllerProviderInterface
{
    /**
     * Connect
     *
     * @param  Application $app
     *
     * @return ControllerCollection
     */
    public function connect(Application $app)
    {
        $controllers = $app['controllers_factory'];

        $repositoryProvider = function ($repository) use ($app) {
            return $app['satis']->findOneRepository($repository);
        };

        /**
         * repository
         *
         * GET /
         * List all repositories definitions
         */
        $controllers->get('/', function () use ($app) {
            $repositories = $app['satis']->findAllRepositories();

            return $app['twig']->render('home.html.twig', array('repositories' => $repositories));
        })
        ->bind('repository');

        /**
         * repository_new
         *
         * GET /new
         * Get the form to add a new repository definition
         */
        $controllers->get('/new', function () use ($app) {
            $repository = (new Repository())
            ->setType($app['composer.repository.type_default'])
            ->setUrl($app['composer.repository.url_default']);

            $form = $app['form.factory']->create(new RepositoryType(), $repository, array(
                'pattern' => $app['repository.pattern']
            ));

            return $app['twig']->render('new.html.twig', array('form' => $form->createView()));
        })
        ->bind('repository_new');

        /**
         * repository_upload_form
         *
         * GET /upload
         * Get the form to upload a composer.lock file
         */
        $controllers->get('/upload', function () use ($app) {
            $form = $app['form.factory']->create(new ComposerLockType());

            return $app['twig']->render('upload.html.twig', array('form' => $form->createView()));
        })
        ->bind('repository_upload_form');

        /**
         * repository_upload
         *
         * POST /
         * Add repository definitions from a composer.lock file
         */
        $controllers->post('/upload', function (Request $request) use ($app) {
            $form = $app['form.factory']->create(new ComposerLockType());

            $form->bind($request);

            if ($form->isValid()) {
                $lockFile = $form['file']->getData()->openFile();
                $app['satis.lock']->processFile($lockFile);

                return $app->redirect($app['url_generator']->generate('repository'));
            }

            return $app['twig']->render('upload.html.twig', array('form' => $form->createView()));
        })
        ->bind('repository_upload');

        /**
         * repository_create
         *
         * POST /
         * Add a new repository definition
         */
        $controllers->post('/', function (Request $request) use ($app) {
            $form = $app['form.factory']->create(new RepositoryType(), new Repository(), array(
                'pattern' => $app['repository.pattern']
            ));

            $form->bind($request);

            if ($form->isValid()) {
                $app['satis']->add($form->getData());

                return $app->redirect($app['url_generator']->generate('repository'));
            }

            return $app['twig']->render('new.html.twig', array('form' => $form->createView()));
        })
        ->bind('repository_create');

        /**
         * repository_edit
         *
         * GET /edit
         * Get the form to edit an existing repository definition
         */
        $controllers->get('/edit/{repository}', function (Repository $repository) use ($app) {
            $form = $app['form.factory']->create(new RepositoryType(), $repository, array(
                'pattern' => $app['repository.pattern']
            ));

            return $app['twig']->render('edit.html.twig', array('form' => $form->createView()));
        })
        ->bind('repository_edit')
        ->assert('repository', '[a-zA-Z0-9_-]+')
        ->convert('repository', $repositoryProvider);

        /**
         * repository_update
         *
         * PUT /
         * Update an existing repository definition
         */
        $controllers->put('/{repository}', function (Repository $repository, Request $request) use ($app) {
            $form = $app['form.factory']->create(new RepositoryType(), new Repository(), array(
                'pattern' => $app['repository.pattern']
            ));

            $form->bind($request);

            if ($form->isValid()) {
                $app['satis']->update($repository, $form->getData()->getUrl());

                return $app->redirect($app['url_generator']->generate('repository'));
            }

            return $app['twig']->render('edit.html.twig', array('form' => $form->createView()));
        })
        ->bind('repository_update')
        ->assert('repository', '[a-zA-Z0-9_-]+')
        ->convert('repository', $repositoryProvider);

        /**
         * repository_erase
         *
         * GET /delete/{repository}
         * Get the form to delete a repository definition
         */
        $controllers->get('/delete/{repository}', function (Repository $repository) use ($app) {
            $form = $app['form.factory']->create();

            return $app['twig']->render('delete.html.twig', array('form' => $form->createView(), 'repository' => $repository));
        })
        ->bind('repository_erase')
        ->assert('repository', '[a-zA-Z0-9_-]+')
        ->convert('repository', $repositoryProvider);

        /**
         * repository_delete
         *
         * DELETE /{repository}
         * Delete a repository definition
         */
        $controllers->delete('/{repository}', function (Repository $repository, Request $request) use ($app) {
            $form = $app['form.factory']->create();

            $form->bind($request);

            if ($form->isValid()) {
                $app['satis']->delete($repository);

                return $app->redirect($app['url_generator']->generate('repository'));
            }

            return $app['twig']->render('delete.html.twig', array('form' => $form->createView(), 'repository' => $repository));
        })
        ->bind('repository_delete')
        ->assert('repository', '[a-zA-Z0-9_-]+')
        ->convert('repository', $repositoryProvider);

        return $controllers;
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import configObject from '../../config/app.js'

//components
import TextTd from './td/textTdComponent'
import NumberTd from './td/numberTdComponent'
import URLTd from './td/urlTdComponent'
import BooleanTd from './td/booleanTdComponent'
import DateTd from './td/dateTdComponent'
import IdTd from './td/idTdComponent'
import PasswordTd from './td/passwordTdComponent'
import EmailTd from './td/emailTdComponent'
import ObjectTd from './td/objectTdComponent'
import GeoTd from './td/geoTdComponent'
import FileTd from './td/fileTdComponent'
import ListTd from './td/listTdComponent'
import RelationTd from './td/relationTdComponent'
import ACLTd from './td/aclTdComponent'

class GenericNewTd extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			elementData:null,
			elementDataBackup:null,
			componentToRender:TextTd,
			isRequired:false
		}
	}
	componentDidMount(){
		this.generaliseComponent(this.props)
	}
	componentWillReceiveProps(props){
		this.generaliseComponent(props)
	}
	generaliseComponent(props){
		switch (props.columnType.dataType) {
			case "Text":
				this.state.componentToRender =  TextTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "Number":
				this.state.componentToRender =  NumberTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "URL":
				this.state.componentToRender =  URLTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "Boolean":
				this.state.componentToRender =  BooleanTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "Email":
				this.state.componentToRender =  EmailTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "Id":
				this.state.componentToRender =  IdTd
				this.state.elementData = props.columnData.document['_id']
				break;

			case "EncryptedText":
				this.state.componentToRender =  PasswordTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "DateTime":
				this.state.componentToRender =  DateTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "Object":
				this.state.componentToRender =  ObjectTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "GeoPoint":
				this.state.componentToRender =  GeoTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "File":
				this.state.componentToRender =  FileTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "List":
				this.state.componentToRender =  ListTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "Relation":
				this.state.componentToRender =  RelationTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			case "ACL":
				this.state.componentToRender =  ACLTd
				this.state.elementData = props.columnData.document[props.columnType.name]
				break;

			default:
				this.state.componentToRender =  TextTd
				this.state.elementData = "a"
				break;
		}
		if(this.state.elementData == undefined && props.columnType.required == true){
			this.state.isRequired = true
		}
		this.state.elementDataBackup = this.state.elementData
		this.setState(this.state)
	}
	updateObject(){
		if(this.state.elementData && this.props.columnType.required == true){
			this.state.isRequired = false
		}
		this.props.columnData.set(this.props.columnType.name,this.state.elementData)
		this.props.columnData.save().then((res)=>{
			this.state.elementDataBackup = res.document[this.props.columnType.name]
			this.setState(this.state)
			this.props.setError(false)
		},(err)=>{
			console.log(err)
			this.props.setError(err)
			//this.fetchObject()
		})
	}
	fetchObject(){
		this.state.elementData = this.state.elementDataBackup
		this.setState(this.state)
	}
	updateElement(data){
		this.state.elementData = data
		this.setState(this.state)
	}

	render() {
		return (
           React.createElement(this.state.componentToRender, {
		       	elementData:this.state.elementData,
		       	updateObject:this.updateObject.bind(this),
		       	updateElement:this.updateElement.bind(this),
		       	fetchObject:this.fetchObject.bind(this),
		       	columnName:this.props.columnType.name,
		       	columnData:this.props.columnData,
		       	columnType:this.props.columnType,
		       	isRequired:this.state.isRequired
           })
		);
	}
}

export default GenericNewTd;


text:
/*
 * helpers.js: Test helpers for winston
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENSE
 *
 */

require.paths.unshift(require('path').join(__dirname, '..', 'lib'));

var fs = require('fs'),
    util = require('util'),
    path = require('path'),
    vows = require('vows'),
    assert = require('assert'),
    winston = require('winston'),
    loggly = require('loggly')

var helpers = exports;

helpers.loadConfig = function () {
  try {
    if (helpers.config) return helpers.config;
    var configFile = path.join(__dirname, 'test-config.json'),
        stats = fs.statSync(configFile)
        config = JSON.parse(fs.readFileSync(configFile).toString());

    helpers.config = config;
    return config;
  }
  catch (ex) {
    util.puts('Config file test-config.json must be created with valid data before running tests');
    process.exit(0);
  }
};

helpers.size = function(obj) {
  var size = 0, key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) size++;
  }

  return size;
};

helpers.assertLogger = function (logger, level) {
  assert.instanceOf(logger, winston.Logger);
  assert.isFunction(logger.log);
  assert.isFunction(logger.add);
  assert.isFunction(logger.remove);
  assert.equal(logger.level, level || "info");
  Object.keys(logger.levels).forEach(function (method) {
    assert.isFunction(logger[method]);
  });
};

helpers.assertConsole = function (transport) {
  assert.instanceOf(transport, winston.transports.Console);
  assert.isFunction(transport.log);
};

helpers.assertFile = function (transport) {
  assert.instanceOf(transport, winston.transports.File);
  assert.isFunction(transport.log);
}

helpers.assertLoggly = function (transport) {
  assert.instanceOf(transport, winston.transports.Loggly);
  assert.isFunction(transport.log);
};

helpers.assertRiak = function (transport) {
  assert.instanceOf(transport, winston.transports.Riak);
  assert.isFunction(transport.log);
};

helpers.assertMongoDB = function (transport) {
  assert.instanceOf(transport, winston.transports.MongoDB);
  assert.isFunction(transport.log);
};

helpers.testNpmLevels = function (transport, assertMsg, assertFn) {
  return helpers.testLevels(winston.config.npm.levels, transport, assertMsg, assertFn);
};

helpers.testSyslogLevels = function (transport, assertMsg, assertFn) {
  return helpers.testLevels(winston.config.syslog.levels, transport, assertMsg, assertFn);
};

helpers.testLevels = function (levels, transport, assertMsg, assertFn) {
  var tests = {};

  Object.keys(levels).forEach(function (level) {
    var test = {
      topic: function () {
        transport.log(level, 'test message', {}, this.callback.bind(this, null));
      }
    };

    test[assertMsg] = assertFn;
    tests['with the ' + level + ' level'] = test;
  });

  var test = {
    topic: function () {
      transport.log('info', 'test message', { metadata: true }, this.callback.bind(this, null));
    }
  };

  test[assertMsg] = assertFn;
  tests['when passed metadata'] = test;
  return tests;
};


text:
package dentry;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Registro {

	// Atributos
	private String cabecera;
	private String detalle;

	private int numeroLinea;
	private String fechaPractica;
	private String numeroAfiliado;
	private String codigoPractica;
	private int cantidad;
	private int numeroRecepcion;
	private Float monto;

	private String COMA = ",";
	private String COMILLA = "\"";
	private String NULO = "";
	private String NL = "\n";

	// Getters y Setters

	public String getCabecera() {
		return cabecera;
	}

	public String getFechaPractica() {
		return fechaPractica;
	}

	public void setFechaPractica(String fechaPractica) {
		this.fechaPractica = fechaPractica;
	}

	public void setMonto(Float monto) {
		this.monto = monto;
	}

	public void setCabecera(String cabecera) {
		this.cabecera = cabecera;
	}

	public String getDetalle() {
		return detalle;
	}

	public void setDetalle(String detalle) {
		this.detalle = detalle;
	}

	public String getNumeroAfiliado() {
		return numeroAfiliado;
	}

	public void setNumeroAfiliado(String numeroAfiliado) {
		this.numeroAfiliado = numeroAfiliado;
	}

	public String getCodigoPractica() {
		return codigoPractica;
	}

	public void setCodigoPractica(String codigoPractica) {
		this.codigoPractica = codigoPractica;
	}

	public int getCantidad() {
		return cantidad;
	}

	public void setCantidad(int cantidad) {
		this.cantidad = cantidad;
	}

	public int getNumeroRecepcion() {
		return numeroRecepcion;
	}

	public void setNumeroRecepcion(int numeroRecepcion) {
		this.numeroRecepcion = numeroRecepcion;
	}

	public float getMonto() {
		return monto;
	}

	public void setMonto(float monto) {
		this.monto = monto;
	}

	// Constructor
	public Registro(int numeroLinea) {
		this.numeroLinea = numeroLinea;
	}

	// Metodos de instancia

	public String crearCabecera() throws CustomException {
		String linea = "";

		// Controles //
		// Invierte fecha
		String fechaPracticaConv = this.invertirFecha(fechaPractica);

		// Configura punto decimal (debe ser coma)
		String montoConv = monto.toString().replace(".", ",");

		// Genera linea de cabecera
		// <num_linea>,0,<fechaPractica_mmddaaaa>,<fechaPractica_mmddaaaa>,<nulo>,<nulo>,121,<num_afiliado{8}>,<num_afiliado{2}>,
		// MC999999,0,0,<nulo>,<nulo>,<nulo>,<nulo>,<nulo>,<nulo>,0,<monto>
        linea = numeroLinea + COMA + "0" + COMA
                + fechaPracticaConv + COMA + fechaPracticaConv + COMA
                + NULO + COMA + NULO + COMA
                + "121" + COMA + numeroAfiliado.substring(0, 8) + COMA
                + numeroAfiliado.substring(8, 10) + COMA + "MC999999" + COMA
                + "0" + COMA + "0" + COMA
                + NULO + COMA + NULO + COMA
                + NULO + COMA + NULO + COMA
                + NULO + COMA + NULO + COMA
                + "0" + COMA + numeroRecepcion + COMA
                + COMILLA + montoConv + COMILLA + NL ;

		return linea;
	}

	public String crearDetalle() throws CustomException {
		String linea = "";

		// Controles //
		// Invierte fecha
		String fechaPracticaConv = this.invertirFecha(fechaPractica);

		// Configura punto decimal (debe ser coma)
		String montoConv = monto.toString().replace(".", ",");

		// Genera linea de detalle
		// <num_linea>,1,<fechaPractica_mmddaaaa>,<fechaPractica_mmddaaaa>,<nulo>,<CodPractica>,<nulo>,<cantidad>,<monto>
        linea = numeroLinea + COMA + "1" + COMA
                + fechaPracticaConv + COMA + fechaPracticaConv + COMA
                + NULO + COMA + codigoPractica + COMA
                + NULO+ COMA + cantidad + COMA
                + COMILLA + montoConv + COMILLA + NL ;

		return linea;
	}

	public String invertirFecha(String fechaStr) throws CustomException{

		SimpleDateFormat inputFormat = new SimpleDateFormat("ddMMyyyy");
	    SimpleDateFormat outputFormat = new SimpleDateFormat("MMddyyyy");
	    Date fecha = null;
		try {
			if(fechaStr.length() == 8){
				fecha = inputFormat.parse(fechaStr);
			}
			else{
				throw new CustomException("Fecha inválida");
			}

		} catch (ParseException e) {
			throw new CustomException("Fecha inválida.");
		}

	    return outputFormat.format(fecha);
	}

	public void armar() throws CustomException{
		setCabecera(crearCabecera());
		setDetalle(crearDetalle());
	}

}


text:
package libstorage

import (
	"context"
	"math"
	"net"
	"strconv"
	"strings"
	"sync"

	"google.golang.org/grpc"

	log "github.com/sirupsen/logrus"
	xctx "golang.org/x/net/context"

	gofig "github.com/akutz/gofig/types"
	"github.com/codedellemc/gocsi"
	"github.com/codedellemc/gocsi/csi"
	"github.com/codedellemc/goioc"

	apictx "github.com/codedellemc/rexray/libstorage/api/context"
	apitypes "github.com/codedellemc/rexray/libstorage/api/types"
	apiutils "github.com/codedellemc/rexray/libstorage/api/utils"
)

func init() {
	goioc.Register("libstorage", func() interface{} { return &driver{} })
}

// ctxConfigKey is an interface-wrapped key used to access a possible
// config object in the context given to the provider's Serve function
var ctxConfigKey = interface{}("csi.config")

type driver struct {
	ctx          apitypes.Context
	client       apitypes.Client
	config       gofig.Config
	server       *grpc.Server
	svcName      string
	storType     apitypes.StorageType
	iid          *apitypes.InstanceID
	nodeID       *csi.NodeID
	attTokens    map[string]string
	attTokensRWL sync.RWMutex
}

func (d *driver) Serve(ctx context.Context, lis net.Listener) error {

	d.attTokens = map[string]string{}

	d.ctx = apictx.New(ctx)
	d.client = apictx.MustClient(d.ctx)

	// Check for a gofig.Config in the context.
	if config, ok := d.ctx.Value(ctxConfigKey).(gofig.Config); ok {
		log.Info("init csi libstorage bridge w ctx.config")
		d.config = config
	}

	// Cache the name of the libStorage service for which this bridge
	// is configured.
	svcName, ok := apictx.ServiceName(d.ctx)
	if !ok {
		return errMissingServiceName
	}
	d.svcName = svcName

	// Cache the instance ID for the service.
	iid, err := d.client.Executor().InstanceID(d.ctx, apiutils.NewStore())
	if err != nil {
		return err
	}
	d.iid = iid

	// Cache the storage type of the service.
	storType, err := d.client.Storage().Type(d.ctx)
	if err != nil {
		return err
	}
	d.storType = storType

	// Cache the node ID.
	d.nodeID = toNodeID(d.iid)

	// Create a gRPC server with an idempotent interceptor.
	d.server = grpc.NewServer(
		grpc.UnaryInterceptor(gocsi.NewIdempotentInterceptor(d)))

	csi.RegisterControllerServer(d.server, d)
	csi.RegisterIdentityServer(d.server, d)
	csi.RegisterNodeServer(d.server, d)
	return d.server.Serve(lis)
}

func (d *driver) Stop(ctx context.Context) {
	d.server.Stop()
}

func (d *driver) GracefulStop(ctx context.Context) {
	d.server.GracefulStop()
}

////////////////////////////////////////////////////////////////////////////////
//                            Controller Service                              //
////////////////////////////////////////////////////////////////////////////////

func (d *driver) CreateVolume(
	ctx xctx.Context,
	req *csi.CreateVolumeRequest) (
	*csi.CreateVolumeResponse, error) {

	// Make sure the requested volume capability is supported for
	// the cached storage type.
	if !isVolCapSupported(d.storType, req.VolumeCapabilities...) {
		return gocsi.ErrCreateVolume(
			csi.Error_CreateVolumeError_INVALID_PARAMETER_VALUE,
			"invalid volume capability request"), nil
	}

	opts := &apitypes.VolumeCreateOpts{Opts: apiutils.NewStore()}

	// Determine the requested volume size by selecting the
	// greater of the two values: Required and Limit bytes.
	if req.CapacityRange != nil {
		size := req.CapacityRange.LimitBytes
		if req.CapacityRange.RequiredBytes > size {
			size = req.CapacityRange.RequiredBytes
		}
		if size > 0 {
			if size > math.MaxInt64 {
				size = math.MaxInt64
			}
			opts.Size = addrOfInt64(b2gib(size))
		}
	}

	// Parse the request parameters and if any of the
	// keys match libStorage volume creation options then
	// attempt to use them.
	for k, v := range req.Parameters {
		if strings.EqualFold(k, "availabilityzone") {
			opts.AvailabilityZone = &v
		} else if strings.EqualFold(k, "encrypted") {
			b, _ := strconv.ParseBool(v)
			opts.Encrypted = &b
		} else if strings.EqualFold(k, "encryptionkey") {
			opts.EncryptionKey = &v
		} else if strings.EqualFold(k, "iops") {
			i, err := strconv.ParseInt(v, 10, 64)
			if err == nil {
				opts.IOPS = addrOfInt64(int64(i))
			}
		} else if strings.EqualFold(k, "type") {
			opts.Type = &v
		}
	}

	// Use the integration driver to create the volume.
	vol, err := d.client.Integration().Create(d.ctx, req.Name, opts)
	if err != nil {
		return nil, err
	}

	// Transform the created volume into a csi.VolumeInfo
	volInfo := toVolumeInfo(vol)

	return &csi.CreateVolumeResponse{
		Reply: &csi.CreateVolumeResponse_Result_{
			Result: &csi.CreateVolumeResponse_Result{
				VolumeInfo: volInfo,
			},
		},
	}, nil
}

func (d *driver) DeleteVolume(
	ctx xctx.Context,
	req *csi.DeleteVolumeRequest) (
	*csi.DeleteVolumeResponse, error) {

	volumeID, ok := req.VolumeId.Values["id"]
	if !ok {
		return gocsi.ErrDeleteVolume(
			csi.Error_DeleteVolumeError_INVALID_VOLUME_ID,
			`missing "id" field`), nil
	}

	opts := &apitypes.VolumeRemoveOpts{Opts: apiutils.NewStore()}

	err := d.client.Storage().VolumeRemove(d.ctx, volumeID, opts)
	if err != nil {
		return nil, err
	}

	return &csi.DeleteVolumeResponse{
		Reply: &csi.DeleteVolumeResponse_Result_{
			Result: &csi.DeleteVolumeResponse_Result{},
		},
	}, nil
}

func (d *driver) ControllerPublishVolume(
	ctx xctx.Context,
	req *csi.ControllerPublishVolumeRequest) (
	*csi.ControllerPublishVolumeResponse, error) {

	// Make sure the requested volume capability is supported for
	// the cached storage type.
	if !isVolCapSupported(d.storType, req.VolumeCapability) {
		return gocsi.ErrControllerPublishVolume(
			csi.Error_ControllerPublishVolumeError_UNSUPPORTED_VOLUME_TYPE,
			"invalid volume capability request"), nil
	}

	iid, err := toInstanceID(req.NodeId)
	if err != nil {
		return gocsi.ErrControllerPublishVolume(
			csi.Error_ControllerPublishVolumeError_INVALID_NODE_ID,
			err.Error()), nil
	}
	_ = iid

	//d.client.Storage().VolumeAttach(d.ctx, volumeID, opts)

	return nil, nil
}

func (d *driver) ControllerUnpublishVolume(
	ctx xctx.Context,
	req *csi.ControllerUnpublishVolumeRequest) (
	*csi.ControllerUnpublishVolumeResponse, error) {

	return nil, nil
}

func (d *driver) ValidateVolumeCapabilities(
	ctx xctx.Context,
	req *csi.ValidateVolumeCapabilitiesRequest) (
	*csi.ValidateVolumeCapabilitiesResponse, error) {

	return &csi.ValidateVolumeCapabilitiesResponse{
		Reply: &csi.ValidateVolumeCapabilitiesResponse_Result_{
			Result: &csi.ValidateVolumeCapabilitiesResponse_Result{
				Supported: isVolCapSupported(
					d.storType, req.VolumeCapabilities...),
			},
		},
	}, nil
}

func (d *driver) ListVolumes(
	ctx xctx.Context,
	req *csi.ListVolumesRequest) (
	*csi.ListVolumesResponse, error) {

	opts := &apitypes.VolumesOpts{Opts: apiutils.NewStore()}

	// Use the storage driver to list the volumes.
	vols, err := d.client.Storage().Volumes(d.ctx, opts)
	if err != nil {
		return nil, err
	}

	// Convert the libStorage volumes to CSI volume info objects.
	entries := make([]*csi.ListVolumesResponse_Result_Entry, len(vols))
	for i, v := range vols {
		entries[i] = &csi.ListVolumesResponse_Result_Entry{
			VolumeInfo: toVolumeInfo(v),
		}
	}

	return &csi.ListVolumesResponse{
		Reply: &csi.ListVolumesResponse_Result_{
			Result: &csi.ListVolumesResponse_Result{
				Entries: entries,
			},
		},
	}, nil
}

func (d *driver) GetCapacity(
	ctx xctx.Context,
	req *csi.GetCapacityRequest) (
	*csi.GetCapacityResponse, error) {

	return gocsi.ErrGetCapacity(
		csi.Error_GeneralError_UNDEFINED,
		"call not implemented"), nil
}

func (d *driver) ControllerGetCapabilities(
	ctx xctx.Context,
	req *csi.ControllerGetCapabilitiesRequest) (
	*csi.ControllerGetCapabilitiesResponse, error) {

	return &csi.ControllerGetCapabilitiesResponse{
		Reply: &csi.ControllerGetCapabilitiesResponse_Result_{
			Result: &csi.ControllerGetCapabilitiesResponse_Result{
				Capabilities: []*csi.ControllerServiceCapability{
					&csi.ControllerServiceCapability{
						Type: &csi.ControllerServiceCapability_Rpc{
							Rpc: &csi.ControllerServiceCapability_RPC{
								Type: csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME,
							},
						},
					},
					&csi.ControllerServiceCapability{
						Type: &csi.ControllerServiceCapability_Rpc{
							Rpc: &csi.ControllerServiceCapability_RPC{
								Type: csi.ControllerServiceCapability_RPC_PUBLISH_UNPUBLISH_VOLUME,
							},
						},
					},
					&csi.ControllerServiceCapability{
						Type: &csi.ControllerServiceCapability_Rpc{
							Rpc: &csi.ControllerServiceCapability_RPC{
								Type: csi.ControllerServiceCapability_RPC_LIST_VOLUMES,
							},
						},
					},
				},
			},
		},
	}, nil
}

////////////////////////////////////////////////////////////////////////////////
//                             Identity Service                               //
////////////////////////////////////////////////////////////////////////////////

func (d *driver) GetSupportedVersions(
	ctx xctx.Context,
	req *csi.GetSupportedVersionsRequest) (
	*csi.GetSupportedVersionsResponse, error) {

	return &csi.GetSupportedVersionsResponse{
		Reply: &csi.GetSupportedVersionsResponse_Result_{
			Result: &csi.GetSupportedVersionsResponse_Result{
				SupportedVersions: []*csi.Version{
					&csi.Version{
						Major: 0,
						Minor: 0,
						Patch: 0,
					},
				},
			},
		},
	}, nil
}

func (d *driver) GetPluginInfo(
	ctx xctx.Context,
	req *csi.GetPluginInfoRequest) (
	*csi.GetPluginInfoResponse, error) {

	return &csi.GetPluginInfoResponse{
		Reply: &csi.GetPluginInfoResponse_Result_{
			Result: &csi.GetPluginInfoResponse_Result{
				Name:          "REX-Ray CSI Bridge",
				VendorVersion: "0.0.0",
				Manifest:      nil,
			},
		},
	}, nil
}

////////////////////////////////////////////////////////////////////////////////
//                               Node Service                                 //
////////////////////////////////////////////////////////////////////////////////

func (d *driver) NodePublishVolume(
	ctx xctx.Context,
	req *csi.NodePublishVolumeRequest) (
	*csi.NodePublishVolumeResponse, error) {

	// Make sure the requested volume capability is supported for
	// the cached storage type.
	if !isVolCapSupported(d.storType, req.VolumeCapability) {
		return gocsi.ErrNodePublishVolume(
			csi.Error_NodePublishVolumeError_UNSUPPORTED_VOLUME_TYPE,
			"invalid volume capability request"), nil
	}

	return nil, nil
}

func (d *driver) NodeUnpublishVolume(
	ctx xctx.Context,
	req *csi.NodeUnpublishVolumeRequest) (
	*csi.NodeUnpublishVolumeResponse, error) {

	return nil, nil
}

func (d *driver) GetNodeID(
	ctx xctx.Context,
	req *csi.GetNodeIDRequest) (
	*csi.GetNodeIDResponse, error) {

	return &csi.GetNodeIDResponse{
		Reply: &csi.GetNodeIDResponse_Result_{
			Result: &csi.GetNodeIDResponse_Result{
				NodeId: d.nodeID,
			},
		},
	}, nil
}

func (d *driver) ProbeNode(
	ctx xctx.Context,
	req *csi.ProbeNodeRequest) (
	*csi.ProbeNodeResponse, error) {

	sup, err := d.client.Executor().Supported(d.ctx, apiutils.NewStore())
	if err != nil {
		return nil, err
	}

	// If the supported mask is anything but zero then return
	// a positive result.
	if sup > apitypes.LSXSOpNone {
		return &csi.ProbeNodeResponse{
			Reply: &csi.ProbeNodeResponse_Result_{
				Result: &csi.ProbeNodeResponse_Result{},
			},
		}, nil
	}

	// Return an error indicating no support.
	return gocsi.ErrProbeNode(
			csi.Error_ProbeNodeError_MISSING_REQUIRED_HOST_DEPENDENCY, ""),
		nil
}

func (d *driver) NodeGetCapabilities(
	ctx xctx.Context,
	req *csi.NodeGetCapabilitiesRequest) (
	*csi.NodeGetCapabilitiesResponse, error) {

	return &csi.NodeGetCapabilitiesResponse{
		Reply: &csi.NodeGetCapabilitiesResponse_Result_{
			Result: &csi.NodeGetCapabilitiesResponse_Result{
				Capabilities: []*csi.NodeServiceCapability{
					&csi.NodeServiceCapability{
						Type: &csi.NodeServiceCapability_Rpc{
							Rpc: &csi.NodeServiceCapability_RPC{
								Type: csi.NodeServiceCapability_RPC_UNKNOWN,
							},
						},
					},
				},
			},
		},
	}, nil
}


text:
We would love for you to contribute to **Lets Food** and help us make this even better! Start reading this document to see it is not difficult as you might have imagined.

## Table of Contents

- [Open an Issue](#open-an-issue)
- [Submit a Pull Request](#submit-a-pull-request)
- [Building](#building)
- [Style Guide](#style-guide)
- [Test](#test)
- [Code of Conduct](#code-of-conduct)
- [License](#license)

## Open an Issue

[Open an Issue](https://github.com/letsfood/letsfood.github.io/issues/new) to report any problems or improvements. When necessary, use [Codepen](http://codepen.io/) to show the problem. Be sure to include some description to explain the problem.

## Submit a Pull Request

To submit a new feature, make sure that changes are done to the source code. [Follow our style guide](#style-guide) and do not forget the tests and attach the link [Codepen](http://codepen.io/) along with the description.

Try to solve a problem for each pull request, this increases the chances of acceptance. When in doubt, open a [new issue](#open-an-issue) so we can answer you. Look existing issues for ideas or to see if a similar issue has already been submitted.

1. Fork the Github repo: `git clone https://github.com/letsfood/letsfood.github.io.git`
1. Create a new branch: `git checkout -b issuenumber-feature-name`
1. Commit your changes: `git commit -m 'issuenumber-feature-name'`
1. Push to the branch: `git push origin my-feature-name`
1. Submit a pull request!

## Building

First install [Node.js](https://nodejs.org/en/download/) for the build process. Now install all the dependencies, run `npm install` from the project directory. Once you have the dependencies installed, run `npm start`.

## Style Guide

**Lets Food** use [Sass](http://sass-lang.com/) to give super powers to CSS. Look at how the code is being maintained, we must always be consistent. We try to follow best practices as much as possible. In addition, here are some tips you should follow:

- Properties and selectors are sorted in alphabetical order
- Always use tab to indentation, no spaces
- Always use single quote, i.e. `content: ' '`
- Quote attribute values in selectors, i.e. `input[type='checkbox']`
- Avoid specifying units for zero-values, i.e. `margin: 0`
- Use `rem` unit instead of `px`
- Use lowercase and shorthand hex values, i.e. `#fff`
- Use one discrete selector per line in multi-selector rulesets
- Include a single space after colon and after each comma
- Separate each ruleset by a blank line
- Don't use prefixes, there is a task to generate this automatically

```sass
.selector-a,
.selector-b,
.selector-c,
.selector-d[type='text']
	box-sizing: border-box
	color: #333
	content: ''
	display: inline-block
	font-family: 'Helvetica-Neue', 'Helvetica', 'Arial', sans-serif
	margin-bottom: 0
	margin-left: 5.0rem

	.other-selector-a
		background: #fff

		.other-selector-b
			background: #fff

		&.increasing-the-specificity
			color: #000
```

*Note: This style guide was inspired by [Idiomatic.css](https://github.com/necolas/idiomatic-css). **Lets Food** uses an `.editorconfig` file, which most editors support, to enforce these coding standards.*

For JavaScript code quality, **Lets Food** uses [JavaScript Styled](https://github.com/cjpatoilo/eslint-config-styled):

- No semicolons.
- No unused variables.
- Use tab for indentation.
- Use `===` instead of `==`.
- Use single quotes for strings except to avoid escaping.
- Add a space after keywords.
- Add a space before a function declaration's parentheses.
- Infix operators must be spaced.
- Commas should have a space after them.
- Keep else statements on the same line as their curly braces.
- For multi-line if statements, use curly braces.
- Always handle the `err` function parameter.
- Always prefix browser globals with `window.`.
- Multiple blank lines not allowed.
- For the ternary operator in a multi-line setting, place `?` and `:` on their own lines.
- For var declarations, write each declaration in its own statement.
- Wrap conditional assignments with additional parentheses. This makes it clear that the expression is intentionally an assignment (`=`) rather than a typo for equality (`===`).

*NOTE: The best way to learn about that is to just install it and give it a try on your code.*

## Test

To test run `npm test`.

## Code of Conduct

Help us keep **Lets Food** open and inclusive. Please read and follow our thoughts on [Code of Conduct](http://confcodeofconduct.com/).

## License

By contributing your code, you agree to license your contribution under the [MIT license](https://github.com/letsfood/letsfood.github.io#license).


text:
* Bump minimum PHP version to PHP 8.1.
* Add PHPStan to CI build & fixes to make package validate at PHPStan level 9.
* Add PHPCS to CI build & fixes so that package validates with PSR-12 settings.
* Deprecate getters across the board in favour of readonly public properties.
* General code-style updates to take advantage of PHP 8.1 features.

## 1.0.2 - 2021-08-11

* Fixed handling of changes to single-line files, thanks to [anomiex](https://github.com/anomiex) for this fix.

## 1.0.1 - 2021-02-16

* Updated composer version constraint to allow installation on PHP >= 8.0.

## 1.0.0 - 2020-10-31

* First stable release.


text:
meteor-defense
==============

A game make with HTML5 using createJS for Windows 8 store.
The game can be found here http://apps.microsoft.com/windows/en-ca/app/19089b97-8246-4e7f-85b4-0091f90e12a1


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

  <style name="Theme.Pomodoro" parent="@android:style/Theme.DeviceDefault.Light">

  </style>

  <style name="TextAppearance.Wearable.Large" parent="android:TextAppearance.Medium">
    <item name="android:textSize">24sp</item>
    <item name="android:textColor">@color/primary_text_light</item>
  </style>

  <style name="TextAppearance.Wearable.Medium" parent="android:TextAppearance.Medium">
    <item name="android:textSize">20sp</item>
    <item name="android:textColor">@color/primary_text_light</item>
  </style>

  <style name="TextAppearance.Wearable.Small" parent="android:TextAppearance.Medium">
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">@color/primary_text_light</item>
  </style>

  <style name="TextView.Large" parent="@android:style/Widget.Holo.Light">
    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textAppearance">@style/TextAppearance.Wearable.Large</item>
  </style>

  <style name="TextView.Large.Light">
    <item name="android:fontFamily">sans-serif-condensed-light</item>
    <item name="android:textAppearance">@style/TextAppearance.Wearable.Large</item>
  </style>

  <style name="TextView.Medium" parent="@android:style/Widget.Holo.Light">
    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textAppearance">@style/TextAppearance.Wearable.Medium</item>
  </style>

  <style name="TextView.Medium.Light">
    <item name="android:fontFamily">sans-serif-condensed-light</item>
    <item name="android:textAppearance">@style/TextAppearance.Wearable.Medium</item>
  </style>

  <style name="TextView.Small" parent="@android:style/Widget.Holo.Light">
    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textAppearance">@style/TextAppearance.Wearable.Small</item>
  </style>

  <style name="TextView.Small.Light">
    <item name="android:fontFamily">sans-serif-condensed-light</item>
    <item name="android:textAppearance">@style/TextAppearance.Wearable.Small</item>
  </style>
</resources>


text:
var OAuth = require('oauth').OAuth;
var _ = require('underscore');

/**
 * Parameters: required object credentials
 **/
var TradeKing = function(credentials) {
  this.connection = new OAuth(null, null, credentials.consumer_key, credentials.consumer_secret, "1.0", null, "HMAC-SHA1");
  this.__credentials__ = credentials;
}

/**
 * Parameters: required array symbols
 * Returns a promise with resolve(stream) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.openStream = function(symbols) {
  var queryObject = {
    symbols: {
      required: true,
      values: symbols
    }
  };
  var url = TradeKing.generateEndpoint("https://stream.tradeking.com/v1/market/quotes", "json", queryObject);
  return new Promise(function(resolve, reject) {
    var request = this.connection.get(url, this.__credentials__.access_token, this.__credentials__.access_secret);
    request.on('response', function(response) {
      response.setEncoding('utf8');
      resolve(response);
    });

    request.on("error", function(error) {
      reject(error);
    });

    request.end();
  }.bind(this));
}

/**
 * Parameters: None
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getMarketClock = function() {
  return this.getDataFromEndpoint("https://api.tradeking.com/v1/market/clock.json");
};

/**
 * Parameters: required array symbols, array fields
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getQuotesForSymbols = function(symbols, fields) {
  var queryObject = {
    symbols: {
      required: true,
      values: symbols
    },
    fields: {
      required: false,
      values: fields
    }
  };
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/ext/quotes", "json", queryObject));
};

/**
 * Parameters: object object containing:
 *  array keywords,
 *  array symbols,
 *  int maxhits,
 *  required string startdate,
 *  required string enddate
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getNews = function(object) {
  if(!_.isObject(object)) { throw new Error("A query object is required for getNews"); }
  var queryObject = {
    keywords: {
      required: false,
      values: object.keywords
    },
    symbols: {
      required: false,
      values: object.symbols
    },
    maxhits: {
      required: false,
      values: _.isNumber(object.maxhits) ? [object.maxhits.toString()]:null
    },
    startdate: {
      required: false,
      values: _.isString(object.startdate) ? [object.startdate]:null
    },
    enddate: {
      required: false,
      values: _.isString(object.enddate) ? [object.enddate]:null
    }
  };
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/news/search", "json", queryObject));
};

/**
 * Parameters: string articleId
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getArticleById = function(articleId) {
  if(!_.isString(articleId)) { throw new Error("getArticleById expects a string argument"); }
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/news/" + articleId, "json"));
};

/**
 * Parameters: required string symbols, required array query (unescaped and without ANDs), array fields
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.searchOptionsForSymbol = function(symbol, query, fields) {
  var queryObject = {
    symbol: {
      required: true,
      values: _.isString(symbol) ? [symbol]:null
    },
    query: {
      required: true,
      values: query
    },
    fields: {
      required: false,
      values: fields
    }
  };
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/options/search", "json", queryObject));
};

/**
 * Parameters: required string symbol
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getStrikesForSymbol = function(symbol) {
  var queryObject = {
    symbol: {
      required: true,
      values: _.isString(symbol) ? [symbol]:null
    }
  };
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/options/strikes", "json", queryObject));
};

/**
 * Parameters: required string symbol
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getOptionExpirationsForSymbol = function(symbol) {
  var queryObject = {
    symbol: {
      required: true,
      values: _.isString(symbol) ? [symbol]:null
    }
  };
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/options/expirations", "json", queryObject));
};

/**
 * Parameters: object containing:
 *  required array symbols,
 *  string interval,
 *  int rpp,
 *  int index,
 *  required string startdate,
 *  required string enddate
 *  string starttime
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getTimeSalesForSymbols = function(object) {
  if(!_.isObject(object)) { throw new Error("A query object is required for getTimesalesForSymbols"); }
  var queryObject = {
    symbols: {
      required: true,
      values: object.symbols
    },
    startdate: {
      required: true,
      values: _.isString(object.startdate) ? [object.startdate]:null
    },
    enddate: {
      required: false,
      values: _.isString(object.enddate) ? [object.enddate]:null
    },
    interval: {
      required: true,
      values: _.isString(object.interval) ? [object.interval]:null
    },
    rpp: {
      required: false,
      values: _.isNumber(object.rpp) ? [object.rpp.toString()]:null
    },
    index: {
      required: false,
      values: _.isNumber(object.index) ? [object.index.toString()]:null
    },
    starttime: {
      required: false,
      values: _.isString(object.starttime) ? [object.starttime]:null
    }
  };
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/timesales", "json", queryObject));
};

/**
 * Parameters: string listType (toplosers, toppctlosers, topvolume, etc. from https://developers.tradeking.com/documentation/market-toplists-get)
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 **/
TradeKing.prototype.getTopLists = function(listType) {
  if(!_.isString(listType)) { throw new Error("getTopLists expects a string argument"); }
  return this.getDataFromEndpoint(TradeKing.generateEndpoint("https://api.tradeking.com/v1/market/toplists/" + listType, "json"));
};

/**
 * Parameters: endpoint (fully escaped https url)
 * Returns a promise with resolve(response as JSON) and reject(error) as the possible outcomes
 * Note: Should be used directly whenever a static endpoint is possible (efficiency)
 * Note: Does not work for streams
 **/
TradeKing.prototype.getDataFromEndpoint = function(endpoint) {
  return new Promise(function(resolve, reject) {
    this.connection.get(endpoint,
      this.__credentials__.access_token,
      this.__credentials__.access_secret,
      function(error, data, response) {
        if(error) {
          reject(error);
        }
        else {
          try {
            var result = JSON.parse(data).response;
            resolve(result);
          }
          catch(error) {
            reject(error);
          }
        }
      }
    );
  }.bind(this));
};

/**
 * Parameters: string baseUrl, string dataType (json or xml), object queryParameters {symbols: {required: true, values: []}} (use for symbols, fields, query, etc.) (all values are arrays)
 * Returns a completely escaped url string
 * Note: Should be used directly whenever a static endpoint is possible (efficiency)
 * Note: Will throw errors from queryParameter validation
 **/
TradeKing.generateEndpoint = function(baseUrl, dataType, queryParameters) {
  var endpoint = baseUrl + "." + dataType;
  if(!_.isObject(queryParameters) || Object.keys(queryParameters).length <= 0) {
    console.log(endpoint);
    return endpoint;
  }

  endpoint += "?";
  var queryStrings = [];
  _.each(queryParameters, function(value, key) {
    if(!TradeKing.__validateQueryParameter__(value, key)) {
      return;
    }

    var tempString = key + "=";
    if(key === "query") {
      tempString += value.values.join("%20AND%20");
      tempString = tempString.replace(/:\s*/g, "%3A");
    } else {
      tempString += value.values.join();
    }
    queryStrings.push(tempString);
  });
  console.log(endpoint + queryStrings.join("&"));
  return endpoint + queryStrings.join("&");
};

/**
 * Parameters: object value: {required: true, values: []}, string key: (symbols, fields, query, etc.)
 * Returns true if valid, false if not. Throws an error if a required parameter is invalid.
 **/
TradeKing.__validateQueryParameter__ = function(value, key) {
  var isValid = false;
  if(value.required ===  true) {
    if(!_.isArray(value.values) || value.values.length <= 0) {
      throw new Error("Required parameter is invalid or missing: " + key);
    }
    isValid = true;
  } else {
    isValid = _.isArray(value.values) ? ((value.values.length > 0)? true:false):false;
  }

  if(isValid === true) {
    _.each(value.values, function(item) {
      if(!_.isString(item)) { throw new Error("A query parameter has invalid values: " + key); }
    });
  }
  return isValid;
};

module.exports = TradeKing;


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

#include "net/spdy/buffered_spdy_framer.h"

#include <algorithm>
#include <utility>

#include "base/logging.h"
#include "net/log/net_log_with_source.h"
#include "net/spdy/spdy_test_util_common.h"
#include "testing/platform_test.h"

namespace net {

namespace {

class TestBufferedSpdyVisitor : public BufferedSpdyFramerVisitorInterface {
 public:
  TestBufferedSpdyVisitor()
      : buffered_spdy_framer_(kMaxHeaderListSizeForTest, NetLogWithSource()),
        error_count_(0),
        setting_count_(0),
        headers_frame_count_(0),
        push_promise_frame_count_(0),
        goaway_count_(0),
        altsvc_count_(0),
        header_stream_id_(static_cast<spdy::SpdyStreamId>(-1)),
        promised_stream_id_(static_cast<spdy::SpdyStreamId>(-1)) {}

  void OnError(
      http2::Http2DecoderAdapter::SpdyFramerError spdy_framer_error) override {
    VLOG(1) << "spdy::SpdyFramer Error: " << spdy_framer_error;
    error_count_++;
  }

  void OnStreamError(spdy::SpdyStreamId stream_id,
                     const std::string& description) override {
    VLOG(1) << "spdy::SpdyFramer Error on stream: " << stream_id << " "
            << description;
    error_count_++;
  }

  void OnHeaders(spdy::SpdyStreamId stream_id,
                 bool has_priority,
                 int weight,
                 spdy::SpdyStreamId parent_stream_id,
                 bool exclusive,
                 bool fin,
                 spdy::Http2HeaderBlock headers,
                 base::TimeTicks recv_first_byte_time) override {
    header_stream_id_ = stream_id;
    headers_frame_count_++;
    headers_ = std::move(headers);
  }

  void OnDataFrameHeader(spdy::SpdyStreamId stream_id,
                         size_t length,
                         bool fin) override {
    ADD_FAILURE() << "Unexpected OnDataFrameHeader call.";
  }

  void OnStreamFrameData(spdy::SpdyStreamId stream_id,
                         const char* data,
                         size_t len) override {
    LOG(FATAL) << "Unexpected OnStreamFrameData call.";
  }

  void OnStreamEnd(spdy::SpdyStreamId stream_id) override {
    LOG(FATAL) << "Unexpected OnStreamEnd call.";
  }

  void OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) override {
    LOG(FATAL) << "Unexpected OnStreamPadding call.";
  }

  void OnSettings() override {}

  void OnSettingsAck() override {}

  void OnSettingsEnd() override {}

  void OnSetting(spdy::SpdySettingsId id, uint32_t value) override {
    setting_count_++;
  }

  void OnPing(spdy::SpdyPingId unique_id, bool is_ack) override {}

  void OnRstStream(spdy::SpdyStreamId stream_id,
                   spdy::SpdyErrorCode error_code) override {}

  void OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,
                spdy::SpdyErrorCode error_code,
                base::StringPiece debug_data) override {
    goaway_count_++;
    goaway_last_accepted_stream_id_ = last_accepted_stream_id;
    goaway_error_code_ = error_code;
    goaway_debug_data_.assign(debug_data.data(), debug_data.size());
  }

  void OnDataFrameHeader(const spdy::SpdySerializedFrame* frame) {
    LOG(FATAL) << "Unexpected OnDataFrameHeader call.";
  }

  void OnRstStream(const spdy::SpdySerializedFrame& frame) {}
  void OnGoAway(const spdy::SpdySerializedFrame& frame) {}
  void OnPing(const spdy::SpdySerializedFrame& frame) {}
  void OnWindowUpdate(spdy::SpdyStreamId stream_id,
                      int delta_window_size) override {}

  void OnPushPromise(spdy::SpdyStreamId stream_id,
                     spdy::SpdyStreamId promised_stream_id,
                     spdy::Http2HeaderBlock headers) override {
    header_stream_id_ = stream_id;
    push_promise_frame_count_++;
    promised_stream_id_ = promised_stream_id;
    headers_ = std::move(headers);
  }

  void OnAltSvc(spdy::SpdyStreamId stream_id,
                base::StringPiece origin,
                const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector&
                    altsvc_vector) override {
    altsvc_count_++;
    altsvc_stream_id_ = stream_id;
    altsvc_origin_.assign(origin.data(), origin.size());
    altsvc_vector_ = altsvc_vector;
  }

  bool OnUnknownFrame(spdy::SpdyStreamId stream_id,
                      uint8_t frame_type) override {
    return true;
  }

  // Convenience function which runs a framer simulation with particular input.
  void SimulateInFramer(const spdy::SpdySerializedFrame& frame) {
    const char* input_ptr = frame.data();
    size_t input_remaining = frame.size();
    buffered_spdy_framer_.set_visitor(this);
    while (input_remaining > 0 &&
           buffered_spdy_framer_.spdy_framer_error() ==
               http2::Http2DecoderAdapter::SPDY_NO_ERROR) {
      // To make the tests more interesting, we feed random (amd small) chunks
      // into the framer.  This simulates getting strange-sized reads from
      // the socket.
      const size_t kMaxReadSize = 32;
      size_t bytes_read =
          (rand() % std::min(input_remaining, kMaxReadSize)) + 1;
      size_t bytes_processed =
          buffered_spdy_framer_.ProcessInput(input_ptr, bytes_read);
      input_remaining -= bytes_processed;
      input_ptr += bytes_processed;
    }
  }

  BufferedSpdyFramer buffered_spdy_framer_;

  // Counters from the visitor callbacks.
  int error_count_;
  int setting_count_;
  int headers_frame_count_;
  int push_promise_frame_count_;
  int goaway_count_;
  int altsvc_count_;

  // Header block streaming state:
  spdy::SpdyStreamId header_stream_id_;
  spdy::SpdyStreamId promised_stream_id_;

  // Headers from OnHeaders and OnPushPromise for verification.
  spdy::Http2HeaderBlock headers_;

  // OnGoAway parameters.
  spdy::SpdyStreamId goaway_last_accepted_stream_id_;
  spdy::SpdyErrorCode goaway_error_code_;
  std::string goaway_debug_data_;

  // OnAltSvc parameters.
  spdy::SpdyStreamId altsvc_stream_id_;
  std::string altsvc_origin_;
  spdy::SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector_;
};

}  // namespace

class BufferedSpdyFramerTest : public PlatformTest {};

TEST_F(BufferedSpdyFramerTest, OnSetting) {
  spdy::SpdyFramer framer(spdy::SpdyFramer::ENABLE_COMPRESSION);
  spdy::SpdySettingsIR settings_ir;
  settings_ir.AddSetting(spdy::SETTINGS_INITIAL_WINDOW_SIZE, 2);
  settings_ir.AddSetting(spdy::SETTINGS_MAX_CONCURRENT_STREAMS, 3);
  spdy::SpdySerializedFrame control_frame(
      framer.SerializeSettings(settings_ir));
  TestBufferedSpdyVisitor visitor;

  visitor.SimulateInFramer(control_frame);
  EXPECT_EQ(0, visitor.error_count_);
  EXPECT_EQ(2, visitor.setting_count_);
}

TEST_F(BufferedSpdyFramerTest, HeaderListTooLarge) {
  spdy::Http2HeaderBlock headers;
  std::string long_header_value(256 * 1024, 'x');
  headers["foo"] = long_header_value;
  spdy::SpdyHeadersIR headers_ir(/*stream_id=*/1, std::move(headers));

  NetLogWithSource net_log;
  BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
  spdy::SpdySerializedFrame control_frame = framer.SerializeFrame(headers_ir);

  TestBufferedSpdyVisitor visitor;
  visitor.SimulateInFramer(control_frame);

  EXPECT_EQ(1, visitor.error_count_);
  EXPECT_EQ(0, visitor.headers_frame_count_);
  EXPECT_EQ(0, visitor.push_promise_frame_count_);
  EXPECT_EQ(spdy::Http2HeaderBlock(), visitor.headers_);
}

TEST_F(BufferedSpdyFramerTest, ValidHeadersAfterInvalidHeaders) {
  spdy::Http2HeaderBlock headers;
  headers["invalid"] = "\r\n\r\n";

  spdy::Http2HeaderBlock headers2;
  headers["alpha"] = "beta";

  SpdyTestUtil spdy_test_util;
  spdy::SpdySerializedFrame headers_frame(
      spdy_test_util.ConstructSpdyReply(1, std::move(headers)));
  spdy::SpdySerializedFrame headers_frame2(
      spdy_test_util.ConstructSpdyReply(2, std::move(headers2)));

  TestBufferedSpdyVisitor visitor;
  visitor.SimulateInFramer(headers_frame);
  EXPECT_EQ(1, visitor.error_count_);
  EXPECT_EQ(0, visitor.headers_frame_count_);

  visitor.SimulateInFramer(headers_frame2);
  EXPECT_EQ(1, visitor.error_count_);
  EXPECT_EQ(1, visitor.headers_frame_count_);
}

TEST_F(BufferedSpdyFramerTest, ReadHeadersHeaderBlock) {
  spdy::Http2HeaderBlock headers;
  headers["alpha"] = "beta";
  headers["gamma"] = "delta";
  spdy::SpdyHeadersIR headers_ir(/*stream_id=*/1, headers.Clone());

  NetLogWithSource net_log;
  BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
  spdy::SpdySerializedFrame control_frame = framer.SerializeFrame(headers_ir);

  TestBufferedSpdyVisitor visitor;
  visitor.SimulateInFramer(control_frame);
  EXPECT_EQ(0, visitor.error_count_);
  EXPECT_EQ(1, visitor.headers_frame_count_);
  EXPECT_EQ(0, visitor.push_promise_frame_count_);
  EXPECT_EQ(headers, visitor.headers_);
}

TEST_F(BufferedSpdyFramerTest, ReadPushPromiseHeaderBlock) {
  spdy::Http2HeaderBlock headers;
  headers["alpha"] = "beta";
  headers["gamma"] = "delta";
  NetLogWithSource net_log;
  BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
  spdy::SpdyPushPromiseIR push_promise_ir(
      /*stream_id=*/1, /*promised_stream_id=*/2, headers.Clone());
  spdy::SpdySerializedFrame control_frame =
      framer.SerializeFrame(push_promise_ir);

  TestBufferedSpdyVisitor visitor;
  visitor.SimulateInFramer(control_frame);
  EXPECT_EQ(0, visitor.error_count_);
  EXPECT_EQ(0, visitor.headers_frame_count_);
  EXPECT_EQ(1, visitor.push_promise_frame_count_);
  EXPECT_EQ(headers, visitor.headers_);
  EXPECT_EQ(1u, visitor.header_stream_id_);
  EXPECT_EQ(2u, visitor.promised_stream_id_);
}

TEST_F(BufferedSpdyFramerTest, GoAwayDebugData) {
  spdy::SpdyGoAwayIR go_ir(/*last_accepted_stream_id=*/2,
                           spdy::ERROR_CODE_FRAME_SIZE_ERROR, "foo");
  NetLogWithSource net_log;
  BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
  spdy::SpdySerializedFrame goaway_frame = framer.SerializeFrame(go_ir);

  TestBufferedSpdyVisitor visitor;
  visitor.SimulateInFramer(goaway_frame);
  EXPECT_EQ(0, visitor.error_count_);
  EXPECT_EQ(1, visitor.goaway_count_);
  EXPECT_EQ(2u, visitor.goaway_last_accepted_stream_id_);
  EXPECT_EQ(spdy::ERROR_CODE_FRAME_SIZE_ERROR, visitor.goaway_error_code_);
  EXPECT_EQ("foo", visitor.goaway_debug_data_);
}

// ALTSVC frame on stream 0 must have an origin.
TEST_F(BufferedSpdyFramerTest, OnAltSvcOnStreamZero) {
  const spdy::SpdyStreamId altsvc_stream_id(0);
  spdy::SpdyAltSvcIR altsvc_ir(altsvc_stream_id);
  spdy::SpdyAltSvcWireFormat::AlternativeService alternative_service(
      "quic", "alternative.example.org", 443, 86400,
      spdy::SpdyAltSvcWireFormat::VersionVector());
  altsvc_ir.add_altsvc(alternative_service);
  const char altsvc_origin[] = "https://www.example.org";
  altsvc_ir.set_origin(altsvc_origin);
  NetLogWithSource net_log;
  BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
  spdy::SpdySerializedFrame altsvc_frame(framer.SerializeFrame(altsvc_ir));

  TestBufferedSpdyVisitor visitor;
  visitor.SimulateInFramer(altsvc_frame);
  EXPECT_EQ(0, visitor.error_count_);
  EXPECT_EQ(1, visitor.altsvc_count_);
  EXPECT_EQ(altsvc_stream_id, visitor.altsvc_stream_id_);
  EXPECT_EQ(altsvc_origin, visitor.altsvc_origin_);
  ASSERT_EQ(1u, visitor.altsvc_vector_.size());
  EXPECT_EQ(alternative_service, visitor.altsvc_vector_[0]);
}

// ALTSVC frame on a non-zero stream must not have an origin.
TEST_F(BufferedSpdyFramerTest, OnAltSvcOnNonzeroStream) {
  const spdy::SpdyStreamId altsvc_stream_id(1);
  spdy::SpdyAltSvcIR altsvc_ir(altsvc_stream_id);
  spdy::SpdyAltSvcWireFormat::AlternativeService alternative_service(
      "quic", "alternative.example.org", 443, 86400,
      spdy::SpdyAltSvcWireFormat::VersionVector());
  altsvc_ir.add_altsvc(alternative_service);
  NetLogWithSource net_log;
  BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
  spdy::SpdySerializedFrame altsvc_frame(framer.SerializeFrame(altsvc_ir));

  TestBufferedSpdyVisitor visitor;
  visitor.SimulateInFramer(altsvc_frame);
  EXPECT_EQ(0, visitor.error_count_);
  EXPECT_EQ(1, visitor.altsvc_count_);
  EXPECT_EQ(altsvc_stream_id, visitor.altsvc_stream_id_);
  EXPECT_TRUE(visitor.altsvc_origin_.empty());
  ASSERT_EQ(1u, visitor.altsvc_vector_.size());
  EXPECT_EQ(alternative_service, visitor.altsvc_vector_[0]);
}

}  // namespace net


text: Zabbix module for monitoring Elastic Search Cluster and Nodes


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.twelvemonkeys.imageio</groupId>
  <artifactId>imageio</artifactId>
  <versioning>
    <versions>
      <version>3.0-SNAPSHOT</version>
    </versions>
    <lastUpdated>20140105224139</lastUpdated>
  </versioning>
</metadata>


text:
namespace Lender.Slos.ImplicitTyping
{
    using System.Linq;

    public interface IRepository<TEntity>
        where TEntity : class
    {
        int Create(TEntity entity);

        TEntity Retrieve(int id);

        void Update(TEntity entity);

        void Delete(TEntity entity);

        IQueryable<ApplicationEntity> Query<T>();
    }
}